@velastack/patterns 0.14.3 → 0.15.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 (156) hide show
  1. package/README.md +28 -0
  2. package/dist/chunks/{_page-44USwLXO.js → _page-6d3DCr0p.js} +2 -2
  3. package/dist/chunks/{_page-44USwLXO.js.map → _page-6d3DCr0p.js.map} +1 -1
  4. package/dist/chunks/{auth-pages-BW3_yluN.js → auth-pages-DHzh31mw.js} +2 -2
  5. package/dist/chunks/{auth-pages-BW3_yluN.js.map → auth-pages-DHzh31mw.js.map} +1 -1
  6. package/dist/chunks/{collections-B_-NTtLW.js → collections-FKsKGtaH.js} +70 -73
  7. package/dist/chunks/collections-FKsKGtaH.js.map +1 -0
  8. package/dist/chunks/{constants-CTp-0HKk.js → constants-BHuzzsKu.js} +19 -19
  9. package/dist/chunks/constants-BHuzzsKu.js.map +1 -0
  10. package/dist/chunks/{currency.server-DOX4Rzyb.js → currency.server-DRuEFc6D.js} +4 -4
  11. package/dist/chunks/{currency.server-DOX4Rzyb.js.map → currency.server-DRuEFc6D.js.map} +1 -1
  12. package/dist/chunks/{env-vars-BbS_mWyP.js → env-vars-BcHu8247.js} +4 -4
  13. package/dist/chunks/{env-vars-BbS_mWyP.js.map → env-vars-BcHu8247.js.map} +1 -1
  14. package/dist/chunks/{generate-B4uDCW5D.js → generate-9O0VdZOl.js} +4 -4
  15. package/dist/chunks/{generate-B4uDCW5D.js.map → generate-9O0VdZOl.js.map} +1 -1
  16. package/dist/chunks/{generate-CKuUg3p-.js → generate-BDGmczK8.js} +2 -2
  17. package/dist/chunks/{generate-CKuUg3p-.js.map → generate-BDGmczK8.js.map} +1 -1
  18. package/dist/chunks/{generate-DYq5Oj58.js → generate-BrO9MOgL.js} +2 -2
  19. package/dist/chunks/{generate-DYq5Oj58.js.map → generate-BrO9MOgL.js.map} +1 -1
  20. package/dist/chunks/{generate-Bwkx_usZ.js → generate-CXAKf1Hh.js} +4 -4
  21. package/dist/chunks/{generate-Bwkx_usZ.js.map → generate-CXAKf1Hh.js.map} +1 -1
  22. package/dist/chunks/{generate-4iujJNAW.js → generate-CkfJrlEg.js} +5 -5
  23. package/dist/chunks/{generate-4iujJNAW.js.map → generate-CkfJrlEg.js.map} +1 -1
  24. package/dist/chunks/{generate-BJY8AtAp.js → generate-a3U8uDzW.js} +5 -5
  25. package/dist/chunks/{generate-BJY8AtAp.js.map → generate-a3U8uDzW.js.map} +1 -1
  26. package/dist/chunks/{generate-JkvSNTy-.js → generate-rcDj36TD.js} +31 -188
  27. package/dist/chunks/generate-rcDj36TD.js.map +1 -0
  28. package/dist/chunks/{generate.runtime-D0lI3Gt8.js → generate.runtime-4gS2ZHpj.js} +5 -5
  29. package/dist/chunks/{generate.runtime-D0lI3Gt8.js.map → generate.runtime-4gS2ZHpj.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-BFX_8erf.js → generate.runtime-As1It8o7.js} +10 -9
  31. package/dist/chunks/{generate.runtime-BFX_8erf.js.map → generate.runtime-As1It8o7.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-XT_JQlTk.js → generate.runtime-B5SP9iyN.js} +2 -2
  33. package/dist/chunks/{generate.runtime-XT_JQlTk.js.map → generate.runtime-B5SP9iyN.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-DiEiFoxR.js → generate.runtime-B8t8HtB6.js} +3 -3
  35. package/dist/chunks/{generate.runtime-DiEiFoxR.js.map → generate.runtime-B8t8HtB6.js.map} +1 -1
  36. package/dist/chunks/{generate.runtime-XpYi9SlM.js → generate.runtime-B9U3kzHD.js} +3 -3
  37. package/dist/chunks/{generate.runtime-XpYi9SlM.js.map → generate.runtime-B9U3kzHD.js.map} +1 -1
  38. package/dist/chunks/{generate.runtime-RTGpwxcS.js → generate.runtime-BDVPJJbh.js} +6 -12
  39. package/dist/chunks/generate.runtime-BDVPJJbh.js.map +1 -0
  40. package/dist/chunks/{generate.runtime-CBVcsole.js → generate.runtime-BGLekCHZ.js} +2 -2
  41. package/dist/chunks/{generate.runtime-CBVcsole.js.map → generate.runtime-BGLekCHZ.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-PDnSxiek.js → generate.runtime-BKA41qV0.js} +6 -6
  43. package/dist/chunks/{generate.runtime-PDnSxiek.js.map → generate.runtime-BKA41qV0.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-DhSH1o8H.js → generate.runtime-BKsrh3ZN.js} +3 -3
  45. package/dist/chunks/{generate.runtime-DhSH1o8H.js.map → generate.runtime-BKsrh3ZN.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-BXNBWGYr.js → generate.runtime-BL7O2fy8.js} +2 -2
  47. package/dist/chunks/{generate.runtime-BXNBWGYr.js.map → generate.runtime-BL7O2fy8.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-VMTLHWLk.js → generate.runtime-BOtYaNA5.js} +55 -60
  49. package/dist/chunks/generate.runtime-BOtYaNA5.js.map +1 -0
  50. package/dist/chunks/{generate.runtime-bsuqrKOm.js → generate.runtime-BY5VmBG4.js} +2 -2
  51. package/dist/chunks/{generate.runtime-bsuqrKOm.js.map → generate.runtime-BY5VmBG4.js.map} +1 -1
  52. package/dist/chunks/{generate.runtime-Dm7IEo2h.js → generate.runtime-BYhWm9JA.js} +5 -5
  53. package/dist/chunks/{generate.runtime-Dm7IEo2h.js.map → generate.runtime-BYhWm9JA.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-D9OC1RXu.js → generate.runtime-BmdO8oKV.js} +2 -2
  55. package/dist/chunks/{generate.runtime-D9OC1RXu.js.map → generate.runtime-BmdO8oKV.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-BROXlbeJ.js → generate.runtime-C7NexMXs.js} +3 -3
  57. package/dist/chunks/{generate.runtime-BROXlbeJ.js.map → generate.runtime-C7NexMXs.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-wiWdXXPi.js → generate.runtime-CFSBH8yG.js} +6 -6
  59. package/dist/chunks/{generate.runtime-wiWdXXPi.js.map → generate.runtime-CFSBH8yG.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-ZgLxGWuy.js → generate.runtime-CG3udLj8.js} +3 -3
  61. package/dist/chunks/{generate.runtime-ZgLxGWuy.js.map → generate.runtime-CG3udLj8.js.map} +1 -1
  62. package/dist/chunks/{generate.runtime-DuAYqKxl.js → generate.runtime-CGbSe_nd.js} +2 -2
  63. package/dist/chunks/{generate.runtime-DuAYqKxl.js.map → generate.runtime-CGbSe_nd.js.map} +1 -1
  64. package/dist/chunks/{generate.runtime-BU-4sjyu.js → generate.runtime-CI_rUVZo.js} +110 -113
  65. package/dist/chunks/generate.runtime-CI_rUVZo.js.map +1 -0
  66. package/dist/chunks/{generate.runtime-CCaCaXNu.js → generate.runtime-COo85dGX.js} +2 -2
  67. package/dist/chunks/{generate.runtime-CCaCaXNu.js.map → generate.runtime-COo85dGX.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-DLoYscQO.js → generate.runtime-CTQvLaU0.js} +3 -3
  69. package/dist/chunks/{generate.runtime-DLoYscQO.js.map → generate.runtime-CTQvLaU0.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-TQmspB4Z.js → generate.runtime-Cc5Aw1zc.js} +27 -34
  71. package/dist/chunks/generate.runtime-Cc5Aw1zc.js.map +1 -0
  72. package/dist/chunks/{generate.runtime-B7XOa9_A.js → generate.runtime-CnGVlvxN.js} +3 -3
  73. package/dist/chunks/{generate.runtime-B7XOa9_A.js.map → generate.runtime-CnGVlvxN.js.map} +1 -1
  74. package/dist/chunks/{generate.runtime-sjFAWbZc.js → generate.runtime-Cqbsn5Ov.js} +7 -7
  75. package/dist/chunks/{generate.runtime-sjFAWbZc.js.map → generate.runtime-Cqbsn5Ov.js.map} +1 -1
  76. package/dist/chunks/{generate.runtime-Cm75waRD.js → generate.runtime-CtV9Gn9T.js} +2 -2
  77. package/dist/chunks/{generate.runtime-Cm75waRD.js.map → generate.runtime-CtV9Gn9T.js.map} +1 -1
  78. package/dist/chunks/{generate.runtime-UtkANHk1.js → generate.runtime-Cxa24AOd.js} +3 -3
  79. package/dist/chunks/{generate.runtime-UtkANHk1.js.map → generate.runtime-Cxa24AOd.js.map} +1 -1
  80. package/dist/chunks/generate.runtime-CyteiEzT.js +169 -0
  81. package/dist/chunks/generate.runtime-CyteiEzT.js.map +1 -0
  82. package/dist/chunks/{generate.runtime-BlEy2fFF.js → generate.runtime-D7EETq9M.js} +3 -3
  83. package/dist/chunks/{generate.runtime-BlEy2fFF.js.map → generate.runtime-D7EETq9M.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-nXjFqHyb.js → generate.runtime-DaJ4gLPv.js} +4 -4
  85. package/dist/chunks/{generate.runtime-nXjFqHyb.js.map → generate.runtime-DaJ4gLPv.js.map} +1 -1
  86. package/dist/chunks/{generate.runtime-D6l6uLiY.js → generate.runtime-DcBEbV-k.js} +2 -2
  87. package/dist/chunks/{generate.runtime-D6l6uLiY.js.map → generate.runtime-DcBEbV-k.js.map} +1 -1
  88. package/dist/chunks/{generate.runtime-B8-ORwxT.js → generate.runtime-DiAnQ9MW.js} +6 -6
  89. package/dist/chunks/{generate.runtime-B8-ORwxT.js.map → generate.runtime-DiAnQ9MW.js.map} +1 -1
  90. package/dist/chunks/{generate.runtime-Duw_JI_b.js → generate.runtime-Dp3x08St.js} +2 -2
  91. package/dist/chunks/{generate.runtime-Duw_JI_b.js.map → generate.runtime-Dp3x08St.js.map} +1 -1
  92. package/dist/chunks/{generate.runtime-D77ueFKY.js → generate.runtime-DsW0Q5S5.js} +118 -134
  93. package/dist/chunks/generate.runtime-DsW0Q5S5.js.map +1 -0
  94. package/dist/chunks/{generate.runtime-27KTIg_o.js → generate.runtime-DtcKbzOm.js} +48 -53
  95. package/dist/chunks/generate.runtime-DtcKbzOm.js.map +1 -0
  96. package/dist/chunks/{generate.runtime-DxyQqNpu.js → generate.runtime-ICaKVEuW.js} +5 -11
  97. package/dist/chunks/generate.runtime-ICaKVEuW.js.map +1 -0
  98. package/dist/chunks/{generate.runtime-CuvdtjKc.js → generate.runtime-SZInujfP.js} +2 -2
  99. package/dist/chunks/{generate.runtime-CuvdtjKc.js.map → generate.runtime-SZInujfP.js.map} +1 -1
  100. package/dist/chunks/gitignore-CPardo4E.js +139 -0
  101. package/dist/chunks/gitignore-CPardo4E.js.map +1 -0
  102. package/dist/chunks/{i18n-mnzzcYhz.js → i18n-C8OfN_nr.js} +2 -2
  103. package/dist/chunks/{i18n-mnzzcYhz.js.map → i18n-C8OfN_nr.js.map} +1 -1
  104. package/dist/chunks/{modify-file-CgJIza72.js → modify-file-DvIwtj4o.js} +3 -3
  105. package/dist/chunks/{modify-file-CgJIza72.js.map → modify-file-DvIwtj4o.js.map} +1 -1
  106. package/dist/chunks/pocketbase-Ir-TPv7H.js +232 -0
  107. package/dist/chunks/pocketbase-Ir-TPv7H.js.map +1 -0
  108. package/dist/chunks/{providers-CDUFaOeQ.js → providers-B386TYCN.js} +3 -3
  109. package/dist/chunks/{providers-CDUFaOeQ.js.map → providers-B386TYCN.js.map} +1 -1
  110. package/dist/chunks/{providers-tjlFH5di.js → providers-DrK_hjSr.js} +2 -2
  111. package/dist/chunks/{providers-tjlFH5di.js.map → providers-DrK_hjSr.js.map} +1 -1
  112. package/dist/chunks/route-BJBV1DtX.js +162 -0
  113. package/dist/chunks/route-BJBV1DtX.js.map +1 -0
  114. package/dist/chunks/schema-DSNYWlel.js +116 -0
  115. package/dist/chunks/schema-DSNYWlel.js.map +1 -0
  116. package/dist/chunks/shared-BofFBVmT.js +1182 -0
  117. package/dist/chunks/shared-BofFBVmT.js.map +1 -0
  118. package/dist/chunks/{shared-BjTRQ5QH.js → shared-CZHopdly.js} +3 -3
  119. package/dist/chunks/{shared-BjTRQ5QH.js.map → shared-CZHopdly.js.map} +1 -1
  120. package/dist/chunks/{site-C8Wcg6LT.js → site-B9-emR6D.js} +3 -3
  121. package/dist/chunks/{site-C8Wcg6LT.js.map → site-B9-emR6D.js.map} +1 -1
  122. package/dist/chunks/{table-core-RvMjoXpT.js → table-core-CHsfbi-n.js} +3 -3
  123. package/dist/chunks/{table-core-RvMjoXpT.js.map → table-core-CHsfbi-n.js.map} +1 -1
  124. package/dist/chunks/test-setup-jqVMmL83.js +103 -0
  125. package/dist/chunks/test-setup-jqVMmL83.js.map +1 -0
  126. package/dist/chunks/{ui-CE-8llQS.js → ui-BUhkIHse.js} +3 -3
  127. package/dist/chunks/{ui-CE-8llQS.js.map → ui-BUhkIHse.js.map} +1 -1
  128. package/dist/chunks/{util-ILWdjRAd.js → util-mXrQ89nG.js} +8 -2
  129. package/dist/chunks/util-mXrQ89nG.js.map +1 -0
  130. package/dist/chunks/{whatsapp-DT10x76l.js → whatsapp-DFZUsKWe.js} +2 -2
  131. package/dist/chunks/{whatsapp-DT10x76l.js.map → whatsapp-DFZUsKWe.js.map} +1 -1
  132. package/dist/chunks/write-result-Bkdkp7u2.js +539 -0
  133. package/dist/chunks/write-result-Bkdkp7u2.js.map +1 -0
  134. package/dist/index.d.ts +81 -0
  135. package/dist/index.js +2387 -3275
  136. package/dist/index.js.map +1 -1
  137. package/package.json +3 -3
  138. package/dist/chunks/collections-B_-NTtLW.js.map +0 -1
  139. package/dist/chunks/constants-CTp-0HKk.js.map +0 -1
  140. package/dist/chunks/generate-JkvSNTy-.js.map +0 -1
  141. package/dist/chunks/generate.runtime-27KTIg_o.js.map +0 -1
  142. package/dist/chunks/generate.runtime-BU-4sjyu.js.map +0 -1
  143. package/dist/chunks/generate.runtime-D77ueFKY.js.map +0 -1
  144. package/dist/chunks/generate.runtime-Dn0_y2iV.js +0 -161
  145. package/dist/chunks/generate.runtime-Dn0_y2iV.js.map +0 -1
  146. package/dist/chunks/generate.runtime-DxyQqNpu.js.map +0 -1
  147. package/dist/chunks/generate.runtime-RTGpwxcS.js.map +0 -1
  148. package/dist/chunks/generate.runtime-TQmspB4Z.js.map +0 -1
  149. package/dist/chunks/generate.runtime-VMTLHWLk.js.map +0 -1
  150. package/dist/chunks/pocketbase-S8lUt0nI.js +0 -219
  151. package/dist/chunks/pocketbase-S8lUt0nI.js.map +0 -1
  152. package/dist/chunks/test-setup-CpjhQSl-.js +0 -176
  153. package/dist/chunks/test-setup-CpjhQSl-.js.map +0 -1
  154. package/dist/chunks/util-ILWdjRAd.js.map +0 -1
  155. package/dist/chunks/write-result-BguSfKV-.js +0 -499
  156. package/dist/chunks/write-result-BguSfKV-.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-DxyQqNpu.js","names":["getLogger","languageFromPath","createCollectionIdempotent","applyCollectionRulePatches","migrationDelay","getMigrationFile","modifyOutcomeToFile","modifyUtils","dedent","SvelteFile","withInMemoryScript","formatLikeSource","ensureImports","NOTIFICATION_RULE_PATCHES","fs","path","BELL_SNIPPET","IMPORT_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","modifyAppLayout","layoutPath","file","out","source","sf","FETCH_STATEMENT","NOTIFICATIONS_STATEMENT","DEPENDS_STATEMENT","modifyLayoutServer","layoutServerPath","snippet","originalSource","sourceFile","Project","addProperty","obj","name","initializer","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","elementNames","el","hasDepends","hasLocals","existingParts","parts","currentName","body","blockBody","statements","declaresVar","stmt","d","hasDependsCall","ce","args","argText","hasNotificationsList","hasNotifications","returnIdx","s","insertAt","augmentReturnObject","augmentReturns","expr","ret","inner","arrowBody","bodyExpr","fnBody","pushMigrationCreates","created","migrationFile","collectionName","options","creates","generate","logger","withPocketbase","userCollection","pb","create","spec","result","ruleMigrations","modifies","pushResult","appLayoutPath","appLayoutServerPath","utilsPath"],"sources":["../../src/patterns/enable/notifications/modifies/modify-app-layout.ts","../../src/patterns/enable/notifications/modifies/+layout.server.ts","../../src/patterns/enable/notifications/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BELL_SNIPPET = `\n\t\t<div class=\"ml-auto px-4\">\n\t\t\t<NotificationsBell />\n\t\t</div>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import NotificationsBell from '#lib/components/notifications-bell.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the notifications bell inside the (app) layout's <header>.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with a <header> that includes the bell.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nexport function modifyAppLayout(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"NotificationsBell\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"NotificationsBell\",\n moduleSpecifier: \"#lib/components/notifications-bell.svelte\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"header\", BELL_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FETCH_STATEMENT = dedent`\n const notificationsList = await locals.pb\n .collection(\"notifications\")\n .getList(1, 5, {\n filter: \\`user = \"\\${locals.pb.authStore.record!.id}\" && read = false\\`,\n sort: \"-created\",\n });\n`;\n\nconst NOTIFICATIONS_STATEMENT =\n \"const notifications = { count: notificationsList.totalItems, items: notificationsList.items };\";\n\nconst DEPENDS_STATEMENT = 'depends(\"app:notifications\");';\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n ${FETCH_STATEMENT}\n ${NOTIFICATIONS_STATEMENT}\n ${DEPENDS_STATEMENT}\n return { notifications };\n };\n `;\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n if (obj.getProperty(name)) return;\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n if (vs?.hasExportKeyword()) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n\n if (!loadArrow && !loadFn) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) loadFn = maybeFn;\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n FETCH_STATEMENT,\n NOTIFICATIONS_STATEMENT,\n DEPENDS_STATEMENT,\n \"return { notifications };\",\n ],\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike = (loadArrow ?? loadFn!) as\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression;\n\n // Ensure first param destructures { locals, depends }\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const elementNames = obp.getElements().map((el) => el.getName());\n const hasDepends = elementNames.includes(\"depends\");\n const hasLocals = elementNames.includes(\"locals\");\n\n if (!hasDepends || !hasLocals) {\n const existingParts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const parts: string[] = hasLocals ? [] : [\"locals\"];\n parts.push(...existingParts);\n if (!hasDepends) parts.push(\"depends\");\n first.set({\n name: `{ ${parts.join(\", \")} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) loadArrow.setIsAsync(true);\n else if (loadFn && !loadFn.isAsync()) loadFn.setIsAsync(true);\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const declaresVar = (name: string) =>\n statements.some((stmt) => {\n if (stmt.getKind() !== SyntaxKind.VariableStatement) return false;\n return (stmt as import(\"ts-morph\").VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === name);\n });\n\n const hasDependsCall = statements.some(\n (stmt) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt.getDescendantsOfKind(SyntaxKind.CallExpression).some((ce) => {\n if (ce.getExpression().getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:notifications'\" ||\n argText === '\"app:notifications\"')\n );\n }),\n );\n\n const hasNotificationsList = declaresVar(\"notificationsList\");\n const hasNotifications = declaresVar(\"notifications\");\n\n const returnIdx = statements.findIndex(\n (s) => s.getKind() === SyntaxKind.ReturnStatement,\n );\n let insertAt = returnIdx >= 0 ? returnIdx : statements.length;\n\n if (!hasNotificationsList) {\n blockBody.insertStatements(insertAt, FETCH_STATEMENT);\n insertAt++;\n }\n if (!hasNotifications) {\n blockBody.insertStatements(insertAt, NOTIFICATIONS_STATEMENT);\n insertAt++;\n }\n if (!hasDependsCall) {\n blockBody.insertStatements(insertAt, DEPENDS_STATEMENT);\n }\n }\n\n const augmentReturnObject = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n ) => {\n addProperty(obj, \"notifications\", \"notifications\");\n };\n\n const augmentReturns = (target: import(\"ts-morph\").Node) => {\n const returns = target.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n });\n };\n\n if (loadArrow) {\n const arrowBody = loadArrow.getBody();\n if (arrowBody.getKind() === SyntaxKind.Block) {\n augmentReturns(arrowBody);\n } else {\n const bodyExpr = arrowBody as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n bodyExpr as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) augmentReturns(fnBody);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { NOTIFICATION_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating notifications collection\");\n const result = await create({\n name: \"notifications\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"user\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"title\",\n type: \"text\",\n required: true,\n },\n {\n name: \"body\",\n type: \"text\",\n },\n {\n name: \"read\",\n type: \"bool\",\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n indexes: [\n \"CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"notifications\",\n options,\n result.created,\n );\n\n logger.info(\"Applying notifications rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n NOTIFICATION_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Modifying utils.ts\");\n const utilsPath = path.join(options.root, \"src\", \"lib\", \"utils.ts\");\n pushResult(modifyOutcomeToFile(utilsPath, modifyUtils(utilsPath)));\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;AASA,IAAMgB,IAAe,2EAMfC,IAAiB,CAAM;;GAIvBC,IAAe;CACnB;CACA;CACA;CACA;CACAD;CACA;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI,GAELG,IAAiB;CACrB;CACA;CACA;CACA;CACAF;CACA;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgBI,EAAgB,GAAmC;CACjE,IAAI,CAACN,EAAG,WAAWO,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAASF;CAAe;CAGxD,IAAMG,IAAOb,EAAW,SAASY,CAAU;CAsB3C,OArBKC,EAAK,WAAW,QAAQ,IAGzBA,EAAK,WAAW,mBAAmB,IAC9B;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7CA,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQC,MAAQb,EAAmBc,IAAS,MAAO;GACzD,EAAcC,GAAI,CAChB;IACE,eAAe;IACf,iBAAiB;GACnB,CACF,CAAC;EACH,CAAC;EACD,OAAOF;CAC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ACE9F,EAAoB+F,GAAejF,EAAgBiF,CAAa,CAAC,CACnE,GAEAV,EAAO,KAAK,mCAAmC;CAC/C,IAAMW,IAAsBvF,EAAK,KAC/ByE,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAQA,AAPAY,EACE9F,EACEgG,GACAzE,EAAmByE,CAAmB,CACxC,CACF,GAEAX,EAAO,KAAK,oBAAoB;CAChC,IAAMY,IAAYxF,EAAK,KAAKyE,EAAQ,MAAM,OAAO,OAAO,UAAU;CAGlE,OAFAY,EAAW9F,EAAoBiG,GAAWhG,EAAYgG,CAAS,CAAC,CAAC,GAE1D;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-RTGpwxcS.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","NOT_FOUND_HINT","getLogger","languageFromPath","createCollectionIdempotent","applyCollectionRulePatches","migrationDelay","getMigrationFile","modifyOutcomeToFile","ensureSiteFile","SvelteFile","withInMemoryScript","formatLikeSource","ensureImports","addNavItemToScript","dedent","TEAM_RULE_PATCHES","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$2","modifyAppLayoutSvelte","layoutPath","file","NEW_HEADER","IMPORT_SNIPPET","LEGACY_NAME","FAILURE_HINT$1","NOT_FOUND_HINT$1","updateAppSidebarScript","out","source","legacyName","sf","decl","init","nameNode","SyntaxKind","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","appSidebarPath","modifyLayoutServer","layoutServerPath","snippet","originalSource","sourceFile","Project","addProperty","obj","name","initializer","loadArrow","loadFn","varDecl","directArrow","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","obp","hasDepends","el","hasLocals","parts","tail","currentName","body","blockBody","statements","hasTeam","stmt","id","hasTeams","hasDependsTeam","ce","args","argText","expr","ret","inner","bodyExpr","fnBody","TEAMS_NAV_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","addItemToNavUser","navUserSnippet","wasAdded","tryAdd","run","result","title","url","icon","iconImportPath","fn","modifyNavUser","navUserPath","newNavUserSnippet","pushMigrationCreates","created","migrationFile","collectionName","options","creates","generate","logger","withPocketbase","userCollection","pb","create","spec","teamsResult","teamsCollection","teamMembershipsResult","teamMembershipsCollection","teamUsersResult","teamInvitesResult","teamInviteLinksResult","ruleMigrations","modifies","pushResult","appLayoutPath","siteFile"],"sources":["../../src/patterns/enable/teams/modifies/modify-app-layout.ts","../../src/patterns/enable/teams/modifies/modify-app-sidebar.ts","../../src/patterns/enable/teams/modifies/+layout.server.ts","../../src/patterns/enable/teams/modifies/modify-nav-user.ts","../../src/patterns/enable/teams/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass team props to <AppSidebar> in your app layout:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app layout that renders <AppSidebar> with team props:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(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(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"teams\")) {\n return { status: \"success\", changed: false };\n }\n\n file.appendToAttributes(\n \"AppSidebar\",\n \" team={data.team} teams={data.teams ?? []}\",\n );\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEW_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<TeamSwitcher {teams}>\n\t\t\t\t{#snippet children()}\n\t\t\t\t\t{@const activeTeam = teams.find((t) => t.id === team)}\n\t\t\t\t\t{#if activeTeam}\n\t\t\t\t\t\t<Avatar.Root class=\"size-8 rounded-lg\">\n\t\t\t\t\t\t\t<Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{:else}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<img src={favicon} alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{site.name}</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t\t<ChevronsUpDownIcon class=\"ml-auto\" />\n\t\t\t\t{/snippet}\n\t\t\t</TeamSwitcher>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\nconst IMPORT_SNIPPET = [\n \"import favicon from '#lib/assets/favicon.svg';\",\n \"import TeamSwitcher from '#lib/components/team-switcher.svelte';\",\n \"import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\",\n \"import * as Avatar from '#lib/components/ui/avatar/index.js';\",\n \"import { site } from '#lib/site.js';\",\n].join(\"\\n\");\n\n/**\n * A sidebar from before `#lib/site.js` names the app with a `meta` prop. Keep\n * whichever the header already uses, so an older project stays consistent.\n */\nconst LEGACY_NAME = \"{meta.appName}\";\n\nconst FAILURE_HINT = [\n \"Replace the <Sidebar.Header> in your app sidebar with the team switcher.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Props to destructure in $props(): team, teams = []\",\n \"\",\n \"Markup to use as the header:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app sidebar with a <Sidebar.Header> containing the team switcher.\",\n \"\",\n \"Imports:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Header markup:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nfunction updateAppSidebarScript(source: string, legacyName: boolean): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n if (!legacyName) {\n ensureImports(sf, [\n { namedImports: [\"site\"], moduleSpecifier: \"#lib/site.js\" },\n ]);\n }\n ensureImports(sf, [\n {\n defaultImport: \"favicon\",\n moduleSpecifier: \"#lib/assets/favicon.svg\",\n },\n {\n defaultImport: \"TeamSwitcher\",\n moduleSpecifier: \"#lib/components/team-switcher.svelte\",\n },\n {\n defaultImport: \"ChevronsUpDownIcon\",\n moduleSpecifier: \"@lucide/svelte/icons/chevrons-up-down\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"#lib/components/ui/avatar/index.js\",\n },\n ]);\n\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n\n if (elements.some((e) => e.getName() === \"team\")) continue;\n\n // Type changes first — name change can shift positions and invalidate type node refs.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^team\\b/.test(t))) break;\n propTexts.push(\n \"team?: string | undefined\",\n \"teams?: { id: string; name: string }[]\",\n );\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Rebuild binding pattern: insert team, teams = [] before first rest/initializer element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elements.length;\n elementTexts.splice(insertIdx, 0, \"team\", \"teams = []\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n }\n formatLikeSource(sf);\n });\n return out;\n}\n\nexport function modifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasElement(\"Sidebar.Header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const legacyName = file.toString().includes(LEGACY_NAME);\n file.modifyScript((source) => updateAppSidebarScript(source, legacyName));\n file.replaceElement(\n \"Sidebar.Header\",\n legacyName ? NEW_HEADER.replace(\"{site.name}\", LEGACY_NAME) : NEW_HEADER,\n );\n file.writeTo(appSidebarPath);\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\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n const team = locals.team;\n const teams = await locals.pb.collection(\"teams\").getFullList();\n depends(\"app:team\");\n\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n return { user, team, teams, breadcrumbs };\n };\n `;\n\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n const hasProperty = !!obj.getProperty(name);\n if (!hasProperty) {\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n 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 (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n \"const user = locals.pb.authStore.record!;\",\n \"const team = locals.team;\",\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n 'depends(\"app:team\");',\n \"\",\n 'const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];',\n \"return { user, team, teams, breadcrumbs };\",\n ],\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasDepends = obp\n .getElements()\n .some((el) => el.getName() === \"depends\");\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n\n if (!hasDepends) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n\n if (hasLocals) {\n first.set({\n name: `{ depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) {\n loadArrow.setIsAsync(true);\n } else if (loadFn && !loadFn.isAsync()) {\n loadFn.setIsAsync(true);\n }\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const hasTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id: import(\"ts-morph\").Identifier) => id.getText() === \"team\"),\n );\n\n const hasTeams = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id: import(\"ts-morph\").Identifier) => id.getText() === \"teams\",\n ),\n );\n\n const hasDependsTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((ce: import(\"ts-morph\").CallExpression) => {\n const expr = ce.getExpression();\n if (expr.getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:team'\" || argText === '\"app:team\"')\n );\n }),\n );\n\n if (!hasTeam) {\n blockBody.insertStatements(1, \"const team = locals.team;\");\n }\n\n if (!hasTeams) {\n blockBody.insertStatements(\n 2,\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n );\n }\n\n if (!hasDependsTeam) {\n blockBody.insertStatements(3, 'depends(\"app:team\");');\n }\n }\n\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 const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n } else {\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = bodyExpr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) {\n const returns = fnBody.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\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 const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\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 TEAMS_NAV_SNIPPET = [\n \"import UsersIcon from '@lucide/svelte/icons/users';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Teams', url: '/teams', icon: UsersIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Teams nav item to nav-user.svelte:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Teams entry:\",\n \"\",\n TEAMS_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(\"/teams\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Teams\",\n \"/teams\",\n \"UsersIcon\",\n \"@lucide/svelte/icons/users\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { TEAM_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n // Wait so the next schema op lands in a different PocketBase timestamp second.\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) {\n return;\n }\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating teams collection\");\n const teamsResult = await create({\n name: \"teams\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"name\",\n type: \"text\",\n required: true,\n },\n {\n name: \"owner\",\n type: \"relation\",\n cascadeDelete: false,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n });\n const teamsCollection = teamsResult.collection;\n await pushMigrationCreates(creates, \"teams\", options, teamsResult.created);\n\n logger.info(\"Creating team_memberships collection\");\n const teamMembershipsResult = await create({\n name: \"team_memberships\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"user\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const teamMembershipsCollection = teamMembershipsResult.collection;\n await pushMigrationCreates(\n creates,\n \"team_memberships\",\n options,\n teamMembershipsResult.created,\n );\n\n logger.info(\"Creating team_users view\");\n const teamUsersResult = await create({\n name: \"team_users\",\n type: \"view\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"email\",\n exceptDomains: null,\n onlyDomains: null,\n // Accounts made with a phone number may have no email.\n required: false,\n type: \"email\",\n },\n {\n name: \"name\",\n max: 255,\n required: false,\n type: \"text\",\n },\n {\n name: \"membership_id\",\n cascadeDelete: false,\n collectionId: teamMembershipsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: false,\n type: \"relation\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n ],\n viewQuery:\n \"select users.id, users.email, users.name, team_memberships.id as membership_id, team_memberships.team, team_memberships.role from users join team_memberships on team_memberships.user = users.id;\",\n });\n await pushMigrationCreates(\n creates,\n \"team_users\",\n options,\n teamUsersResult.created,\n );\n\n logger.info(\"Creating team_invites collection\");\n const teamInvitesResult = await create({\n name: \"team_invites\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"team\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"email\",\n type: \"email\",\n required: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invites\",\n options,\n teamInvitesResult.created,\n );\n\n logger.info(\"Creating team_invite_links collection\");\n const teamInviteLinksResult = await create({\n name: \"team_invite_links\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n indexes: [\n \"CREATE UNIQUE INDEX `idx_9y3Oz1KVzz` ON `team_invite_links` (`team`)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invite_links\",\n options,\n teamInviteLinksResult.created,\n );\n\n logger.info(\"Applying team rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n TEAM_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerPath, modifyLayoutServer(layoutServerPath)),\n );\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Modifying app-sidebar\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user\");\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 // The invite and join pages and the sidebar header show `site.name`.\n const siteFile = await ensureSiteFile(options);\n if (siteFile) creates.push(siteFile);\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":";;;;;;;;;;;;;;AAIA,IAAMA,IAAe,mHAMfC,IAAiB;AAMvB,SAAgBsB,EAAsB,GAAmC;CACvE,IAAI,CAACJ,EAAG,WAAWK,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAASvB;CAAe;CAGxD,IAAMwB,IAAOb,EAAW,SAASY,CAAU;CAa3C,OAZKC,EAAK,WAAW,YAAY,IAG7BA,EAAK,aAAa,cAAc,OAAO,IAClC;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7CA,EAAK,mBACH,cACA,4CACF,GACAA,EAAK,QAAQD,CAAU,GAChB;EAAE,QAAQ;EAAW,SAASC,EAAK,WAAW;CAAE,KAX9C;EAAE,QAAQ;EAAU,SAASzB;CAAa;AAYrD;;ACzBA,IAAM0B,IAAa,ulCAgCbC,IAAiB,kSAYjBC,IAAc,kBAEd1B,IAAe;CACnB;CACA;CACA;CACA;CACAyB;CACA;CACA;CACA;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI,GAELvB,IAAiB;CACrB;CACA;CACA;CACA;CACAwB;CACA;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAASK,EAAuB,GAAgB,GAA6B;CAC3E,IAAM,EAAE,QAAQC,MAAQnB,EAAmBoB,IAAS,MAAO;EAMzD,AALKC,KACHnB,EAAcoB,GAAI,CAChB;GAAE,cAAc,CAAC,MAAM;GAAG,iBAAiB;EA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C,GAAgBD,EAAiBC,CAAc,CAAC,CACtE,GAEAqE,EAAO,KAAK,oBAAoB;CAChC,IAAMT,IAAc5F,EAAK,KACvBkG,EAAQ,MACR,OACA,OACA,cACA,iBACF;CACA,EAAW5G,EAAoBsG,GAAaD,EAAcC,CAAW,CAAC,CAAC;CAGvE,IAAM0B,IAAW,MAAM/H,EAAe2G,CAAO;CAG7C,OAFIoB,KAAUnB,EAAQ,KAAKmB,CAAQ,GAE5B;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-TQmspB4Z.js","names":["getLogger","withPocketbase","getMigrationFile","modifyOutcomeToFile","hasWhatsAppPlugin","writeWhatsAppConfigMigration","enableWhatsAppAuth","MIN_POCKETBASE_SERVER","fs","path","modifyTestSetup","setupPath","original","content","indent","head","tail","bodyIndent","value","fieldIndent","DOCS_URL","migrationCreate","file","generate","logger","options","creates","pb","setupWhatsAppFields","migrationDelay","configMigration","modifies","outcomes","swapAuthPages","filePath","outcome","testSetup","testSetupFile"],"sources":["../../src/patterns/enable/whatsapp/modifies/modify-test-setup.ts","../../src/patterns/enable/whatsapp/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * `email` turns optional on `users`, which the generated types follow, so a\n * test setup from before enable-backend handled that no longer type-checks:\n * its `authenticateUser` takes `{ email: string }` and it signs the test\n * user in with `context.user.email`. Brings those two spots up to the\n * current setup; anything else in the file is the project's own.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(setupPath, \"utf8\");\n let content = original;\n\n content = content.replace(\n /^([ \\t]*)(async function authenticateUser\\(agent: Agent, user: \\{ )email: string( \\}\\) \\{\\n)([ \\t]*)/m,\n (_, indent, head, tail, bodyIndent) =>\n `${indent}${head}email?: string${tail}` +\n `${bodyIndent}// Logs in with the password, so it needs the email (made optional by\\n` +\n `${bodyIndent}// enable-whatsapp, for accounts that sign in with a phone number).\\n` +\n `${bodyIndent}if (!user.email) {\\n` +\n `${bodyIndent}${bodyIndent.includes(\"\\t\") ? \"\\t\" : \" \"}throw new Error('authenticateUser needs a user with an email');\\n` +\n `${bodyIndent}}\\n` +\n bodyIndent,\n );\n\n // The user is made with a known email: sign in with that.\n content = content.replace(\n /^([ \\t]*)context\\.user = await context\\.admin\\.collection\\('users'\\)\\.create\\(\\{\\n([ \\t]*)email: (`test-\\$\\{Math\\.random\\(\\)\\.toString\\(36\\)\\.slice\\(2\\)\\}@example\\.com`),/m,\n (_, indent, fieldIndent, value) =>\n `${indent}const email = ${value};\\n` +\n `${indent}context.user = await context.admin.collection('users').create({\\n` +\n `${fieldIndent}email,`,\n );\n if (content.includes(\"const email = `test-\")) {\n content = content.replace(\n \".authWithPassword(context.user.email, testUserPassword)\",\n \".authWithPassword(email, testUserPassword)\",\n );\n }\n\n if (content === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(setupPath, content, \"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 getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n MIN_POCKETBASE_SERVER,\n enableWhatsAppAuth,\n hasWhatsAppPlugin,\n setupWhatsAppFields,\n writeWhatsAppConfigMigration,\n} from \"./runtime/whatsapp\";\nimport { swapAuthPages } from \"./modifies/auth-pages\";\nimport { modifyTestSetup } from \"./modifies/modify-test-setup\";\n\nexport const DOCS_URL = \"https://velastack.dev/docs/enable/whatsapp\";\n\nfunction migrationCreate(file: string): File {\n return {\n path: file,\n language: \"js\",\n content: fs.readFileSync(file, \"utf8\"),\n status: \"success\",\n };\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n if (!(await hasWhatsAppPlugin(pb))) {\n throw new Error(\n `This PocketBase has no WhatsApp sign-in. It comes with pocketbase-server ${MIN_POCKETBASE_SERVER} and later: run \\`npm install -D pocketbase-server@^${MIN_POCKETBASE_SERVER}\\`, then \\`vela enable whatsapp\\` again.`,\n );\n }\n\n logger.info(\"Adding the phone fields to users and making email optional\");\n if (await setupWhatsAppFields(pb)) {\n await migrationDelay();\n const file = getMigrationFile(\"users\", \"updated\", options);\n if (file) creates.push(migrationCreate(file));\n }\n\n logger.info(\"Turning on WhatsApp sign-in for users\");\n await enableWhatsAppAuth(pb);\n await migrationDelay();\n const configMigration = writeWhatsAppConfigMigration(options, true);\n if (configMigration) creates.push(migrationCreate(configMigration));\n });\n\n logger.info(\"Adding WhatsApp to the login and signup pages\");\n const modifies: File[] = [];\n const outcomes = await swapAuthPages(\n options.root,\n \"enable\",\n (filePath) =>\n `${path.relative(options.root, filePath)} is not the page enable-auth wrote, so it was left as it is. Add the WhatsApp option to it by hand: ${DOCS_URL}`,\n );\n for (const [filePath, outcome] of outcomes) {\n const file = modifyOutcomeToFile(filePath, outcome);\n if (file) modifies.push(file);\n }\n\n logger.info(\"Updating test/setup.ts for an optional email\");\n const testSetup = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetup,\n modifyTestSetup(testSetup),\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":";;;;;;;;AAUA,SAAgBU,EAAgB,GAAkC;CAChE,IAAI,CAACF,EAAG,WAAWG,CAAS,GAC1B,OAAO;EAAE,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AAO,KAAK,uCAAuC,GACnD,MAAMlB,EAAmBqB,CAAE,GAC3B,MAAME,EAAe;EACrB,IAAMC,IAAkBzB,EAA6BoB,GAAS,EAAI;EAClE,AAAIK,KAAiBJ,EAAQ,KAAKL,EAAgBS,CAAe,CAAC;CACpE,CAAC,GAEDN,EAAO,KAAK,+CAA+C;CAC3D,IAAMO,IAAmB,CAAC,GACpBC,IAAW,MAAMC,EACrBR,EAAQ,MACR,WACC,MACC,GAAGhB,EAAK,SAASgB,EAAQ,MAAMS,CAAQ,EAAE,sGAAsGd,GACnJ;CACA,KAAK,IAAM,CAACc,GAAUC,MAAYH,GAAU;EAC1C,IAAMV,IAAOnB,EAAoB+B,GAAUC,CAAO;EAClD,AAAIb,KAAMS,EAAS,KAAKT,CAAI;CAC9B;CAEA,EAAO,KAAK,8CAA8C;CAC1D,IAAMc,IAAY3B,EAAK,KAAKgB,EAAQ,MAAM,QAAQ,UAAU,GACtDY,IAAgBlC,EACpBiC,GACA1B,EAAgB0B,CAAS,CAC3B;CAGA,OAFIC,KAAeN,EAAS,KAAKM,CAAa,GAEvC;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-VMTLHWLk.js","names":["__import_glob__0_0_","__import_glob__0_1_","envEditsFor","currency_server_test_default","META","currency_server_default","getLogger","resolveProvider","suppliedProviderEnv","languageFromPath","mergeResults","filesFromGlob","modifyOutcomeToFile","modifyEnv","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyLayoutServerCurrency","modifyLayoutSvelteCurrency","modifyHooksServerCurrency","modifyRootLayoutCurrencySelect","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","dedent","withPocketbase","migrationDelay","getMigrationFile","ensureCollectionFields","createCollectionIdempotent","modifyNavUser","modifyUserSignup","_taggedTemplateLiteral","InvalidArgumentError","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","fs","path","Stripe","setupShopify","logger","options","variantId","creates","syncUsersToStripeCustomers","stripe","stripeSecretKey","users","pb","existing","linkedUserIds","c","result","user","matching","label","customer","isExistingCustomer","error","paymentMethods","paymentMethod","defaultPaymentMethod","createTestProductAndPrice","products","product","prices","getProductAndPriceById","price","priceId","_templateObject","pushMigrationCreates","created","migrationFile","collectionName","action","paymentPageSnippet","setupStripe","stripePriceId","isAppMode","modifies","pushResult","file","create","spec","customersResult","stripeCustomersCollection","paymentMethodsResult","stripePaymentMethodsCollection","transactionsResult","syncResult","navUserPath","userSignupPath","setupWhatsApp","business","given","wuchaleConfig","edit","createsServerRaw","serverCreates","unitTests","a","b","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","providerEnvVars","siteExisted","siteFile","currency","country","currencies","layoutPath","layoutServerPath","layoutServer","hooksServerPath","rootLayoutPath","env","setup"],"sources":["../../src/patterns/enable/payments/runtime/setup-shopify.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/runtime/setup-stripe.ts","../../src/patterns/enable/payments/runtime/setup-whatsapp.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import type { Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { buyPageSnippet } from \"../shopify-page\";\n\n/**\n * Shopify keeps products, customers and checkout on its side, so past the env\n * there is only the demo page, and only when a variant to sell was given.\n */\nexport async function setupShopify(options: Options) {\n const logger = getLogger(options);\n const variantId =\n typeof options.input.demoId === \"string\" ? options.input.demoId.trim() : \"\";\n\n const creates = [];\n if (variantId) {\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: buyPageSnippet(variantId),\n status: \"success\" as const,\n });\n }\n\n return {\n creates,\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb.collection(\"users\").getFullList<{\n id: string;\n email?: string;\n name?: string;\n phone?: string;\n }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n // A user made with a phone number may have no email to match on.\n const matching = user.email\n ? await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n })\n : { data: [] };\n const label = user.email || user.id;\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${label}`);\n } else {\n customer = await stripe.customers.create(\n user.email\n ? { email: user.email }\n : { name: user.name || undefined, phone: user.phone || undefined },\n );\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${label}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${label}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { suppliedProviderEnv } from \"../../../../core/providers\";\nimport { languageFromPath } from \"../../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../../runtime/pocketbase\";\nimport {\n createCollectionIdempotent,\n ensureCollectionFields,\n} from \"../../../../runtime/collections\";\nimport { STRIPE_PRICES, STRIPE_PRODUCTS } from \"./collections\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport { modifyNavUser } from \"../modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"../modifies/modify-user-signup\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '#lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\n/**\n * Everything Stripe needs past its env: the catalog and customer collections,\n * the existing users as Stripe customers, a product/price for the demo page,\n * and, with auth, the billing nav item and the signup link to Stripe.\n */\nexport async function setupStripe(options: Options) {\n const stripeSecretKey = suppliedProviderEnv(options).STRIPE_SECRET_KEY ?? \"\";\n const stripePriceId =\n typeof options.input.demoId === \"string\" && options.input.demoId !== \"\"\n ? options.input.demoId\n : undefined;\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n // The catalog: created, or, when a project enabled payments before a\n // field existed, brought up to the spec (the next sync fills the field).\n for (const spec of [STRIPE_PRODUCTS, STRIPE_PRICES]) {\n logger.info(`Creating ${spec.name} collection`);\n const result = await create(spec);\n await pushMigrationCreates(\n creates,\n spec.name,\n \"created\",\n options,\n result.created,\n );\n if (!result.created) {\n creates.push(\n ...(await ensureCollectionFields(pb, spec, options, logger)),\n );\n }\n }\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, modifyUserSignup(userSignupPath)),\n );\n }\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { InvalidArgumentError } from \"../../../../core/errors\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport type { SiteBusiness } from \"../../../../runtime/site\";\nimport {\n modifyWuchaleJsFiles,\n TRANSLATED_LIB_FILES,\n} from \"../../../../runtime/wuchale-config\";\n\n/**\n * WhatsApp keeps nothing past the env: orders go to the business's chat, and\n * the hosted form they are recorded to is created by the CLI. Every price is\n * in `site.currency`, so a project without one can't take orders: `business`\n * is what `src/lib/site.ts` declares after the shared step wrote it.\n */\nexport async function setupWhatsApp(options: Options, business: SiteBusiness) {\n if (!business.currency) {\n const given = options.input.currency;\n throw new InvalidArgumentError(\n given === undefined || given === \"\"\n ? \"Payments on WhatsApp need the business's currency, the one it prices in (an ISO 4217 code such as MXN or EUR). Pass --currency, or set `currency` in src/lib/site.ts.\"\n : `${String(given)} is not an ISO 4217 currency code, such as MXN or EUR.`,\n );\n }\n const modifies: File[] = [];\n\n // The order message is text a visitor sends, so with wuchale on it is\n // translated like the pages: the js adapter has to be told about the module.\n const wuchaleConfig = path.join(options.root, \"wuchale.config.js\");\n if (fs.existsSync(wuchaleConfig)) {\n getLogger(options).info(\"Adding src/lib/order.ts to wuchale's js adapter\");\n const edit = modifyOutcomeToFile(\n wuchaleConfig,\n modifyWuchaleJsFiles(wuchaleConfig, TRANSLATED_LIB_FILES),\n );\n if (edit) modifies.push(edit);\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","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 providerEnvVars,\n resolveProvider,\n suppliedProviderEnv,\n} from \"../../../core/providers\";\nimport { filesFromGlob, mergeResults } from \"../../../core/util\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnv } from \"../../../runtime/env\";\nimport {\n ensureSiteBusiness,\n normalizeCountry,\n normalizeCurrencies,\n normalizeCurrency,\n sitePath,\n} from \"../../../runtime/site\";\nimport { envEditsFor, META } from \"./generate\";\nimport { modifyHooksServerCurrency } from \"./modifies/hooks.server\";\nimport { modifyLayoutServerCurrency } from \"./modifies/layout.server\";\nimport { modifyLayoutSvelteCurrency } from \"./modifies/layout.svelte\";\nimport { modifyRootLayoutCurrencySelect } from \"./modifies/root-layout.svelte\";\nimport { setupShopify } from \"./runtime/setup-shopify\";\nimport { setupStripe } from \"./runtime/setup-stripe\";\nimport { setupWhatsApp } from \"./runtime/setup-whatsapp\";\n\nconst createsServerRaw = import.meta.glob<string>(\"./creates-server/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The server half of the currency store, for a project with a server load. */\nexport function serverCreates(unitTests: boolean): File[] {\n return Object.values(filesFromGlob(createsServerRaw, \"./creates-server/\"))\n .filter((file) => unitTests || !file.path.endsWith(\".test.ts\"))\n .sort((a, b) => a.path.localeCompare(b.path));\n}\n\n/** Whether the project can run a unit test (`vitest` in package.json). */\nexport function hasVitest(root: string): boolean {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return Boolean(pkg.devDependencies?.vitest || pkg.dependencies?.vitest);\n } catch {\n return false;\n }\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const provider = resolveProvider(META, options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(`Writing ${provider.label} credentials to .env`);\n const envPath = path.join(options.root, \".env\");\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnv(envPath, envEditsFor(provider, suppliedProviderEnv(options))),\n ),\n );\n\n // SvelteKit 3 exposes only declared variables, and only `public: true`\n // ones through `$app/env/public`.\n logger.info(`Declaring ${provider.label} variables in src/env.ts`);\n const envVars = modifyEnvVarsFiles(options.root, providerEnvVars(provider));\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n // What the business declares in src/lib/site.ts: the currency it prices\n // in, the country it is in, and the other currencies it shows prices in.\n // Asked for by the CLI; a value already there is kept.\n const { currency, country, currencies } = options.input;\n const siteExisted = fs.existsSync(sitePath(options.root));\n const { file: siteFile, business } = await ensureSiteBusiness(options, {\n currency: normalizeCurrency(currency) ?? undefined,\n country: normalizeCountry(country) ?? undefined,\n currencies:\n normalizeCurrencies(\n currencies,\n normalizeCurrency(currency) ?? undefined,\n ) ?? undefined,\n });\n if (siteFile) (siteExisted ? modifies : creates).push(siteFile);\n\n logger.info(\"Adding the currency select to the navbar\");\n const layoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"root-layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutPath, modifyRootLayoutCurrencySelect(layoutPath)),\n );\n\n // With a server, the visitor's currency is decided per request and the\n // first render already shows it. A static site (a universal root load) keeps\n // the store's browser-side start.\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n if (fs.existsSync(layoutServerPath)) {\n logger.info(\"Resolving the visitor's currency on the server\");\n const layoutServer = modifyLayoutServerCurrency(layoutServerPath);\n pushResult(modifyOutcomeToFile(layoutServerPath, layoutServer));\n if (layoutServer.status === \"success\") {\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerCurrency(hooksServerPath),\n ),\n );\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyLayoutSvelteCurrency(rootLayoutPath),\n ),\n );\n for (const file of serverCreates(hasVitest(options.root)))\n creates.push(file);\n }\n }\n\n const env: Result = {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n const setup =\n provider.id === \"stripe\"\n ? await setupStripe(options)\n : provider.id === \"shopify\"\n ? await setupShopify(options)\n : await setupWhatsApp(options, business);\n\n return mergeResults([env, setup]) satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA,eAAsByC,EAAa,GAAkB;CACnD,IAAMC,IAASpC,EAAUqC,CAAO,GAC1BC,IACJ,OAAOD,EAAQ,MAAM,UAAW,WAAWA,EAAQ,MAAM,OAAO,KAAK,IAAI,IAErEE,IAAU,CAAC;CAWjB,OAVID,MACFF,EAAO,KAAK,+BAA+B,GAC3CG,EAAQ,KAAK;EACX,MAAM;EACN,UAAU;EACV,SAAStB,EAAeqB,CAAS;EACjC,QAAQ;CACV,CAAC,IAGI;EACL;EACA,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF;;AChBA,eAAsBE,EACpB,GACA,GACA,GAC0B;CAC1B,IAAMC,IAAS,IAAIP,EAAOQ,CAAe,GACnCC,IAAQ,MAAMC,EAAG,WAAW,OAAO,CAAC,CAAC,YAKxC,GAEGC,IAAW,MAAMD,EACpB,WAAW,kBAAkB,CAAC,CAC9B,YAA0C,GACvCE,IAAgB,IAAI,IAAID,EAAS,KAAK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AAM9B,EAAYnC,CAAO,IACzBiE,EAAS,OAAO,YACd,MAAMnE,EAAaE,CAAO,IAC1B,MAAMmD,EAAcnD,GAASoD,CAAQ;CAE7C,OAAOrF,EAAa,CAACiH,GAAKC,CAAK,CAAC;AAClC"}
@@ -1,219 +0,0 @@
1
- import { n as e } from "./rolldown-runtime-CwxnZyOB.js";
2
- import { i as t, s as n } from "./constants-CTp-0HKk.js";
3
- import { existsSync as r, readFileSync as i, readdirSync as a } from "node:fs";
4
- import o from "node:path";
5
- import s from "pocketbase";
6
- import { detect as c } from "package-manager-detector";
7
- import { resolveCommand as l } from "package-manager-detector/commands";
8
- import u from "cross-spawn";
9
- import d from "node:net";
10
- // src/runtime/net.ts
11
- var f = /* @__PURE__ */ new Set([
12
- 1,
13
- 7,
14
- 9,
15
- 11,
16
- 13,
17
- 15,
18
- 17,
19
- 19,
20
- 20,
21
- 21,
22
- 22,
23
- 23,
24
- 25,
25
- 37,
26
- 42,
27
- 43,
28
- 53,
29
- 69,
30
- 77,
31
- 79,
32
- 87,
33
- 95,
34
- 101,
35
- 102,
36
- 103,
37
- 104,
38
- 109,
39
- 110,
40
- 111,
41
- 113,
42
- 115,
43
- 117,
44
- 119,
45
- 123,
46
- 135,
47
- 137,
48
- 139,
49
- 143,
50
- 161,
51
- 179,
52
- 389,
53
- 427,
54
- 465,
55
- 512,
56
- 513,
57
- 514,
58
- 515,
59
- 526,
60
- 530,
61
- 531,
62
- 532,
63
- 540,
64
- 548,
65
- 554,
66
- 556,
67
- 563,
68
- 587,
69
- 601,
70
- 636,
71
- 989,
72
- 990,
73
- 993,
74
- 995,
75
- 1719,
76
- 1720,
77
- 1723,
78
- 2049,
79
- 3659,
80
- 4045,
81
- 4190,
82
- 5060,
83
- 5061,
84
- 6e3,
85
- 6566,
86
- 6665,
87
- 6666,
88
- 6667,
89
- 6668,
90
- 6669,
91
- 6679,
92
- 6697,
93
- 10080
94
- ]);
95
- function p(e) {
96
- return new Promise((t, n) => {
97
- let r = d.createServer();
98
- r.unref(), r.once("error", n), r.listen(0, e, () => {
99
- let { port: e } = r.address();
100
- r.close(() => t(e));
101
- });
102
- });
103
- }
104
- async function m(e) {
105
- for (;;) {
106
- let t = await p(e);
107
- if (!f.has(t)) return t;
108
- }
109
- }
110
- function h(e, t, n = 60) {
111
- return new Promise((r, i) => {
112
- let a = 0, o = () => {
113
- a++;
114
- let s = new d.Socket();
115
- s.once("error", () => {
116
- s.destroy(), a === n ? i(/* @__PURE__ */ Error(`Timed out waiting for port ${e} to be available`)) : setTimeout(o, 500);
117
- }), s.connect(e, t, () => {
118
- s.destroy(), r();
119
- });
120
- };
121
- o();
122
- });
123
- }
124
- function g(e) {
125
- if (!(e instanceof Error)) return String(e);
126
- let { cause: t } = e;
127
- return t instanceof Error ? t.code || t.message || e.message : t === void 0 ? e.message : String(t);
128
- }
129
- function _(e, t = 60) {
130
- return new Promise((n, r) => {
131
- let i = 0, a = "no attempt made", o = async () => {
132
- i++;
133
- try {
134
- let t = await fetch(`${e}/api/health`);
135
- if (t.status === 200) {
136
- n();
137
- return;
138
- }
139
- a = `HTTP ${t.status}`;
140
- } catch (e) {
141
- a = g(e);
142
- }
143
- i === t ? r(/* @__PURE__ */ Error(`Timed out waiting for health check at ${e}/api/health (last attempt: ${a})`)) : setTimeout(o, 500);
144
- };
145
- o();
146
- });
147
- }
148
- // src/runtime/pocketbase.ts
149
- var v = /* @__PURE__ */ e({ withPocketbase: () => w }), y = 1100;
150
- function b() {
151
- return new Promise((e) => setTimeout(e, y));
152
- }
153
- function x(e, t, r) {
154
- let i = `${t}_${e}.js`, s = a(o.join(r.root, n)).filter((e) => e.endsWith(i)).sort().pop();
155
- if (s) return o.join(r.root, n, s);
156
- }
157
- function S(e) {
158
- let t = o.join(e, "node_modules", ".vite", "_pocketbase_metadata.json");
159
- return r(t) ? JSON.parse(i(t, "utf8")) : null;
160
- }
161
- async function C(e, t, n) {
162
- let r = !1;
163
- for (let i = 1; i <= 3; i++) try {
164
- await e.collection("_superusers").authWithPassword(t, n), r = !0;
165
- break;
166
- } catch {
167
- i < 3 && await new Promise((e) => setTimeout(e, 100));
168
- }
169
- if (!r) throw Error("Failed to authenticate with PocketBase. Check your superuser credentials.");
170
- }
171
- async function w(e, i) {
172
- let a = o.join(e, t), d = o.join(e, n), f = "localhost";
173
- if (!r(a)) throw Error("PocketBase data directory does not exist");
174
- let p = S(e);
175
- if (p && p.pocketbaseUrl) {
176
- let e = new s(p.pocketbaseUrl);
177
- await C(e, process.env.POCKETBASE_SUPERUSER_EMAIL, process.env.POCKETBASE_SUPERUSER_PASSWORD), await i(e);
178
- return;
179
- }
180
- let g = await m(f), v = [
181
- "pocketbase-server",
182
- "serve",
183
- "--dir",
184
- a,
185
- "--migrationsDir",
186
- d,
187
- "--http",
188
- `${f}:${g}`
189
- ], y = (await c({ cwd: e }))?.name ?? "npm", { command: b, args: x } = l(y, "execute", v);
190
- y === "npm" && x.unshift("--yes");
191
- let w = process.platform !== "win32", E = u(b, x, {
192
- cwd: e,
193
- stdio: "ignore",
194
- detached: w
195
- }), D = new Promise((e, t) => {
196
- E.once("exit", (e, n) => {
197
- t(/* @__PURE__ */ Error(`pocketbase-server exited before listening on ${f}:${g} (${n ?? `code ${e}`})`));
198
- }), E.once("error", t);
199
- });
200
- try {
201
- await Promise.race([(async () => {
202
- await h(g, f), await _(`http://${f}:${g}`);
203
- })(), D]);
204
- let e = new s(`http://${f}:${g}`);
205
- await C(e, process.env.POCKETBASE_SUPERUSER_EMAIL, process.env.POCKETBASE_SUPERUSER_PASSWORD), await i(e);
206
- } finally {
207
- T(E, w);
208
- }
209
- }
210
- function T(e, t) {
211
- if (t && e.pid) try {
212
- process.kill(-e.pid, "SIGTERM");
213
- return;
214
- } catch {}
215
- e.kill();
216
- }
217
- export { w as i, b as n, v as r, x as t };
218
-
219
- //# sourceMappingURL=pocketbase-S8lUt0nI.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pocketbase-S8lUt0nI.js","names":["__exportAll","DATA_DIR","MIGRATIONS_DIR","path","PocketBase","spawn","net","BAD_PORTS","osAssignedPort","server","reject","host","resolve","port","freePort","waitForPort","attempts","tryConnect","socket","maxAttempts","describeFetchError","error","cause","waitForHealth","lastFailure","tryHealth","response","url","pocketbase_exports","withPocketbase","MIGRATION_DELAY_MS","migrationDelay","getMigrationFile","ending","action","collectionName","migrationFile","readdirSync","options","file","getPocketbaseMetadata","metadataPath","cwd","existsSync","readFileSync","authWithRetries","authSuccess","attempt","pb","email","password","dir","migrationsDir","metadata","fn","commandArgs","packageManager","detect","resolveCommand","args","detached","serverProcess","command","exited","signal","code","stopProcessTree","child"],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAaO,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CACxE;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CACxE;CAAM;CAAM;AACd,CAAC;AAED,SAASC,EAAe,GAA+B;CACrD,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAMC,IAASH,EAAI,aAAa;EAGhC,AAFA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