@velastack/patterns 0.4.3 → 0.6.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 (145) hide show
  1. package/README.md +22 -2
  2. package/dist/chunks/{_page-e_I-fdSR.js → _page-DoPdZgZv.js} +2 -2
  3. package/dist/chunks/_page-DoPdZgZv.js.map +1 -0
  4. package/dist/chunks/collections-B_DisSfA.js +203 -0
  5. package/dist/chunks/collections-B_DisSfA.js.map +1 -0
  6. package/dist/chunks/{constants-Rq8SCXwH.js → constants-iej3WkEa.js} +3 -3
  7. package/dist/chunks/constants-iej3WkEa.js.map +1 -0
  8. package/dist/chunks/dispatch-BIvOwbKN.js +6 -0
  9. package/dist/chunks/dispatch-BIvOwbKN.js.map +1 -0
  10. package/dist/chunks/{env-vars-CcE6ODqC.js → env-vars-cqQU0ECK.js} +32 -20
  11. package/dist/chunks/env-vars-cqQU0ECK.js.map +1 -0
  12. package/dist/chunks/generate-8FS2ROOJ.js +170 -0
  13. package/dist/chunks/generate-8FS2ROOJ.js.map +1 -0
  14. package/dist/chunks/{generate-CFqpRi9D.js → generate-Bm_jOMtF.js} +4 -4
  15. package/dist/chunks/{generate-CFqpRi9D.js.map → generate-Bm_jOMtF.js.map} +1 -1
  16. package/dist/chunks/{generate-Bg0E3eWm.js → generate-CXoQPz7n.js} +4 -4
  17. package/dist/chunks/{generate-Bg0E3eWm.js.map → generate-CXoQPz7n.js.map} +1 -1
  18. package/dist/chunks/{generate-B6Odfk5f.js → generate-Cqwa8kD9.js} +2 -2
  19. package/dist/chunks/{generate-B6Odfk5f.js.map → generate-Cqwa8kD9.js.map} +1 -1
  20. package/dist/chunks/{generate-CZGHByV3.js → generate-D3mSFPdT.js} +7 -7
  21. package/dist/chunks/{generate-CZGHByV3.js.map → generate-D3mSFPdT.js.map} +1 -1
  22. package/dist/chunks/{generate-DetW_gbr.js → generate-DyV5R8NP.js} +7 -7
  23. package/dist/chunks/{generate-DetW_gbr.js.map → generate-DyV5R8NP.js.map} +1 -1
  24. package/dist/chunks/generate-jx5Iuq5w.js +75 -0
  25. package/dist/chunks/generate-jx5Iuq5w.js.map +1 -0
  26. package/dist/chunks/{generate.runtime-Djas9UNy.js → generate.runtime-B2r11K7S.js} +4 -4
  27. package/dist/chunks/{generate.runtime-Djas9UNy.js.map → generate.runtime-B2r11K7S.js.map} +1 -1
  28. package/dist/chunks/{generate.runtime-Bcrht4M9.js → generate.runtime-B4u9C2YH.js} +9 -9
  29. package/dist/chunks/{generate.runtime-Bcrht4M9.js.map → generate.runtime-B4u9C2YH.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-DVB7uuht.js → generate.runtime-BRCzUO94.js} +3 -3
  31. package/dist/chunks/{generate.runtime-DVB7uuht.js.map → generate.runtime-BRCzUO94.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-IWEhGhWY.js → generate.runtime-BVavIXtX.js} +6 -6
  33. package/dist/chunks/{generate.runtime-IWEhGhWY.js.map → generate.runtime-BVavIXtX.js.map} +1 -1
  34. package/dist/chunks/generate.runtime-Bh9Z2cRN.js +82 -0
  35. package/dist/chunks/generate.runtime-Bh9Z2cRN.js.map +1 -0
  36. package/dist/chunks/{generate.runtime-DJHUBL4Z.js → generate.runtime-BxDUtkpT.js} +12 -12
  37. package/dist/chunks/{generate.runtime-DJHUBL4Z.js.map → generate.runtime-BxDUtkpT.js.map} +1 -1
  38. package/dist/chunks/{generate.runtime-hTKzxH2M.js → generate.runtime-BxUGDXIK.js} +7 -7
  39. package/dist/chunks/{generate.runtime-hTKzxH2M.js.map → generate.runtime-BxUGDXIK.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-5rIc-RNL.js → generate.runtime-CHb4znYx.js} +66 -66
  41. package/dist/chunks/{generate.runtime-5rIc-RNL.js.map → generate.runtime-CHb4znYx.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-E-zoeSKW.js → generate.runtime-CRhD98rs.js} +7 -7
  43. package/dist/chunks/{generate.runtime-E-zoeSKW.js.map → generate.runtime-CRhD98rs.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-BpMN5Uq-.js → generate.runtime-CWnIiXwV.js} +3 -3
  45. package/dist/chunks/{generate.runtime-BpMN5Uq-.js.map → generate.runtime-CWnIiXwV.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-kciwaXxh.js → generate.runtime-CYBs0JgY.js} +4 -4
  47. package/dist/chunks/{generate.runtime-kciwaXxh.js.map → generate.runtime-CYBs0JgY.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-CAn1qIQ_.js → generate.runtime-CkmledBw.js} +3 -3
  49. package/dist/chunks/{generate.runtime-CAn1qIQ_.js.map → generate.runtime-CkmledBw.js.map} +1 -1
  50. package/dist/chunks/generate.runtime-CyGR8VTx.js +48 -0
  51. package/dist/chunks/generate.runtime-CyGR8VTx.js.map +1 -0
  52. package/dist/chunks/{generate.runtime-a3R4hqFy.js → generate.runtime-DCqf7nYM.js} +12 -12
  53. package/dist/chunks/{generate.runtime-a3R4hqFy.js.map → generate.runtime-DCqf7nYM.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-uLUiPgqx.js → generate.runtime-DUo-pLRr.js} +6 -6
  55. package/dist/chunks/{generate.runtime-uLUiPgqx.js.map → generate.runtime-DUo-pLRr.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-CpMKXBkn.js → generate.runtime-DY5vQ3aZ.js} +7 -7
  57. package/dist/chunks/{generate.runtime-CpMKXBkn.js.map → generate.runtime-DY5vQ3aZ.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-CEqLgLT9.js → generate.runtime-DYdkrHJ1.js} +70 -70
  59. package/dist/chunks/{generate.runtime-CEqLgLT9.js.map → generate.runtime-DYdkrHJ1.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-DHHlYfTD.js → generate.runtime-DdcVnK8J.js} +3 -3
  61. package/dist/chunks/{generate.runtime-DHHlYfTD.js.map → generate.runtime-DdcVnK8J.js.map} +1 -1
  62. package/dist/chunks/{generate.runtime-koQxLywh.js → generate.runtime-DeniHg8L.js} +48 -48
  63. package/dist/chunks/{generate.runtime-koQxLywh.js.map → generate.runtime-DeniHg8L.js.map} +1 -1
  64. package/dist/chunks/{generate.runtime-DoZJHtZh.js → generate.runtime-Dmob2wFf.js} +6 -6
  65. package/dist/chunks/{generate.runtime-DoZJHtZh.js.map → generate.runtime-Dmob2wFf.js.map} +1 -1
  66. package/dist/chunks/{generate.runtime-Db0HZyj3.js → generate.runtime-Du4uf98c.js} +2 -2
  67. package/dist/chunks/{generate.runtime-Db0HZyj3.js.map → generate.runtime-Du4uf98c.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-axm9wcQv.js → generate.runtime-Dug2UIhV.js} +4 -4
  69. package/dist/chunks/{generate.runtime-axm9wcQv.js.map → generate.runtime-Dug2UIhV.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-rs1ZOIET.js → generate.runtime-FGYc365Q.js} +15 -15
  71. package/dist/chunks/{generate.runtime-rs1ZOIET.js.map → generate.runtime-FGYc365Q.js.map} +1 -1
  72. package/dist/chunks/{generate.runtime-BK3mR0Rj.js → generate.runtime-N1KtAG8C.js} +169 -129
  73. package/dist/chunks/generate.runtime-N1KtAG8C.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-CbE9RHcf.js → generate.runtime-_c7daMAw.js} +5 -5
  75. package/dist/chunks/generate.runtime-_c7daMAw.js.map +1 -0
  76. package/dist/chunks/generate.runtime-aN5QWygO.js +106 -0
  77. package/dist/chunks/generate.runtime-aN5QWygO.js.map +1 -0
  78. package/dist/chunks/{generate.runtime-CZ46nkSL.js → generate.runtime-bpH3DB0t.js} +2 -2
  79. package/dist/chunks/{generate.runtime-CZ46nkSL.js.map → generate.runtime-bpH3DB0t.js.map} +1 -1
  80. package/dist/chunks/{generate.runtime-CqncBFNg.js → generate.runtime-gFr2Gsjz.js} +4 -4
  81. package/dist/chunks/{generate.runtime-CqncBFNg.js.map → generate.runtime-gFr2Gsjz.js.map} +1 -1
  82. package/dist/chunks/{generate.runtime-CK10Mum5.js → generate.runtime-kpqW3dVO.js} +25 -25
  83. package/dist/chunks/{generate.runtime-CK10Mum5.js.map → generate.runtime-kpqW3dVO.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-Dl6OQ7pe.js → generate.runtime-wGRE1zwZ.js} +4 -4
  85. package/dist/chunks/{generate.runtime-Dl6OQ7pe.js.map → generate.runtime-wGRE1zwZ.js.map} +1 -1
  86. package/dist/chunks/{generate.runtime-aQnBmH8D.js → generate.runtime-wziCW3ct.js} +69 -69
  87. package/dist/chunks/{generate.runtime-aQnBmH8D.js.map → generate.runtime-wziCW3ct.js.map} +1 -1
  88. package/dist/chunks/{generate.runtime-DJ9MVVPC.js → generate.runtime-x-o4LS8d.js} +123 -110
  89. package/dist/chunks/generate.runtime-x-o4LS8d.js.map +1 -0
  90. package/dist/chunks/modify-file-289rStJ2.js +53 -0
  91. package/dist/chunks/modify-file-289rStJ2.js.map +1 -0
  92. package/dist/chunks/{modify-nav-user-BLyrW2sK.js → modify-nav-user-B8h8WTrM.js} +2 -2
  93. package/dist/chunks/{modify-nav-user-BLyrW2sK.js.map → modify-nav-user-B8h8WTrM.js.map} +1 -1
  94. package/dist/chunks/{pocketbase-CgwbH1gI.js → pocketbase-B017Cqjq.js} +2 -2
  95. package/dist/chunks/{pocketbase-CgwbH1gI.js.map → pocketbase-B017Cqjq.js.map} +1 -1
  96. package/dist/chunks/providers-CL9kQ4hp.js +98 -0
  97. package/dist/chunks/providers-CL9kQ4hp.js.map +1 -0
  98. package/dist/chunks/providers-CN5J5_fY.js +38 -0
  99. package/dist/chunks/providers-CN5J5_fY.js.map +1 -0
  100. package/dist/chunks/{shared-Cc_ns5-y.js → shared-BPlAVf-T.js} +2 -2
  101. package/dist/chunks/{shared-Cc_ns5-y.js.map → shared-BPlAVf-T.js.map} +1 -1
  102. package/dist/chunks/shopify-page-D-VFwGxI.js +11 -0
  103. package/dist/chunks/shopify-page-D-VFwGxI.js.map +1 -0
  104. package/dist/chunks/site-DkU1-VRq.js +108 -0
  105. package/dist/chunks/site-DkU1-VRq.js.map +1 -0
  106. package/dist/chunks/stripe-customer-B3tP8gtD.js +6 -0
  107. package/dist/chunks/stripe-customer-B3tP8gtD.js.map +1 -0
  108. package/dist/chunks/{svelte-file-B3RfgVdt.js → svelte-file-Dv5-bl79.js} +37 -2
  109. package/dist/chunks/svelte-file-Dv5-bl79.js.map +1 -0
  110. package/dist/chunks/{table-core-DhDqT03G.js → table-core-vXEjJDYP.js} +2 -2
  111. package/dist/chunks/{table-core-DhDqT03G.js.map → table-core-vXEjJDYP.js.map} +1 -1
  112. package/dist/chunks/{test-setup-B9fQ5L_-.js → test-setup-CAfgVlwc.js} +3 -3
  113. package/dist/chunks/{test-setup-B9fQ5L_-.js.map → test-setup-CAfgVlwc.js.map} +1 -1
  114. package/dist/chunks/{ui-CuCsupFq.js → ui-CTdsenEv.js} +3 -3
  115. package/dist/chunks/{ui-CuCsupFq.js.map → ui-CTdsenEv.js.map} +1 -1
  116. package/dist/chunks/{whatsapp-CguKGTtw.js → whatsapp-5qJ_xCV1.js} +2 -2
  117. package/dist/chunks/{whatsapp-CguKGTtw.js.map → whatsapp-5qJ_xCV1.js.map} +1 -1
  118. package/dist/chunks/{write-result-DiZsCS_y.js → write-result-0HYIr5a6.js} +4 -4
  119. package/dist/chunks/write-result-0HYIr5a6.js.map +1 -0
  120. package/dist/index.d.ts +283 -22
  121. package/dist/index.js +2233 -2031
  122. package/dist/index.js.map +1 -1
  123. package/package.json +1 -1
  124. package/dist/chunks/_page-e_I-fdSR.js.map +0 -1
  125. package/dist/chunks/collections-zzZ_HQxB.js +0 -192
  126. package/dist/chunks/collections-zzZ_HQxB.js.map +0 -1
  127. package/dist/chunks/constants-Rq8SCXwH.js.map +0 -1
  128. package/dist/chunks/dispatch-D4TN9pdW.js +0 -6
  129. package/dist/chunks/dispatch-D4TN9pdW.js.map +0 -1
  130. package/dist/chunks/env-vars-CcE6ODqC.js.map +0 -1
  131. package/dist/chunks/env-vars-De0Xs0L2.js +0 -20
  132. package/dist/chunks/env-vars-De0Xs0L2.js.map +0 -1
  133. package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +0 -1
  134. package/dist/chunks/generate.runtime-CbE9RHcf.js.map +0 -1
  135. package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +0 -1
  136. package/dist/chunks/generate.runtime-EQnytCFL.js +0 -122
  137. package/dist/chunks/generate.runtime-EQnytCFL.js.map +0 -1
  138. package/dist/chunks/modify-file-DK-tCH9k.js +0 -46
  139. package/dist/chunks/modify-file-DK-tCH9k.js.map +0 -1
  140. package/dist/chunks/providers-BHR6-XZ7.js +0 -76
  141. package/dist/chunks/providers-BHR6-XZ7.js.map +0 -1
  142. package/dist/chunks/site-lj0CDdQ1.js +0 -55
  143. package/dist/chunks/site-lj0CDdQ1.js.map +0 -1
  144. package/dist/chunks/svelte-file-B3RfgVdt.js.map +0 -1
  145. package/dist/chunks/write-result-DiZsCS_y.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"modify-nav-user-BLyrW2sK.js","names":["withInMemoryScript","fs","NOT_FOUND_HINT","FAILURE_HINT","SUBSCRIPTION_TYPE","PLAN_LABEL","PLAN_LINES","propsStatement","sf","s","d","SyntaxKind","bindingText","current","texts","indent","close","t","addSubscriptionProp","statement","decl","binding","type","rest","writer","modifyNavUser","filePath","original","file","SvelteFile","added","content","source","markupStart","names","out","i","match","end"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-nav-user.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind, type SourceFile, type VariableStatement } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\n\nconst NOT_FOUND_HINT = [\n \"src/lib/components/nav-user.svelte is missing.\",\n \"Enable auth and payments first; subscriptions layers a plan label on top of the existing nav-user.\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Could not find the props and the name lines in nav-user.svelte. Show the plan by hand:\",\n \"\",\n \"let { user, subscription = null }: { ...; subscription?: { id: string; productName: string | null } | null } = $props();\",\n \"const planLabel = $derived(subscription?.productName ?? 'Free');\",\n \"\",\n \"<!-- Under the name, in the trigger and in the dropdown label: -->\",\n '<span class=\"truncate text-xs text-muted-foreground\">{planLabel}</span>',\n].join(\"\\n\");\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\nconst PLAN_LABEL =\n \"const planLabel = $derived(subscription?.productName ?? 'Free');\";\n\n/** The line under the name: muted in the trigger, plain in the dropdown label. */\nconst PLAN_LINES = [\n '<span class=\"truncate text-xs text-muted-foreground\">{planLabel}</span>',\n '<span class=\"truncate text-xs\">{planLabel}</span>',\n];\n\n/** `let { ... }: { ... } = $props();` */\nexport function propsStatement(sf: SourceFile): VariableStatement | undefined {\n return sf\n .getVariableStatements()\n .find((s) =>\n s\n .getDeclarations()\n .some(\n (d) =>\n d.getInitializer()?.getText() === \"$props()\" &&\n d.getNameNode().getKind() === SyntaxKind.ObjectBindingPattern,\n ),\n );\n}\n\n/** `{ a, b }` with `texts` as its elements, one per line if it was. */\nexport function bindingText(current: string, texts: string[]): string {\n if (!current.includes(\"\\n\")) return `{ ${texts.join(\", \")} }`;\n const indent = current.match(/\\n([ \\t]+)\\S/)?.[1] ?? \"\\t\";\n const close = current.match(/\\n([ \\t]*)\\}$/)?.[1] ?? \"\";\n return `{\\n${texts.map((t) => indent + t).join(\",\\n\")}\\n${close}}`;\n}\n\nfunction addSubscriptionProp(sf: SourceFile): boolean {\n const statement = propsStatement(sf);\n const decl = statement?.getDeclarations()[0];\n const binding = decl?.getNameNode().asKind(SyntaxKind.ObjectBindingPattern);\n const type = decl?.getTypeNode()?.asKind(SyntaxKind.TypeLiteral);\n if (!statement || !decl || !binding || !type) return false;\n\n if (!binding.getElements().some((e) => e.getName() === \"subscription\")) {\n const texts = binding.getElements().map((e) => e.getText());\n const rest = binding.getElements().findIndex((e) => e.getDotDotDotToken());\n texts.splice(rest === -1 ? texts.length : rest, 0, \"subscription = null\");\n binding.replaceWithText(bindingText(binding.getText(), texts));\n }\n if (!type.getProperty(\"subscription\")) {\n type.addProperty({\n name: \"subscription\",\n hasQuestionToken: true,\n type: SUBSCRIPTION_TYPE,\n });\n }\n sf.insertStatements(sf.getStatements().indexOf(statement) + 1, (writer) =>\n writer.blankLine().write(PLAN_LABEL),\n );\n return true;\n}\n\n/**\n * Shows the user's plan under their name in nav-user: a `subscription` prop\n * (the (app) layout passes it), `planLabel` from it, and a line under each\n * name. Edits the file rather than replacing it, so the items other patterns\n * added to the menu (teams, API keys) stay.\n */\nexport function modifyNavUser(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"planLabel\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n let added = false;\n file.modifyScript(\n (content) =>\n withInMemoryScript(content, (sf) => {\n added = addSubscriptionProp(sf);\n }).source,\n );\n if (!added) return { status: \"failed\", message: FAILURE_HINT };\n\n // The name lines, in the markup after the script.\n const source = file.toString();\n const markupStart = source.indexOf(\"</script>\");\n const names = [\n ...source\n .slice(markupStart)\n .matchAll(\n /^([ \\t]*)<span class=\"truncate font-medium\">[\\s\\S]*?<\\/span>/gm,\n ),\n ];\n if (names.length < 2) return { status: \"failed\", message: FAILURE_HINT };\n\n let out = source;\n // From the last, so the earlier offsets stay put.\n for (const [i, match] of [...names.slice(0, 2).entries()].reverse()) {\n const end = markupStart + match.index! + match[0].length;\n out = `${out.slice(0, end)}\\n${match[1]}${PLAN_LINES[i]}${out.slice(end)}`;\n }\n\n fs.writeFileSync(filePath, out, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;AAMA,IAA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GAAG;EACnE,IAAMI,IAAML,IAAcI,EAAM,QAASA,EAAM,EAAE,CAAC;EAClD,IAAM,GAAGF,EAAI,MAAM,GAAGG,CAAG,EAAE,IAAID,EAAM,KAAK/B,EAAW8B,KAAKD,EAAI,MAAMG,CAAG;CACzE;CAGA,OADArC,EAAG,cAAcyB,GAAUS,GAAK,MAAM,GAC/B;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
1
+ {"version":3,"file":"modify-nav-user-B8h8WTrM.js","names":["withInMemoryScript","fs","NOT_FOUND_HINT","FAILURE_HINT","SUBSCRIPTION_TYPE","PLAN_LABEL","PLAN_LINES","propsStatement","sf","s","d","SyntaxKind","bindingText","current","texts","indent","close","t","addSubscriptionProp","statement","decl","binding","type","rest","writer","modifyNavUser","filePath","original","file","SvelteFile","added","content","source","markupStart","names","out","i","match","end"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-nav-user.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind, type SourceFile, type VariableStatement } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\n\nconst NOT_FOUND_HINT = [\n \"src/lib/components/nav-user.svelte is missing.\",\n \"Enable auth and payments first; subscriptions layers a plan label on top of the existing nav-user.\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Could not find the props and the name lines in nav-user.svelte. Show the plan by hand:\",\n \"\",\n \"let { user, subscription = null }: { ...; subscription?: { id: string; productName: string | null } | null } = $props();\",\n \"const planLabel = $derived(subscription?.productName ?? 'Free');\",\n \"\",\n \"<!-- Under the name, in the trigger and in the dropdown label: -->\",\n '<span class=\"truncate text-xs text-muted-foreground\">{planLabel}</span>',\n].join(\"\\n\");\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\nconst PLAN_LABEL =\n \"const planLabel = $derived(subscription?.productName ?? 'Free');\";\n\n/** The line under the name: muted in the trigger, plain in the dropdown label. */\nconst PLAN_LINES = [\n '<span class=\"truncate text-xs text-muted-foreground\">{planLabel}</span>',\n '<span class=\"truncate text-xs\">{planLabel}</span>',\n];\n\n/** `let { ... }: { ... } = $props();` */\nexport function propsStatement(sf: SourceFile): VariableStatement | undefined {\n return sf\n .getVariableStatements()\n .find((s) =>\n s\n .getDeclarations()\n .some(\n (d) =>\n d.getInitializer()?.getText() === \"$props()\" &&\n d.getNameNode().getKind() === SyntaxKind.ObjectBindingPattern,\n ),\n );\n}\n\n/** `{ a, b }` with `texts` as its elements, one per line if it was. */\nexport function bindingText(current: string, texts: string[]): string {\n if (!current.includes(\"\\n\")) return `{ ${texts.join(\", \")} }`;\n const indent = current.match(/\\n([ \\t]+)\\S/)?.[1] ?? \"\\t\";\n const close = current.match(/\\n([ \\t]*)\\}$/)?.[1] ?? \"\";\n return `{\\n${texts.map((t) => indent + t).join(\",\\n\")}\\n${close}}`;\n}\n\nfunction addSubscriptionProp(sf: SourceFile): boolean {\n const statement = propsStatement(sf);\n const decl = statement?.getDeclarations()[0];\n const binding = decl?.getNameNode().asKind(SyntaxKind.ObjectBindingPattern);\n const type = decl?.getTypeNode()?.asKind(SyntaxKind.TypeLiteral);\n if (!statement || !decl || !binding || !type) return false;\n\n if (!binding.getElements().some((e) => e.getName() === \"subscription\")) {\n const texts = binding.getElements().map((e) => e.getText());\n const rest = binding.getElements().findIndex((e) => e.getDotDotDotToken());\n texts.splice(rest === -1 ? texts.length : rest, 0, \"subscription = null\");\n binding.replaceWithText(bindingText(binding.getText(), texts));\n }\n if (!type.getProperty(\"subscription\")) {\n type.addProperty({\n name: \"subscription\",\n hasQuestionToken: true,\n type: SUBSCRIPTION_TYPE,\n });\n }\n sf.insertStatements(sf.getStatements().indexOf(statement) + 1, (writer) =>\n writer.blankLine().write(PLAN_LABEL),\n );\n return true;\n}\n\n/**\n * Shows the user's plan under their name in nav-user: a `subscription` prop\n * (the (app) layout passes it), `planLabel` from it, and a line under each\n * name. Edits the file rather than replacing it, so the items other patterns\n * added to the menu (teams, API keys) stay.\n */\nexport function modifyNavUser(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"planLabel\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n let added = false;\n file.modifyScript(\n (content) =>\n withInMemoryScript(content, (sf) => {\n added = addSubscriptionProp(sf);\n }).source,\n );\n if (!added) return { status: \"failed\", message: FAILURE_HINT };\n\n // The name lines, in the markup after the script.\n const source = file.toString();\n const markupStart = source.indexOf(\"</script>\");\n const names = [\n ...source\n .slice(markupStart)\n .matchAll(\n /^([ \\t]*)<span class=\"truncate font-medium\">[\\s\\S]*?<\\/span>/gm,\n ),\n ];\n if (names.length < 2) return { status: \"failed\", message: FAILURE_HINT };\n\n let out = source;\n // From the last, so the earlier offsets stay put.\n for (const [i, match] of [...names.slice(0, 2).entries()].reverse()) {\n const end = markupStart + match.index! + match[0].length;\n out = `${out.slice(0, end)}\\n${match[1]}${PLAN_LINES[i]}${out.slice(end)}`;\n }\n\n fs.writeFileSync(filePath, out, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;AAMA,IAAME,IAAiB,CACrB,kDACA,oGACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAoB,qDACpBC,IACJ,oEAGIC,IAAa,CACjB,6EACA,qDACF;AAGA,SAAgBC,EAAe,GAA+C;CAC5E,OAAOC,EACJ,sBAAsB,CAAC,CACvB,MAAM,MACLC,EACG,gBAAgB,CAAC,CACjB,MACE,MACCC,EAAE,eAAe,CAAC,EAAE,QAAQ,MAAM,cAClCA,EAAE,YAAY,CAAC,CAAC,QAAQ,MAAMC,EAAW,oBAC7C,C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,GACO;AACT;AAQA,SAAgBoB,EAAc,GAAiC;CAC7D,IAAI,CAACxB,EAAG,WAAWyB,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAASxB;CAAe;CAExD,IAAMyB,IAAW1B,EAAG,aAAayB,GAAU,MAAM;CACjD,IAAIC,EAAS,SAAS,WAAW,GAC/B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAO,IAAIC,EAAWF,CAAQ,GAChCG,IAAQ;CAOZ,IANAF,EAAK,cACF,MACC5B,EAAmB+B,IAAU,MAAO;EAClC,IAAQb,EAAoBV,CAAE;CAChC,CAAC,CAAC,CAAC,MACP,GACI,CAACsB,GAAO,OAAO;EAAE,QAAQ;EAAU,SAAS3B;CAAa;CAG7D,IAAM6B,IAASJ,EAAK,SAAS,GACvBK,IAAcD,EAAO,QAAQ,YAAW,GACxCE,IAAQ,CACZ,GAAGF,EACA,MAAMC,CAAW,CAAC,CAClB,SACC,gEACF,CACJ;CACA,IAAIC,EAAM,SAAS,GAAG,OAAO;EAAE,QAAQ;EAAU,SAAS/B;CAAa;CAEvE,IAAIgC,IAAMH;CAEV,KAAK,IAAM,CAACI,GAAGC,MAAU,CAAC,GAAGH,EAAM,MAAM,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,GAAG;EACnE,IAAMI,IAAML,IAAcI,EAAM,QAASA,EAAM,EAAE,CAAC;EAClD,IAAM,GAAGF,EAAI,MAAM,GAAGG,CAAG,EAAE,IAAID,EAAM,KAAK/B,EAAW8B,KAAKD,EAAI,MAAMG,CAAG;CACzE;CAGA,OADArC,EAAG,cAAcyB,GAAUS,GAAK,MAAM,GAC/B;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
@@ -1,5 +1,5 @@
1
1
  import { n as e } from "./rolldown-runtime-DArdT4gl.js";
2
- import { c as t, i as n } from "./constants-Rq8SCXwH.js";
2
+ import { c as t, i as n } from "./constants-iej3WkEa.js";
3
3
  import { existsSync as r, readFileSync as i, readdirSync as a } from "node:fs";
4
4
  import o from "node:path";
5
5
  import s from "pocketbase";
@@ -232,4 +232,4 @@ function T(e, t) {
232
232
  //#endregion
233
233
  export { w as i, b as n, v as r, x as t };
234
234
 
235
- //# sourceMappingURL=pocketbase-CgwbH1gI.js.map
235
+ //# sourceMappingURL=pocketbase-B017Cqjq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pocketbase-CgwbH1gI.js","names":["__exportAll","MIGRATIONS_DIR","DATA_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","authWithRetries","getMigrationFile","getPocketbaseMetadata","migrationDelay","withPocketbase","MIGRATION_DELAY_MS","ending","action","collectionName","migrationFile","readdirSync","options","file","metadataPath","cwd","existsSync","readFileSync","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;CA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AAK,IAAImD,KAAU,QAAQC,IAAO,EAC5F,CACF;EACF,CAAC,GACDJ,EAAc,KAAK,SAASnD,CAAM;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAMK,EAAYF,GAAMF,CAAI,GAC5B,MAAMY,EAAc,UAAUZ,EAAK,GAAGE,GAAM;EAC9C,EAAA,CAAG,GACHkD,CACF,CAAC;EAED,IAAMf,IAAK,IAAI5C,EAAW,UAAUO,EAAK,GAAGE,GAAM;EAMlD,AALA,MAAMgB,EACJmB,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAMM,EAAGN,CAAE;CACb,UAAU;EAER,EAAgBa,GAAeD,CAAQ;CACzC;AACF;AAEA,SAASM,EACP,GACA,GACM;CACN,IAAIN,KAAYO,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAACA,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
1
+ {"version":3,"file":"pocketbase-B017Cqjq.js","names":["__exportAll","MIGRATIONS_DIR","DATA_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","authWithRetries","getMigrationFile","getPocketbaseMetadata","migrationDelay","withPocketbase","MIGRATION_DELAY_MS","ending","action","collectionName","migrationFile","readdirSync","options","file","metadataPath","cwd","existsSync","readFileSync","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 }\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EAAO,EAAE,OAAI,CAAC,EAAA,EAAI,QAAQ,OAClD,EAAE,YAAS,YAASC,EACxBF,GACA,WACAD,CACF;CAGA,AAAIC,MAAmB,SAAOG,EAAK,QAAQ,OAAO;CAMlD,IAAMC,IAAW,QAAQ,aAAa,SAChCC,IAAgBxD,EAAMyD,GAASH,GAAM;EACzC;EACA,OAAO;EACP;CACF,CAAC,GAIKI,IAAS,IAAI,SAAgB,GAAG,MAAW;EAQ/C,AAPAF,EAAc,KAAK,SAAS,GAAM,MAAW;GAC3C,EACE,gBAAI,MACF,gDAAgDlD,EAAK,GAAGE,EAAK,IAAImD,KAAU,QAAQC,IAAO,EAC5F,CACF;EACF,CAAC,GACDJ,EAAc,KAAK,SAASnD,CAAM;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAMK,EAAYF,GAAMF,CAAI,GAC5B,MAAMY,EAAc,UAAUZ,EAAK,GAAGE,GAAM;EAC9C,EAAA,CAAG,GACHkD,CACF,CAAC;EAED,IAAMf,IAAK,IAAI5C,EAAW,UAAUO,EAAK,GAAGE,GAAM;EAMlD,AALA,MAAMgB,EACJmB,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAMM,EAAGN,CAAE;CACb,UAAU;EAER,EAAgBa,GAAeD,CAAQ;CACzC;AACF;AAEA,SAASM,EACP,GACA,GACM;CACN,IAAIN,KAAYO,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAACA,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
@@ -0,0 +1,98 @@
1
+ import { t as e } from "./errors-DR3gF_7a.js";
2
+ import { i as t } from "./util-BLYliuUK.js";
3
+ //#region src/core/providers.ts
4
+ function n(e) {
5
+ return e.replace(/^enable-/, "");
6
+ }
7
+ function r(e) {
8
+ for (let t = 0; t < e.length; t++) {
9
+ let n = e[t];
10
+ if (n === "--provider") return e[t + 1];
11
+ if (n.startsWith("--provider=")) return n.slice(11);
12
+ }
13
+ }
14
+ function i(e, t, n) {
15
+ return [
16
+ `Unknown provider "${t}" for ${e}.`,
17
+ "",
18
+ "Available providers:",
19
+ ...n.map((e) => ` ${e.id}`)
20
+ ].join("\n");
21
+ }
22
+ function a(e) {
23
+ return `--provider <${e.map((e) => e.id).join("|")}>`;
24
+ }
25
+ function o(e) {
26
+ if (e.markers) return e.markers;
27
+ let t = e.env?.[0];
28
+ return t ? [{ env: t.key }] : [];
29
+ }
30
+ function s(t, o) {
31
+ let s = t.providers ?? [], l = n(t.slug);
32
+ if (s.length === 0) throw Error(`${t.slug} declares no providers.`);
33
+ let u = typeof o.input.provider == "string" ? o.input.provider : r(o.argv);
34
+ if (t.inheritsProvider) return c(t.inheritsProvider, l, s, u, o);
35
+ if (u === void 0 || u === "") {
36
+ if (o.env === "preview") return s[0];
37
+ throw new e(`Choose a provider for ${l}: ${a(s)}`);
38
+ }
39
+ let d = s.find((e) => e.id === u);
40
+ if (!d) throw new e(i(l, u, s));
41
+ return d;
42
+ }
43
+ function c(t, n, r, a, o) {
44
+ let s = o.providers?.[t];
45
+ if (s === void 0) {
46
+ if (o.env === "preview") {
47
+ if (a === void 0 || a === "") return r[0];
48
+ let t = r.find((e) => e.id === a);
49
+ if (t) return t;
50
+ throw new e(i(n, a, r));
51
+ }
52
+ throw new e(`${n} is built on ${t}, and this project has none. Run \`vela enable ${t}\` first.`);
53
+ }
54
+ let c = r.find((e) => e.id === s);
55
+ if (!c) throw new e(`${n} does not support "${s}" ${t} yet. Supported: ${r.map((e) => e.id).join(", ")}.`);
56
+ if (a !== void 0 && a !== "" && a !== s) throw new e(`This project uses ${c.label} ${t}, and ${n} follows it. Leave out --provider, or pass --provider ${s}.`);
57
+ return c;
58
+ }
59
+ function l(e, t, n = {}) {
60
+ return [{
61
+ type: "comment",
62
+ key: t
63
+ }, ...(e.env ?? []).map((e) => ({
64
+ type: "var",
65
+ key: e.key,
66
+ value: n[e.key]?.trim() || e.default || ""
67
+ }))];
68
+ }
69
+ function u(e) {
70
+ return (e.env ?? []).map((e) => ({
71
+ name: e.key,
72
+ ...e.public ? { public: !0 } : {},
73
+ description: e.description ?? e.label
74
+ }));
75
+ }
76
+ function d(e) {
77
+ let t = e.input.providerEnv;
78
+ if (!t || typeof t != "object") return {};
79
+ let n = {};
80
+ for (let [e, r] of Object.entries(t)) typeof r == "string" && (n[e] = r);
81
+ return n;
82
+ }
83
+ function f(e, t) {
84
+ let n = /* @__PURE__ */ new Set();
85
+ for (let r of Object.keys(e)) {
86
+ let e = r.match(/\/providers(?:-[^/]+)?\/([^/]+)\/(.+)$/);
87
+ e && (t === void 0 || e[1] === t) && n.add(e[2]);
88
+ }
89
+ return [...n].sort();
90
+ }
91
+ function p(e, n, r = "./providers/") {
92
+ let i = t(e, `${r}${n}/`);
93
+ return Object.values(i).sort((e, t) => e.path.localeCompare(t.path));
94
+ }
95
+ //#endregion
96
+ export { u as a, s as c, l as i, d as l, n, r as o, p as r, o as s, f as t, i as u };
97
+
98
+ //# sourceMappingURL=providers-CL9kQ4hp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers-CL9kQ4hp.js","names":["InvalidArgumentError","filesUnderPrefix","capabilityName","slug","providerFromArgv","i","argv","arg","unknownProviderMessage","raw","name","providers","provider","providerChoices","providerMarkers","first","resolveProvider","pattern","options","resolveInheritedProvider","candidate","detectedId","capability","detected","providerEnvEdits","heading","variable","supplied","providerEnvVars","suppliedProviderEnv","values","key","value","allProviderPaths","paths","providersRaw","match","id","providerCreates","files","root","a","b"],"sources":["../../src/core/providers.ts"],"sourcesContent":["import type { EnvEdit } from \"../runtime/env\";\nimport type { EnvVarSpec } from \"../runtime/env-vars-file\";\nimport { InvalidArgumentError } from \"./errors\";\nimport type { File, Options, Pattern, Provider, ProviderMarker } from \"./types\";\nimport { filesUnderPrefix } from \"./util\";\n\ntype ProviderPattern = Pick<Pattern, \"slug\" | \"providers\" | \"inheritsProvider\">;\n\n/** `analytics` for `enable-analytics`: how the capability is named to users. */\nexport function capabilityName(slug: string): string {\n return slug.replace(/^enable-/, \"\");\n}\n\n/** `--provider <id>` or `--provider=<id>`, for callers that hand flags through in argv. */\nexport function providerFromArgv(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--provider\") return argv[i + 1];\n if (arg.startsWith(\"--provider=\")) return arg.slice(\"--provider=\".length);\n }\n return undefined;\n}\n\nexport function unknownProviderMessage(\n name: string,\n raw: string,\n providers: Provider[],\n): string {\n return [\n `Unknown provider \"${raw}\" for ${name}.`,\n \"\",\n \"Available providers:\",\n ...providers.map((provider) => ` ${provider.id}`),\n ].join(\"\\n\");\n}\n\nexport function providerChoices(providers: Provider[]): string {\n return `--provider <${providers.map((provider) => provider.id).join(\"|\")}>`;\n}\n\n/**\n * What `detectProviders` looks for: the declared markers, else the first env\n * key's declaration in `src/env.ts`. Empty for a provider with neither, which\n * can't be detected.\n */\nexport function providerMarkers(provider: Provider): ProviderMarker[] {\n if (provider.markers) return provider.markers;\n const first = provider.env?.[0];\n return first ? [{ env: first.key }] : [];\n}\n\n/**\n * The provider a generate call should produce, from `input.provider` or\n * `--provider` in argv.\n *\n * An unknown id is rejected with the list of known ones. With no provider at\n * all, a runtime call is rejected too: the CLI always supplies one, so this\n * is a caller bug. A preview call falls back to the first declared provider,\n * because the website loads patterns with argv only.\n *\n * A pattern with `inheritsProvider` takes the provider detected for that\n * capability instead; see `resolveInheritedProvider`.\n */\nexport function resolveProvider(\n pattern: ProviderPattern,\n options: Pick<Options, \"input\" | \"argv\" | \"env\" | \"providers\">,\n): Provider {\n const providers = pattern.providers ?? [];\n const name = capabilityName(pattern.slug);\n if (providers.length === 0) {\n throw new Error(`${pattern.slug} declares no providers.`);\n }\n\n const raw =\n typeof options.input.provider === \"string\"\n ? options.input.provider\n : providerFromArgv(options.argv);\n\n if (pattern.inheritsProvider) {\n return resolveInheritedProvider(\n pattern.inheritsProvider,\n name,\n providers,\n raw,\n options,\n );\n }\n\n if (raw === undefined || raw === \"\") {\n if (options.env === \"preview\") return providers[0];\n throw new InvalidArgumentError(\n `Choose a provider for ${name}: ${providerChoices(providers)}`,\n );\n }\n\n const provider = providers.find((candidate) => candidate.id === raw);\n if (!provider) {\n throw new InvalidArgumentError(\n unknownProviderMessage(name, raw, providers),\n );\n }\n return provider;\n}\n\n/**\n * A pattern built on another capability uses that capability's provider:\n * enable-ecommerce on a project with Shopify payments generates the Shopify\n * cart. A `--provider` that repeats the detected one is accepted; a different\n * one is an error, because switching means disabling the capability first.\n *\n * In preview nothing is detected, so it falls back like `resolveProvider`.\n */\nfunction resolveInheritedProvider(\n capability: string,\n name: string,\n providers: Provider[],\n raw: string | undefined,\n options: Pick<Options, \"env\" | \"providers\">,\n): Provider {\n const detectedId = options.providers?.[capability];\n\n if (detectedId === undefined) {\n if (options.env === \"preview\") {\n if (raw === undefined || raw === \"\") return providers[0];\n const provider = providers.find((candidate) => candidate.id === raw);\n if (provider) return provider;\n throw new InvalidArgumentError(\n unknownProviderMessage(name, raw, providers),\n );\n }\n throw new InvalidArgumentError(\n `${name} is built on ${capability}, and this project has none. ` +\n `Run \\`vela enable ${capability}\\` first.`,\n );\n }\n\n const detected = providers.find((candidate) => candidate.id === detectedId);\n if (!detected) {\n throw new InvalidArgumentError(\n `${name} does not support \"${detectedId}\" ${capability} yet. ` +\n `Supported: ${providers.map((provider) => provider.id).join(\", \")}.`,\n );\n }\n\n if (raw !== undefined && raw !== \"\" && raw !== detectedId) {\n throw new InvalidArgumentError(\n `This project uses ${detected.label} ${capability}, and ${name} follows it. ` +\n `Leave out --provider, or pass --provider ${detectedId}.`,\n );\n }\n\n return detected;\n}\n\n/**\n * The `.env` lines for a provider: `# heading`, then one `KEY=value` per\n * declared env var. `supplied` holds what the CLI collected; a blank value\n * falls back to the provider's default, else an empty assignment the\n * developer fills in later. Prompt placeholders are never written.\n */\nexport function providerEnvEdits(\n provider: Provider,\n heading: string,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return [\n { type: \"comment\", key: heading },\n ...(provider.env ?? []).map((variable): EnvEdit => ({\n type: \"var\",\n key: variable.key,\n value: supplied[variable.key]?.trim() || variable.default || \"\",\n })),\n ];\n}\n\n/**\n * The `src/env.ts` declarations for a provider's env vars: optional, so an\n * empty `.env` still builds, and public only where the provider says so.\n */\nexport function providerEnvVars(provider: Provider): EnvVarSpec[] {\n return (provider.env ?? []).map((variable) => ({\n name: variable.key,\n ...(variable.public ? { public: true } : {}),\n description: variable.description ?? variable.label,\n }));\n}\n\n/** The string values of `input.providerEnv`, as the CLI collected them. */\nexport function suppliedProviderEnv(\n options: Pick<Options, \"input\">,\n): Record<string, string> {\n const raw = options.input.providerEnv;\n if (!raw || typeof raw !== \"object\") return {};\n const values: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw)) {\n if (typeof value === \"string\") values[key] = value;\n }\n return values;\n}\n\n/**\n * Every app-relative path the providers create, sorted, for a disable pattern\n * that removes the files whichever provider was chosen. Works on a glob taken\n * from anywhere (`../../enable/<x>/providers/**`): only the part after\n * `providers/<id>/` (or `providers-<variant>/<id>/`) counts. `id` limits it to\n * one provider's files.\n */\nexport function allProviderPaths(\n providersRaw: Record<string, string>,\n id?: string,\n): string[] {\n const paths = new Set<string>();\n for (const key of Object.keys(providersRaw)) {\n const match = key.match(/\\/providers(?:-[^/]+)?\\/([^/]+)\\/(.+)$/);\n if (match && (id === undefined || match[1] === id)) paths.add(match[2]);\n }\n return [...paths].sort();\n}\n\n/**\n * The files under `providers/<id>/**` of a pattern, as creates. The glob map\n * is one `import.meta.glob(\"./providers/**\")` covering every provider. `root`\n * names a sibling tree for a variant of the provider's files, such as\n * `./providers-app-mode/`.\n */\nexport function providerCreates(\n providersRaw: Record<string, string>,\n id: string,\n root = \"./providers/\",\n): File[] {\n const files = filesUnderPrefix(providersRaw, `${root}${id}/`);\n return Object.values(files).sort((a, b) => a.path.localeCompare(b.path));\n}\n"],"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EACd,OAAOC,EAASD,EAAS,IAAI,EAAE,KAAK,KAAKA,EAAS,WAAW;CAC/D,EAAE,CACJ;AACF;AAMA,SAAgBE,EAAgB,GAAkC;CAChE,QAAQhB,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,OAAc;EAC7C,MAAMc,EAAS;EACf,GAAIA,EAAS,SAAS,EAAE,QAAQ,GAAK,IAAI,CAAC;EAC1C,aAAaA,EAAS,eAAeA,EAAS;CAChD,EAAE;AACJ;AAGA,SAAgBG,EACd,GACwB;CACxB,IAAMpB,IAAMS,EAAQ,MAAM;CAC1B,IAAI,CAACT,KAAO,OAAOA,KAAQ,UAAU,OAAO,CAAC;CAC7C,IAAMqB,IAAiC,CAAC;CACxC,KAAK,IAAM,CAACC,GAAKC,MAAU,OAAO,QAAQvB,CAAG,GAC3C,AAAI,OAAOuB,KAAU,aAAU,EAAOD,KAAOC;CAE/C,OAAOF;AACT;AASA,SAAgBG,EACd,GACA,GACU;CACV,IAAMC,oBAAQ,IAAI,IAAY;CAC9B,KAAK,IAAMH,KAAO,OAAO,KAAKI,CAAY,GAAG;EAC3C,IAAMC,IAAQL,EAAI,MAAM,wCAAwC;EAChE,AAAIK,MAAUC,MAAO,KAAA,KAAaD,EAAM,OAAOC,MAAKH,EAAM,IAAIE,EAAM,EAAE;CACxE;CACA,OAAO,CAAC,GAAGF,CAAK,CAAC,CAAC,KAAK;AACzB;AAQA,SAAgBI,EACd,GACA,GACA,IAAO,gBACC;CACR,IAAMC,IAAQtC,EAAiBkC,GAAc,GAAGK,IAAOH,EAAG,EAAE;CAC5D,OAAO,OAAO,OAAOE,CAAK,CAAC,CAAC,MAAM,GAAG,MAAME,EAAE,KAAK,cAAcC,EAAE,IAAI,CAAC;AACzE"}
@@ -0,0 +1,38 @@
1
+ import { n as e, s as t } from "./providers-CL9kQ4hp.js";
2
+ import { readEnvVarNames as n } from "./env-vars-cqQU0ECK.js";
3
+ import r from "node:fs";
4
+ import i from "node:path";
5
+ //#region src/runtime/providers.ts
6
+ function a(n, r) {
7
+ let i = {
8
+ providers: {},
9
+ ambiguous: []
10
+ }, a = o(n);
11
+ for (let n of r) {
12
+ if (!n.providers?.length || n.inheritsProvider) continue;
13
+ let r = n.providers.filter((e) => t(e).some(a)).map((e) => e.id), o = e(n.slug);
14
+ r.length === 1 && (i.providers[o] = r[0]), r.length > 1 && i.ambiguous.push({
15
+ capability: o,
16
+ ids: r
17
+ });
18
+ }
19
+ return i;
20
+ }
21
+ function o(e) {
22
+ let t, a;
23
+ return (o) => "env" in o ? (t ??= n(e), t.has(o.env)) : "path" in o ? r.existsSync(i.join(e, o.path)) : (a ??= s(e), a.has(o.dependency));
24
+ }
25
+ function s(e) {
26
+ let t = i.join(e, "package.json");
27
+ if (!r.existsSync(t)) return /* @__PURE__ */ new Set();
28
+ try {
29
+ let e = JSON.parse(r.readFileSync(t, "utf8"));
30
+ return /* @__PURE__ */ new Set([...Object.keys(e.dependencies ?? {}), ...Object.keys(e.devDependencies ?? {})]);
31
+ } catch {
32
+ return /* @__PURE__ */ new Set();
33
+ }
34
+ }
35
+ //#endregion
36
+ export { a as detectProviders };
37
+
38
+ //# sourceMappingURL=providers-CN5J5_fY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers-CN5J5_fY.js","names":["capabilityName","providerMarkers","fs","path","detectProviders","detected","present","markerProbe","root","pattern","patterns","ids","provider","capability","envNames","dependencies","marker","readEnvVarNames","readDependencies","file","pkg"],"sources":["../../src/runtime/providers.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { capabilityName, providerMarkers } from \"../core/providers\";\nimport type { DetectedProviders, Pattern, ProviderMarker } from \"../core/types\";\nimport { readEnvVarNames } from \"./env-vars\";\n\ntype DetectablePattern = Pick<\n Pattern,\n \"slug\" | \"providers\" | \"inheritsProvider\"\n>;\n\n/**\n * The provider in use for each capability, read from what the providers left\n * in the project. Nothing records the choice, so this is the only way to know\n * it. A pattern that inherits its provider is skipped: its files say nothing\n * the capability it is built on doesn't already.\n *\n * The registry is passed in rather than imported, so this module and the\n * package entry don't import each other.\n */\nexport function detectProviders(\n root: string,\n patterns: readonly DetectablePattern[],\n): DetectedProviders {\n const detected: DetectedProviders = { providers: {}, ambiguous: [] };\n const present = markerProbe(root);\n\n for (const pattern of patterns) {\n if (!pattern.providers?.length || pattern.inheritsProvider) continue;\n const ids = pattern.providers\n .filter((provider) => providerMarkers(provider).some(present))\n .map((provider) => provider.id);\n\n const capability = capabilityName(pattern.slug);\n if (ids.length === 1) detected.providers[capability] = ids[0];\n if (ids.length > 1) detected.ambiguous.push({ capability, ids });\n }\n\n return detected;\n}\n\n/** Checks one marker against the project; `src/env.ts` and `package.json` are read once. */\nfunction markerProbe(root: string): (marker: ProviderMarker) => boolean {\n let envNames: Set<string> | undefined;\n let dependencies: Set<string> | undefined;\n\n return (marker) => {\n if (\"env\" in marker) {\n envNames ??= readEnvVarNames(root);\n return envNames.has(marker.env);\n }\n if (\"path\" in marker) {\n return fs.existsSync(path.join(root, marker.path));\n }\n dependencies ??= readDependencies(root);\n return dependencies.has(marker.dependency);\n };\n}\n\nfunction readDependencies(root: string): Set<string> {\n const file = path.join(root, \"package.json\");\n if (!fs.existsSync(file)) return new Set();\n try {\n const pkg = JSON.parse(fs.readFileSync(file, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return new Set([\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.devDependencies ?? {}),\n ]);\n } catch {\n return new Set();\n }\n}\n"],"mappings":";;;;;AAoBA,SAAgBI,EACd,GACA,GACmB;CACnB,IAAMC,IAA8B;EAAE,WAAW,CAAC;EAAG,WAAW,CAAC;CAAE,GAC7DC,IAAUC,EAAYC,CAAI;CAEhC,KAAK,IAAMC,KAAWC,GAAU;EAC9B,IAAI,CAACD,EAAQ,WAAW,UAAUA,EAAQ,kBAAkB;EAC5D,IAAME,IAAMF,EAAQ,UACjB,QAAQ,MAAaR,EAAgBW,CAAQ,CAAC,CAAC,KAAKN,CAAO,CAAC,CAAC,CAC7D,KAAK,MAAaM,EAAS,EAAE,GAE1BC,IAAab,EAAeS,EAAQ,IAAI;EAE9C,AADIE,EAAI,WAAW,MAAG,EAAS,UAAUE,KAAcF,EAAI,KACvDA,EAAI,SAAS,KAAGN,EAAS,UAAU,KAAK;GAAE;GAAY;EAAI,CAAC;CACjE;CAEA,OAAOA;AACT;AAGA,SAASE,EAAY,GAAmD;CACtE,IAAIO,GACAC;CAEJ,QAAQ,MACF,SAASC,KACX,MAAaC,EAAgBT,CAAI,GAC1BM,EAAS,IAAIE,EAAO,GAAG,KAE5B,UAAUA,IACLd,EAAG,WAAWC,EAAK,KAAKK,GAAMQ,EAAO,IAAI,CAAC,KAEnD,MAAiBE,EAAiBV,CAAI,GAC/BO,EAAa,IAAIC,EAAO,UAAU;AAE7C;AAEA,SAASE,EAAiB,GAA2B;CACnD,IAAMC,IAAOhB,EAAK,KAAKK,GAAM,cAAc;CAC3C,IAAI,CAACN,EAAG,WAAWiB,CAAI,GAAG,uBAAO,IAAI,IAAI;CACzC,IAAI;EACF,IAAMC,IAAM,KAAK,MAAMlB,EAAG,aAAaiB,GAAM,MAAM,CAAC;EAIpD,uBAAO,IAAI,IAAI,CACb,GAAG,OAAO,KAAKC,EAAI,gBAAgB,CAAC,CAAC,GACrC,GAAG,OAAO,KAAKA,EAAI,mBAAmB,CAAC,CAAC,CAC1C,CAAC;CACH,QAAQ;EACN,uBAAO,IAAI,IAAI;CACjB;AACF"}
@@ -15,7 +15,7 @@ async function n(e, t) {
15
15
  exists: !0,
16
16
  rowCount: 0
17
17
  }));
18
- let { withPocketbase: n } = await import("./pocketbase-CgwbH1gI.js").then((e) => e.r), { planCollectionDrops: r } = await import("./collections-zzZ_HQxB.js"), i = [];
18
+ let { withPocketbase: n } = await import("./pocketbase-B017Cqjq.js").then((e) => e.r), { planCollectionDrops: r } = await import("./collections-B_DisSfA.js").then((e) => e.n), i = [];
19
19
  return await n(t.root, async (t) => {
20
20
  let n = await r(t, e);
21
21
  i.push(...n);
@@ -24,4 +24,4 @@ async function n(e, t) {
24
24
  //#endregion
25
25
  export { t as n, n as t };
26
26
 
27
- //# sourceMappingURL=shared-Cc_ns5-y.js.map
27
+ //# sourceMappingURL=shared-BPlAVf-T.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-Cc_ns5-y.js","names":["languageFromPath","toDeleteEntry","path","planDropsForCollections","collectionNames","options","n","drops","withPocketbase","plans","planCollectionDrops","pb"],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgBC,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAUD,EAAiBE,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsBC,EACpB,GACA,GAC+B;CAC/B,IAAIC,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAIC,EAAQ,QAAQ,WAClB,OAAOD,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,2BAAA,CAAA,MAAA,MAAAE,EAAA,CAAA,GAClC,EAAE,2BAAwB,MAAM,OAAO,8BACvCC,IAA8B,CAAC;CAKrC,OAJA,MAAMC,EAAeH,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAMI,IAAQ,MAAMC,EAAoBC,GAAIP,CAAe;EAC3D,EAAM,KAAK,GAAGK,CAAK;CACrB,CAAC,GACMF;AACT"}
1
+ {"version":3,"file":"shared-BPlAVf-T.js","names":["languageFromPath","toDeleteEntry","path","planDropsForCollections","collectionNames","options","n","drops","withPocketbase","plans","planCollectionDrops","pb"],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgBC,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAUD,EAAiBE,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsBC,EACpB,GACA,GAC+B;CAC/B,IAAIC,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAIC,EAAQ,QAAQ,WAClB,OAAOD,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,2BAAA,CAAA,MAAA,MAAAE,EAAA,CAAA,GAClC,EAAE,2BAAwB,MAAM,OAAO,4BAAA,CAAA,MAAA,MAAAA,EAAA,CAAA,GACvCC,IAA8B,CAAC;CAKrC,OAJA,MAAMC,EAAeH,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAMI,IAAQ,MAAMC,EAAoBC,GAAIP,CAAe;EAC3D,EAAM,KAAK,GAAGK,CAAK;CACrB,CAAC,GACMF;AACT"}
@@ -0,0 +1,11 @@
1
+ import { t as e } from "./dedent-Gq6Krl4n.js";
2
+ import { t } from "./taggedTemplateLiteral-CswN2AAa.js";
3
+ //#region src/patterns/enable/payments/shopify-page.ts
4
+ var n;
5
+ function r(r) {
6
+ return e(n ||= t(["\n <script lang=\"ts\">\n import BuyButton from '#lib/components/payments/buy-button.svelte';\n <\/script>\n\n <section data-role=\"content\">\n <BuyButton variantId=\"", "\" />\n </section>\n "]), r);
7
+ }
8
+ //#endregion
9
+ export { r as t };
10
+
11
+ //# sourceMappingURL=shopify-page-D-VFwGxI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shopify-page-D-VFwGxI.js","names":["dedent","_templateObject","buyPageSnippet","_taggedTemplateLiteral","variantId"],"sources":["../../src/patterns/enable/payments/shopify-page.ts"],"sourcesContent":["import dedent from \"dedent\";\n\n/** The demo page: one Buy button for the variant named on the command line. */\nexport function buyPageSnippet(variantId: string): string {\n return dedent`\n <script lang=\"ts\">\n import BuyButton from '#lib/components/payments/buy-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <BuyButton variantId=\"${variantId}\" />\n </section>\n `;\n}\n"],"mappings":";;;;AAGA,SAAgBE,EAAe,GAA2B;CACxD,OAAOF,EAAA,AAAAC,MAAAE,EAAA,CAAA,+LAAA,2BAAA,CAAA,GAMqBC,CAE5B;AACF"}
@@ -0,0 +1,108 @@
1
+ import { a as e } from "./util-BLYliuUK.js";
2
+ import { n as t } from "./logger-CQONztPm.js";
3
+ import { i as n } from "./pocketbase-B017Cqjq.js";
4
+ import r from "node:fs";
5
+ import i from "node:path";
6
+ //#region src/runtime/site.ts
7
+ function a(e) {
8
+ return i.join(e, "src", "lib", "site.ts");
9
+ }
10
+ function o(e, t = "http://localhost:5173", n) {
11
+ return [
12
+ "/**",
13
+ " * Site-wide metadata, and the one place the app's name and public URL live.",
14
+ " *",
15
+ " * Set `url` to where the site is deployed: canonical links, Open Graph images",
16
+ " * and feeds are built from it, including in prerendered pages. With a backend,",
17
+ " * `vela dev` and `vela deploy` copy `name` into PocketBase's application name",
18
+ " * for the emails it sends, so change it here rather than in the admin panel.",
19
+ " */",
20
+ "export const site = {",
21
+ `\tname: ${f(e)},`,
22
+ n ? [`\turl: ${f(t)},`, ...s(n)].join("\n") : `\turl: ${f(t)}`,
23
+ "};",
24
+ ""
25
+ ].join("\n");
26
+ }
27
+ function s(e) {
28
+ return [" /** ISO 4217: the currency the business prices in and is paid in. */", `\tcurrency: ${f(e)}`];
29
+ }
30
+ function c(e) {
31
+ if (typeof e != "string") return null;
32
+ let t = e.trim().toUpperCase();
33
+ return /^[A-Z]{3}$/.test(t) && Intl.supportedValuesOf("currency").includes(t) ? t : null;
34
+ }
35
+ var l = /export const site = \{\n([\s\S]*?)\n\};/;
36
+ function u(e, t) {
37
+ let n = l.exec(e);
38
+ if (!n || /^\s*currency\s*:/m.test(n[1])) return null;
39
+ let r = n[1].replace(/,?\s*$/, ",");
40
+ return e.replace(n[0], `export const site = {\n${r}\n${s(t).join("\n")}\n};`);
41
+ }
42
+ function d(e) {
43
+ try {
44
+ let t = r.readFileSync(a(e), "utf8");
45
+ return /^\s*currency\s*:\s*['"]([A-Za-z]{3})['"]/m.exec(t)?.[1] ?? null;
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+ function f(e) {
51
+ return `'${e.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
52
+ }
53
+ async function p(e) {
54
+ if (e.features.backend) try {
55
+ let t;
56
+ if (await n(e.root, async (e) => {
57
+ t = (await e.settings.getAll()).meta?.appName;
58
+ }), typeof t == "string" && t.trim()) return t;
59
+ } catch {}
60
+ try {
61
+ let t = JSON.parse(r.readFileSync(i.join(e.root, "package.json"), "utf8"));
62
+ if (typeof t.name == "string" && t.name.trim()) return t.name;
63
+ } catch {}
64
+ return "My App";
65
+ }
66
+ async function m(n) {
67
+ let i = a(n.root);
68
+ return r.existsSync(i) ? null : (t(n).info("Creating src/lib/site.ts"), {
69
+ path: i,
70
+ language: e(i),
71
+ content: o(await p(n)),
72
+ status: "success"
73
+ });
74
+ }
75
+ async function h(n, i) {
76
+ let s = a(n.root);
77
+ if (!r.existsSync(s)) return t(n).info("Creating src/lib/site.ts"), {
78
+ file: {
79
+ path: s,
80
+ language: e(s),
81
+ content: o(await p(n), void 0, i),
82
+ status: "success"
83
+ },
84
+ currency: i
85
+ };
86
+ let c = d(n.root);
87
+ if (c) return {
88
+ file: null,
89
+ currency: c
90
+ };
91
+ let l = u(r.readFileSync(s, "utf8"), i);
92
+ return l === null ? {
93
+ file: null,
94
+ currency: i
95
+ } : (t(n).info(`Adding currency ${i} to src/lib/site.ts`), {
96
+ file: {
97
+ path: s,
98
+ language: e(s),
99
+ content: l,
100
+ status: "success"
101
+ },
102
+ currency: i
103
+ });
104
+ }
105
+ //#endregion
106
+ export { o as a, d as i, m as n, a as o, c as r, h as t };
107
+
108
+ //# sourceMappingURL=site-DkU1-VRq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-DkU1-VRq.js","names":["intl","languageFromPath","getLogger","withPocketbase","fs","path","sitePath","root","siteModule","quote","name","currency","url","currencyLines","normalizeCurrency","raw","code","SITE_OBJECT","withSiteCurrency","match","source","body","siteCurrency","value","existingName","options","appName","pb","pkg","ensureSiteFile","file","ensureSiteCurrency","existing","next"],"sources":["../../src/runtime/site.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options } from \"../core/types\";\nimport { getLogger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { withPocketbase } from \"./pocketbase\";\n\n/** Where every VelaStack app keeps its name and public URL. */\nexport function sitePath(root: string): string {\n return path.join(root, \"src\", \"lib\", \"site.ts\");\n}\n\n/**\n * `src/lib/site.ts` as the CLI templates ship it (`site.template.ts`), with\n * the placeholders filled in, plus the business's currency when one is given.\n */\nexport function siteModule(\n name: string,\n url = \"http://localhost:5173\",\n currency?: string,\n): string {\n return [\n \"/**\",\n \" * Site-wide metadata, and the one place the app's name and public URL live.\",\n \" *\",\n \" * Set `url` to where the site is deployed: canonical links, Open Graph images\",\n \" * and feeds are built from it, including in prerendered pages. With a backend,\",\n \" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name\",\n \" * for the emails it sends, so change it here rather than in the admin panel.\",\n \" */\",\n \"export const site = {\",\n `\\tname: ${quote(name)},`,\n currency\n ? [`\\turl: ${quote(url)},`, ...currencyLines(currency)].join(\"\\n\")\n : `\\turl: ${quote(url)}`,\n \"};\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** The `currency` property, with what it means; no trailing comma, as the last property. */\nfunction currencyLines(currency: string): string[] {\n return [\n \"\\t/** ISO 4217: the currency the business prices in and is paid in. */\",\n `\\tcurrency: ${quote(currency)}`,\n ];\n}\n\n/** A three-letter code `Intl` knows, upper-cased; anything else is refused. */\nexport function normalizeCurrency(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{3}$/.test(code)) return null;\n // Any well-formed code formats, so ask for the list of real ones. Node has\n // had it since 18; the repo's ES2020 lib types just don't declare it.\n const intl = Intl as unknown as {\n supportedValuesOf: (key: \"currency\") => string[];\n };\n return intl.supportedValuesOf(\"currency\").includes(code) ? code : null;\n}\n\nconst SITE_OBJECT = /export const site = \\{\\n([\\s\\S]*?)\\n\\};/;\n\n/**\n * `src/lib/site.ts` with `currency` added as the object's last property,\n * or `null` when it already has one (a project's currency is never changed\n * behind its back) or has no `export const site = { ... };` to add it to.\n */\nexport function withSiteCurrency(\n source: string,\n currency: string,\n): string | null {\n const match = SITE_OBJECT.exec(source);\n if (!match || /^\\s*currency\\s*:/m.test(match[1])) return null;\n const body = match[1].replace(/,?\\s*$/, \",\");\n return source.replace(\n match[0],\n `export const site = {\\n${body}\\n${currencyLines(currency).join(\"\\n\")}\\n};`,\n );\n}\n\n/** The currency `src/lib/site.ts` declares, if any. */\nexport function siteCurrency(root: string): string | null {\n try {\n const source = fs.readFileSync(sitePath(root), \"utf8\");\n return (\n /^\\s*currency\\s*:\\s*['\"]([A-Za-z]{3})['\"]/m.exec(source)?.[1] ?? null\n );\n } catch {\n return null;\n }\n}\n\n/** Single-quoted, as the templates write their strings. */\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/**\n * The name a project created before `site.ts` existed already goes by.\n *\n * Those projects kept it in PocketBase's settings, so that is asked first; the\n * package name is the fallback for a project without a backend, or one whose\n * database can't be reached.\n */\nasync function existingName(options: Options): Promise<string> {\n if (options.features.backend) {\n try {\n let appName: unknown;\n await withPocketbase(options.root, async (pb) => {\n const settings = (await pb.settings.getAll()) as {\n meta?: { appName?: unknown };\n };\n appName = settings.meta?.appName;\n });\n if (typeof appName === \"string\" && appName.trim()) return appName;\n } catch {\n // No database to ask; fall through to package.json.\n }\n }\n\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(options.root, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name;\n } catch {\n // No package.json to name the site after; the placeholder stands.\n }\n return \"My App\";\n}\n\n/**\n * Create `src/lib/site.ts` for a pattern whose files import `#lib/site.js`, when\n * the project doesn't have one yet. Every template ships it; projects created\n * before that read the app name from `locals.meta` instead.\n *\n * Returns null when the file exists, so an existing one is never overwritten.\n */\nexport async function ensureSiteFile(options: Options): Promise<File | null> {\n const file = sitePath(options.root);\n if (fs.existsSync(file)) return null;\n\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options)),\n status: \"success\",\n };\n}\n\n/**\n * Make `src/lib/site.ts` declare the business's currency: create the file\n * with it, or add it to an existing one that has none. An existing currency\n * is kept, whatever `currency` says; the result says which it was.\n */\nexport async function ensureSiteCurrency(\n options: Options,\n currency: string,\n): Promise<{ file: File | null; currency: string }> {\n const file = sitePath(options.root);\n if (!fs.existsSync(file)) {\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options), undefined, currency),\n status: \"success\",\n },\n currency,\n };\n }\n const existing = siteCurrency(options.root);\n if (existing) return { file: null, currency: existing };\n const next = withSiteCurrency(fs.readFileSync(file, \"utf8\"), currency);\n if (next === null) return { file: null, currency };\n getLogger(options).info(`Adding currency ${currency} to src/lib/site.ts`);\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: next,\n status: \"success\",\n },\n currency,\n };\n}\n"],"mappings":";;;;;;AAQA,SAAgBM,EAAS,GAAsB;CAC7C,OAAOD,EAAK,KAAKE,GAAM,OAAO,OAAO,SAAS;AAChD;AAMA,SAAgBC,EACd,GACA,IAAM,yBACN,GACQ;CACR,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAWC,EAAMC,CAAI,EAAE;EACvBC,IACI,CAAC,UAAUF,EAAMG,CAAG,EAAE,IAAI,GAAGC,EAAcF,CAAQ,CAAC,CAAC,CAAC,KAAK,IAAI,IAC/D,UAAUF,EAAMG,CAAG;EACvB;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAGA,SAAS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ib/server/stripe-customer.ts?raw
2
+ var e = "import { linkStripeCustomer } from '#lib/workflows/link-stripe-customer.js';\n\n/**\n * The user's Stripe customer id. Signup starts link-stripe-customer in the\n * background, so a user can get here before it finishes, or without it ever\n * starting (a one-time-code signup, an import). Either way this starts or\n * joins that same run (the user's id is its idempotency key, so there is still\n * one customer) and waits a little for it.\n *\n * Throws when the customer is not there in time; the caller decides whether to\n * say \"try again shortly\" or fail.\n */\nexport async function getStripeCustomerId(\n admin: App.Locals['admin'],\n user: { id: string; email?: string },\n timeoutMs = 10_000\n): Promise<string> {\n try {\n const customer = await admin\n .collection('stripe_customers')\n .getFirstListItem(admin.filter('user = {:user}', { user: user.id }));\n return customer.id;\n } catch {\n // Not linked yet.\n }\n\n const handle = await linkStripeCustomer.run(\n { userId: user.id, email: user.email || undefined },\n { idempotencyKey: user.id }\n );\n const { customerId } = await handle.result({ timeoutMs });\n return customerId;\n}\n";
3
+ //#endregion
4
+ export { e as t };
5
+
6
+ //# sourceMappingURL=stripe-customer-B3tP8gtD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stripe-customer-B3tP8gtD.js","names":["stripe_customer_default"],"sources":[],"mappings":""}
@@ -36,7 +36,7 @@ var r = class r {
36
36
  return n !== e.content && (this.s.overwrite(e.start, e.end, n), !0);
37
37
  }
38
38
  findElement(e) {
39
- return i(this.ast.fragment, (t) => (t.type === "Component" || t.type === "RegularElement") && t.name === e);
39
+ return a(this.ast.fragment, (t) => (t.type === "Component" || t.type === "RegularElement") && t.name === e);
40
40
  }
41
41
  hasElement(e) {
42
42
  return this.findElement(e) !== null;
@@ -58,6 +58,38 @@ var r = class r {
58
58
  removeElement(e) {
59
59
  return this.replaceElement(e, "");
60
60
  }
61
+ findElementContaining(e, t) {
62
+ return a(this.ast.fragment, (n) => i(n, e) && a(n.fragment, (e) => i(e, t)) !== null);
63
+ }
64
+ childElements(e, t) {
65
+ return (this.findElement(e)?.fragment?.nodes ?? []).filter((e) => i(e, t));
66
+ }
67
+ insertBeforeElement(e, t) {
68
+ let n = this.indentOf(e.start);
69
+ this.s.appendLeft(e.start, `${this.reindent(t, n)}\n${n}`);
70
+ }
71
+ insertAfterElement(e, t) {
72
+ let n = this.indentOf(e.start);
73
+ this.s.appendLeft(e.end, `\n${n}${this.reindent(t, n)}`);
74
+ }
75
+ removeElementContaining(e, t) {
76
+ let n = this.findElementContaining(e, t);
77
+ if (!n) return !1;
78
+ let r = n.start;
79
+ for (; r > 0 && /[ \t]/.test(this.source[r - 1]);) r--;
80
+ return r > 0 && this.source[r - 1] === "\n" && r--, this.s.remove(r, n.end), !0;
81
+ }
82
+ indentOf(e) {
83
+ let t = this.source.lastIndexOf("\n", e - 1) + 1, n = this.source.slice(t, e);
84
+ return /^[ \t]*$/.test(n) ? n : "";
85
+ }
86
+ reindent(e, t) {
87
+ let n = t.includes(" ") ? " " : " ";
88
+ return e.split("\n").map((e, r) => {
89
+ let i = e.replace(/^\t+/, (e) => n.repeat(e.length));
90
+ return r === 0 ? i : `${t}${i}`;
91
+ }).join("\n");
92
+ }
61
93
  appendMarkup(e) {
62
94
  this.s.append(e);
63
95
  }
@@ -97,6 +129,9 @@ var r = class r {
97
129
  }
98
130
  };
99
131
  function i(e, t) {
132
+ return (e?.type === "Component" || e?.type === "RegularElement") && e.name === t;
133
+ }
134
+ function a(e, t) {
100
135
  let n = /* @__PURE__ */ new WeakSet();
101
136
  function r(e) {
102
137
  if (!e || typeof e != "object" || n.has(e)) return null;
@@ -120,4 +155,4 @@ function i(e, t) {
120
155
  //#endregion
121
156
  export { r as t };
122
157
 
123
- //# sourceMappingURL=svelte-file-B3RfgVdt.js.map
158
+ //# sourceMappingURL=svelte-file-Dv5-bl79.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"svelte-file-Dv5-bl79.js","names":["fs","MagicString","SvelteFile","source","parse","filePath","script","start","end","fn","block","next","findNode","node","name","componentName","attr","attrName","closingTag","closingPos","content","newContent","isElement","outer","child","inner","candidate","indent","lineStart","pos","lead","unit","nested","line","tabs","i","nodes","index","trimmed","prev","last","insertAt","attrs","a","seen","visit","predicate","key","item","found","root"],"sources":["../../src/runtime/svelte-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { parse, type AST } from \"svelte/compiler\";\nimport MagicString from \"magic-string\";\n\ntype SvelteAst = AST.Root;\ntype SvelteNode = any;\n\ninterface ScriptBlock {\n content: string;\n start: number;\n end: number;\n}\n\n/**\n * Surgical, AST-aware editing of .svelte files.\n *\n * Parses the source with svelte/compiler to discover precise character offsets,\n * then applies edits via magic-string so untouched regions remain byte-for-byte\n * identical to the original. Script-block contents are exposed as plain strings\n * so callers can hand them to ts-morph.\n */\nexport class SvelteFile {\n private readonly source: string;\n private readonly ast: SvelteAst;\n private readonly s: MagicString;\n\n constructor(source: string) {\n this.source = source;\n this.ast = parse(source, { modern: true });\n this.s = new MagicString(source);\n }\n\n static fromPath(filePath: string): SvelteFile {\n return new SvelteFile(fs.readFileSync(filePath, \"utf8\"));\n }\n\n getScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).instance);\n }\n\n getModuleScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).module);\n }\n\n private scriptInner(script: SvelteNode | null): ScriptBlock | null {\n if (!script) return null;\n const start = script.content.start as number;\n const end = script.content.end as number;\n return { content: this.source.slice(start, end), start, end };\n }\n\n /**\n * Replace the inner contents of <script>. Use for ts-morph round-trips.\n * Returns true when an edit was made.\n */\n modifyScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getScript(), fn);\n }\n\n modifyModuleScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getModuleScript(), fn);\n }\n\n private modifyScriptBlock(\n block: ScriptBlock | null,\n fn: (content: string) => string,\n ): boolean {\n if (!block) return false;\n const next = fn(block.content);\n if (next === block.content) return false;\n this.s.overwrite(block.start, block.end, next);\n return true;\n }\n\n /** First Component or RegularElement node with the given name. */\n findElement(name: string): SvelteNode | null {\n return findNode(\n (this.ast as any).fragment,\n (node) =>\n (node.type === \"Component\" || node.type === \"RegularElement\") &&\n node.name === name,\n );\n }\n\n hasElement(name: string): boolean {\n return this.findElement(name) !== null;\n }\n\n hasAttribute(componentName: string, attrName: string): boolean {\n const node = this.findElement(componentName);\n if (!node) return false;\n return (node.attributes ?? []).some(\n (attr: SvelteNode) => attr.type === \"Attribute\" && attr.name === attrName,\n );\n }\n\n /**\n * Insert content at the end of <ComponentName>'s children, just before the\n * closing tag. No-op if the element is not found.\n */\n insertBeforeClosingTag(name: string, content: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const closingTag = `</${name}>`;\n const closingPos = this.source.lastIndexOf(closingTag, node.end);\n if (closingPos === -1) return false;\n this.s.appendLeft(closingPos, content);\n return true;\n }\n\n /** Replace the element entirely (start tag through close tag). */\n replaceElement(name: string, newContent: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n this.s.overwrite(node.start, node.end, newContent);\n return true;\n }\n\n /** Remove the element (start tag through close tag). */\n removeElement(name: string): boolean {\n return this.replaceElement(name, \"\");\n }\n\n /**\n * The first <outer> element with an <inner> element somewhere inside it:\n * the `Navbar.Item` that holds `AuthMenu.Root`, among several items.\n */\n findElementContaining(outer: string, inner: string): SvelteNode | null {\n return findNode(\n (this.ast as any).fragment,\n (node) =>\n isElement(node, outer) &&\n findNode(node.fragment, (child) => isElement(child, inner)) !== null,\n );\n }\n\n /** The <child> elements directly inside the first <name> element, in order. */\n childElements(name: string, child: string): SvelteNode[] {\n const node = this.findElement(name);\n const nodes: SvelteNode[] = node?.fragment?.nodes ?? [];\n return nodes.filter((candidate) => isElement(candidate, child));\n }\n\n /**\n * Put `content` on its own line directly before `node`, at `node`'s\n * indentation. Lines after the first are indented to match too, with their\n * leading tabs turned into the file's indent unit.\n */\n insertBeforeElement(node: SvelteNode, content: string): void {\n const indent = this.indentOf(node.start as number);\n this.s.appendLeft(\n node.start as number,\n `${this.reindent(content, indent)}\\n${indent}`,\n );\n }\n\n /** Like `insertBeforeElement`, on the line after `node`. */\n insertAfterElement(node: SvelteNode, content: string): void {\n const indent = this.indentOf(node.start as number);\n this.s.appendLeft(\n node.end as number,\n `\\n${indent}${this.reindent(content, indent)}`,\n );\n }\n\n /**\n * Remove the first <outer> containing <inner>, and the line it stood on\n * when nothing else shared it. Returns false when there is none.\n */\n removeElementContaining(outer: string, inner: string): boolean {\n const node = this.findElementContaining(outer, inner);\n if (!node) return false;\n let start = node.start as number;\n while (start > 0 && /[ \\t]/.test(this.source[start - 1]!)) start--;\n if (start > 0 && this.source[start - 1] === \"\\n\") start--;\n this.s.remove(start, node.end as number);\n return true;\n }\n\n /** The whitespace between the start of `pos`'s line and `pos`. */\n private indentOf(pos: number): string {\n const lineStart = this.source.lastIndexOf(\"\\n\", pos - 1) + 1;\n const lead = this.source.slice(lineStart, pos);\n return /^[ \\t]*$/.test(lead) ? lead : \"\";\n }\n\n private reindent(content: string, indent: string): string {\n const unit = indent.includes(\" \") ? \" \" : \"\\t\";\n return content\n .split(\"\\n\")\n .map((line, i) => {\n const nested = line.replace(/^\\t+/, (tabs) => unit.repeat(tabs.length));\n return i === 0 ? nested : `${indent}${nested}`;\n })\n .join(\"\\n\");\n }\n\n /** Append raw markup to the end of the source file. */\n appendMarkup(content: string): void {\n this.s.append(content);\n }\n\n /**\n * Insert markup so it renders before the layout's children — i.e. ahead of\n * the top-level `{@render children()}` (or legacy `<slot />`). The markup\n * lands on its own line directly after the preceding sibling, so\n *\n * <Toaster />\n *\n * {@render children?.()}\n *\n * becomes `<Toaster />\\n<AdminBar />\\n\\n{@render children?.()}`. When the\n * render tag is the first node the markup goes immediately before it.\n * Returns false (and changes nothing) if no such tag exists.\n */\n insertBeforeChildren(content: string): boolean {\n const nodes: SvelteNode[] = (this.ast as any).fragment?.nodes ?? [];\n const index = nodes.findIndex(\n (node) =>\n node.type === \"RenderTag\" ||\n node.type === \"SlotElement\" ||\n (node.type === \"RegularElement\" && node.name === \"slot\"),\n );\n if (index === -1) return false;\n\n const trimmed = content.trim();\n for (let i = index - 1; i >= 0; i--) {\n const prev = nodes[i]!;\n if (prev.type === \"Text\" && prev.data.trim() === \"\") continue;\n this.s.appendLeft(prev.end as number, `\\n${trimmed}`);\n return true;\n }\n this.s.appendLeft(nodes[index]!.start as number, `${trimmed}\\n\\n`);\n return true;\n }\n\n /**\n * Append attribute text (e.g. \" team={data.team}\") just after the last\n * existing attribute on the element's start tag.\n */\n appendToAttributes(name: string, attrs: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const last = (node.attributes ?? []).at(-1) as SvelteNode | undefined;\n const insertAt = last\n ? (last.end as number)\n : (node.start as number) + `<${name}`.length;\n this.s.appendLeft(insertAt, attrs);\n return true;\n }\n\n /**\n * Remove a named attribute from a component's start tag, including the\n * leading whitespace. No-op if the element or attribute isn't present.\n */\n removeAttribute(name: string, attrName: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const attr = (node.attributes ?? []).find(\n (a: SvelteNode) => a.type === \"Attribute\" && a.name === attrName,\n );\n if (!attr) return false;\n // Extend the removal backwards over the whitespace between the previous\n // token and this attribute so the tag doesn't collapse `<Foo />`.\n let start = attr.start as number;\n while (start > 0 && /\\s/.test(this.source[start - 1]!)) start--;\n this.s.remove(start, attr.end as number);\n return true;\n }\n\n hasChanged(): boolean {\n return this.s.hasChanged();\n }\n\n toString(): string {\n return this.s.toString();\n }\n\n writeTo(filePath: string): void {\n if (this.hasChanged()) {\n fs.writeFileSync(filePath, this.toString(), \"utf8\");\n }\n }\n}\n\nfunction isElement(node: any, name: string): boolean {\n return (\n (node?.type === \"Component\" || node?.type === \"RegularElement\") &&\n node.name === name\n );\n}\n\nfunction findNode(\n root: unknown,\n predicate: (node: any) => boolean,\n): any | null {\n const seen = new WeakSet<object>();\n function visit(node: unknown): any | null {\n if (!node || typeof node !== \"object\" || seen.has(node as object)) {\n return null;\n }\n seen.add(node as object);\n if (predicate(node as any)) return node;\n for (const key of Object.keys(node as Record<string, unknown>)) {\n if (key === \"parent\") continue;\n const child = (node as Record<string, unknown>)[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n const found = visit(item);\n if (found) return found;\n }\n } else if (\n child &&\n typeof child === \"object\" &&\n \"type\" in (child as object)\n ) {\n const found = visit(child);\n if (found) return found;\n }\n }\n return null;\n }\n return visit(root);\n}\n"],"mappings":";;;;AAqBA,IAAaE,IAAb,MAAaA,EAAW;CAKtB,YAAY,GAAgB;EAG1B,AAFA,KAAK,SAASC,GACd,KAAK,MAAMC,EAAMD,GAAQ,EAAE,QAAQ,GAAK,CAAC,GACzC,KAAK,IAAI,IAAIF,EAAYE,CAAM;CACjC;CAEA,OAAO,SAAS,GAA8B;EAC5C,OAAO,IAAID,EAAWF,EAAG,aAAaK,GAAU,MAAM,CAAC;CACzD;CAEA,YAAgC;EAC9B,OAAO,KAAK,YAAa,KAAK,IAAY,QAAQ;CACpD;CAEA,kBAAsC;EACpC,OAAO,KAAK,YAAa,KAAK,IAAY,MAAM;CAClD;CAEA,YAAoB,GAA+C;EACjE,IAAI,CAACC,GAAQ,OAAO;EACpB,IAAMC,IAAQD,EAAO,QAAQ,OACvBE,IAAMF,EAAO,QAAQ;EAC3B,OAAO;GAAE,SAAS,KAAK,OAAO,MAAMC,GAAOC,CAAG;GAAG;GAAO;EAAI;CAC9D;CAMA,aAAa,GAA0C;EACrD,OAAO,KAAK,kBAAkB,KAAK,UAAU,GAAGC,CAAE;CACpD;CAEA,mBAAmB,GAA0C;EAC3D,OAAO,KAAK,kBAAkB,KAAK,gBAAgB,GAAGA,CAAE;CAC1D;CAEA,kBACE,GACA,GACS;EACT,IAAI,CAACC,GAAO,OAAO;EACnB,IAAMC,IAAOF,EAAGC,EAAM,OAAO;EAG7B,OAFIC,MAASD,EAAM,YACnB,KAAK,EAAE,UAAUA,EAAM,OAAOA,EAAM,KAAKC,CAAI,GACtC;CACT;CAGA,YAAY,GAAiC;EAC3C,OAAOC,EACJ,KAAK,IAAY,WACjB,OACEC,EAAK,SAAS,eAAeA,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