@velastack/patterns 0.3.4 → 0.4.1

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 (207) hide show
  1. package/README.md +44 -2
  2. package/dist/chunks/_layout-kkgN0IF7.js +62 -0
  3. package/dist/chunks/_layout-kkgN0IF7.js.map +1 -0
  4. package/dist/chunks/{collections-CrOvS2E7.js → collections-Dz2fvKnz.js} +2 -2
  5. package/dist/chunks/collections-Dz2fvKnz.js.map +1 -0
  6. package/dist/chunks/{compose-handle-B-CkDcQD.js → compose-handle-D_Rz3Fzo.js} +10 -4
  7. package/dist/chunks/compose-handle-D_Rz3Fzo.js.map +1 -0
  8. package/dist/chunks/{config-target-Bln26FJe.js → config-target-Dx3w6WSk.js} +59 -70
  9. package/dist/chunks/config-target-Dx3w6WSk.js.map +1 -0
  10. package/dist/chunks/constants-BjyMU5s8.js +6 -0
  11. package/dist/chunks/constants-BjyMU5s8.js.map +1 -0
  12. package/dist/chunks/dedent-Gq6Krl4n.js.map +1 -1
  13. package/dist/chunks/dispatch-CXOXPLFk.js +6 -0
  14. package/dist/chunks/dispatch-CXOXPLFk.js.map +1 -0
  15. package/dist/chunks/env-BPfk1VAw.js.map +1 -1
  16. package/dist/chunks/env-vars-C1NUX-bf.js +268 -0
  17. package/dist/chunks/env-vars-C1NUX-bf.js.map +1 -0
  18. package/dist/chunks/env-vars-Cr4lbMD_.js +21 -0
  19. package/dist/chunks/env-vars-Cr4lbMD_.js.map +1 -0
  20. package/dist/chunks/env-vars-De0Xs0L2.js +20 -0
  21. package/dist/chunks/env-vars-De0Xs0L2.js.map +1 -0
  22. package/dist/chunks/env-vars-file-B_6esJW3.js +34 -0
  23. package/dist/chunks/env-vars-file-B_6esJW3.js.map +1 -0
  24. package/dist/chunks/env-vars-mnRA0hOe.js +19 -0
  25. package/dist/chunks/env-vars-mnRA0hOe.js.map +1 -0
  26. package/dist/chunks/env.preview-uMRKT5Pc.js.map +1 -1
  27. package/dist/chunks/errors-DR3gF_7a.js.map +1 -1
  28. package/dist/chunks/format-result-DZ8De8KY.js.map +1 -1
  29. package/dist/chunks/generate-BW3l5Fxw.js +252 -0
  30. package/dist/chunks/generate-BW3l5Fxw.js.map +1 -0
  31. package/dist/chunks/{generate-CyuY2Ci7.js → generate-DeaBlnK6.js} +25 -24
  32. package/dist/chunks/generate-DeaBlnK6.js.map +1 -0
  33. package/dist/chunks/generate-DetW_gbr.js +68 -0
  34. package/dist/chunks/generate-DetW_gbr.js.map +1 -0
  35. package/dist/chunks/{generate-DwADTUob.js → generate-Gcc8iRkZ.js} +9 -6
  36. package/dist/chunks/generate-Gcc8iRkZ.js.map +1 -0
  37. package/dist/chunks/{generate-DQeWOEPY.js → generate-WMJo3QGZ.js} +9 -6
  38. package/dist/chunks/generate-WMJo3QGZ.js.map +1 -0
  39. package/dist/chunks/generate.runtime-1-91UmM8.js +85 -0
  40. package/dist/chunks/generate.runtime-1-91UmM8.js.map +1 -0
  41. package/dist/chunks/generate.runtime-6FXJM8hT.js +67 -0
  42. package/dist/chunks/generate.runtime-6FXJM8hT.js.map +1 -0
  43. package/dist/chunks/generate.runtime-B1jVAnDI.js +155 -0
  44. package/dist/chunks/generate.runtime-B1jVAnDI.js.map +1 -0
  45. package/dist/chunks/generate.runtime-BA3tDKnn.js +147 -0
  46. package/dist/chunks/generate.runtime-BA3tDKnn.js.map +1 -0
  47. package/dist/chunks/{generate.runtime-4FDxnvCl.js → generate.runtime-BO778G0r.js} +5 -5
  48. package/dist/chunks/generate.runtime-BO778G0r.js.map +1 -0
  49. package/dist/chunks/{generate.runtime-Um77JfwC.js → generate.runtime-B_UVGa3q.js} +7 -7
  50. package/dist/chunks/generate.runtime-B_UVGa3q.js.map +1 -0
  51. package/dist/chunks/{generate.runtime-BKiJvE8I.js → generate.runtime-BgTz41Zg.js} +105 -101
  52. package/dist/chunks/generate.runtime-BgTz41Zg.js.map +1 -0
  53. package/dist/chunks/{generate.runtime-FdZw277n.js → generate.runtime-C6bSvGMb.js} +108 -142
  54. package/dist/chunks/generate.runtime-C6bSvGMb.js.map +1 -0
  55. package/dist/chunks/generate.runtime-C8zJRNYG.js +124 -0
  56. package/dist/chunks/generate.runtime-C8zJRNYG.js.map +1 -0
  57. package/dist/chunks/generate.runtime-CCr1lvo4.js +43 -0
  58. package/dist/chunks/generate.runtime-CCr1lvo4.js.map +1 -0
  59. package/dist/chunks/generate.runtime-CYagyR5c.js +326 -0
  60. package/dist/chunks/generate.runtime-CYagyR5c.js.map +1 -0
  61. package/dist/chunks/{generate.runtime-n9AFWtPp.js → generate.runtime-Ce_rwzNa.js} +4 -4
  62. package/dist/chunks/generate.runtime-Ce_rwzNa.js.map +1 -0
  63. package/dist/chunks/{generate.runtime-cQGLxuZM.js → generate.runtime-CexC1Oky.js} +4 -4
  64. package/dist/chunks/generate.runtime-CexC1Oky.js.map +1 -0
  65. package/dist/chunks/{generate.runtime-AYQVW1S-.js → generate.runtime-CnPraLKv.js} +35 -31
  66. package/dist/chunks/generate.runtime-CnPraLKv.js.map +1 -0
  67. package/dist/chunks/generate.runtime-CslAvllQ.js +112 -0
  68. package/dist/chunks/generate.runtime-CslAvllQ.js.map +1 -0
  69. package/dist/chunks/{generate.runtime-onBnOiS7.js → generate.runtime-CuNhY5hn.js} +10 -10
  70. package/dist/chunks/generate.runtime-CuNhY5hn.js.map +1 -0
  71. package/dist/chunks/{generate.runtime-B45MvtYm.js → generate.runtime-DD51OSuL.js} +14 -14
  72. package/dist/chunks/generate.runtime-DD51OSuL.js.map +1 -0
  73. package/dist/chunks/generate.runtime-DHBRyMAq.js +65 -0
  74. package/dist/chunks/generate.runtime-DHBRyMAq.js.map +1 -0
  75. package/dist/chunks/{generate.runtime-D1DNAY6k.js → generate.runtime-DM4o_QYY.js} +9 -9
  76. package/dist/chunks/generate.runtime-DM4o_QYY.js.map +1 -0
  77. package/dist/chunks/generate.runtime-DV3WmZtb.js +35 -0
  78. package/dist/chunks/generate.runtime-DV3WmZtb.js.map +1 -0
  79. package/dist/chunks/generate.runtime-D_sQOeQa.js +164 -0
  80. package/dist/chunks/generate.runtime-D_sQOeQa.js.map +1 -0
  81. package/dist/chunks/{generate.runtime-ofdnLtxS.js → generate.runtime-DqD3PW-W.js} +3 -3
  82. package/dist/chunks/generate.runtime-DqD3PW-W.js.map +1 -0
  83. package/dist/chunks/{generate.runtime-VgVwRiiN.js → generate.runtime-Dtgw9IQO.js} +8 -8
  84. package/dist/chunks/generate.runtime-Dtgw9IQO.js.map +1 -0
  85. package/dist/chunks/{generate.runtime-CN5c2xH8.js → generate.runtime-IlBCcXvv.js} +14 -14
  86. package/dist/chunks/generate.runtime-IlBCcXvv.js.map +1 -0
  87. package/dist/chunks/{generate.runtime-BSRFv4cJ.js → generate.runtime-cwvAoKoH.js} +3 -3
  88. package/dist/chunks/generate.runtime-cwvAoKoH.js.map +1 -0
  89. package/dist/chunks/{generate.runtime-DG-3G00z.js → generate.runtime-kvxmTlQb.js} +3 -3
  90. package/dist/chunks/{generate.runtime-DG-3G00z.js.map → generate.runtime-kvxmTlQb.js.map} +1 -1
  91. package/dist/chunks/generate.runtime-pVLzzpUM.js +122 -0
  92. package/dist/chunks/generate.runtime-pVLzzpUM.js.map +1 -0
  93. package/dist/chunks/{generate.runtime-BFOXm2DD.js → generate.runtime-zJpEufTc.js} +10 -10
  94. package/dist/chunks/generate.runtime-zJpEufTc.js.map +1 -0
  95. package/dist/chunks/lib-specifier-Cngo1zF_.js +33 -0
  96. package/dist/chunks/lib-specifier-Cngo1zF_.js.map +1 -0
  97. package/dist/chunks/logger-CQONztPm.js.map +1 -1
  98. package/dist/chunks/{modify-file-Dwfv0dCI.js → modify-file-BlDeeurK.js} +3 -3
  99. package/dist/chunks/modify-file-BlDeeurK.js.map +1 -0
  100. package/dist/chunks/{modify-svelte-config-remote-BUU_EaDf.js → modify-svelte-config-remote-p0TfVzxm.js} +8 -10
  101. package/dist/chunks/modify-svelte-config-remote-p0TfVzxm.js.map +1 -0
  102. package/dist/chunks/modify-utils-Cw-on_cL.js.map +1 -1
  103. package/dist/chunks/nav-user-BRIHOOpG.js +6 -0
  104. package/dist/chunks/nav-user-BRIHOOpG.js.map +1 -0
  105. package/dist/chunks/package-imports-Bbw3iMPg.js +173 -0
  106. package/dist/chunks/package-imports-Bbw3iMPg.js.map +1 -0
  107. package/dist/chunks/pocketbase-C5GS-Dh5.js.map +1 -1
  108. package/dist/chunks/pocketbase-DpudAAmd.js.map +1 -1
  109. package/dist/chunks/{pocketbase-BkhUywtb.js → pocketbase-Dry6ry17.js} +2 -2
  110. package/dist/chunks/pocketbase-Dry6ry17.js.map +1 -0
  111. package/dist/chunks/{providers-BL9vJP_9.js → providers-BHR6-XZ7.js} +11 -4
  112. package/dist/chunks/providers-BHR6-XZ7.js.map +1 -0
  113. package/dist/chunks/{shared-C8GtNxpm.js → shared-CZC4d7Uj.js} +2 -2
  114. package/dist/chunks/shared-CZC4d7Uj.js.map +1 -0
  115. package/dist/chunks/{site-BdMX8qrH.js → site-BwCA18Sv.js} +2 -2
  116. package/dist/chunks/site-BwCA18Sv.js.map +1 -0
  117. package/dist/chunks/svelte-file-B3RfgVdt.js.map +1 -1
  118. package/dist/chunks/table-core-AjBpYi-y.js +127 -0
  119. package/dist/chunks/table-core-AjBpYi-y.js.map +1 -0
  120. package/dist/chunks/{taggedTemplateLiteral-Dx0fjWiw.js → taggedTemplateLiteral-CswN2AAa.js} +1 -1
  121. package/dist/chunks/{test-setup-DHEFKEHE.js → test-setup-DEmWd9Ul.js} +76 -67
  122. package/dist/chunks/test-setup-DEmWd9Ul.js.map +1 -0
  123. package/dist/chunks/{ts-morph-helpers-CeduA--o.js → ts-morph-helpers-CDW4lhox.js} +77 -63
  124. package/dist/chunks/ts-morph-helpers-CDW4lhox.js.map +1 -0
  125. package/dist/chunks/ui-DD4NltyN.js.map +1 -1
  126. package/dist/chunks/{ui-TlEuI2Sz.js → ui-X698F10c.js} +47 -47
  127. package/dist/chunks/ui-X698F10c.js.map +1 -0
  128. package/dist/chunks/{unmodify-load-jfdcVZ_a.js → unmodify-load-CyGzC1Hu.js} +2 -2
  129. package/dist/chunks/unmodify-load-CyGzC1Hu.js.map +1 -0
  130. package/dist/chunks/util-BLYliuUK.js.map +1 -1
  131. package/dist/chunks/write-result-B68lvI57.js +511 -0
  132. package/dist/chunks/write-result-B68lvI57.js.map +1 -0
  133. package/dist/index.d.ts +224 -1
  134. package/dist/index.js +2121 -2064
  135. package/dist/index.js.map +1 -1
  136. package/package.json +7 -7
  137. package/dist/chunks/_layout-B7ujvjnA.js +0 -55
  138. package/dist/chunks/_layout-B7ujvjnA.js.map +0 -1
  139. package/dist/chunks/collections-CrOvS2E7.js.map +0 -1
  140. package/dist/chunks/compose-handle-B-CkDcQD.js.map +0 -1
  141. package/dist/chunks/config-target-Bln26FJe.js.map +0 -1
  142. package/dist/chunks/constants-BYkd9jeJ.js +0 -6
  143. package/dist/chunks/constants-BYkd9jeJ.js.map +0 -1
  144. package/dist/chunks/dispatch-BRnt8PcW.js +0 -6
  145. package/dist/chunks/dispatch-BRnt8PcW.js.map +0 -1
  146. package/dist/chunks/generate-6snrlnpA.js +0 -64
  147. package/dist/chunks/generate-6snrlnpA.js.map +0 -1
  148. package/dist/chunks/generate-Ca_6FlPi.js +0 -252
  149. package/dist/chunks/generate-Ca_6FlPi.js.map +0 -1
  150. package/dist/chunks/generate-CyuY2Ci7.js.map +0 -1
  151. package/dist/chunks/generate-DQeWOEPY.js.map +0 -1
  152. package/dist/chunks/generate-DwADTUob.js.map +0 -1
  153. package/dist/chunks/generate.runtime-4FDxnvCl.js.map +0 -1
  154. package/dist/chunks/generate.runtime-AYQVW1S-.js.map +0 -1
  155. package/dist/chunks/generate.runtime-B2aFFaac.js +0 -117
  156. package/dist/chunks/generate.runtime-B2aFFaac.js.map +0 -1
  157. package/dist/chunks/generate.runtime-B45MvtYm.js.map +0 -1
  158. package/dist/chunks/generate.runtime-BFOXm2DD.js.map +0 -1
  159. package/dist/chunks/generate.runtime-BHkFmI2Y.js +0 -146
  160. package/dist/chunks/generate.runtime-BHkFmI2Y.js.map +0 -1
  161. package/dist/chunks/generate.runtime-BKiJvE8I.js.map +0 -1
  162. package/dist/chunks/generate.runtime-BSRFv4cJ.js.map +0 -1
  163. package/dist/chunks/generate.runtime-BUqsF3AF.js +0 -123
  164. package/dist/chunks/generate.runtime-BUqsF3AF.js.map +0 -1
  165. package/dist/chunks/generate.runtime-BsaSyTnU.js +0 -82
  166. package/dist/chunks/generate.runtime-BsaSyTnU.js.map +0 -1
  167. package/dist/chunks/generate.runtime-CMnvmeVt.js +0 -111
  168. package/dist/chunks/generate.runtime-CMnvmeVt.js.map +0 -1
  169. package/dist/chunks/generate.runtime-CN5c2xH8.js.map +0 -1
  170. package/dist/chunks/generate.runtime-CgoSrP55.js +0 -146
  171. package/dist/chunks/generate.runtime-CgoSrP55.js.map +0 -1
  172. package/dist/chunks/generate.runtime-D1DNAY6k.js.map +0 -1
  173. package/dist/chunks/generate.runtime-DQwSY6Nc.js +0 -38
  174. package/dist/chunks/generate.runtime-DQwSY6Nc.js.map +0 -1
  175. package/dist/chunks/generate.runtime-D_yqWLcI.js +0 -66
  176. package/dist/chunks/generate.runtime-D_yqWLcI.js.map +0 -1
  177. package/dist/chunks/generate.runtime-Drmahmdl.js +0 -313
  178. package/dist/chunks/generate.runtime-Drmahmdl.js.map +0 -1
  179. package/dist/chunks/generate.runtime-FdZw277n.js.map +0 -1
  180. package/dist/chunks/generate.runtime-Lh1cW9Tz.js +0 -94
  181. package/dist/chunks/generate.runtime-Lh1cW9Tz.js.map +0 -1
  182. package/dist/chunks/generate.runtime-QGHToXRY.js +0 -32
  183. package/dist/chunks/generate.runtime-QGHToXRY.js.map +0 -1
  184. package/dist/chunks/generate.runtime-Um77JfwC.js.map +0 -1
  185. package/dist/chunks/generate.runtime-VgVwRiiN.js.map +0 -1
  186. package/dist/chunks/generate.runtime-YyIVd4oy.js +0 -61
  187. package/dist/chunks/generate.runtime-YyIVd4oy.js.map +0 -1
  188. package/dist/chunks/generate.runtime-cQGLxuZM.js.map +0 -1
  189. package/dist/chunks/generate.runtime-n9AFWtPp.js.map +0 -1
  190. package/dist/chunks/generate.runtime-ofdnLtxS.js.map +0 -1
  191. package/dist/chunks/generate.runtime-onBnOiS7.js.map +0 -1
  192. package/dist/chunks/modify-file-Dwfv0dCI.js.map +0 -1
  193. package/dist/chunks/modify-svelte-config-remote-BUU_EaDf.js.map +0 -1
  194. package/dist/chunks/nav-user-BYI-h8Od.js +0 -6
  195. package/dist/chunks/nav-user-BYI-h8Od.js.map +0 -1
  196. package/dist/chunks/pocketbase-BkhUywtb.js.map +0 -1
  197. package/dist/chunks/providers-BL9vJP_9.js.map +0 -1
  198. package/dist/chunks/shared-C8GtNxpm.js.map +0 -1
  199. package/dist/chunks/site-BdMX8qrH.js.map +0 -1
  200. package/dist/chunks/table-core-G9Shld4F.js +0 -126
  201. package/dist/chunks/table-core-G9Shld4F.js.map +0 -1
  202. package/dist/chunks/test-setup-DHEFKEHE.js.map +0 -1
  203. package/dist/chunks/ts-morph-helpers-CeduA--o.js.map +0 -1
  204. package/dist/chunks/ui-TlEuI2Sz.js.map +0 -1
  205. package/dist/chunks/unmodify-load-jfdcVZ_a.js.map +0 -1
  206. package/dist/chunks/write-result-Djy0SZXX.js +0 -376
  207. package/dist/chunks/write-result-Djy0SZXX.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-Um77JfwC.js","names":[],"sources":["../../src/patterns/enable/notifications/modifies/modify-app-layout.ts","../../src/patterns/enable/notifications/modifies/+layout.server.ts","../../src/patterns/enable/notifications/generate.runtime.ts"],"sourcesContent":["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 BELL_SNIPPET = `\n\t\t<div class=\"ml-auto px-4\">\n\t\t\t<NotificationsBell />\n\t\t</div>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import NotificationsBell from '$lib/components/notifications-bell.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the notifications bell inside the (app) layout's <header>.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with a <header> that includes the bell.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nexport function modifyAppLayout(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(\"header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"NotificationsBell\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"NotificationsBell\",\n moduleSpecifier: \"$lib/components/notifications-bell.svelte\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"header\", BELL_SNIPPET);\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 FETCH_STATEMENT = dedent`\n const notificationsList = await locals.pb\n .collection(\"notifications\")\n .getList(1, 5, {\n filter: \\`user = \"\\${locals.pb.authStore.record!.id}\" && read = false\\`,\n sort: \"-created\",\n });\n`;\n\nconst NOTIFICATIONS_STATEMENT =\n \"const notifications = { count: notificationsList.totalItems, items: notificationsList.items };\";\n\nconst DEPENDS_STATEMENT = 'depends(\"app:notifications\");';\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n ${FETCH_STATEMENT}\n ${NOTIFICATIONS_STATEMENT}\n ${DEPENDS_STATEMENT}\n return { notifications };\n };\n `;\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n if (obj.getProperty(name)) return;\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n };\n\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 if (vs?.hasExportKeyword()) {\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) loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n\n if (!loadArrow && !loadFn) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) loadFn = maybeFn;\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n FETCH_STATEMENT,\n NOTIFICATIONS_STATEMENT,\n DEPENDS_STATEMENT,\n \"return { notifications };\",\n ],\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike = (loadArrow ?? loadFn!) as\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression;\n\n // Ensure first param destructures { locals, depends }\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\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 elementNames = obp.getElements().map((el) => el.getName());\n const hasDepends = elementNames.includes(\"depends\");\n const hasLocals = elementNames.includes(\"locals\");\n\n if (!hasDepends || !hasLocals) {\n const existingParts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const parts: string[] = hasLocals ? [] : [\"locals\"];\n parts.push(...existingParts);\n if (!hasDepends) parts.push(\"depends\");\n first.set({\n name: `{ ${parts.join(\", \")} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) loadArrow.setIsAsync(true);\n else if (loadFn && !loadFn.isAsync()) loadFn.setIsAsync(true);\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const declaresVar = (name: string) =>\n statements.some((stmt) => {\n if (stmt.getKind() !== SyntaxKind.VariableStatement) return false;\n return (stmt as import(\"ts-morph\").VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === name);\n });\n\n const hasDependsCall = statements.some(\n (stmt) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt.getDescendantsOfKind(SyntaxKind.CallExpression).some((ce) => {\n if (ce.getExpression().getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:notifications'\" ||\n argText === '\"app:notifications\"')\n );\n }),\n );\n\n const hasNotificationsList = declaresVar(\"notificationsList\");\n const hasNotifications = declaresVar(\"notifications\");\n\n const returnIdx = statements.findIndex(\n (s) => s.getKind() === SyntaxKind.ReturnStatement,\n );\n let insertAt = returnIdx >= 0 ? returnIdx : statements.length;\n\n if (!hasNotificationsList) {\n blockBody.insertStatements(insertAt, FETCH_STATEMENT);\n insertAt++;\n }\n if (!hasNotifications) {\n blockBody.insertStatements(insertAt, NOTIFICATIONS_STATEMENT);\n insertAt++;\n }\n if (!hasDependsCall) {\n blockBody.insertStatements(insertAt, DEPENDS_STATEMENT);\n }\n }\n\n const augmentReturnObject = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n ) => {\n addProperty(obj, \"notifications\", \"notifications\");\n };\n\n const augmentReturns = (target: import(\"ts-morph\").Node) => {\n const returns = target.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(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 augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n });\n };\n\n if (loadArrow) {\n const arrowBody = loadArrow.getBody();\n if (arrowBody.getKind() === SyntaxKind.Block) {\n augmentReturns(arrowBody);\n } else {\n const bodyExpr = arrowBody 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 augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n bodyExpr as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) augmentReturns(fnBody);\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 path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { NOTIFICATION_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", 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\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating notifications collection\");\n const result = await create({\n name: \"notifications\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"user\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"title\",\n type: \"text\",\n required: true,\n },\n {\n name: \"body\",\n type: \"text\",\n },\n {\n name: \"read\",\n type: \"bool\",\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n indexes: [\n \"CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"notifications\",\n options,\n result.created,\n );\n\n logger.info(\"Applying notifications rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n NOTIFICATION_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayout(appLayoutPath)),\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 modifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Modifying utils.ts\");\n const utilsPath = path.join(options.root, \"src\", \"lib\", \"utils.ts\");\n pushResult(modifyOutcomeToFile(utilsPath, modifyUtils(utilsPath)));\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":";;;;;;;;;;;;;;AASA,IAAM,IAAe,2EAMf,IAAiB,CAAM;;GAIvB,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAgB,GAAmC;CACjE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAO,EAAW,SAAS,CAAU;CAsB3C,OArBK,EAAK,WAAW,QAAQ,IAGzB,EAAK,WAAW,mBAAmB,IAC9B;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;GACzD,EAAc,GAAI,CAChB;IACE,eAAe;IACf,iBAAiB;GACnB,CACF,CAAC;EACH,CAAC;EACD,OAAO;CACT,CAAC,GAED,EAAK,uBAAuB,UAAU,CAAY,GAClD,EAAK,QAAQ,CAAU,GAChB;EAAE,QAAQ;EAAW,SAAS,EAAK,WAAW;CAAE,KApB9C;EAAE,QAAQ;EAAU,SAAS;CAAa;AAqBrD;;;AC/DA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KACX,WAAW;KACX,UAAU;IACZ;IACA;KACE,MAAM;KACN,MAAM;KACN,UAAU;IACZ;IACA;KACE,MAAM;KACN,MAAM;IACR;IACA;KACE,MAAM;KACN,MAAM;IACR;IACA;KACE,MAAM;KACN,MAAM;KACN,UAAU;KACV,UAAU;IACZ;IACA;KACE,MAAM;KACN,MAAM;KACN,UAAU;KACV,UAAU;IACZ;GACF;GACA,SAAS,CACP,wGACF;EACF,CAAC;EAQD,AAPA,MAAM,EACJ,GACA,iBACA,GACA,EAAO,OACT,GAEA,EAAO,KAAK,qCAAqC;EACjD,IAAM,IAAiB,MAAM,EAC3B,GACA,GACA,GACA,CACF;EACA,EAAQ,KAAK,GAAG,CAAc;CAChC,CAAC;CAED,IAAM,IAAmB,CAAC,GACpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAgB,EAAK,KACzB,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAKA,AAJA,EACE,EAAoB,GAAe,EAAgB,CAAa,CAAC,CACnE,GAEA,EAAO,KAAK,mCAAmC;CAC/C,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAQA,AAPA,EACE,EACE,GACA,EAAmB,CAAmB,CACxC,CACF,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,OAAO,UAAU;CAGlE,OAFA,EAAW,EAAoB,GAAW,EAAY,CAAS,CAAC,CAAC,GAE1D;EACL;EACA;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-VgVwRiiN.js","names":[],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/load-function.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type Block,\n type FunctionDeclaration,\n type FunctionExpression,\n type ObjectLiteralExpression,\n type ParameterDeclaration,\n type ReturnStatement,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * What the two layout modifiers have in common: finding a SvelteKit `load`,\n * working out how it receives its event, and locating the object it returns.\n */\n\nexport type LoadFunction =\n ArrowFunction | FunctionExpression | FunctionDeclaration;\n\nexport function newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\nexport function ensureNamedImports(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n names: string[],\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({ namedImports: names, moduleSpecifier });\n return;\n }\n for (const name of names) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n }\n}\n\nexport function ensureImportSpec(sourceFile: SourceFile, spec: ImportSpec) {\n if (spec.namedImports?.length) {\n ensureNamedImports(sourceFile, spec.moduleSpecifier, spec.namedImports);\n }\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({\n moduleSpecifier: spec.moduleSpecifier,\n defaultImport: spec.defaultImport,\n namespaceImport: spec.namespaceImport,\n });\n}\n\n/** Peel wrappers (`loadFlash(fn)`, `(fn)`, `fn satisfies X`) down to the function. */\nfunction unwrapFunction(node: Node): ArrowFunction | FunctionExpression | null {\n if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) {\n return node;\n }\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node)\n ) {\n return unwrapFunction(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n for (const arg of node.getArguments()) {\n const fn = unwrapFunction(arg);\n if (fn) return fn;\n }\n }\n return null;\n}\n\n/** The exported `load`, whether declared as a function or wrapped in a const. */\nexport function findLoadFunction(sourceFile: SourceFile): LoadFunction | null {\n const declaration = sourceFile.getFunction(\"load\");\n if (declaration) {\n return declaration.isExported() ? declaration : null;\n }\n\n const variable = sourceFile.getVariableDeclaration(\"load\");\n if (!variable) return null;\n if (!variable.getVariableStatement()?.isExported()) return null;\n\n const initializer = variable.getInitializer();\n return initializer ? unwrapFunction(initializer) : null;\n}\n\nfunction isFunctionNode(node: Node): boolean {\n return (\n Node.isArrowFunction(node) ||\n Node.isFunctionExpression(node) ||\n Node.isFunctionDeclaration(node) ||\n Node.isMethodDeclaration(node)\n );\n}\n\n/**\n * The single, final `return <expression>` of the load body, or null when the\n * body has early returns — those would need any insertion hoisted above them,\n * and guessing where is worse than refusing.\n */\nexport function findFinalReturn(\n fn: LoadFunction,\n body: Block,\n): ReturnStatement | null {\n const statements = body.getStatements();\n const last = statements[statements.length - 1];\n if (!last || !Node.isReturnStatement(last)) return null;\n\n const returns = body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .filter((r) => r.getFirstAncestor(isFunctionNode) === fn);\n if (returns.length !== 1) return null;\n\n return last;\n}\n\n/** The object literal a return statement yields, unwrapping parentheses. */\nexport function returnedObject(\n statement: ReturnStatement,\n): ObjectLiteralExpression | null {\n let expression = statement.getExpression();\n while (expression && Node.isParenthesizedExpression(expression)) {\n expression = expression.getExpression();\n }\n if (!expression || !Node.isObjectLiteralExpression(expression)) return null;\n return expression;\n}\n\nexport function hasProperty(\n object: ObjectLiteralExpression,\n name: string,\n): boolean {\n return object.getProperties().some((property) => {\n if (\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ) {\n return property.getName() === name;\n }\n return false;\n });\n}\n\nexport function hasSpreadOf(\n object: ObjectLiteralExpression,\n expressionText: string,\n): boolean {\n return object\n .getProperties()\n .some(\n (property) =>\n Node.isSpreadAssignment(property) &&\n property.getExpression().getText() === expressionText,\n );\n}\n\n/** How a load receives its event: not at all, by name, or destructured. */\nexport type EventParameter =\n | { kind: \"none\" }\n | { kind: \"identifier\"; name: string; param: ParameterDeclaration }\n | {\n kind: \"binding\";\n pattern: import(\"ts-morph\").ObjectBindingPattern;\n param: ParameterDeclaration;\n }\n | { kind: \"unsupported\" };\n\nexport function inspectEventParameter(fn: LoadFunction): EventParameter {\n const params = fn.getParameters();\n if (params.length === 0) return { kind: \"none\" };\n if (params.length > 1) return { kind: \"unsupported\" };\n\n const param = params[0];\n if (param.getInitializer() || param.isRestParameter()) {\n return { kind: \"unsupported\" };\n }\n const nameNode = param.getNameNode();\n if (Node.isIdentifier(nameNode)) {\n return { kind: \"identifier\", name: nameNode.getText(), param };\n }\n if (Node.isObjectBindingPattern(nameNode)) {\n return { kind: \"binding\", pattern: nameNode, param };\n }\n return { kind: \"unsupported\" };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/** A wuchale site: the locale enable-i18n's reroute already resolved from the URL. */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"$locales/main.url\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '$lib/cms';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n // insertStatements counts comment lines, which getStatements() skips.\n const returnIndex = body.getStatementsWithComments().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"$lib/cms\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\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 { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> 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, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<AdminBar />` at the top level of the root layout, ahead of\n * `{@render children()}` so the bar is in the DOM before the page content.\n * Falls back to appending when the layout has no render tag or slot.\n */\nexport function modifyLayoutSvelte(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(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const locale = i18n ? WUCHALE_LOCALE : DEFAULT_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\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":";;;;;;;;;;;AAYA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAS,EAAY,GAAsB;CACzC,OAAO,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgB,EACd,GACA,IAAa,IACE;CACf,IAAM,IAAO,OAAO,EAAW;CAC/B,IAAI,CAAC,EAAG,WAAW,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAOxD,IAAM,IAAa,IAJC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoB,CAAc,GAEzD,IAAU,IACV,IAAS;CAMb,AAJkB,EACf,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAE1C,MACH,EAAW,wBAAwB,GAAG;EACpC,cAAc,CAAC,KAAK;EACpB,iBAAiB;CACnB,CAAC,GACD,IAAU;CAOZ,IAAM,IAJmB,EACtB,qBAAqB,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,cAE/B,CAAA,EAAkB,aAAa,CAAC,GAAG,IAC/C,IACJ,GAAW,QAAQ,MAAM,EAAW,0BAC/B,IACD;CAEN,IAAI,CAAC,GACH,IAAS;MACJ;EACL,IAAM,IAAc,EAAU,YAAY,SAAS;EACnD,IAA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IA,EAAO,KAAK,iCAAiC;CAC7C,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,YACF;CAQA,AAPA,EACE,EACE,GACA,EAAsB,CAAmB,CAC3C,CACF,GAEA,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAmB,EAAK,KAC5B,EAAQ,MACR,OACA,UACA,gBACF;CAKA,OAJA,EACE,EAAoB,GAAkB,EAAmB,CAAgB,CAAC,CAC5E,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,61 +0,0 @@
1
- import { n as e } from "./logger-CQONztPm.js";
2
- import { t } from "./generate-DQeWOEPY.js";
3
- import { n } from "./env-BPfk1VAw.js";
4
- import { _ as r, n as i, u as a } from "./ts-morph-helpers-CeduA--o.js";
5
- import { envRevertOutcomeToFile as o, modifyOutcomeToFile as s } from "./modify-file-Dwfv0dCI.js";
6
- import { t as c } from "./svelte-file-B3RfgVdt.js";
7
- import l from "node:fs";
8
- import u from "node:path";
9
- //#region src/patterns/disable/analytics/modifies/layout.svelte.ts
10
- var d = "$lib/components/analytics/analytics.svelte";
11
- function f(e) {
12
- if (!l.existsSync(e)) return {
13
- status: "success",
14
- changed: !1
15
- };
16
- let t = l.readFileSync(e, "utf8");
17
- if (!t.includes(d) && !t.includes("<Analytics")) return {
18
- status: "success",
19
- changed: !1
20
- };
21
- let n = c.fromPath(e);
22
- n.modifyScript((e) => {
23
- let { source: t } = r(e, (e) => {
24
- a(e, d), i(e);
25
- });
26
- return t;
27
- });
28
- let o = n.toString().replace(/[ \t]*<Analytics\s*\/>[ \t]*\r?\n?/g, "");
29
- return o === t ? {
30
- status: "success",
31
- changed: !1
32
- } : (l.writeFileSync(e, o, "utf8"), {
33
- status: "success",
34
- changed: !0
35
- });
36
- }
37
- //#endregion
38
- //#region src/patterns/disable/analytics/generate.runtime.ts
39
- async function p(r) {
40
- let i = e(r), a = [], c = [], l = (e) => {
41
- e && a.push(e);
42
- };
43
- i.info("Reverting src/routes/+layout.svelte");
44
- let d = u.join(r.root, "src", "routes", "+layout.svelte");
45
- l(s(d, f(d))), i.info("Removing analytics variables from .env");
46
- let p = u.join(r.root, ".env"), m = o(p, n(p, t()));
47
- return l(m.modify), m.delete && c.push(m.delete), {
48
- creates: [],
49
- modifies: a,
50
- deletes: c,
51
- components: [],
52
- packages: [],
53
- collections: [],
54
- collectionPatches: [],
55
- collectionDrops: []
56
- };
57
- }
58
- //#endregion
59
- export { p as generate };
60
-
61
- //# sourceMappingURL=generate.runtime-YyIVd4oy.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-YyIVd4oy.js","names":[],"sources":["../../src/patterns/disable/analytics/modifies/layout.svelte.ts","../../src/patterns/disable/analytics/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst MODULE_SPECIFIER = \"$lib/components/analytics/analytics.svelte\";\n\n/**\n * Takes `<Analytics />` and its import back out of the root layout. The\n * element goes with its whole line, since enable-analytics put it on one of\n * its own. A layout without it, or no layout at all, is left alone.\n */\nexport function unmodifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (\n !original.includes(MODULE_SPECIFIER) &&\n !original.includes(\"<Analytics\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, MODULE_SPECIFIER);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n const updated = file\n .toString()\n .replace(/[ \\t]*<Analytics\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyEnvRemove } from \"../../../runtime/env\";\nimport {\n envRevertOutcomeToFile,\n modifyOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport { allEnvEdits } from \"./generate\";\nimport { unmodifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\nexport async function generate(options: Options) {\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(\"Reverting src/routes/+layout.svelte\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.svelte\");\n pushResult(modifyOutcomeToFile(layoutPath, unmodifyLayoutSvelte(layoutPath)));\n\n logger.info(\"Removing analytics variables from .env\");\n const envPath = path.join(options.root, \".env\");\n const env = envRevertOutcomeToFile(\n envPath,\n modifyEnvRemove(envPath, allEnvEdits()),\n );\n pushResult(env.modify);\n if (env.delete) deletes.push(env.delete);\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":";;;;;;;;;AASA,IAAM,IAAmB;AAOzB,SAAgB,EAAqB,GAAmC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAW,EAAG,aAAa,GAAY,MAAM;CACnD,IACE,CAAC,EAAS,SAAS,CAAgB,KACnC,CAAC,EAAS,SAAS,YAAY,GAE/B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAO,EAAW,SAAS,CAAU;CAC3C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;GAEzD,AADA,EAA8B,GAAI,CAAgB,GAClD,EAA4B,CAAE;EAChC,CAAC;EACD,OAAO;CACT,CAAC;CAED,IAAM,IAAU,EACb,SAAS,CAAC,CACV,QAAQ,uCAAuC,EAAE;CAMpD,OAJI,MAAY,IACP;EAAE,QAAQ;EAAW,SAAS;CAAM,KAE7C,EAAG,cAAc,GAAY,GAAS,MAAM,GACrC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;;;ACpCA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAmB,CAAC,GACpB,IAAkB,CAAC,GACnB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAa,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAG5E,AAFA,EAAW,EAAoB,GAAY,EAAqB,CAAU,CAAC,CAAC,GAE5E,EAAO,KAAK,wCAAwC;CACpD,IAAM,IAAU,EAAK,KAAK,EAAQ,MAAM,MAAM,GACxC,IAAM,EACV,GACA,EAAgB,GAAS,EAAY,CAAC,CACxC;CAIA,OAHA,EAAW,EAAI,MAAM,GACjB,EAAI,UAAQ,EAAQ,KAAK,EAAI,MAAM,GAEhC;EACL,SAAS,CAAC;EACV;EACA;EACA,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-cQGLxuZM.js","names":[],"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,IAAM,IAAe,CAAM;;;;;;;;;;;;;;;;;;GAoBrB,IACJ,0GAEI,IAA6B,CAAM;;;;;;;;;;;;;AAczC,SAAgB,EAAoB,GAAiC;CACnE,IAAI,CAAC,EAAG,WAAW,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAW,EAAG,aAAa,GAAU,MAAM;CACjD,IAAI,EAAS,SAAS,2BAA2B,GAC/C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAI,IAAa,IACX,EAAE,cAAW,EAAmB,IAAW,MAAO;EACtD,EAAc,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,IA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AAO,KAAK,mCAAmC;CAC/C,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAWA,AAVA,EACE,EACE,GACA,EACE,GACA,EAAS,oCAAoC,CAC/C,CACF,CACF,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPA,EACE,EACE,GACA,EAAsB,CAAmB,CAC3C,CACF,GAEA,EAAO,KAAK,8BAA8B;CAC1C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE,GAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAWA,AAVA,EACE,EACE,GACA,EACE,GACA,EAAS,oCAAoC,CAC/C,CACF,CACF,GAEA,EAAO,KAAK,mCAAmC;CAC/C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVA,EACE,EACE,GACA,EACE,GACA,EAAS,0CAA0C,CACrD,CACF,CACF,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAWA,OAVA,EACE,EACE,GACA,EACE,GACA,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-n9AFWtPp.js","names":[],"sources":["../../src/patterns/disable/api-keys/modifies/hooks.server.ts","../../src/patterns/disable/api-keys/modifies/nav-user.svelte.ts","../../src/patterns/disable/api-keys/generate.runtime.ts"],"sourcesContent":["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 apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp || apiProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { status: \"success\", changed: false };\n }\n\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!apiInit || apiInit.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const apiKeysProp = apiObj.getProperty(\"apiKeys\");\n if (!apiKeysProp) {\n return { status: \"success\", changed: false };\n }\n\n apiKeysProp.remove();\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 { 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(\"/api-keys\")) {\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 \"API Keys\",\n \"@lucide/svelte/icons/key-round\",\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 path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { unmodifyNavUser } from \"./modifies/nav-user.svelte\";\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 hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerPath, unmodifyHooksServer(hooksServerPath)),\n );\n\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 const collectionDrops = await planDropsForCollections([\"api_keys\"], options);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collection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,GAC9B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAO,IAAI,EAAW,CAAM,GAC9B,IAAa,IAEX,KAAa,MAAgD;EAC7D,KACJ,GAAK,MAAQ;GACX,IAAM,IAAS,EACb,GACA,YACA,gCACF;GAEA,OADI,EAAO,eAAY,IAAa,KAC7B,EAAO;EAChB,CAAC;CACH;CAUA,OARA,GAAW,MAAO,EAAK,mBAAmB,CAAE,CAAC,GACxC,KAAY,GAAW,MAAO,EAAK,aAAa,CAAE,CAAC,GAEnD,KAIL,EAAG,cAAc,GAAa,EAAK,SAAS,GAAG,MAAM,GAC9C;EAAE,QAAQ;EAAW,SAAS;CAAK,KAJjC;EAAE,QAAQ;EAAW,SAAS;CAAM;AAK/C;;;AChCA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAmB,CAAC,GACpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAKxE,AAJA,EACE,EAAoB,GAAiB,EAAoB,CAAe,CAAC,CAC3E,GAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAKA,OAJA,EAAW,EAAoB,GAAa,EAAgB,CAAW,CAAC,CAAC,GAIlE;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAV4B,EAAwB,CAAC,UAAU,GAAG,CAAO;CAW3E;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-ofdnLtxS.js","names":[],"sources":["../../src/patterns/disable/api/modifies/hooks.server.ts","../../src/patterns/disable/api/generate.runtime.ts"],"sourcesContent":["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\n if (!callExpr) {\n return { status: \"success\", changed: false };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n return { status: \"success\", changed: false };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp) {\n return { status: \"success\", changed: false };\n }\n\n apiProp.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 type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],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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-onBnOiS7.js","names":[],"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';\n import * as Avatar from '$lib/components/ui/avatar';\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\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\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,SAAgB,EAAmB,GAAmC;CACpE,IAAI,CAAC,EAAG,WAAW,CAAU,GAAG;EAC9B,IAAM,IAAU,CAAM;;;;;EAOtB,OADA,EAAG,cAAc,GAAY,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAM,IAAiB,EAAG,aAAa,GAAY,MAAM,GAEnD,IAAa,IADC,EACD,CAAA,CAAQ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AAiB,EAAkB,CAAe,CAAC,CACzE,GAEA,EAAO,KAAK,yBAAyB;CACrC,IAAM,IAAgB,EAAK,KAAK,EAAQ,MAAM,QAAQ,UAAU;CAKhE,AAJA,EACE,EAAoB,GAAe,EAAgB,CAAa,CAAC,CACnE,GAEA,EAAO,KAAK,uCAAuC;CACnD,IAAM,IAAS,EAAyB,EAAQ,IAAI;CACpD,EAAW,EAAoB,EAAO,UAAU,EAAO,OAAO,CAAC;CAG/D,IAAM,IAAW,MAAM,EAAe,CAAO;CAE7C,OAAO;EACL,SAAS,IAAW,CAAC,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":"modify-file-Dwfv0dCI.js","names":[],"sources":["../../src/runtime/modify-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { isEffectivelyEmpty, withInMemoryScript } from \"./ts-morph-helpers\";\n\nexport function modifyOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): File | null {\n const language = languageFromPath(filePath);\n\n if (outcome.status === \"success\") {\n if (!outcome.changed) return null;\n return {\n path: filePath,\n language,\n content: fs.readFileSync(filePath, \"utf8\"),\n status: \"success\",\n };\n }\n\n const content =\n outcome.status === \"failed\" && fs.existsSync(filePath)\n ? fs.readFileSync(filePath, \"utf8\")\n : \"\";\n\n return {\n path: filePath,\n language,\n content,\n status: outcome.status,\n message: outcome.message,\n };\n}\n\n/**\n * `modifyOutcomeToFile` for a revert that may have taken out everything the\n * file held: a script left with no statements, only comments and whitespace,\n * is reported as a delete. For hooks files a pattern created, or that ended\n * up holding nothing but what patterns put there.\n */\nexport function revertOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(filePath) &&\n withInMemoryScript(fs.readFileSync(filePath, \"utf8\"), isEffectivelyEmpty)\n .result\n ) {\n return { modify: null, delete: toDeleteEntry(filePath) };\n }\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * `modifyOutcomeToFile` for a `.env` revert: a file the revert left empty is\n * reported as a delete. The enable pattern most likely created it, and an\n * empty `.env` holds nothing worth keeping.\n */\nexport function envRevertOutcomeToFile(\n envPath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(envPath) &&\n fs.readFileSync(envPath, \"utf8\").trim() === \"\"\n ) {\n return { modify: null, delete: toDeleteEntry(envPath) };\n }\n return { modify: modifyOutcomeToFile(envPath, outcome), delete: null };\n}\n\n/**\n * Drop any create that already exists on disk.\n *\n * `writeResult` overwrites an existing create whose content differs and\n * reports it as a modify, which would mean a re-run silently resetting a\n * developer's edits, or a create clobbering a file other patterns have\n * already written to. The file is theirs once it exists; a pattern that has\n * something to add to it does so with a modifier.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n"],"mappings":";;;;;;AAOA,SAAgB,EACd,GACA,GACa;CACb,IAAM,IAAW,EAAiB,CAAQ;CAiB1C,OAfI,EAAQ,WAAW,YAChB,EAAQ,UACN;EACL,MAAM;EACN;EACA,SAAS,EAAG,aAAa,GAAU,MAAM;EACzC,QAAQ;CACV,IAN6B,OAcxB;EACL,MAAM;EACN;EACA,SAPA,EAAQ,WAAW,YAAY,EAAG,WAAW,CAAQ,IACjD,EAAG,aAAa,GAAU,MAAM,IAChC;EAMJ,QAAQ,EAAQ;EAChB,SAAS,EAAQ;CACnB;AACF;AAQA,SAAgB,EACd,GACA,GAC8C;CAU9C,OARE,EAAQ,WAAW,aACnB,EAAQ,WACR,EAAG,WAAW,CAAQ,KACtB,EAAmB,EAAG,aAAa,GAAU,MAAM,GAAG,CAAkB,CAAC,CACtE,SAEI;EAAE,QAAQ;EAAM,QAAQ,EAAc,CAAQ;CAAE,IAElD;EAAE,QAAQ,EAAoB,GAAU,CAAO;EAAG,QAAQ;CAAK;AACxE;AAOA,SAAgB,EACd,GACA,GAC8C;CAS9C,OAPE,EAAQ,WAAW,aACnB,EAAQ,WACR,EAAG,WAAW,CAAO,KACrB,EAAG,aAAa,GAAS,MAAM,CAAC,CAAC,KAAK,MAAM,KAErC;EAAE,QAAQ;EAAM,QAAQ,EAAc,CAAO;CAAE,IAEjD;EAAE,QAAQ,EAAoB,GAAS,CAAO;EAAG,QAAQ;CAAK;AACvE;AAWA,SAAgB,EAAY,GAAiB,GAAsB;CACjE,OAAO,EAAQ,QAAQ,MAAS,CAAC,EAAG,WAAW,EAAK,KAAK,GAAM,EAAK,IAAI,CAAC,CAAC;AAC5E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"modify-svelte-config-remote-BUU_EaDf.js","names":[],"sources":["../../src/runtime/modify-svelte-config-remote.ts"],"sourcesContent":["import {\n ensureBooleanTrue,\n getOrCreateObjectLiteralProperty,\n modifyConfig,\n type ConfigModifyResult,\n} from \"./config-target\";\n\nconst FAILURE_HINT = [\n \"Enable SvelteKit remote functions and Svelte async in your config\",\n \"(the sveltekit() plugin arg in vite.config, or svelte.config):\",\n \"\",\n \"experimental: { remoteFunctions: true },\",\n \"compilerOptions: { experimental: { async: true } },\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Enable SvelteKit remote functions and Svelte async by passing config to the\",\n \"sveltekit() plugin in vite.config.ts:\",\n \"\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { defineConfig } from 'vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [\",\n \" sveltekit({\",\n \" experimental: { remoteFunctions: true },\",\n \" compilerOptions: { experimental: { async: true } },\",\n \" }),\",\n \" ],\",\n \"});\",\n].join(\"\\n\");\n\n/**\n * Enable SvelteKit remote functions (`experimental.remoteFunctions`) and Svelte\n * async (`compilerOptions.experimental.async`) in whichever config the project\n * uses — the inline `sveltekit()` arg in vite.config, or svelte.config.\n *\n * `remoteFunctions` is kit-namespaced (→ `kitContainer()`); `async` is a\n * root-level compiler option (→ `configObject`).\n */\nexport function modifySvelteConfigRemote(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n const kit = target.kitContainer();\n if (!kit) return false;\n const kitExperimental = getOrCreateObjectLiteralProperty(\n kit,\n \"experimental\",\n \"{}\",\n );\n if (!kitExperimental) return false;\n ensureBooleanTrue(kitExperimental, \"remoteFunctions\");\n\n const compilerObj = getOrCreateObjectLiteralProperty(\n target.configObject,\n \"compilerOptions\",\n \"{}\",\n );\n if (!compilerObj) return false;\n const compilerExperimental = getOrCreateObjectLiteralProperty(\n compilerObj,\n \"experimental\",\n \"{}\",\n );\n if (!compilerExperimental) return false;\n ensureBooleanTrue(compilerExperimental, \"async\");\n\n return true;\n },\n );\n}\n"],"mappings":";;AAOA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAUX,SAAgB,EAAyB,GAAkC;CACzE,OAAO,EACL,GACA;EAAE,UAAU;EAAgB,QAAQ;CAAa,IAChD,MAAW;EACV,IAAM,IAAM,EAAO,aAAa;EAChC,IAAI,CAAC,GAAK,OAAO;EACjB,IAAM,IAAkB,EACtB,GACA,gBACA,IACF;EACA,IAAI,CAAC,GAAiB,OAAO;EAC7B,EAAkB,GAAiB,iBAAiB;EAEpD,IAAM,IAAc,EAClB,EAAO,cACP,mBACA,IACF;EACA,IAAI,CAAC,GAAa,OAAO;EACzB,IAAM,IAAuB,EAC3B,GACA,gBACA,IACF;EAIA,OAHK,KACL,EAAkB,GAAsB,OAAO,GAExC,MAH2B;CAIpC,CACF;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\";\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';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\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';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\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-BYI-h8Od.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"nav-user-BYI-h8Od.js","names":[],"sources":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pocketbase-BkhUywtb.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAa,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CACxE;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CACxE;CAAM;CAAM;AACd,CAAC;AAED,SAAS,EAAe,GAA+B;CACrD,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAM,IAAS,EAAI,aAAa;EAGhC,AAFA,EAAO,MAAM,GACb,EAAO,KAAK,SAAS,CAAM,GAC3B,EAAO,OAAO,GAAG,SAAY;GAC3B,IAAM,EAAE,YAAS,EAAO,QAAQ;GAChC,EAAO,YAAY,EAAQ,CAAI,CAAC;EAClC,CAAC;CACH,CAAC;AACH;AAQA,eAAsB,EAAS,GAA+B;CAC5D,SAAS;EACP,IAAM,IAAO,MAAM,EAAe,CAAI;EACtC,IAAI,CAAC,EAAU,IAAI,CAAI,GAAG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EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG,EAAK,GAAG;CACb,GAEM,KAAkB,MAAM,EAAO,EAAE,OAAI,CAAC,EAAA,EAAI,QAAQ,OAClD,EAAE,YAAS,YAAS,EACxB,GACA,WACA,CACF;CAGA,AAAI,MAAmB,SAAO,EAAK,QAAQ,OAAO;CAMlD,IAAM,IAAW,QAAQ,aAAa,SAChC,IAAgB,EAAM,GAAS,GAAM;EACzC;EACA,OAAO;EACP;CACF,CAAC,GAIK,IAAS,IAAI,SAAgB,GAAG,MAAW;EAQ/C,AAPA,EAAc,KAAK,SAAS,GAAM,MAAW;GAC3C,EACE,gBAAI,MACF,gDAAgD,EAAK,GAAG,EAAK,IAAI,KAAU,QAAQ,IAAO,EAC5F,CACF;EACF,CAAC,GACD,EAAc,KAAK,SAAS,CAAM;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAM,EAAY,GAAM,CAAI,GAC5B,MAAM,EAAc,UAAU,EAAK,GAAG,GAAM;EAC9C,EAAA,CAAG,GACH,CACF,CAAC;EAED,IAAM,IAAK,IAAI,EAAW,UAAU,EAAK,GAAG,GAAM;EAMlD,AALA,MAAM,EACJ,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAM,EAAG,CAAE;CACb,UAAU;EAER,EAAgB,GAAe,CAAQ;CACzC;AACF;AAEA,SAAS,EACP,GACA,GACM;CACN,IAAI,KAAY,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAAC,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"providers-BL9vJP_9.js","names":[],"sources":["../../src/core/providers.ts"],"sourcesContent":["import type { EnvEdit } from \"../runtime/env\";\nimport { InvalidArgumentError } from \"./errors\";\nimport type { File, Options, Pattern, Provider } from \"./types\";\nimport { filesUnderPrefix } from \"./util\";\n\ntype ProviderPattern = Pick<Pattern, \"slug\" | \"providers\">;\n\n/** `analytics` for `enable-analytics`: how the capability is named to users. */\nexport function capabilityName(slug: string): string {\n return slug.replace(/^enable-/, \"\");\n}\n\n/** `--provider <id>` or `--provider=<id>`, for callers that hand flags through in argv. */\nexport function providerFromArgv(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--provider\") return argv[i + 1];\n if (arg.startsWith(\"--provider=\")) return arg.slice(\"--provider=\".length);\n }\n return undefined;\n}\n\nexport function unknownProviderMessage(\n name: string,\n raw: string,\n providers: Provider[],\n): string {\n return [\n `Unknown provider \"${raw}\" for ${name}.`,\n \"\",\n \"Available providers:\",\n ...providers.map((provider) => ` ${provider.id}`),\n ].join(\"\\n\");\n}\n\nexport function providerChoices(providers: Provider[]): string {\n return `--provider <${providers.map((provider) => provider.id).join(\"|\")}>`;\n}\n\n/**\n * The provider a generate call should produce, from `input.provider` or\n * `--provider` in argv.\n *\n * An unknown id is rejected with the list of known ones. With no provider at\n * all, a runtime call is rejected too: the CLI always supplies one, so this\n * is a caller bug. A preview call falls back to the first declared provider,\n * because the website loads patterns with argv only.\n */\nexport function resolveProvider(\n pattern: ProviderPattern,\n options: Pick<Options, \"input\" | \"argv\" | \"env\">,\n): Provider {\n const providers = pattern.providers ?? [];\n const name = capabilityName(pattern.slug);\n if (providers.length === 0) {\n throw new Error(`${pattern.slug} declares no providers.`);\n }\n\n const raw =\n typeof options.input.provider === \"string\"\n ? options.input.provider\n : providerFromArgv(options.argv);\n\n if (raw === undefined || raw === \"\") {\n if (options.env === \"preview\") return providers[0];\n throw new InvalidArgumentError(\n `Choose a provider for ${name}: ${providerChoices(providers)}`,\n );\n }\n\n const provider = providers.find((candidate) => candidate.id === raw);\n if (!provider) {\n throw new InvalidArgumentError(\n unknownProviderMessage(name, raw, providers),\n );\n }\n return provider;\n}\n\n/**\n * The `.env` lines for a provider: `# heading`, then one `KEY=value` per\n * declared env var. `supplied` holds what the CLI collected; a blank value\n * falls back to the provider's default, else an empty assignment the\n * developer fills in later. Prompt placeholders are never written.\n */\nexport function providerEnvEdits(\n provider: Provider,\n heading: string,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return [\n { type: \"comment\", key: heading },\n ...(provider.env ?? []).map((variable): EnvEdit => ({\n type: \"var\",\n key: variable.key,\n value: supplied[variable.key]?.trim() || variable.default || \"\",\n })),\n ];\n}\n\n/** The string values of `input.providerEnv`, as the CLI collected them. */\nexport function suppliedProviderEnv(\n options: Pick<Options, \"input\">,\n): Record<string, string> {\n const raw = options.input.providerEnv;\n if (!raw || typeof raw !== \"object\") return {};\n const values: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw)) {\n if (typeof value === \"string\") values[key] = value;\n }\n return values;\n}\n\n/**\n * Every app-relative path any provider creates, sorted, for a disable pattern\n * that removes the files whichever provider was chosen. Works on a glob taken\n * from anywhere (`../../enable/<x>/providers/**`): only the part after\n * `providers/<id>/` counts.\n */\nexport function allProviderPaths(\n providersRaw: Record<string, string>,\n): string[] {\n const paths = new Set<string>();\n for (const key of Object.keys(providersRaw)) {\n const match = key.match(/\\/providers\\/[^/]+\\/(.+)$/);\n if (match) paths.add(match[1]);\n }\n return [...paths].sort();\n}\n\n/**\n * The files under `providers/<id>/**` of a pattern, as creates. The glob map\n * is one `import.meta.glob(\"./providers/**\")` covering every provider.\n */\nexport function providerCreates(\n providersRaw: Record<string, string>,\n id: string,\n): File[] {\n const files = filesUnderPrefix(providersRaw, `./providers/${id}/`);\n return Object.values(files).sort((a, b) => a.path.localeCompare(b.path));\n}\n"],"mappings":";;;AAQA,SAAgB,EAAe,GAAsB;CACnD,OAAO,EAAK,QAAQ,YAAY,EAAE;AACpC;AAGA,SAAgB,EAAiB,GAAoC;CACnE,KAAK,IAAI,IAAI,GAAG,IAAI,EAAK,QAAQ,KAAK;EACpC,IAAM,IAAM,EAAK;EACjB,IAAI,MAAQ,cAAc,OAAO,EAAK,IAAI;EAC1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1B,IAAI,CAAC,KAAO,OAAO,KAAQ,UAAU,OAAO,CAAC;CAC7C,IAAM,IAAiC,CAAC;CACxC,KAAK,IAAM,CAAC,GAAK,MAAU,OAAO,QAAQ,CAAG,GAC3C,AAAI,OAAO,KAAU,aAAU,EAAO,KAAO;CAE/C,OAAO;AACT;AAQA,SAAgB,EACd,GACU;CACV,IAAM,oBAAQ,IAAI,IAAY;CAC9B,KAAK,IAAM,KAAO,OAAO,KAAK,CAAY,GAAG;EAC3C,IAAM,IAAQ,EAAI,MAAM,2BAA2B;EACnD,AAAI,KAAO,EAAM,IAAI,EAAM,EAAE;CAC/B;CACA,OAAO,CAAC,GAAG,CAAK,CAAC,CAAC,KAAK;AACzB;AAMA,SAAgB,EACd,GACA,GACQ;CACR,IAAM,IAAQ,EAAiB,GAAc,eAAe,EAAG,EAAE;CACjE,OAAO,OAAO,OAAO,CAAK,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AACzE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"shared-C8GtNxpm.js","names":[],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgB,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAU,EAAiB,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsB,EACpB,GACA,GAC+B;CAC/B,IAAI,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAI,EAAQ,QAAQ,WAClB,OAAO,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,2BAAA,CAAA,MAAA,MAAA,EAAA,CAAA,GAClC,EAAE,2BAAwB,MAAM,OAAO,8BACvC,IAA8B,CAAC;CAKrC,OAJA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAM,IAAQ,MAAM,EAAoB,GAAI,CAAe;EAC3D,EAAM,KAAK,GAAG,CAAK;CACrB,CAAC,GACM;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"site-BdMX8qrH.js","names":[],"sources":["../../src/runtime/site.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options } from \"../core/types\";\nimport { getLogger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { withPocketbase } from \"./pocketbase\";\n\n/** Where every VelaStack app keeps its name and public URL. */\nexport function sitePath(root: string): string {\n return path.join(root, \"src\", \"lib\", \"site.ts\");\n}\n\n/**\n * `src/lib/site.ts` as the CLI templates ship it (`site.template.ts`), with\n * the placeholders filled in.\n */\nexport function siteModule(\n name: string,\n url = \"http://localhost:5173\",\n): string {\n return [\n \"/**\",\n \" * Site-wide metadata, and the one place the app's name and public URL live.\",\n \" *\",\n \" * Set `url` to where the site is deployed: canonical links, Open Graph images\",\n \" * and feeds are built from it, including in prerendered pages. With a backend,\",\n \" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name\",\n \" * for the emails it sends, so change it here rather than in the admin panel.\",\n \" */\",\n \"export const site = {\",\n `\\tname: ${quote(name)},`,\n `\\turl: ${quote(url)}`,\n \"};\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Single-quoted, as the templates write their strings. */\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/**\n * The name a project created before `site.ts` existed already goes by.\n *\n * Those projects kept it in PocketBase's settings, so that is asked first; the\n * package name is the fallback for a project without a backend, or one whose\n * database can't be reached.\n */\nasync function existingName(options: Options): Promise<string> {\n if (options.features.backend) {\n try {\n let appName: unknown;\n await withPocketbase(options.root, async (pb) => {\n const settings = (await pb.settings.getAll()) as {\n meta?: { appName?: unknown };\n };\n appName = settings.meta?.appName;\n });\n if (typeof appName === \"string\" && appName.trim()) return appName;\n } catch {\n // No database to ask; fall through to package.json.\n }\n }\n\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(options.root, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name;\n } catch {\n // No package.json to name the site after; the placeholder stands.\n }\n return \"My App\";\n}\n\n/**\n * Create `src/lib/site.ts` for a pattern whose files import `$lib/site`, when\n * the project doesn't have one yet. Every template ships it; projects created\n * before that read the app name from `locals.meta` instead.\n *\n * Returns null when the file exists, so an existing one is never overwritten.\n */\nexport async function ensureSiteFile(options: Options): Promise<File | null> {\n const file = sitePath(options.root);\n if (fs.existsSync(file)) return null;\n\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options)),\n status: \"success\",\n };\n}\n"],"mappings":";;;;;;AAQA,SAAgB,EAAS,GAAsB;CAC7C,OAAO,EAAK,KAAK,GAAM,OAAO,OAAO,SAAS;AAChD;AAMA,SAAgB,EACd,GACA,IAAM,yBACE;CACR,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,EAAM,CAAI,EAAE;EACvB,UAAU,EAAM,CAAG;EACnB;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAGA,SAAS,EAAM,GAAuB;CACpC,OAAO,IAAI,EAAM,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,KAAK,EAAE;AAC/D;AASA,eAAe,EAAa,GAAmC;CAC7D,IAAI,EAAQ,SAAS,SACnB,IAAI;EACF,IAAI;EAOJ,IANA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;GAI/C,KAAU,MAHc,EAAG,SAAS,OAAO,EAAA,CAGxB,MAAM;EAC3B,CAAC,GACG,OAAO,KAAY,YAAY,EAAQ,KAAK,GAAG,OAAO;CAC5D,QAAQ,CAER;CAGF,IAAI;EACF,IAAM,IAAM,KAAK,MACf,EAAG,aAAa,EAAK,KAAK,EAAQ,MAAM,cAAc,GAAG,MAAM,CACjE;EACA,IAAI,OAAO,EAAI,QAAS,YAAY,EAAI,KAAK,KAAK,GAAG,OAAO,EAAI;CAClE,QAAQ,CAER;CACA,OAAO;AACT;AASA,eAAsB,EAAe,GAAwC;CAC3E,IAAM,IAAO,EAAS,EAAQ,IAAI;CAIlC,OAHI,EAAG,WAAW,CAAI,IAAU,QAEhC,EAAU,CAAO,CAAC,CAAC,KAAK,0BAA0B,GAC3C;EACL,MAAM;EACN,UAAU,EAAiB,CAAI;EAC/B,SAAS,EAAW,MAAM,EAAa,CAAO,CAAC;EAC/C,QAAQ;CACV;AACF"}