@velastack/patterns 0.4.2 → 0.5.0

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 (130) hide show
  1. package/README.md +22 -2
  2. package/dist/chunks/{_page-e_I-fdSR.js → _page-DoPdZgZv.js} +2 -2
  3. package/dist/chunks/_page-DoPdZgZv.js.map +1 -0
  4. package/dist/chunks/collections-Cpjo2OiQ.js +203 -0
  5. package/dist/chunks/collections-Cpjo2OiQ.js.map +1 -0
  6. package/dist/chunks/dispatch-BIvOwbKN.js +6 -0
  7. package/dist/chunks/dispatch-BIvOwbKN.js.map +1 -0
  8. package/dist/chunks/{env-vars-CcE6ODqC.js → env-vars-Bj41Nccm.js} +32 -20
  9. package/dist/chunks/env-vars-Bj41Nccm.js.map +1 -0
  10. package/dist/chunks/generate-BClgUH4J.js +137 -0
  11. package/dist/chunks/generate-BClgUH4J.js.map +1 -0
  12. package/dist/chunks/{generate-CZGHByV3.js → generate-DjBMRzsB.js} +6 -6
  13. package/dist/chunks/{generate-CZGHByV3.js.map → generate-DjBMRzsB.js.map} +1 -1
  14. package/dist/chunks/{generate-DetW_gbr.js → generate-DyV5R8NP.js} +7 -7
  15. package/dist/chunks/{generate-DetW_gbr.js.map → generate-DyV5R8NP.js.map} +1 -1
  16. package/dist/chunks/generate-ZIOVLH6Q.js +72 -0
  17. package/dist/chunks/generate-ZIOVLH6Q.js.map +1 -0
  18. package/dist/chunks/{generate-Bg0E3eWm.js → generate-dNlBII84.js} +4 -4
  19. package/dist/chunks/{generate-Bg0E3eWm.js.map → generate-dNlBII84.js.map} +1 -1
  20. package/dist/chunks/{generate-CFqpRi9D.js → generate-yi8AP3xH.js} +4 -4
  21. package/dist/chunks/{generate-CFqpRi9D.js.map → generate-yi8AP3xH.js.map} +1 -1
  22. package/dist/chunks/{generate.runtime-CpMKXBkn.js → generate.runtime-B4QoBn5v.js} +6 -6
  23. package/dist/chunks/{generate.runtime-CpMKXBkn.js.map → generate.runtime-B4QoBn5v.js.map} +1 -1
  24. package/dist/chunks/{generate.runtime-aQnBmH8D.js → generate.runtime-BKINIJ2c.js} +3 -3
  25. package/dist/chunks/{generate.runtime-aQnBmH8D.js.map → generate.runtime-BKINIJ2c.js.map} +1 -1
  26. package/dist/chunks/{generate.runtime-Dl6OQ7pe.js → generate.runtime-BKTkVCEm.js} +4 -4
  27. package/dist/chunks/{generate.runtime-Dl6OQ7pe.js.map → generate.runtime-BKTkVCEm.js.map} +1 -1
  28. package/dist/chunks/{generate.runtime-CAn1qIQ_.js → generate.runtime-BXZDKLbA.js} +3 -3
  29. package/dist/chunks/{generate.runtime-CAn1qIQ_.js.map → generate.runtime-BXZDKLbA.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-hTKzxH2M.js → generate.runtime-BYfyZHhs.js} +7 -7
  31. package/dist/chunks/{generate.runtime-hTKzxH2M.js.map → generate.runtime-BYfyZHhs.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-DoZJHtZh.js → generate.runtime-BavEh01F.js} +6 -6
  33. package/dist/chunks/{generate.runtime-DoZJHtZh.js.map → generate.runtime-BavEh01F.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-DJ9MVVPC.js → generate.runtime-BcgjZJug.js} +123 -110
  35. package/dist/chunks/generate.runtime-BcgjZJug.js.map +1 -0
  36. package/dist/chunks/generate.runtime-BdHv7Jp1.js +82 -0
  37. package/dist/chunks/generate.runtime-BdHv7Jp1.js.map +1 -0
  38. package/dist/chunks/{generate.runtime-CqncBFNg.js → generate.runtime-BdmoAVJK.js} +4 -4
  39. package/dist/chunks/{generate.runtime-CqncBFNg.js.map → generate.runtime-BdmoAVJK.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-BpMN5Uq-.js → generate.runtime-Bdpu4rX0.js} +3 -3
  41. package/dist/chunks/{generate.runtime-BpMN5Uq-.js.map → generate.runtime-Bdpu4rX0.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-uLUiPgqx.js → generate.runtime-C7s1Mx5L.js} +6 -6
  43. package/dist/chunks/{generate.runtime-uLUiPgqx.js.map → generate.runtime-C7s1Mx5L.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-CEqLgLT9.js → generate.runtime-CCV4O6_I.js} +3 -3
  45. package/dist/chunks/{generate.runtime-CEqLgLT9.js.map → generate.runtime-CCV4O6_I.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-CK10Mum5.js → generate.runtime-CSUnP0l-.js} +10 -10
  47. package/dist/chunks/{generate.runtime-CK10Mum5.js.map → generate.runtime-CSUnP0l-.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-koQxLywh.js → generate.runtime-CV4soy2n.js} +6 -6
  49. package/dist/chunks/{generate.runtime-koQxLywh.js.map → generate.runtime-CV4soy2n.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-Db0HZyj3.js → generate.runtime-CWgZhxQt.js} +2 -2
  51. package/dist/chunks/{generate.runtime-Db0HZyj3.js.map → generate.runtime-CWgZhxQt.js.map} +1 -1
  52. package/dist/chunks/{generate.runtime-IWEhGhWY.js → generate.runtime-CcPCAEV0.js} +6 -6
  53. package/dist/chunks/{generate.runtime-IWEhGhWY.js.map → generate.runtime-CcPCAEV0.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-DG2z6kqH.js → generate.runtime-D-qtaVdq.js} +3 -3
  55. package/dist/chunks/{generate.runtime-DG2z6kqH.js.map → generate.runtime-D-qtaVdq.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-E-zoeSKW.js → generate.runtime-DBBtYTAa.js} +7 -7
  57. package/dist/chunks/{generate.runtime-E-zoeSKW.js.map → generate.runtime-DBBtYTAa.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-5rIc-RNL.js → generate.runtime-DRRyPa-e.js} +6 -6
  59. package/dist/chunks/{generate.runtime-5rIc-RNL.js.map → generate.runtime-DRRyPa-e.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-BK3mR0Rj.js → generate.runtime-DaRVyiSg.js} +148 -127
  61. package/dist/chunks/generate.runtime-DaRVyiSg.js.map +1 -0
  62. package/dist/chunks/{generate.runtime-DVB7uuht.js → generate.runtime-DetYynf4.js} +3 -3
  63. package/dist/chunks/{generate.runtime-DVB7uuht.js.map → generate.runtime-DetYynf4.js.map} +1 -1
  64. package/dist/chunks/{generate.runtime-a3R4hqFy.js → generate.runtime-DjCzW3zU.js} +12 -12
  65. package/dist/chunks/{generate.runtime-a3R4hqFy.js.map → generate.runtime-DjCzW3zU.js.map} +1 -1
  66. package/dist/chunks/{generate.runtime-Djas9UNy.js → generate.runtime-DlbG-8Xm.js} +4 -4
  67. package/dist/chunks/{generate.runtime-Djas9UNy.js.map → generate.runtime-DlbG-8Xm.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-CbE9RHcf.js → generate.runtime-DmsOEsJV.js} +5 -5
  69. package/dist/chunks/generate.runtime-DmsOEsJV.js.map +1 -0
  70. package/dist/chunks/{generate.runtime-axm9wcQv.js → generate.runtime-MjWwR2Bd.js} +3 -3
  71. package/dist/chunks/{generate.runtime-axm9wcQv.js.map → generate.runtime-MjWwR2Bd.js.map} +1 -1
  72. package/dist/chunks/generate.runtime-NaSIZlP5.js +48 -0
  73. package/dist/chunks/generate.runtime-NaSIZlP5.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-CZ46nkSL.js → generate.runtime-OEgsdWRP.js} +2 -2
  75. package/dist/chunks/{generate.runtime-CZ46nkSL.js.map → generate.runtime-OEgsdWRP.js.map} +1 -1
  76. package/dist/chunks/{generate.runtime-rs1ZOIET.js → generate.runtime-QbmCPT42.js} +3 -3
  77. package/dist/chunks/{generate.runtime-rs1ZOIET.js.map → generate.runtime-QbmCPT42.js.map} +1 -1
  78. package/dist/chunks/generate.runtime-azOvp6tl.js +106 -0
  79. package/dist/chunks/generate.runtime-azOvp6tl.js.map +1 -0
  80. package/dist/chunks/{generate.runtime-kciwaXxh.js → generate.runtime-b2RtuPy4.js} +4 -4
  81. package/dist/chunks/{generate.runtime-kciwaXxh.js.map → generate.runtime-b2RtuPy4.js.map} +1 -1
  82. package/dist/chunks/{generate.runtime-Dp7SsCQG.js → generate.runtime-pMpn0Pbf.js} +3 -3
  83. package/dist/chunks/{generate.runtime-Dp7SsCQG.js.map → generate.runtime-pMpn0Pbf.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-DHHlYfTD.js → generate.runtime-utFLS6Jz.js} +3 -3
  85. package/dist/chunks/{generate.runtime-DHHlYfTD.js.map → generate.runtime-utFLS6Jz.js.map} +1 -1
  86. package/dist/chunks/modify-file-Bbhyfiy_.js +53 -0
  87. package/dist/chunks/modify-file-Bbhyfiy_.js.map +1 -0
  88. package/dist/chunks/{modify-nav-user-BLyrW2sK.js → modify-nav-user-B8h8WTrM.js} +2 -2
  89. package/dist/chunks/{modify-nav-user-BLyrW2sK.js.map → modify-nav-user-B8h8WTrM.js.map} +1 -1
  90. package/dist/chunks/providers-CL9kQ4hp.js +98 -0
  91. package/dist/chunks/providers-CL9kQ4hp.js.map +1 -0
  92. package/dist/chunks/providers-DwbwccSW.js +38 -0
  93. package/dist/chunks/providers-DwbwccSW.js.map +1 -0
  94. package/dist/chunks/{shared-Cc_ns5-y.js → shared-D5GOS97l.js} +2 -2
  95. package/dist/chunks/{shared-Cc_ns5-y.js.map → shared-D5GOS97l.js.map} +1 -1
  96. package/dist/chunks/shopify-page-D-VFwGxI.js +11 -0
  97. package/dist/chunks/shopify-page-D-VFwGxI.js.map +1 -0
  98. package/dist/chunks/stripe-customer-B3tP8gtD.js +6 -0
  99. package/dist/chunks/stripe-customer-B3tP8gtD.js.map +1 -0
  100. package/dist/chunks/{svelte-file-B3RfgVdt.js → svelte-file-Dv5-bl79.js} +37 -2
  101. package/dist/chunks/svelte-file-Dv5-bl79.js.map +1 -0
  102. package/dist/chunks/{test-setup-B9fQ5L_-.js → test-setup-DZoyF8Ak.js} +2 -2
  103. package/dist/chunks/{test-setup-B9fQ5L_-.js.map → test-setup-DZoyF8Ak.js.map} +1 -1
  104. package/dist/chunks/{ui-CuCsupFq.js → ui-BuocThuh.js} +2 -2
  105. package/dist/chunks/{ui-CuCsupFq.js.map → ui-BuocThuh.js.map} +1 -1
  106. package/dist/chunks/{write-result-DiZsCS_y.js → write-result-Cq-9A7Zy.js} +2 -2
  107. package/dist/chunks/write-result-Cq-9A7Zy.js.map +1 -0
  108. package/dist/index.d.ts +284 -22
  109. package/dist/index.js +2199 -2035
  110. package/dist/index.js.map +1 -1
  111. package/package.json +1 -1
  112. package/dist/chunks/_page-e_I-fdSR.js.map +0 -1
  113. package/dist/chunks/collections-zzZ_HQxB.js +0 -192
  114. package/dist/chunks/collections-zzZ_HQxB.js.map +0 -1
  115. package/dist/chunks/dispatch-D4TN9pdW.js +0 -6
  116. package/dist/chunks/dispatch-D4TN9pdW.js.map +0 -1
  117. package/dist/chunks/env-vars-CcE6ODqC.js.map +0 -1
  118. package/dist/chunks/env-vars-De0Xs0L2.js +0 -20
  119. package/dist/chunks/env-vars-De0Xs0L2.js.map +0 -1
  120. package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +0 -1
  121. package/dist/chunks/generate.runtime-CbE9RHcf.js.map +0 -1
  122. package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +0 -1
  123. package/dist/chunks/generate.runtime-EQnytCFL.js +0 -122
  124. package/dist/chunks/generate.runtime-EQnytCFL.js.map +0 -1
  125. package/dist/chunks/modify-file-DK-tCH9k.js +0 -46
  126. package/dist/chunks/modify-file-DK-tCH9k.js.map +0 -1
  127. package/dist/chunks/providers-BHR6-XZ7.js +0 -76
  128. package/dist/chunks/providers-BHR6-XZ7.js.map +0 -1
  129. package/dist/chunks/svelte-file-B3RfgVdt.js.map +0 -1
  130. package/dist/chunks/write-result-DiZsCS_y.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CqncBFNg.js","names":["libModule","getLogger","planDropsForCollections","withInMemoryScript","ensureBlankLineAfterImports","removeImportByModuleSpecifier","SvelteFile","removeFromLoad","fs","path","unmodifyAppLayout","layoutPath","original","file","out","source","sf","updated","unmodifyLayoutServer","layoutServerPath","generate","logger","options","modifies","pushResult","appLayoutPath","modifyOutcomeToFile","appLayoutServerPath"],"sources":["../../src/patterns/disable/notifications/modifies/modify-app-layout.ts","../../src/patterns/disable/notifications/modifies/+layout.server.ts","../../src/patterns/disable/notifications/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\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\n/** Take the bell (and the wrapper enable-notifications put it in) out of the header. */\nexport function unmodifyAppLayout(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 (!original.includes(\"NotificationsBell\")) {\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(\n sf,\n libModule(\"components/notifications-bell.svelte\"),\n );\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n let updated = file.toString();\n updated = updated.replace(\n /\\n*[ \\t]*<div class=\"ml-auto px-4\">\\s*<NotificationsBell\\s*\\/>\\s*<\\/div>[ \\t]*/g,\n \"\",\n );\n updated = updated.replace(/[ \\t]*<NotificationsBell\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n","import type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\n\n/** Take the unread-notifications query back out of the (app) layout's load. */\nexport function unmodifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n return removeFromLoad(layoutServerPath, {\n variables: [\"notificationsList\", \"notifications\"],\n dependsKeys: [\"app:notifications\"],\n returnProps: [\"notifications\"],\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 { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\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 (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, unmodifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Reverting (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 unmodifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n // The timeAgo helper enable-notifications added to #lib/utils.js stays: it is\n // generic, and other code may have started using it.\n\n const collectionDrops = await planDropsForCollections(\n [\"notifications\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgBU,EAAkB,GAAmC;CACnE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWJ,EAAG,aAAaG,GAAY,MAAM;CACnD,IAAI,CAACC,EAAS,SAAS,mBAAmB,GACxC,OA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MAb4BzB,EAC5B,CAAC,eAAe,GAChBoB,CACF;CAWA;AACF"}
1
+ {"version":3,"file":"generate.runtime-BdmoAVJK.js","names":["libModule","getLogger","planDropsForCollections","withInMemoryScript","ensureBlankLineAfterImports","removeImportByModuleSpecifier","modifyOutcomeToFile","SvelteFile","removeFromLoad","fs","path","unmodifyAppLayout","layoutPath","original","file","out","source","sf","updated","unmodifyLayoutServer","layoutServerPath","generate","logger","options","modifies","pushResult","appLayoutPath","appLayoutServerPath"],"sources":["../../src/patterns/disable/notifications/modifies/modify-app-layout.ts","../../src/patterns/disable/notifications/modifies/+layout.server.ts","../../src/patterns/disable/notifications/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\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\n/** Take the bell (and the wrapper enable-notifications put it in) out of the header. */\nexport function unmodifyAppLayout(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 (!original.includes(\"NotificationsBell\")) {\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(\n sf,\n libModule(\"components/notifications-bell.svelte\"),\n );\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n let updated = file.toString();\n updated = updated.replace(\n /\\n*[ \\t]*<div class=\"ml-auto px-4\">\\s*<NotificationsBell\\s*\\/>\\s*<\\/div>[ \\t]*/g,\n \"\",\n );\n updated = updated.replace(/[ \\t]*<NotificationsBell\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n","import type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\n\n/** Take the unread-notifications query back out of the (app) layout's load. */\nexport function unmodifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n return removeFromLoad(layoutServerPath, {\n variables: [\"notificationsList\", \"notifications\"],\n dependsKeys: [\"app:notifications\"],\n returnProps: [\"notifications\"],\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 { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\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 (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, unmodifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Reverting (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 unmodifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n // The timeAgo helper enable-notifications added to #lib/utils.js stays: it is\n // generic, and other code may have started using it.\n\n const collectionDrops = await planDropsForCollections(\n [\"notifications\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgBW,EAAkB,GAAmC;CACnE,IAAI,CAAC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EACEqB,GACAR,EAAqBQ,CAAmB,CAC1C,CACF,GAUO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BzB,EAC5B,CAAC,eAAe,GAChBqB,CACF;CAWA;AACF"}
@@ -1,8 +1,8 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
3
  import { o as n, t as r } from "./ts-morph-helpers-Bepc-Es2.js";
4
- import { modifyOutcomeToFile as i } from "./modify-file-DK-tCH9k.js";
5
- import { t as a } from "./svelte-file-B3RfgVdt.js";
4
+ import { r as i } from "./modify-file-Bbhyfiy_.js";
5
+ import { t as a } from "./svelte-file-Dv5-bl79.js";
6
6
  import { t as o } from "./modify-utils-Cw-on_cL.js";
7
7
  import s from "node:fs";
8
8
  import c from "node:path";
@@ -160,4 +160,4 @@ async function y(e) {
160
160
  //#endregion
161
161
  export { y as generate };
162
162
 
163
- //# sourceMappingURL=generate.runtime-BpMN5Uq-.js.map
163
+ //# sourceMappingURL=generate.runtime-Bdpu4rX0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-BpMN5Uq-.js","names":["FAILURE_HINT","NOT_FOUND_HINT","dedent","getLogger","formatLikeSource","addNavItemToScript","SvelteFile","modifyUtils","fs","path","FAILURE_HINT$1","NOT_FOUND_HINT$1","modifyHooksServer","hooksServerPath","originalSource","sourceFile","Project","callExpr","SyntaxKind","ce","args","firstArg","optionsObj","apiProp","apiInit","apiObj","apiKeysProp","keysInit","keysObj","API_KEYS_NAV_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","addItemToNavUser","file","navUserSnippet","wasAdded","tryAdd","run","result","source","title","url","icon","iconImportPath","fn","modifyNavUser","navUserPath","newNavUserSnippet","generate","logger","options","modifies","pushResult","modifyOutcomeToFile","utilsPath"],"sources":["../../src/patterns/enable/api-keys/modifies/hooks.server.ts","../../src/patterns/enable/api-keys/modifies/nav-user.svelte.ts","../../src/patterns/enable/api-keys/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\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with API keys in hooks.server.ts:\n\n handlePocketbase({\n api: {\n enabled: true,\n apiKeys: { enabled: true },\n },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from 'velastack/handle';\n\n export const handle = handlePocketbase({\n api: {\n enabled: true,\n apiKeys: { enabled: true },\n },\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 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(\n `{ api: { enabled: true, apiKeys: { enabled: true } } }`,\n );\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(\n 0,\n `{ api: { enabled: true, apiKeys: { enabled: true } } }`,\n );\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp) {\n optionsObj.addPropertyAssignment({\n name: \"api\",\n initializer: `{ enabled: true, apiKeys: { enabled: true } }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n if (apiProp.getKind() === SyntaxKind.PropertyAssignment) {\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (apiInit && apiInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const enabledProp = apiObj.getProperty(\"enabled\");\n if (!enabledProp) {\n apiObj.addPropertyAssignment({ name: \"enabled\", initializer: \"true\" });\n }\n\n const apiKeysProp = apiObj.getProperty(\"apiKeys\");\n if (!apiKeysProp) {\n apiObj.addPropertyAssignment({\n name: \"apiKeys\",\n initializer: `{ enabled: true }`,\n });\n } else if (apiKeysProp.getKind() === SyntaxKind.PropertyAssignment) {\n const keysInit = (\n apiKeysProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (\n keysInit &&\n keysInit.getKind() === SyntaxKind.ObjectLiteralExpression\n ) {\n const keysObj =\n keysInit as import(\"ts-morph\").ObjectLiteralExpression;\n const keysEnabled = keysObj.getProperty(\"enabled\");\n if (!keysEnabled) {\n keysObj.addPropertyAssignment({\n name: \"enabled\",\n initializer: \"true\",\n });\n }\n } else {\n (apiKeysProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `{ enabled: true }`,\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 { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst API_KEYS_NAV_SNIPPET = [\n \"import KeyRoundIcon from '@lucide/svelte/icons/key-round';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'API Keys', url: '/api-keys', icon: KeyRoundIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add an API Keys nav item to nav-user.svelte:\",\n \"\",\n API_KEYS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with an API Keys entry:\",\n \"\",\n API_KEYS_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/api-keys\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"API Keys\",\n \"/api-keys\",\n \"KeyRoundIcon\",\n \"@lucide/svelte/icons/key-round\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyNavUser } from \"./modifies/nav-user.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerPath, modifyHooksServer(hooksServerPath)),\n );\n\n logger.info(\"Modifying nav-user\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying 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":";;;;;;;;;;AAMA,IAAMA,IAAe,CAAM;;;;;;;;;GAWrBC,IAAiB,CAAM;;;;;;;;;;;;AAa7B,SAAgBW,EAAkB,GAAwC;CACxE,IAAI,CAACJ,EAAG,WAAWK,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAa,SAASZ;CAAe;CAGxD,IAAMa,IAAiBN,EAAG,aAAaK,GAAiB,MAAM,GAExDE,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBH,CAAe,GAExDI,IAAWF,EACd,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,kBAAkB;CAEnE,IAAI,CAACF,GACH,OAAO;EAAE,QAAQ;EAAU,SAASjB;CAAa;CAGnD,IAAMoB,IAAOH,EAAS,aAA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pBC,KAAc,MAAsB;EACxC,AAAInB,KAAMkB,EAAS,KAAKlB,CAAI;CAC9B;CAEA,EAAO,KAAK,2BAA2B;CACvC,IAAMpB,IAAkBJ,EAAK,KAAKyC,EAAQ,MAAM,OAAO,iBAAiB;CAKxE,AAJAE,EACEC,EAAoBxC,GAAiBD,EAAkBC,CAAe,CAAC,CACzE,GAEAoC,EAAO,KAAK,oBAAoB;CAChC,IAAMH,IAAcrC,EAAK,KACvByC,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAWC,EAAoBP,GAAaD,EAAcC,CAAW,CAAC,CAAC,GAEvEG,EAAO,KAAK,oBAAoB;CAChC,IAAMK,IAAY7C,EAAK,KAAKyC,EAAQ,MAAM,OAAO,OAAO,UAAU;CAGlE,OAFAE,EAAWC,EAAoBC,GAAW/C,EAAY+C,CAAS,CAAC,CAAC,GAE1D;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-Bdpu4rX0.js","names":["FAILURE_HINT","NOT_FOUND_HINT","dedent","getLogger","formatLikeSource","addNavItemToScript","modifyOutcomeToFile","SvelteFile","modifyUtils","fs","path","FAILURE_HINT$1","NOT_FOUND_HINT$1","modifyHooksServer","hooksServerPath","originalSource","sourceFile","Project","callExpr","SyntaxKind","ce","args","firstArg","optionsObj","apiProp","apiInit","apiObj","apiKeysProp","keysInit","keysObj","API_KEYS_NAV_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","addItemToNavUser","file","navUserSnippet","wasAdded","tryAdd","run","result","source","title","url","icon","iconImportPath","fn","modifyNavUser","navUserPath","newNavUserSnippet","generate","logger","options","modifies","pushResult","utilsPath"],"sources":["../../src/patterns/enable/api-keys/modifies/hooks.server.ts","../../src/patterns/enable/api-keys/modifies/nav-user.svelte.ts","../../src/patterns/enable/api-keys/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\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with API keys in hooks.server.ts:\n\n handlePocketbase({\n api: {\n enabled: true,\n apiKeys: { enabled: true },\n },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from 'velastack/handle';\n\n export const handle = handlePocketbase({\n api: {\n enabled: true,\n apiKeys: { enabled: true },\n },\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 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(\n `{ api: { enabled: true, apiKeys: { enabled: true } } }`,\n );\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(\n 0,\n `{ api: { enabled: true, apiKeys: { enabled: true } } }`,\n );\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp) {\n optionsObj.addPropertyAssignment({\n name: \"api\",\n initializer: `{ enabled: true, apiKeys: { enabled: true } }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n if (apiProp.getKind() === SyntaxKind.PropertyAssignment) {\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (apiInit && apiInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const enabledProp = apiObj.getProperty(\"enabled\");\n if (!enabledProp) {\n apiObj.addPropertyAssignment({ name: \"enabled\", initializer: \"true\" });\n }\n\n const apiKeysProp = apiObj.getProperty(\"apiKeys\");\n if (!apiKeysProp) {\n apiObj.addPropertyAssignment({\n name: \"apiKeys\",\n initializer: `{ enabled: true }`,\n });\n } else if (apiKeysProp.getKind() === SyntaxKind.PropertyAssignment) {\n const keysInit = (\n apiKeysProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (\n keysInit &&\n keysInit.getKind() === SyntaxKind.ObjectLiteralExpression\n ) {\n const keysObj =\n keysInit as import(\"ts-morph\").ObjectLiteralExpression;\n const keysEnabled = keysObj.getProperty(\"enabled\");\n if (!keysEnabled) {\n keysObj.addPropertyAssignment({\n name: \"enabled\",\n initializer: \"true\",\n });\n }\n } else {\n (apiKeysProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `{ enabled: true }`,\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 { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst API_KEYS_NAV_SNIPPET = [\n \"import KeyRoundIcon from '@lucide/svelte/icons/key-round';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'API Keys', url: '/api-keys', icon: KeyRoundIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add an API Keys nav item to nav-user.svelte:\",\n \"\",\n API_KEYS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with an API Keys entry:\",\n \"\",\n API_KEYS_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/api-keys\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"API Keys\",\n \"/api-keys\",\n \"KeyRoundIcon\",\n \"@lucide/svelte/icons/key-round\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyNavUser } from \"./modifies/nav-user.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerPath, modifyHooksServer(hooksServerPath)),\n );\n\n logger.info(\"Modifying nav-user\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying 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":";;;;;;;;;;AAMA,IAAMA,IAAe,CAAM;;;;;;;;;GAWrBC,IAAiB,CAAM;;;;;;;;;;;;AAa7B,SAAgBY,EAAkB,GAAwC;CACxE,IAAI,CAACJ,EAAG,WAAWK,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAa,SAASb;CAAe;CAGxD,IAAMc,IAAiBN,EAAG,aAAaK,GAAiB,MAAM,GAExDE,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBH,CAAe,GAExDI,IAAWF,EACd,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,kBAAkB;CAEnE,IAAI,CAACF,GACH,OAAO;EAAE,QAAQ;EAAU,SAASlB;CAAa;CAGnD,IAAMqB,IAAOH,EAAS,aAAa;CACnC,IAAIG,EAAK,WAAW,GAMlB,OALAH,EAAS,YACP,wDACF,GACAd,E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B;CAEA,EAAO,KAAK,2BAA2B;CACvC,IAAMpB,IAAkBJ,EAAK,KAAKyC,EAAQ,MAAM,OAAO,iBAAiB;CAKxE,AAJAE,EACE/C,EAAoBQ,GAAiBD,EAAkBC,CAAe,CAAC,CACzE,GAEAoC,EAAO,KAAK,oBAAoB;CAChC,IAAMH,IAAcrC,EAAK,KACvByC,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAW/C,EAAoByC,GAAaD,EAAcC,CAAW,CAAC,CAAC,GAEvEG,EAAO,KAAK,oBAAoB;CAChC,IAAMI,IAAY5C,EAAK,KAAKyC,EAAQ,MAAM,OAAO,OAAO,UAAU;CAGlE,OAFAE,EAAW/C,EAAoBgD,GAAW9C,EAAY8C,CAAS,CAAC,CAAC,GAE1D;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,10 +1,10 @@
1
- import { o as e } from "./generate-CZGHByV3.js";
1
+ import { o as e } from "./generate-DjBMRzsB.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
- import { n } from "./shared-Cc_ns5-y.js";
4
- import { n as r, r as i, t as a } from "./generate-CFqpRi9D.js";
3
+ import { n } from "./shared-D5GOS97l.js";
4
+ import { n as r, r as i, t as a } from "./generate-yi8AP3xH.js";
5
5
  import { n as o } from "./env-BPfk1VAw.js";
6
- import { envRevertOutcomeToFile as s } from "./modify-file-DK-tCH9k.js";
7
- import { unmodifyEnvVarsFiles as c } from "./env-vars-CcE6ODqC.js";
6
+ import { t as s } from "./modify-file-Bbhyfiy_.js";
7
+ import { unmodifyEnvVarsFiles as c } from "./env-vars-Bj41Nccm.js";
8
8
  import l from "node:fs";
9
9
  import u from "node:path";
10
10
  //#region src/patterns/disable/ai/generate.runtime.ts
@@ -32,4 +32,4 @@ async function d(d) {
32
32
  //#endregion
33
33
  export { d as generate };
34
34
 
35
- //# sourceMappingURL=generate.runtime-uLUiPgqx.js.map
35
+ //# sourceMappingURL=generate.runtime-C7s1Mx5L.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-uLUiPgqx.js","names":["demoDir","getLogger","allEnvNames","demoDirs","allEnvEdits","modifyEnvRemove","fs","path","generate","logger","options","modifies","deletes","current","dir","page","toDeleteEntry","envVars","unmodifyEnvVarsFiles","envPath","env","envRevertOutcomeToFile"],"sources":["../../src/patterns/disable/ai/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyEnvRemove } from \"../../../runtime/env\";\nimport { envRevertOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { demoDir } from \"../../enable/ai/generate\";\nimport { allEnvEdits, allEnvNames, demoDirs } from \"./generate\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n // The base result names the page in the current default group; a page\n // generated before auth was enabled sits in the other one.\n const current = demoDir(options);\n for (const dir of demoDirs(options)) {\n const page = `${dir}/+page.svelte`;\n if (dir !== current && fs.existsSync(path.join(options.root, page))) {\n deletes.push(toDeleteEntry(page));\n }\n }\n\n // Which provider was chosen is not recorded, so every one's key goes; the\n // file goes too when these were all it declared.\n logger.info(\"Removing the AI provider's API key from src/env.ts\");\n const envVars = unmodifyEnvVarsFiles(options.root, allEnvNames());\n if (envVars.modify) modifies.push(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Removing the AI provider's API key from .env\");\n const envPath = path.join(options.root, \".env\");\n const env = envRevertOutcomeToFile(\n envPath,\n modifyEnvRemove(envPath, allEnvEdits()),\n );\n if (env.modify) modifies.push(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":";;;;;;;;;;AAWA,eAAsBQ,EAAS,GAAkB;CAC/C,IAAMC,IAASR,EAAUS,CAAO,GAC1BC,IAAmB,CAAC,GACpBC,IAAkB,CAAC,GAInBC,IAAUb,EAAQU,CAAO;CAC/B,KAAK,IAAMI,KAAOX,EAASO,CAAO,GAAG;EACnC,IAAMK,IAAO,GAAGD,EAAI;EACpB,AAAIA,MAAQD,KAAWP,EAAG,WAAWC,EAAK,KAAKG,EAAQ,MAAMK,CAAI,CAAC,KAChEH,EAAQ,KAAKI,EAAcD,CAAI,CAAC;CAEpC;CAIA,EAAO,KAAK,oDAAoD;CAChE,IAAME,IAAUC,EAAqBR,EAAQ,MAAMR,EAAY,CAAC;CAIhE,AAHIe,EAAQ,UAAQN,EAAS,KAAKM,EAAQ,MAAM,GAC5CA,EAAQ,UAAQL,EAAQ,KAAKK,EAAQ,MAAM,GAE/CR,EAAO,KAAK,8CAA8C;CAC1D,IAAMU,IAAUZ,EAAK,KAAKG,EAAQ,MAAM,MAAM,GACxCU,IAAMC,EACVF,GACAd,EAAgBc,GAASf,EAAY,CAAC,CACxC;CAIA,OAHIgB,EAAI,UAAQT,EAAS,KAAKS,EAAI,MAAM,GACpCA,EAAI,UAAQR,EAAQ,KAAKQ,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
+ {"version":3,"file":"generate.runtime-C7s1Mx5L.js","names":["demoDir","getLogger","allEnvNames","demoDirs","allEnvEdits","modifyEnvRemove","envRevertOutcomeToFile","fs","path","generate","logger","options","modifies","deletes","current","dir","page","toDeleteEntry","envVars","unmodifyEnvVarsFiles","envPath","env"],"sources":["../../src/patterns/disable/ai/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyEnvRemove } from \"../../../runtime/env\";\nimport { envRevertOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { demoDir } from \"../../enable/ai/generate\";\nimport { allEnvEdits, allEnvNames, demoDirs } from \"./generate\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n // The base result names the page in the current default group; a page\n // generated before auth was enabled sits in the other one.\n const current = demoDir(options);\n for (const dir of demoDirs(options)) {\n const page = `${dir}/+page.svelte`;\n if (dir !== current && fs.existsSync(path.join(options.root, page))) {\n deletes.push(toDeleteEntry(page));\n }\n }\n\n // Which provider was chosen is not recorded, so every one's key goes; the\n // file goes too when these were all it declared.\n logger.info(\"Removing the AI provider's API key from src/env.ts\");\n const envVars = unmodifyEnvVarsFiles(options.root, allEnvNames());\n if (envVars.modify) modifies.push(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Removing the AI provider's API key from .env\");\n const envPath = path.join(options.root, \".env\");\n const env = envRevertOutcomeToFile(\n envPath,\n modifyEnvRemove(envPath, allEnvEdits()),\n );\n if (env.modify) modifies.push(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":";;;;;;;;;;AAWA,eAAsBS,EAAS,GAAkB;CAC/C,IAAMC,IAAST,EAAUU,CAAO,GAC1BC,IAAmB,CAAC,GACpBC,IAAkB,CAAC,GAInBC,IAAUd,EAAQW,CAAO;CAC/B,KAAK,IAAMI,KAAOZ,EAASQ,CAAO,GAAG;EACnC,IAAMK,IAAO,GAAGD,EAAI;EACpB,AAAIA,MAAQD,KAAWP,EAAG,WAAWC,EAAK,KAAKG,EAAQ,MAAMK,CAAI,CAAC,KAChEH,EAAQ,KAAKI,EAAcD,CAAI,CAAC;CAEpC;CAIA,EAAO,KAAK,oDAAoD;CAChE,IAAME,IAAUC,EAAqBR,EAAQ,MAAMT,EAAY,CAAC;CAIhE,AAHIgB,EAAQ,UAAQN,EAAS,KAAKM,EAAQ,MAAM,GAC5CA,EAAQ,UAAQL,EAAQ,KAAKK,EAAQ,MAAM,GAE/CR,EAAO,KAAK,8CAA8C;CAC1D,IAAMU,IAAUZ,EAAK,KAAKG,EAAQ,MAAM,MAAM,GACxCU,IAAMf,EACVc,GACAf,EAAgBe,GAAShB,EAAY,CAAC,CACxC;CAIA,OAHIiB,EAAI,UAAQT,EAAS,KAAKS,EAAI,MAAM,GACpCA,EAAI,UAAQR,EAAQ,KAAKQ,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,8 +1,8 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
3
  import { _ as n, a as r, o as i, r as a } from "./ts-morph-helpers-Bepc-Es2.js";
4
- import { modifyOutcomeToFile as o } from "./modify-file-DK-tCH9k.js";
5
- import { t as s } from "./svelte-file-B3RfgVdt.js";
4
+ import { r as o } from "./modify-file-Bbhyfiy_.js";
5
+ import { t as s } from "./svelte-file-Dv5-bl79.js";
6
6
  import { i as c, n as l, t as u } from "./pocketbase-CgwbH1gI.js";
7
7
  import { t as d } from "./site-lj0CDdQ1.js";
8
8
  import { modifySvelteConfigRemote as f } from "./modify-svelte-config-remote-DhuRX4FI.js";
@@ -330,4 +330,4 @@ async function O(e) {
330
330
  //#endregion
331
331
  export { O as generate };
332
332
 
333
- //# sourceMappingURL=generate.runtime-CEqLgLT9.js.map
333
+ //# sourceMappingURL=generate.runtime-CCV4O6_I.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CEqLgLT9.js","names":["FAILURE_HINT","NOT_FOUND_HINT","dedent","getLogger","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","SvelteFile","withPocketbase","migrationDelay","getMigrationFile","ensureSiteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$1","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","COOKIE_LOGIN","modifyTestSetup","setupPath","helper","generate","options","logger","creates","pb","input","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","modifyOutcomeToFile","layoutCandidates","layoutFile","p","hooksServerFile","testSetupFile","remote","modifySvelteConfigRemote","siteFile"],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/modifies/test-setup.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<UserAvatar user={data.user} />\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import UserAvatar from '#lib/components/user-avatar.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"#lib/components/ui/auth-menu/index.js\",\n },\n {\n defaultImport: \"UserAvatar\",\n moduleSpecifier: \"#lib/components/user-avatar.svelte\",\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 // Logs in with the password, so it needs the email (made optional by\n // enable-whatsapp, for accounts that sign in with a phone number).\n if (!user.email) {\n throw new Error('authenticateUser needs a user with an email');\n }\n const client = new PocketBase(process.env.POCKETBASE_URL!);\n await client.collection(\"users\").authWithPassword(user.email, testUserPassword);\n agent.set(\"Cookie\", client.authStore.exportToCookie().split(\";\")[0]);\n }\n`;\n\n/**\n * The template's server-test helper logs in by posting the `/login` form\n * action, which this pattern replaces with a remote function. A project\n * without the helper (or with its own) has nothing to fix.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(setupPath);\n const helper = sourceFile.getFunction(\"authenticateUser\");\n\n if (!helper || !/\\.post\\(\\s*[\"'`]\\/login[\"'`]\\s*\\)/.test(helper.getText())) {\n return { status: \"success\", changed: false };\n }\n\n helper.replaceWithText(COOKIE_LOGIN);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyTestSetup } from \"./modifies/test-setup\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = path.join(options.root, \"test\", \"setup.ts\");\n pushResult(\n modifyOutcomeToFile(testSetupFile, modifyTestSetup(testSetupFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAgBe,EAAmB,GAAmC;CACpE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAAG;EAC9B,IAAMC,IAAU,CAAM;;;;;EAOtB,OADAJ,EAAG,cAAcG,GAAYC,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAMC,IAAiBL,EAAG,aAAaG,GAAY,MAAM,GAEnDG,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBJ,CAAU,GAGnDK,KAAe,MAAoD;EAEvE,AADkBC,EAAI,YAAY,MAAM,KAEtCA,EAAI,sBAAsB;GACxB,MAAM;GACN,aAAa;EACf,CAAC;CAEL,GAGIC,GACAC,GAKEC,IAAUN,EAAW,uBAAuB,MAAM;CACxD,IAAIM,KACSA,EAAQ,uBAAuBC,EAAW,iBAChC,CAAA,EAAI,iBAAiB,GAC1B;EACd,IAAMC,IAAcF,EAAQ,qBAC1BC,EAAW,aACb;EACA,IAAIC,GACF,IAAYA;OACP;GACL,IAAMC,IAAOH,EAAQ,eAAe;GACpC,IAAIG,GAAM;IACR,IAAMC,IAAaD,EAAK,yBACtBF,EAAW,aACb;IACA,IAAIG,GACF,IAAYA;SACP;KACL,IAAMC,IAAcF,EAAK,yBACvBF,EAAW,kBACb;KACA,AAAII,MACF,IAASA;IAEb;GACF;EACF;CACF;CAGF,IAAI,CAACP,GAAW;EACd,IAAMQ,IAAUZ,EAAW,YAAY,MAAM;EAC7C,AAAIY,KAAWA,EAAQ,WAAW,MAChC,IAASA;CAEb;CAGA,IAAI,CAACR,KAAa,CAACC,GAUjB,OATAL,EAAW,YAAY;EACrB,YAAY;EACZ,SAAS;EACT,MAAM;EACN,YAAY,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AQ,IAAI;CACpD,EAAWa,EAAoBM,EAAO,UAAUA,EAAO,OAAO,CAAC;CAG/D,IAAME,IAAW,MAAMrF,EAAegE,CAAO;CAE7C,OAAO;EACL,SAASqB,IAAW,CAACA,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-CCV4O6_I.js","names":["FAILURE_HINT","NOT_FOUND_HINT","dedent","getLogger","withInMemoryScript","ensurePropsBinding","formatLikeSource","ensureImports","modifyOutcomeToFile","SvelteFile","withPocketbase","migrationDelay","getMigrationFile","ensureSiteFile","fs","path","modifyLayoutServer","layoutPath","snippet","originalSource","sourceFile","Project","addUserProp","obj","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","el","parts","tail","currentName","body","expr","ret","inner","bodyExpr","AUTH_MENU_NAVBAR_ITEM","IMPORT_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$1","modifyRootLayoutSvelte","file","out","source","sf","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","callExpr","ce","args","firstArg","optionsObj","authProp","authInit","authObj","prProp","prInit","arr","COOKIE_LOGIN","modifyTestSetup","setupPath","helper","generate","options","logger","creates","pb","input","userCollection","verificationTemplate","resetPasswordTemplate","confirmEmailChangeTemplate","migrationFile","modifies","pushResult","layoutServerFile","layoutCandidates","layoutFile","p","hooksServerFile","testSetupFile","remote","modifySvelteConfigRemote","siteFile"],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/modifies/test-setup.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<UserAvatar user={data.user} />\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '#lib/components/ui/auth-menu/index.js';\n import UserAvatar from '#lib/components/user-avatar.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"#lib/components/ui/auth-menu/index.js\",\n },\n {\n defaultImport: \"UserAvatar\",\n moduleSpecifier: \"#lib/components/user-avatar.svelte\",\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 // Logs in with the password, so it needs the email (made optional by\n // enable-whatsapp, for accounts that sign in with a phone number).\n if (!user.email) {\n throw new Error('authenticateUser needs a user with an email');\n }\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,SAAgBgB,EAAmB,GAAmC;CACpE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAAG;EAC9B,IAAMC,IAAU,CAAM;;;;;EAOtB,OADAJ,EAAG,cAAcG,GAAYC,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAMC,IAAiBL,EAAG,aAAaG,GAAY,MAAM,GAEnDG,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBJ,CAAU,GAGnDK,KAAe,MAAoD;EAEvE,AADkBC,EAAI,YAAY,MAAM,KAEtCA,EAAI,sBAAsB;GACxB,MAAM;GACN,aAAa;EACf,CAAC;CAEL,GAGIC,GACAC,GAKEC,IAAUN,EAAW,uBAAuB,MAAM;CACxD,IAAIM,KACSA,EAAQ,uBAAuBC,EAAW,iBAChC,CAAA,EAAI,iBAAiB,GAC1B;EACd,IAAMC,IAAcF,EAAQ,qBAC1BC,EAAW,aACb;EACA,IAAIC,GACF,IAAYA;OACP;GACL,IAAMC,IAAOH,EAAQ,eAAe;GACpC,IAAIG,GAAM;IACR,IAAMC,IAAaD,EAAK,yBACtBF,EAAW,aACb;IACA,IAAIG,GACF,IAAYA;SACP;KACL,IAAMC,IAAcF,EAAK,yBACvBF,EAAW,kBACb;KACA,AAAII,MACF,IAASA;IAEb;GACF;EACF;CACF;CAGF,IAAI,CAACP,GAAW;EACd,IAAMQ,IAA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AMgB,IAAgB/E,EAAK,KAAK8D,EAAQ,MAAM,QAAQ,UAAU;CAKhE,AAJAW,EACEhF,EAAoBsF,GAAerB,EAAgBqB,CAAa,CAAC,CACnE,GAEAhB,EAAO,KAAK,uCAAuC;CACnD,IAAMiB,IAASC,EAAyBnB,EAAQ,IAAI;CACpD,EAAWrE,EAAoBuF,EAAO,UAAUA,EAAO,OAAO,CAAC;CAG/D,IAAME,IAAW,MAAMpF,EAAegE,CAAO;CAE7C,OAAO;EACL,SAASoB,IAAW,CAACA,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -3,13 +3,13 @@ import { t as n } from "./dedent-Gq6Krl4n.js";
3
3
  import { n as r } from "./logger-CQONztPm.js";
4
4
  import { t as i } from "./env-vars-mnRA0hOe.js";
5
5
  import { t as a } from "./env-vars-Cr4lbMD_.js";
6
- import { n as o } from "./shared-Cc_ns5-y.js";
6
+ import { n as o } from "./shared-D5GOS97l.js";
7
7
  import { c as s, m as c, n as l, o as u } from "./ts-morph-helpers-Bepc-Es2.js";
8
- import { modifyOutcomeToFile as d, revertOutcomeToFile as f } from "./modify-file-DK-tCH9k.js";
9
- import { unmodifyEnvVarsFiles as p } from "./env-vars-CcE6ODqC.js";
8
+ import { a as d, r as f } from "./modify-file-Bbhyfiy_.js";
9
+ import { unmodifyEnvVarsFiles as p } from "./env-vars-Bj41Nccm.js";
10
10
  import { t as m } from "./site-lj0CDdQ1.js";
11
11
  import { n as h } from "./compose-handle-BDlZ7Pif.js";
12
- import { a as g, l as _, s as v } from "./test-setup-B9fQ5L_-.js";
12
+ import { a as g, l as _, s as v } from "./test-setup-DZoyF8Ak.js";
13
13
  import y from "node:fs";
14
14
  import b from "node:path";
15
15
  import { Node as x, Project as S, QuoteKind as C } from "ts-morph";
@@ -120,24 +120,24 @@ function N(e) {
120
120
  async function P(e) {
121
121
  let t = r(e), n = [], s = [], c = [];
122
122
  t.info("Reverting adapter config");
123
- let l = _(e.root), u = d(l.filePath, l.outcome);
123
+ let l = _(e.root), u = f(l.filePath, l.outcome);
124
124
  u && s.push(u), t.info("Reverting hooks.server.ts");
125
- let h = b.join(e.root, "src", "hooks.server.ts"), x = f(h, A(h));
125
+ let h = b.join(e.root, "src", "hooks.server.ts"), x = d(h, A(h));
126
126
  x.modify && s.push(x.modify), x.delete && c.push(x.delete);
127
127
  let S = y.existsSync(b.join(e.root, "src", "lib", "server", "workflows.ts"));
128
128
  t.info(S ? "Removing the PocketBase and workflow variables from src/env.ts" : "Removing the PocketBase variables from src/env.ts");
129
129
  let C = p(e.root, (S ? a : i).map((e) => e.name));
130
130
  C.modify && s.push(C.modify), C.delete && c.push(C.delete), t.info("Reverting .gitignore");
131
- let w = b.join(e.root, ".gitignore"), T = d(w, v(w));
131
+ let w = b.join(e.root, ".gitignore"), T = f(w, v(w));
132
132
  T && s.push(T), t.info("Reverting src/routes/+layout.server.ts");
133
- let E = b.join(e.root, "src", "routes", "+layout.server.ts"), D = d(E, M(E));
133
+ let E = b.join(e.root, "src", "routes", "+layout.server.ts"), D = f(E, M(E));
134
134
  if (D && s.push(D), D?.status === "success") {
135
135
  let t = await m(e);
136
136
  t && n.push(t);
137
137
  }
138
138
  for (let n of N(b.join(e.root, "src"))) t.info(`Removing ${b.relative(e.root, n)}`), c.push(o(n));
139
139
  t.info("Reverting test/setup.ts");
140
- let O = b.join(e.root, "test", "setup.ts"), k = d(O, g(O));
140
+ let O = b.join(e.root, "test", "setup.ts"), k = f(O, g(O));
141
141
  return k && s.push(k), {
142
142
  creates: n,
143
143
  modifies: s,
@@ -152,4 +152,4 @@ async function P(e) {
152
152
  //#endregion
153
153
  export { P as generate };
154
154
 
155
- //# sourceMappingURL=generate.runtime-CK10Mum5.js.map
155
+ //# sourceMappingURL=generate.runtime-CSUnP0l-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CK10Mum5.js","names":["libModule","dedent","getLogger","BACKEND_ENV_VARS","WORKFLOWS_ENV_VARS","toDeleteEntry","pruneUnusedImports","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","ensureSiteFile","removeHandle","unmodifyTestSetup","unmodifySvelteConfig","unmodifyGitignore","fs","path","HANDLE_HINT","INIT_HINT","BACKEND_MODULES","isStartWorkerCall","node","Node","onlyStartsWorker","fn","body","statements","workerInit","sf","decl","target","unmodifyHooksServerBackend","hooksServerPath","original","sourceFile","Project","QuoteKind","init","FAILURE_HINT","unmodifyLayoutServerMeta","layoutServerPath","updated","withoutParam","isLibSpecifier","m","serverTestFiles","dir","found","entry","full","generate","logger","options","creates","modifies","deletes","revert","svelteConfigFile","modifyOutcomeToFile","hooksServerRevert","revertOutcomeToFile","hasWorkflows","envVars","unmodifyEnvVarsFiles","spec","gitignorePath","gitignoreFile","layoutServerFile","siteFile","testFile","testSetupPath","testSetupFile"],"sources":["../../src/patterns/disable/backend/modifies/hooks.server.ts","../../src/patterns/disable/backend/modifies/layout-server.ts","../../src/patterns/disable/backend/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport {\n Node,\n Project,\n QuoteKind,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n pruneUnusedImports,\n removeStatementWithComments,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst HANDLE_HINT = dedent`\n Take handlePocketbase(...) out of the exported handle in src/hooks.server.ts,\n and its imports from '@velastack/pocketbase' and '$app/env/private'.\n`;\n\nconst INIT_HINT = dedent`\n The workflows are removed with the backend. Take the startWorker() call out\n of the init hook in src/hooks.server.ts, and its import:\n\n import { startWorker } from '#lib/server/workflows.js';\n`;\n\n/**\n * Modules only the backend's handle and init import from. An import nothing\n * references any more is dropped; a variable other code still reads stays.\n * `$env/dynamic/private` is the `env` object hooks written before SvelteKit 3\n * read the PocketBase variables from.\n */\nconst BACKEND_MODULES: ModuleMatch[] = [\n \"@velastack/pocketbase\",\n \"$app/env/private\",\n \"$env/dynamic/private\",\n libModule(\"server/workflows\"),\n \"@sveltejs/kit\",\n \"@sveltejs/kit/hooks\",\n];\n\n/** `startWorker()`, `await startWorker()` or `return startWorker()`. */\nfunction isStartWorkerCall(node: Node | undefined): boolean {\n if (!node) return false;\n if (Node.isAwaitExpression(node))\n return isStartWorkerCall(node.getExpression());\n if (Node.isExpressionStatement(node) || Node.isReturnStatement(node)) {\n return isStartWorkerCall(node.getExpression());\n }\n return (\n Node.isCallExpression(node) &&\n node.getExpression().getText() === \"startWorker\" &&\n node.getArguments().length === 0\n );\n}\n\n/** A function whose whole body starts the worker. */\nfunction onlyStartsWorker(fn: Node | undefined): boolean {\n if (\n !Node.isArrowFunction(fn) &&\n !Node.isFunctionExpression(fn) &&\n !Node.isFunctionDeclaration(fn)\n ) {\n return false;\n }\n const body = fn.getBody();\n if (!body) return false;\n if (!Node.isBlock(body)) return isStartWorkerCall(body);\n const statements = body.getStatements();\n return statements.length === 1 && isStartWorkerCall(statements[0]);\n}\n\n/**\n * The `init` export when all it does is start the workflow worker, the way\n * the minimal template and enable-workflows write it. `\"custom\"` when an init\n * starts the worker among other things; null when there is nothing to do.\n */\nfunction workerInit(sf: SourceFile): Statement | \"custom\" | null {\n const fn = sf.getFunction(\"init\");\n const decl = sf.getVariableDeclaration(\"init\");\n const target = fn ?? decl?.getVariableStatement();\n if (!target || !target.getText().includes(\"startWorker\")) return null;\n const onlyWorker = fn\n ? onlyStartsWorker(fn)\n : decl?.getVariableStatement()?.getDeclarations().length === 1 &&\n onlyStartsWorker(decl.getInitializer());\n return onlyWorker ? target : \"custom\";\n}\n\n/**\n * Undo what the backend put in `hooks.server.ts`: the PocketBase handle, and\n * the `init` that starts the workflow worker, which is deleted along with the\n * backend. Whatever else the file holds (i18n, content negotiation) stays; a\n * file with nothing else comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksServerBackend(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (\n !original.includes(\"handlePocketbase\") &&\n !original.includes(\"startWorker\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Checked before anything changes, so a failure leaves the file as it was.\n if (workerInit(sourceFile) === \"custom\") {\n return { status: \"failed\", message: INIT_HINT };\n }\n\n const removed = removeHandle(sourceFile, \"handlePocketbase\");\n if (removed.status === \"unsupported\") {\n return { status: \"failed\", message: HANDLE_HINT };\n }\n // Looked up again: edits to the file forget the nodes found before them.\n const init = workerInit(sourceFile);\n if (init && init !== \"custom\") removeStatementWithComments(sourceFile, init);\n\n pruneUnusedImports(sourceFile, BACKEND_MODULES);\n formatLikeSource(sourceFile);\n ensureBlankLineAfterImports(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst FAILURE_HINT = dedent`\n src/routes/+layout.server.ts still reads locals.meta, which only the\n PocketBase hook provides. Read the values from a static module instead:\n\n import { site } from '#lib/site.js';\n\n // locals.meta.appName -> site.name\n // locals.meta.appURL -> site.url\n // meta: locals.meta -> meta: { appName: site.name, appURL: site.url }\n`;\n\n/**\n * Point an older root layout's meta at `#lib/site.js` instead of `locals.meta`.\n * Templates from before `src/lib/site.ts` read the app name and URL off the\n * PocketBase hook; without the backend nothing sets them, and `App.Locals` no\n * longer declares them. Current templates read `#lib/site.js` already, so this\n * leaves them alone.\n */\nexport function unmodifyLayoutServerMeta(\n layoutServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (!original.includes(\"locals.meta\")) {\n return { status: \"success\", changed: false };\n }\n\n let updated = original\n .replace(/\\blocals\\.meta\\.appName\\b/g, \"site.name\")\n .replace(/\\blocals\\.meta\\.appURL\\b/g, \"site.url\")\n .replace(\n /\\bmeta:\\s*locals\\.meta\\b/g,\n \"meta: { appName: site.name, appURL: site.url }\",\n );\n\n if (updated.includes(\"locals.meta\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // `locals` usually only carried meta; drop it from the destructuring when\n // nothing else reads it.\n const withoutParam = updated\n .replace(/\\(\\{\\s*locals\\s*,\\s*/g, \"({ \")\n .replace(/,\\s*locals\\s*\\}/g, \" }\");\n if (!/\\blocals\\b/.test(withoutParam)) {\n updated = withoutParam;\n }\n\n const importsSite = [...updated.matchAll(/from\\s+['\"]([^'\"]+)['\"]/g)].some(\n (m) => isLibSpecifier(m[1], \"site\"),\n );\n if (!importsSite) {\n updated = \"import { site } from '#lib/site.js';\\n\" + updated;\n }\n\n fs.writeFileSync(layoutServerPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\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 {\n modifyOutcomeToFile,\n revertOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { unmodifyHooksServerBackend } from \"./modifies/hooks.server\";\nimport { unmodifyLayoutServerMeta } from \"./modifies/layout-server\";\nimport { unmodifySvelteConfig } from \"../../enable/backend/modifies/svelte-config\";\nimport { unmodifyGitignore } from \"../../enable/backend/modifies/gitignore\";\nimport { unmodifyTestSetup } from \"../../enable/backend/modifies/test-setup\";\nimport { BACKEND_ENV_VARS } from \"../../enable/backend/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"../../enable/workflows/env-vars\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\n\n/** Every server test under a directory; they need the PocketBase test context. */\nfunction serverTestFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const found: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) found.push(...serverTestFiles(full));\n else if (entry.name === \"server.test.ts\") found.push(full);\n }\n return found;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n logger.info(\"Reverting adapter config\");\n const revert = unmodifySvelteConfig(options.root);\n const svelteConfigFile = modifyOutcomeToFile(revert.filePath, revert.outcome);\n if (svelteConfigFile) modifies.push(svelteConfigFile);\n\n // Only the backend's handle and worker come out; handles other patterns\n // composed in stay. The file goes when nothing else was in it.\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksServerRevert = revertOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerBackend(hooksServerPath),\n );\n if (hooksServerRevert.modify) modifies.push(hooksServerRevert.modify);\n if (hooksServerRevert.delete) deletes.push(hooksServerRevert.delete);\n\n // The file goes when these were all it declared. The workflow runtime\n // (deleted with the backend) is the only reader of its switches, so they\n // go too, but only from a project that has it: `TEST` is a common name.\n const hasWorkflows = fs.existsSync(\n path.join(options.root, \"src\", \"lib\", \"server\", \"workflows.ts\"),\n );\n logger.info(\n hasWorkflows\n ? \"Removing the PocketBase and workflow variables from src/env.ts\"\n : \"Removing the PocketBase variables from src/env.ts\",\n );\n const envVars = unmodifyEnvVarsFiles(\n options.root,\n (hasWorkflows ? WORKFLOWS_ENV_VARS : BACKEND_ENV_VARS).map(\n (spec) => spec.name,\n ),\n );\n if (envVars.modify) modifies.push(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Reverting .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n const gitignoreFile = modifyOutcomeToFile(\n gitignorePath,\n unmodifyGitignore(gitignorePath),\n );\n if (gitignoreFile) modifies.push(gitignoreFile);\n\n logger.info(\"Reverting src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const layoutServerFile = modifyOutcomeToFile(\n layoutServerPath,\n unmodifyLayoutServerMeta(layoutServerPath),\n );\n if (layoutServerFile) modifies.push(layoutServerFile);\n\n // The converted layout reads `src/lib/site.ts`. Every template ships it; a\n // project from before that gets one here, named as PocketBase knew it.\n if (layoutServerFile?.status === \"success\") {\n const siteFile = await ensureSiteFile(options);\n if (siteFile) creates.push(siteFile);\n }\n\n // Server tests run against the PocketBase-backed test context that the\n // backend's test/setup.ts provides; without it they neither type-check nor\n // run.\n for (const testFile of serverTestFiles(path.join(options.root, \"src\"))) {\n logger.info(`Removing ${path.relative(options.root, testFile)}`);\n deletes.push(toDeleteEntry(testFile));\n }\n\n logger.info(\"Reverting test/setup.ts\");\n const testSetupPath = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetupPath,\n unmodifyTestSetup(testSetupPath),\n );\n if (testSetupFile) modifies.push(testSetupFile);\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":";;;;;;;;;;;;;;;;AAoBA,IAAMiB,IAAc,CAAM;;;GAKpBC,IAAY,CAAM;;;;;GAalBC,IAAiC;CACrC;CACA;CACA;CACAnB,EAAU,kBAAkB;CAC5B;CACA;AACF;AAGA,SAASoB,EA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version":3,"file":"generate.runtime-CSUnP0l-.js","names":["libModule","dedent","getLogger","BACKEND_ENV_VARS","WORKFLOWS_ENV_VARS","toDeleteEntry","pruneUnusedImports","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","revertOutcomeToFile","modifyOutcomeToFile","ensureSiteFile","removeHandle","unmodifyTestSetup","unmodifySvelteConfig","unmodifyGitignore","fs","path","HANDLE_HINT","INIT_HINT","BACKEND_MODULES","isStartWorkerCall","node","Node","onlyStartsWorker","fn","body","statements","workerInit","sf","decl","target","unmodifyHooksServerBackend","hooksServerPath","original","sourceFile","Project","QuoteKind","init","FAILURE_HINT","unmodifyLayoutServerMeta","layoutServerPath","updated","withoutParam","isLibSpecifier","m","serverTestFiles","dir","found","entry","full","generate","logger","options","creates","modifies","deletes","revert","svelteConfigFile","hooksServerRevert","hasWorkflows","envVars","unmodifyEnvVarsFiles","spec","gitignorePath","gitignoreFile","layoutServerFile","siteFile","testFile","testSetupPath","testSetupFile"],"sources":["../../src/patterns/disable/backend/modifies/hooks.server.ts","../../src/patterns/disable/backend/modifies/layout-server.ts","../../src/patterns/disable/backend/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport {\n Node,\n Project,\n QuoteKind,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n pruneUnusedImports,\n removeStatementWithComments,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst HANDLE_HINT = dedent`\n Take handlePocketbase(...) out of the exported handle in src/hooks.server.ts,\n and its imports from '@velastack/pocketbase' and '$app/env/private'.\n`;\n\nconst INIT_HINT = dedent`\n The workflows are removed with the backend. Take the startWorker() call out\n of the init hook in src/hooks.server.ts, and its import:\n\n import { startWorker } from '#lib/server/workflows.js';\n`;\n\n/**\n * Modules only the backend's handle and init import from. An import nothing\n * references any more is dropped; a variable other code still reads stays.\n * `$env/dynamic/private` is the `env` object hooks written before SvelteKit 3\n * read the PocketBase variables from.\n */\nconst BACKEND_MODULES: ModuleMatch[] = [\n \"@velastack/pocketbase\",\n \"$app/env/private\",\n \"$env/dynamic/private\",\n libModule(\"server/workflows\"),\n \"@sveltejs/kit\",\n \"@sveltejs/kit/hooks\",\n];\n\n/** `startWorker()`, `await startWorker()` or `return startWorker()`. */\nfunction isStartWorkerCall(node: Node | undefined): boolean {\n if (!node) return false;\n if (Node.isAwaitExpression(node))\n return isStartWorkerCall(node.getExpression());\n if (Node.isExpressionStatement(node) || Node.isReturnStatement(node)) {\n return isStartWorkerCall(node.getExpression());\n }\n return (\n Node.isCallExpression(node) &&\n node.getExpression().getText() === \"startWorker\" &&\n node.getArguments().length === 0\n );\n}\n\n/** A function whose whole body starts the worker. */\nfunction onlyStartsWorker(fn: Node | undefined): boolean {\n if (\n !Node.isArrowFunction(fn) &&\n !Node.isFunctionExpression(fn) &&\n !Node.isFunctionDeclaration(fn)\n ) {\n return false;\n }\n const body = fn.getBody();\n if (!body) return false;\n if (!Node.isBlock(body)) return isStartWorkerCall(body);\n const statements = body.getStatements();\n return statements.length === 1 && isStartWorkerCall(statements[0]);\n}\n\n/**\n * The `init` export when all it does is start the workflow worker, the way\n * the minimal template and enable-workflows write it. `\"custom\"` when an init\n * starts the worker among other things; null when there is nothing to do.\n */\nfunction workerInit(sf: SourceFile): Statement | \"custom\" | null {\n const fn = sf.getFunction(\"init\");\n const decl = sf.getVariableDeclaration(\"init\");\n const target = fn ?? decl?.getVariableStatement();\n if (!target || !target.getText().includes(\"startWorker\")) return null;\n const onlyWorker = fn\n ? onlyStartsWorker(fn)\n : decl?.getVariableStatement()?.getDeclarations().length === 1 &&\n onlyStartsWorker(decl.getInitializer());\n return onlyWorker ? target : \"custom\";\n}\n\n/**\n * Undo what the backend put in `hooks.server.ts`: the PocketBase handle, and\n * the `init` that starts the workflow worker, which is deleted along with the\n * backend. Whatever else the file holds (i18n, content negotiation) stays; a\n * file with nothing else comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksServerBackend(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (\n !original.includes(\"handlePocketbase\") &&\n !original.includes(\"startWorker\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Checked before anything changes, so a failure leaves the file as it was.\n if (workerInit(sourceFile) === \"custom\") {\n return { status: \"failed\", message: INIT_HINT };\n }\n\n const removed = removeHandle(sourceFile, \"handlePocketbase\");\n if (removed.status === \"unsupported\") {\n return { status: \"failed\", message: HANDLE_HINT };\n }\n // Looked up again: edits to the file forget the nodes found before them.\n const init = workerInit(sourceFile);\n if (init && init !== \"custom\") removeStatementWithComments(sourceFile, init);\n\n pruneUnusedImports(sourceFile, BACKEND_MODULES);\n formatLikeSource(sourceFile);\n ensureBlankLineAfterImports(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst FAILURE_HINT = dedent`\n src/routes/+layout.server.ts still reads locals.meta, which only the\n PocketBase hook provides. Read the values from a static module instead:\n\n import { site } from '#lib/site.js';\n\n // locals.meta.appName -> site.name\n // locals.meta.appURL -> site.url\n // meta: locals.meta -> meta: { appName: site.name, appURL: site.url }\n`;\n\n/**\n * Point an older root layout's meta at `#lib/site.js` instead of `locals.meta`.\n * Templates from before `src/lib/site.ts` read the app name and URL off the\n * PocketBase hook; without the backend nothing sets them, and `App.Locals` no\n * longer declares them. Current templates read `#lib/site.js` already, so this\n * leaves them alone.\n */\nexport function unmodifyLayoutServerMeta(\n layoutServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (!original.includes(\"locals.meta\")) {\n return { status: \"success\", changed: false };\n }\n\n let updated = original\n .replace(/\\blocals\\.meta\\.appName\\b/g, \"site.name\")\n .replace(/\\blocals\\.meta\\.appURL\\b/g, \"site.url\")\n .replace(\n /\\bmeta:\\s*locals\\.meta\\b/g,\n \"meta: { appName: site.name, appURL: site.url }\",\n );\n\n if (updated.includes(\"locals.meta\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // `locals` usually only carried meta; drop it from the destructuring when\n // nothing else reads it.\n const withoutParam = updated\n .replace(/\\(\\{\\s*locals\\s*,\\s*/g, \"({ \")\n .replace(/,\\s*locals\\s*\\}/g, \" }\");\n if (!/\\blocals\\b/.test(withoutParam)) {\n updated = withoutParam;\n }\n\n const importsSite = [...updated.matchAll(/from\\s+['\"]([^'\"]+)['\"]/g)].some(\n (m) => isLibSpecifier(m[1], \"site\"),\n );\n if (!importsSite) {\n updated = \"import { site } from '#lib/site.js';\\n\" + updated;\n }\n\n fs.writeFileSync(layoutServerPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\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 {\n modifyOutcomeToFile,\n revertOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { unmodifyHooksServerBackend } from \"./modifies/hooks.server\";\nimport { unmodifyLayoutServerMeta } from \"./modifies/layout-server\";\nimport { unmodifySvelteConfig } from \"../../enable/backend/modifies/svelte-config\";\nimport { unmodifyGitignore } from \"../../enable/backend/modifies/gitignore\";\nimport { unmodifyTestSetup } from \"../../enable/backend/modifies/test-setup\";\nimport { BACKEND_ENV_VARS } from \"../../enable/backend/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"../../enable/workflows/env-vars\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\n\n/** Every server test under a directory; they need the PocketBase test context. */\nfunction serverTestFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const found: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) found.push(...serverTestFiles(full));\n else if (entry.name === \"server.test.ts\") found.push(full);\n }\n return found;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n logger.info(\"Reverting adapter config\");\n const revert = unmodifySvelteConfig(options.root);\n const svelteConfigFile = modifyOutcomeToFile(revert.filePath, revert.outcome);\n if (svelteConfigFile) modifies.push(svelteConfigFile);\n\n // Only the backend's handle and worker come out; handles other patterns\n // composed in stay. The file goes when nothing else was in it.\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksServerRevert = revertOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerBackend(hooksServerPath),\n );\n if (hooksServerRevert.modify) modifies.push(hooksServerRevert.modify);\n if (hooksServerRevert.delete) deletes.push(hooksServerRevert.delete);\n\n // The file goes when these were all it declared. The workflow runtime\n // (deleted with the backend) is the only reader of its switches, so they\n // go too, but only from a project that has it: `TEST` is a common name.\n const hasWorkflows = fs.existsSync(\n path.join(options.root, \"src\", \"lib\", \"server\", \"workflows.ts\"),\n );\n logger.info(\n hasWorkflows\n ? \"Removing the PocketBase and workflow variables from src/env.ts\"\n : \"Removing the PocketBase variables from src/env.ts\",\n );\n const envVars = unmodifyEnvVarsFiles(\n options.root,\n (hasWorkflows ? WORKFLOWS_ENV_VARS : BACKEND_ENV_VARS).map(\n (spec) => spec.name,\n ),\n );\n if (envVars.modify) modifies.push(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Reverting .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n const gitignoreFile = modifyOutcomeToFile(\n gitignorePath,\n unmodifyGitignore(gitignorePath),\n );\n if (gitignoreFile) modifies.push(gitignoreFile);\n\n logger.info(\"Reverting src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const layoutServerFile = modifyOutcomeToFile(\n layoutServerPath,\n unmodifyLayoutServerMeta(layoutServerPath),\n );\n if (layoutServerFile) modifies.push(layoutServerFile);\n\n // The converted layout reads `src/lib/site.ts`. Every template ships it; a\n // project from before that gets one here, named as PocketBase knew it.\n if (layoutServerFile?.status === \"success\") {\n const siteFile = await ensureSiteFile(options);\n if (siteFile) creates.push(siteFile);\n }\n\n // Server tests run against the PocketBase-backed test context that the\n // backend's test/setup.ts provides; without it they neither type-check nor\n // run.\n for (const testFile of serverTestFiles(path.join(options.root, \"src\"))) {\n logger.info(`Removing ${path.relative(options.root, testFile)}`);\n deletes.push(toDeleteEntry(testFile));\n }\n\n logger.info(\"Reverting test/setup.ts\");\n const testSetupPath = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetupPath,\n unmodifyTestSetup(testSetupPath),\n );\n if (testSetupFile) modifies.push(testSetupFile);\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":";;;;;;;;;;;;;;;;AAoBA,IAAMmB,IAAc,CAAM;;;GAKpBC,IAAY,CAAM;;;;;GAalBC,IAAiC;CACrC;CACA;CACA;CACArB,EAAU,kBAAkB;CAC5B;CACA;AACF;AAGA,SAASsB,EAA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 -3,11 +3,11 @@ import { t } from "./dedent-Gq6Krl4n.js";
3
3
  import { n } from "./logger-CQONztPm.js";
4
4
  import { t as r } from "./pocketbase-DpudAAmd.js";
5
5
  import { _ as i, o as a, r as o } from "./ts-morph-helpers-Bepc-Es2.js";
6
- import { modifyOutcomeToFile as s } from "./modify-file-DK-tCH9k.js";
7
- import { t as c } from "./svelte-file-B3RfgVdt.js";
6
+ import { r as s } from "./modify-file-Bbhyfiy_.js";
7
+ import { t as c } from "./svelte-file-Dv5-bl79.js";
8
8
  import { i as l, n as u, t as d } from "./pocketbase-CgwbH1gI.js";
9
9
  import { t as f } from "./modify-utils-Cw-on_cL.js";
10
- import { applyCollectionRulePatches as p, createCollectionIdempotent as m } from "./collections-zzZ_HQxB.js";
10
+ import { r as p, t as m } from "./collections-Cpjo2OiQ.js";
11
11
  import h from "node:fs";
12
12
  import g from "node:path";
13
13
  import { Project as _, SyntaxKind as v } from "ts-morph";
@@ -209,7 +209,7 @@ async function O(t, n, r, i = !0) {
209
209
  async function k(e) {
210
210
  let t = n(e), i = [];
211
211
  await l(e.root, async (n) => {
212
- let a = await n.collections.getOne("users"), o = (e) => m(n, e, t);
212
+ let a = await n.collections.getOne("users"), o = (e) => p(n, e, t);
213
213
  t.info("Creating notifications collection");
214
214
  let s = await o({
215
215
  name: "notifications",
@@ -263,7 +263,7 @@ async function k(e) {
263
263
  indexes: ["CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)"]
264
264
  });
265
265
  await O(i, "notifications", e, s.created), t.info("Applying notifications rule patches");
266
- let c = await p(n, r, e, t);
266
+ let c = await m(n, r, e, t);
267
267
  i.push(...c);
268
268
  });
269
269
  let a = [], o = (e) => {
@@ -289,4 +289,4 @@ async function k(e) {
289
289
  //#endregion
290
290
  export { k as generate };
291
291
 
292
- //# sourceMappingURL=generate.runtime-koQxLywh.js.map
292
+ //# sourceMappingURL=generate.runtime-CV4soy2n.js.map