@velastack/patterns 0.5.0 → 0.7.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 (152) hide show
  1. package/README.md +11 -0
  2. package/dist/chunks/{_layout-D-FzWqn0.js → _layout-Bsx3eNrC.js} +3 -3
  3. package/dist/chunks/{_layout-D-FzWqn0.js.map → _layout-Bsx3eNrC.js.map} +1 -1
  4. package/dist/chunks/{auth-pages-B52ei-4z.js → auth-pages-jsyDV1GR.js} +7 -10
  5. package/dist/chunks/{auth-pages-B52ei-4z.js.map → auth-pages-jsyDV1GR.js.map} +1 -1
  6. package/dist/chunks/collections-BrEA7a62.js +309 -0
  7. package/dist/chunks/collections-BrEA7a62.js.map +1 -0
  8. package/dist/chunks/{collections-Cpjo2OiQ.js → collections-DrUG8ngq.js} +39 -35
  9. package/dist/chunks/collections-DrUG8ngq.js.map +1 -0
  10. package/dist/chunks/{compose-handle-BDlZ7Pif.js → compose-handle-BBlamPfx.js} +18 -22
  11. package/dist/chunks/{compose-handle-BDlZ7Pif.js.map → compose-handle-BBlamPfx.js.map} +1 -1
  12. package/dist/chunks/{config-target-rHgjaA8u.js → config-target-BgyFkbFL.js} +2 -2
  13. package/dist/chunks/{config-target-rHgjaA8u.js.map → config-target-BgyFkbFL.js.map} +1 -1
  14. package/dist/chunks/{constants-Rq8SCXwH.js → constants-iej3WkEa.js} +3 -3
  15. package/dist/chunks/constants-iej3WkEa.js.map +1 -0
  16. package/dist/chunks/dedent-Gq6Krl4n.js.map +1 -1
  17. package/dist/chunks/{env-BPfk1VAw.js → env-BugddEjd.js} +5 -9
  18. package/dist/chunks/{env-BPfk1VAw.js.map → env-BugddEjd.js.map} +1 -1
  19. package/dist/chunks/{env-vars-Bj41Nccm.js → env-vars-CdarYsrc.js} +6 -11
  20. package/dist/chunks/{env-vars-Bj41Nccm.js.map → env-vars-CdarYsrc.js.map} +1 -1
  21. package/dist/chunks/{generate-dNlBII84.js → generate-27CjLiGW.js} +2 -2
  22. package/dist/chunks/{generate-dNlBII84.js.map → generate-27CjLiGW.js.map} +1 -1
  23. package/dist/chunks/{generate-yi8AP3xH.js → generate-BFcy2wrS.js} +3 -3
  24. package/dist/chunks/{generate-yi8AP3xH.js.map → generate-BFcy2wrS.js.map} +1 -1
  25. package/dist/chunks/generate-BxOzEdc_.js +171 -0
  26. package/dist/chunks/generate-BxOzEdc_.js.map +1 -0
  27. package/dist/chunks/{generate-B6Odfk5f.js → generate-Cqwa8kD9.js} +2 -2
  28. package/dist/chunks/{generate-B6Odfk5f.js.map → generate-Cqwa8kD9.js.map} +1 -1
  29. package/dist/chunks/{generate-DjBMRzsB.js → generate-D3mSFPdT.js} +2 -2
  30. package/dist/chunks/{generate-DjBMRzsB.js.map → generate-D3mSFPdT.js.map} +1 -1
  31. package/dist/chunks/{generate-ZIOVLH6Q.js → generate-DdLwP0E7.js} +51 -47
  32. package/dist/chunks/generate-DdLwP0E7.js.map +1 -0
  33. package/dist/chunks/generate-DyV5R8NP.js.map +1 -1
  34. package/dist/chunks/{generate.runtime-MjWwR2Bd.js → generate.runtime-9KuMcI5r.js} +10 -13
  35. package/dist/chunks/{generate.runtime-MjWwR2Bd.js.map → generate.runtime-9KuMcI5r.js.map} +1 -1
  36. package/dist/chunks/{generate.runtime-BKINIJ2c.js → generate.runtime-B10-KA87.js} +69 -69
  37. package/dist/chunks/{generate.runtime-BKINIJ2c.js.map → generate.runtime-B10-KA87.js.map} +1 -1
  38. package/dist/chunks/{generate.runtime-DaRVyiSg.js → generate.runtime-B8-GLMkk.js} +131 -197
  39. package/dist/chunks/generate.runtime-B8-GLMkk.js.map +1 -0
  40. package/dist/chunks/{generate.runtime-Bdpu4rX0.js → generate.runtime-BGuXHl5o.js} +3 -3
  41. package/dist/chunks/{generate.runtime-Bdpu4rX0.js.map → generate.runtime-BGuXHl5o.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-DjCzW3zU.js → generate.runtime-BJxM7FNA.js} +7 -7
  43. package/dist/chunks/{generate.runtime-DjCzW3zU.js.map → generate.runtime-BJxM7FNA.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-BdmoAVJK.js → generate.runtime-BWRtyQeD.js} +5 -5
  45. package/dist/chunks/{generate.runtime-BdmoAVJK.js.map → generate.runtime-BWRtyQeD.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-CV4soy2n.js → generate.runtime-B_tWu-Bw.js} +47 -47
  47. package/dist/chunks/{generate.runtime-CV4soy2n.js.map → generate.runtime-B_tWu-Bw.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-NaSIZlP5.js → generate.runtime-BdghkfNp.js} +3 -3
  49. package/dist/chunks/{generate.runtime-NaSIZlP5.js.map → generate.runtime-BdghkfNp.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-B4QoBn5v.js → generate.runtime-Blb6QPZn.js} +8 -8
  51. package/dist/chunks/{generate.runtime-B4QoBn5v.js.map → generate.runtime-Blb6QPZn.js.map} +1 -1
  52. package/dist/chunks/{generate.runtime-DRRyPa-e.js → generate.runtime-CEexT8cJ.js} +66 -66
  53. package/dist/chunks/{generate.runtime-DRRyPa-e.js.map → generate.runtime-CEexT8cJ.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-BKTkVCEm.js → generate.runtime-CIZO2XO9.js} +4 -4
  55. package/dist/chunks/{generate.runtime-BKTkVCEm.js.map → generate.runtime-CIZO2XO9.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-DmsOEsJV.js → generate.runtime-CK0MTeqc.js} +4 -4
  57. package/dist/chunks/{generate.runtime-DmsOEsJV.js.map → generate.runtime-CK0MTeqc.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-BavEh01F.js → generate.runtime-CMO-Skpk.js} +5 -5
  59. package/dist/chunks/{generate.runtime-BavEh01F.js.map → generate.runtime-CMO-Skpk.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-BXZDKLbA.js → generate.runtime-CVDb-yLt.js} +12 -20
  61. package/dist/chunks/{generate.runtime-BXZDKLbA.js.map → generate.runtime-CVDb-yLt.js.map} +1 -1
  62. package/dist/chunks/generate.runtime-C_5Ghjri.js +17 -0
  63. package/dist/chunks/generate.runtime-C_5Ghjri.js.map +1 -0
  64. package/dist/chunks/{generate.runtime-CWgZhxQt.js → generate.runtime-CbOMXQSo.js} +3 -3
  65. package/dist/chunks/{generate.runtime-CWgZhxQt.js.map → generate.runtime-CbOMXQSo.js.map} +1 -1
  66. package/dist/chunks/{generate.runtime-DBBtYTAa.js → generate.runtime-CbT-EbQT.js} +5 -5
  67. package/dist/chunks/{generate.runtime-DBBtYTAa.js.map → generate.runtime-CbT-EbQT.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-CSUnP0l-.js → generate.runtime-Cxr15Y5H.js} +27 -27
  69. package/dist/chunks/{generate.runtime-CSUnP0l-.js.map → generate.runtime-Cxr15Y5H.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-pMpn0Pbf.js → generate.runtime-CyTxBcX3.js} +10 -10
  71. package/dist/chunks/{generate.runtime-pMpn0Pbf.js.map → generate.runtime-CyTxBcX3.js.map} +1 -1
  72. package/dist/chunks/{generate.runtime-azOvp6tl.js → generate.runtime-D5HxAups.js} +39 -36
  73. package/dist/chunks/generate.runtime-D5HxAups.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-b2RtuPy4.js → generate.runtime-D6vhkGs8.js} +5 -5
  75. package/dist/chunks/{generate.runtime-b2RtuPy4.js.map → generate.runtime-D6vhkGs8.js.map} +1 -1
  76. package/dist/chunks/{generate.runtime-DlbG-8Xm.js → generate.runtime-DIeAeOJg.js} +6 -6
  77. package/dist/chunks/{generate.runtime-DlbG-8Xm.js.map → generate.runtime-DIeAeOJg.js.map} +1 -1
  78. package/dist/chunks/{generate.runtime-QbmCPT42.js → generate.runtime-DMTAocSE.js} +17 -17
  79. package/dist/chunks/{generate.runtime-QbmCPT42.js.map → generate.runtime-DMTAocSE.js.map} +1 -1
  80. package/dist/chunks/{generate.runtime-utFLS6Jz.js → generate.runtime-DlLwmjGF.js} +133 -121
  81. package/dist/chunks/generate.runtime-DlLwmjGF.js.map +1 -0
  82. package/dist/chunks/{generate.runtime-BYfyZHhs.js → generate.runtime-DtCaz98N.js} +6 -6
  83. package/dist/chunks/{generate.runtime-BYfyZHhs.js.map → generate.runtime-DtCaz98N.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-BcgjZJug.js → generate.runtime-HSZD935T.js} +4 -4
  85. package/dist/chunks/{generate.runtime-BcgjZJug.js.map → generate.runtime-HSZD935T.js.map} +1 -1
  86. package/dist/chunks/{generate.runtime-OEgsdWRP.js → generate.runtime-Nnk5E8Pi.js} +3 -3
  87. package/dist/chunks/{generate.runtime-OEgsdWRP.js.map → generate.runtime-Nnk5E8Pi.js.map} +1 -1
  88. package/dist/chunks/{generate.runtime-D-qtaVdq.js → generate.runtime-NxuWvkKt.js} +13 -13
  89. package/dist/chunks/{generate.runtime-D-qtaVdq.js.map → generate.runtime-NxuWvkKt.js.map} +1 -1
  90. package/dist/chunks/{generate.runtime-CCV4O6_I.js → generate.runtime-dFTOU_KE.js} +71 -71
  91. package/dist/chunks/{generate.runtime-CCV4O6_I.js.map → generate.runtime-dFTOU_KE.js.map} +1 -1
  92. package/dist/chunks/{generate.runtime-C7s1Mx5L.js → generate.runtime-m0m43lkL.js} +7 -7
  93. package/dist/chunks/{generate.runtime-C7s1Mx5L.js.map → generate.runtime-m0m43lkL.js.map} +1 -1
  94. package/dist/chunks/{generate.runtime-BdHv7Jp1.js → generate.runtime-si5Za61F.js} +3 -3
  95. package/dist/chunks/{generate.runtime-BdHv7Jp1.js.map → generate.runtime-si5Za61F.js.map} +1 -1
  96. package/dist/chunks/{generate.runtime-DetYynf4.js → generate.runtime-tGKorg85.js} +10 -14
  97. package/dist/chunks/{generate.runtime-DetYynf4.js.map → generate.runtime-tGKorg85.js.map} +1 -1
  98. package/dist/chunks/{generate.runtime-CcPCAEV0.js → generate.runtime-ww3-1FWf.js} +6 -6
  99. package/dist/chunks/{generate.runtime-CcPCAEV0.js.map → generate.runtime-ww3-1FWf.js.map} +1 -1
  100. package/dist/chunks/{modify-file-Bbhyfiy_.js → modify-file-COBp4eCh.js} +4 -4
  101. package/dist/chunks/{modify-file-Bbhyfiy_.js.map → modify-file-COBp4eCh.js.map} +1 -1
  102. package/dist/chunks/{modify-nav-user-B8h8WTrM.js → modify-nav-user-CJ1LevSU.js} +2 -2
  103. package/dist/chunks/{modify-nav-user-B8h8WTrM.js.map → modify-nav-user-CJ1LevSU.js.map} +1 -1
  104. package/dist/chunks/{modify-svelte-config-remote-DhuRX4FI.js → modify-svelte-config-remote-CEyYydL7.js} +2 -2
  105. package/dist/chunks/{modify-svelte-config-remote-DhuRX4FI.js.map → modify-svelte-config-remote-CEyYydL7.js.map} +1 -1
  106. package/dist/chunks/{modify-user-signup-BbqTiUuA.js → modify-user-signup-DLtopazD.js} +2 -2
  107. package/dist/chunks/{modify-user-signup-BbqTiUuA.js.map → modify-user-signup-DLtopazD.js.map} +1 -1
  108. package/dist/chunks/{package-imports-Bbw3iMPg.js → package-imports-Dx05A-4S.js} +2 -2
  109. package/dist/chunks/{package-imports-Bbw3iMPg.js.map → package-imports-Dx05A-4S.js.map} +1 -1
  110. package/dist/chunks/{pocketbase-CgwbH1gI.js → pocketbase-DL02rq73.js} +5 -13
  111. package/dist/chunks/{pocketbase-CgwbH1gI.js.map → pocketbase-DL02rq73.js.map} +1 -1
  112. package/dist/chunks/{providers-DwbwccSW.js → providers-CAehyySB.js} +2 -2
  113. package/dist/chunks/{providers-DwbwccSW.js.map → providers-CAehyySB.js.map} +1 -1
  114. package/dist/chunks/{rolldown-runtime-DArdT4gl.js → rolldown-runtime-5HNE8Q1r.js} +1 -1
  115. package/dist/chunks/{shared-D5GOS97l.js → shared-C_Fr8wph.js} +2 -2
  116. package/dist/chunks/{shared-D5GOS97l.js.map → shared-C_Fr8wph.js.map} +1 -1
  117. package/dist/chunks/site-BoujshKo.js +108 -0
  118. package/dist/chunks/site-BoujshKo.js.map +1 -0
  119. package/dist/chunks/{table-core-DhDqT03G.js → table-core-BPv_RYgD.js} +3 -3
  120. package/dist/chunks/{table-core-DhDqT03G.js.map → table-core-BPv_RYgD.js.map} +1 -1
  121. package/dist/chunks/{taggedTemplateLiteral-CswN2AAa.js → taggedTemplateLiteral-KSUnuvOk.js} +1 -1
  122. package/dist/chunks/{test-setup-DZoyF8Ak.js → test-setup-pYUIfWb2.js} +5 -5
  123. package/dist/chunks/{test-setup-DZoyF8Ak.js.map → test-setup-pYUIfWb2.js.map} +1 -1
  124. package/dist/chunks/{ts-morph-helpers-Bepc-Es2.js → ts-morph-helpers-CHI9wAil.js} +7 -11
  125. package/dist/chunks/{ts-morph-helpers-Bepc-Es2.js.map → ts-morph-helpers-CHI9wAil.js.map} +1 -1
  126. package/dist/chunks/{ui-BuocThuh.js → ui-B2yn8c_-.js} +3 -3
  127. package/dist/chunks/{ui-BuocThuh.js.map → ui-B2yn8c_-.js.map} +1 -1
  128. package/dist/chunks/{unmodify-load-Bl5vXQiL.js → unmodify-load-Buak-r1f.js} +2 -2
  129. package/dist/chunks/{unmodify-load-Bl5vXQiL.js.map → unmodify-load-Buak-r1f.js.map} +1 -1
  130. package/dist/chunks/{whatsapp-CguKGTtw.js → whatsapp-5qJ_xCV1.js} +2 -2
  131. package/dist/chunks/{whatsapp-CguKGTtw.js.map → whatsapp-5qJ_xCV1.js.map} +1 -1
  132. package/dist/chunks/{write-result-Cq-9A7Zy.js → write-result-Bn4bnrBI.js} +20 -50
  133. package/dist/chunks/write-result-Bn4bnrBI.js.map +1 -0
  134. package/dist/chunks/wuchale-config-c3Q4JVSF.js +50 -0
  135. package/dist/chunks/wuchale-config-c3Q4JVSF.js.map +1 -0
  136. package/dist/index.d.ts +162 -1
  137. package/dist/index.js +2193 -2330
  138. package/dist/index.js.map +1 -1
  139. package/package.json +2 -2
  140. package/dist/chunks/collections-Cpjo2OiQ.js.map +0 -1
  141. package/dist/chunks/constants-Rq8SCXwH.js.map +0 -1
  142. package/dist/chunks/generate-BClgUH4J.js +0 -137
  143. package/dist/chunks/generate-BClgUH4J.js.map +0 -1
  144. package/dist/chunks/generate-ZIOVLH6Q.js.map +0 -1
  145. package/dist/chunks/generate.runtime-DaRVyiSg.js.map +0 -1
  146. package/dist/chunks/generate.runtime-azOvp6tl.js.map +0 -1
  147. package/dist/chunks/generate.runtime-utFLS6Jz.js.map +0 -1
  148. package/dist/chunks/shopify-page-D-VFwGxI.js +0 -11
  149. package/dist/chunks/shopify-page-D-VFwGxI.js.map +0 -1
  150. package/dist/chunks/site-lj0CDdQ1.js +0 -55
  151. package/dist/chunks/site-lj0CDdQ1.js.map +0 -1
  152. package/dist/chunks/write-result-Cq-9A7Zy.js.map +0 -1
@@ -1,11 +1,11 @@
1
1
  import { n as e } from "./logger-CQONztPm.js";
2
2
  import { n as t, t as n } from "./_page-DoPdZgZv.js";
3
- import { t as r } from "./shared-D5GOS97l.js";
4
- import { _ as i, h as a, o, u as s } from "./ts-morph-helpers-Bepc-Es2.js";
5
- import { r as c } from "./modify-file-Bbhyfiy_.js";
3
+ import { t as r } from "./shared-C_Fr8wph.js";
4
+ import { _ as i, h as a, o, u as s } from "./ts-morph-helpers-CHI9wAil.js";
5
+ import { r as c } from "./modify-file-COBp4eCh.js";
6
6
  import { t as l } from "./svelte-file-Dv5-bl79.js";
7
- import { t as u } from "./unmodify-load-Bl5vXQiL.js";
8
- import { r as d, t as f } from "./modify-nav-user-B8h8WTrM.js";
7
+ import { t as u } from "./unmodify-load-Buak-r1f.js";
8
+ import { r as d, t as f } from "./modify-nav-user-CJ1LevSU.js";
9
9
  import p from "node:fs";
10
10
  import m from "node:path";
11
11
  import { Project as h, QuoteKind as g, SyntaxKind as _ } from "ts-morph";
@@ -215,4 +215,4 @@ async function O(i) {
215
215
  //#endregion
216
216
  export { O as generate };
217
217
 
218
- //# sourceMappingURL=generate.runtime-CcPCAEV0.js.map
218
+ //# sourceMappingURL=generate.runtime-ww3-1FWf.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CcPCAEV0.js","names":["paymentsBillingPageServerTemplate","paymentsBillingPageSvelteTemplate","getLogger","_page_server_default","_page_default","planDropsForCollections","withInMemoryScript","removeTopLevelStatementByIdentifier","removeImportByModuleSpecifier","modifyOutcomeToFile","SvelteFile","removeFromLoad","propsStatement","bindingText","fs","path","SUBSCRIPTION_CASE_VALUES","unmodifyWebhookServer","filePath","original","sf","switchStmt","SyntaxKind","stmt","toRemove","clause","expr","literal","c","spaced","source","unmodifyAppLayoutSvelte","file","updateScript","out","decl","init","nameNode","pattern","elements","hasSub","typeNode","intersection","member","lit","propTexts","p","t","remaining","unmodifyAppSidebar","hasSubPropType","hasSubProp","hasNavUserSubAttr","unmodifyAppLayoutServer","fromLoad","Project","QuoteKind","formatLikeSource","unmodifyNavUser","content","binding","kept","revertByTemplate","current","enabledMarker","stripped","template","unmodifyBillingPageServer","paymentsBillingPageServerTemplate","unmodifyBillingPageSvelte","paymentsBillingPageSvelteTemplate","generate","logger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/disable/subscriptions/modifies/revert-by-template.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/disable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst SUBSCRIPTION_CASE_VALUES = new Set([\n \"customer.subscription.created\",\n \"customer.subscription.updated\",\n \"customer.subscription.deleted\",\n]);\n\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n removeImportByModuleSpecifier(sf, \"./subscription/created\");\n removeImportByModuleSpecifier(sf, \"./subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./subscription/deleted\");\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n // Collect matching case clauses first — removing invalidates node refs.\n const toRemove = caseBlock\n .getClauses()\n .filter((clause) => {\n if (clause.getKind() !== SyntaxKind.CaseClause) return false;\n const caseClause = clause.asKindOrThrow(SyntaxKind.CaseClause);\n const expr = caseClause.getExpression();\n const literal =\n expr.asKind(SyntaxKind.StringLiteral) ??\n expr.asKind(SyntaxKind.NoSubstitutionTemplateLiteral);\n if (!literal) return false;\n return SUBSCRIPTION_CASE_VALUES.has(literal.getLiteralValue());\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n formatLikeSource(sf);\n });\n\n // Removing the clauses takes the blank line before `default:` with them.\n const spaced = source.replace(/(break;)\\n(\\s*default:)/, \"$1\\n\\n$2\");\n\n if (spaced === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, spaced, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const removed = file.removeAttribute(\"AppSidebar\", \"subscription\");\n if (!removed) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction updateScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const hasSub = elements.some((e) => e.getName() === \"subscription\");\n\n // Strip subscription from the props type literal (the specific type\n // added by enable-subscriptions — leave unrelated `subscription` props\n // alone).\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"))\n .filter((t) => !/^\\s*subscription\\??\\s*:/.test(t));\n lit.replaceWithText(\n propTexts.length ? `{ ${propTexts.join(\"; \")}; }` : \"{}\",\n );\n break;\n }\n }\n\n if (hasSub) {\n const remaining = elements\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n pattern.replaceWithText(`{ ${remaining.join(\", \")} }`);\n }\n }\n formatLikeSource(sf);\n });\n return out;\n}\n\nexport function unmodifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(filePath, \"utf8\");\n const hasSubPropType = /subscription\\??\\s*:\\s*\\{/.test(source);\n const hasSubProp = /\\bsubscription\\s*=\\s*null\\b/.test(source);\n\n const file = new SvelteFile(source);\n const hasNavUserSubAttr =\n file.hasElement(\"NavUser\") && file.hasAttribute(\"NavUser\", \"subscription\");\n\n if (!hasSubPropType && !hasSubProp && !hasNavUserSubAttr) {\n return { status: \"success\", changed: false };\n }\n\n if (hasSubPropType || hasSubProp) {\n file.modifyScript(updateScript);\n }\n if (hasNavUserSubAttr) {\n file.removeAttribute(\"NavUser\", \"subscription\");\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\nimport {\n formatLikeSource,\n removeTopLevelStatementByIdentifier,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * Takes out what enable-subscriptions added to the (app) layout load: the\n * `subscription` it loads and returns, and the `loadActiveSubscription`\n * helper. The rest of the load (what other patterns added) stays.\n */\nexport function unmodifyAppLayoutServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const fromLoad = removeFromLoad(filePath, {\n variables: [\"subscription\"],\n dependsKeys: [],\n returnProps: [\"subscription\"],\n });\n if (fromLoad.status !== \"success\") return fromLoad;\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n removeTopLevelStatementByIdentifier(sf, \"loadActiveSubscription\");\n formatLikeSource(sf);\n sf.saveSync();\n\n return {\n status: \"success\",\n changed: fs.readFileSync(filePath, \"utf8\") !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n bindingText,\n propsStatement,\n} from \"../../../enable/subscriptions/modifies/modify-nav-user\";\n\n/**\n * Takes the plan label out of nav-user: the lines showing it, `planLabel`\n * and the `subscription` prop. What other patterns added stays.\n */\nexport function unmodifyNavUser(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\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 file.modifyScript(\n (content) =>\n withInMemoryScript(\n // With the blank line enable-subscriptions put before it.\n content.replace(\n /\\n[ \\t]*\\n[ \\t]*const planLabel = \\$derived\\([^\\n]*\\);/,\n \"\",\n ),\n (sf) => {\n const decl = propsStatement(sf)?.getDeclarations()[0];\n const binding = decl\n ?.getNameNode()\n .asKind(SyntaxKind.ObjectBindingPattern);\n const kept = binding\n ?.getElements()\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n if (binding && kept) {\n binding.replaceWithText(bindingText(binding.getText(), kept));\n }\n decl\n ?.getTypeNode()\n ?.asKind(SyntaxKind.TypeLiteral)\n ?.getProperty(\"subscription\")\n ?.remove();\n },\n ).source,\n );\n\n // The lines under the name, with the line break before them.\n const out = file\n .toString()\n .replace(/\\n[ \\t]*<span class=\"[^\"]*\">\\s*\\{planLabel\\}\\s*<\\/span>/g, \"\");\n\n fs.writeFileSync(filePath, out, \"utf8\");\n return { status: \"success\", changed: out !== original };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Rewrites a file to the given `template` if the current content still shows\n * the `enabledMarker` (meaning enable-subscriptions is applied). If the marker\n * is absent (already reverted or never applied), it's a no-op.\n *\n * Strips leading `// [!code highlight:N]` / `<!-- [!code highlight:N] -->`\n * lines so templates can be pulled from `preview-modifies/` directories which\n * use those for documentation highlighting.\n */\nexport function revertByTemplate(\n filePath: string,\n template: string,\n enabledMarker: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (!current.includes(enabledMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageServer(\n filePath: string,\n paymentsBillingPageServerTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageServerTemplate,\n \"selectPlan\",\n );\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageSvelte(\n filePath: string,\n paymentsBillingPageSvelteTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageSvelteTemplate,\n \"availablePlans\",\n );\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { unmodifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { unmodifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Pull the \"post-payments\" state of files that enable-subscriptions fully\n// overwrote. For the billing pages, that's exactly what enable-payments\n// writes in creates-app-mode; for nav-user it's the payments preview-modifies\n// snapshot (with highlight annotations stripped by the revert helper).\nimport paymentsBillingPageServerTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.server.ts?raw\";\nimport paymentsBillingPageSvelteTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.svelte?raw\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n unmodifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyAppLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n unmodifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n unmodifyBillingPageServer(\n billingPageServerPath,\n paymentsBillingPageServerTemplate,\n ),\n ),\n );\n\n logger.info(\"Reverting billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n unmodifyBillingPageSvelte(\n billingPageSveltePath,\n paymentsBillingPageSvelteTemplate,\n ),\n ),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"stripe_subscriptions\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAMgB,oBAA2B,IAAI,IAAI;CACvC;CACA;CACA;AACF,CAA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7C,CACF,GAEAL,EAAO,KAAK,gCAAgC;CAC5C,IAAMM,IAAsB/D,EAAK,KAC/B0D,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPAE,EACElE,EACEqE,GACA/C,EAAwB+C,CAAmB,CAC7C,CACF,GAEAN,EAAO,KAAK,8BAA8B;CAC1C,IAAMO,IAAiBhE,EAAK,KAC1B0D,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJAE,EACElE,EAAoBsE,GAAgB9B,EAAmB8B,CAAc,CAAC,CACxE,GAEAP,EAAO,KAAK,2BAA2B;CACvC,IAAMQ,IAAcjE,EAAK,KACvB0D,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAWlE,EAAoBuE,GAAatB,EAAgBsB,CAAW,CAAC,CAAC,GAEzER,EAAO,KAAK,mCAAmC;CAC/C,IAAMS,IAAwBlE,EAAK,KACjC0D,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACElE,EACEwE,GACAd,EACEc,GACAjF,CACF,CACF,CACF,GAEAwE,EAAO,KAAK,gCAAgC;CAC5C,IAAMU,IAAwBnE,EAAK,KACjC0D,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAgBA,OAfAE,EACElE,EACEyE,GACAb,EACEa,GACAjF,CACF,CACF,CACF,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BI,EAC5B,CAAC,sBAAsB,GACvBoE,CACF;CAWA;AACF"}
1
+ {"version":3,"file":"generate.runtime-ww3-1FWf.js","names":["paymentsBillingPageServerTemplate","paymentsBillingPageSvelteTemplate","getLogger","_page_server_default","_page_default","planDropsForCollections","withInMemoryScript","removeTopLevelStatementByIdentifier","removeImportByModuleSpecifier","modifyOutcomeToFile","SvelteFile","removeFromLoad","propsStatement","bindingText","fs","path","SUBSCRIPTION_CASE_VALUES","unmodifyWebhookServer","filePath","original","sf","switchStmt","SyntaxKind","stmt","toRemove","clause","expr","literal","c","spaced","source","unmodifyAppLayoutSvelte","file","updateScript","out","decl","init","nameNode","pattern","elements","hasSub","typeNode","intersection","member","lit","propTexts","p","t","remaining","unmodifyAppSidebar","hasSubPropType","hasSubProp","hasNavUserSubAttr","unmodifyAppLayoutServer","fromLoad","Project","QuoteKind","formatLikeSource","unmodifyNavUser","content","binding","kept","revertByTemplate","current","enabledMarker","stripped","template","unmodifyBillingPageServer","paymentsBillingPageServerTemplate","unmodifyBillingPageSvelte","paymentsBillingPageSvelteTemplate","generate","logger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/disable/subscriptions/modifies/revert-by-template.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/disable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst SUBSCRIPTION_CASE_VALUES = new Set([\n \"customer.subscription.created\",\n \"customer.subscription.updated\",\n \"customer.subscription.deleted\",\n]);\n\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n removeImportByModuleSpecifier(sf, \"./subscription/created\");\n removeImportByModuleSpecifier(sf, \"./subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./subscription/deleted\");\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n // Collect matching case clauses first — removing invalidates node refs.\n const toRemove = caseBlock\n .getClauses()\n .filter((clause) => {\n if (clause.getKind() !== SyntaxKind.CaseClause) return false;\n const caseClause = clause.asKindOrThrow(SyntaxKind.CaseClause);\n const expr = caseClause.getExpression();\n const literal =\n expr.asKind(SyntaxKind.StringLiteral) ??\n expr.asKind(SyntaxKind.NoSubstitutionTemplateLiteral);\n if (!literal) return false;\n return SUBSCRIPTION_CASE_VALUES.has(literal.getLiteralValue());\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n formatLikeSource(sf);\n });\n\n // Removing the clauses takes the blank line before `default:` with them.\n const spaced = source.replace(/(break;)\\n(\\s*default:)/, \"$1\\n\\n$2\");\n\n if (spaced === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, spaced, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const removed = file.removeAttribute(\"AppSidebar\", \"subscription\");\n if (!removed) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction updateScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const hasSub = elements.some((e) => e.getName() === \"subscription\");\n\n // Strip subscription from the props type literal (the specific type\n // added by enable-subscriptions — leave unrelated `subscription` props\n // alone).\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"))\n .filter((t) => !/^\\s*subscription\\??\\s*:/.test(t));\n lit.replaceWithText(\n propTexts.length ? `{ ${propTexts.join(\"; \")}; }` : \"{}\",\n );\n break;\n }\n }\n\n if (hasSub) {\n const remaining = elements\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n pattern.replaceWithText(`{ ${remaining.join(\", \")} }`);\n }\n }\n formatLikeSource(sf);\n });\n return out;\n}\n\nexport function unmodifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(filePath, \"utf8\");\n const hasSubPropType = /subscription\\??\\s*:\\s*\\{/.test(source);\n const hasSubProp = /\\bsubscription\\s*=\\s*null\\b/.test(source);\n\n const file = new SvelteFile(source);\n const hasNavUserSubAttr =\n file.hasElement(\"NavUser\") && file.hasAttribute(\"NavUser\", \"subscription\");\n\n if (!hasSubPropType && !hasSubProp && !hasNavUserSubAttr) {\n return { status: \"success\", changed: false };\n }\n\n if (hasSubPropType || hasSubProp) {\n file.modifyScript(updateScript);\n }\n if (hasNavUserSubAttr) {\n file.removeAttribute(\"NavUser\", \"subscription\");\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\nimport {\n formatLikeSource,\n removeTopLevelStatementByIdentifier,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * Takes out what enable-subscriptions added to the (app) layout load: the\n * `subscription` it loads and returns, and the `loadActiveSubscription`\n * helper. The rest of the load (what other patterns added) stays.\n */\nexport function unmodifyAppLayoutServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const fromLoad = removeFromLoad(filePath, {\n variables: [\"subscription\"],\n dependsKeys: [],\n returnProps: [\"subscription\"],\n });\n if (fromLoad.status !== \"success\") return fromLoad;\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n removeTopLevelStatementByIdentifier(sf, \"loadActiveSubscription\");\n formatLikeSource(sf);\n sf.saveSync();\n\n return {\n status: \"success\",\n changed: fs.readFileSync(filePath, \"utf8\") !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n bindingText,\n propsStatement,\n} from \"../../../enable/subscriptions/modifies/modify-nav-user\";\n\n/**\n * Takes the plan label out of nav-user: the lines showing it, `planLabel`\n * and the `subscription` prop. What other patterns added stays.\n */\nexport function unmodifyNavUser(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\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 file.modifyScript(\n (content) =>\n withInMemoryScript(\n // With the blank line enable-subscriptions put before it.\n content.replace(\n /\\n[ \\t]*\\n[ \\t]*const planLabel = \\$derived\\([^\\n]*\\);/,\n \"\",\n ),\n (sf) => {\n const decl = propsStatement(sf)?.getDeclarations()[0];\n const binding = decl\n ?.getNameNode()\n .asKind(SyntaxKind.ObjectBindingPattern);\n const kept = binding\n ?.getElements()\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n if (binding && kept) {\n binding.replaceWithText(bindingText(binding.getText(), kept));\n }\n decl\n ?.getTypeNode()\n ?.asKind(SyntaxKind.TypeLiteral)\n ?.getProperty(\"subscription\")\n ?.remove();\n },\n ).source,\n );\n\n // The lines under the name, with the line break before them.\n const out = file\n .toString()\n .replace(/\\n[ \\t]*<span class=\"[^\"]*\">\\s*\\{planLabel\\}\\s*<\\/span>/g, \"\");\n\n fs.writeFileSync(filePath, out, \"utf8\");\n return { status: \"success\", changed: out !== original };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Rewrites a file to the given `template` if the current content still shows\n * the `enabledMarker` (meaning enable-subscriptions is applied). If the marker\n * is absent (already reverted or never applied), it's a no-op.\n *\n * Strips leading `// [!code highlight:N]` / `<!-- [!code highlight:N] -->`\n * lines so templates can be pulled from `preview-modifies/` directories which\n * use those for documentation highlighting.\n */\nexport function revertByTemplate(\n filePath: string,\n template: string,\n enabledMarker: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (!current.includes(enabledMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageServer(\n filePath: string,\n paymentsBillingPageServerTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageServerTemplate,\n \"selectPlan\",\n );\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageSvelte(\n filePath: string,\n paymentsBillingPageSvelteTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageSvelteTemplate,\n \"availablePlans\",\n );\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { unmodifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { unmodifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Pull the \"post-payments\" state of files that enable-subscriptions fully\n// overwrote. For the billing pages, that's exactly what enable-payments\n// writes in creates-app-mode; for nav-user it's the payments preview-modifies\n// snapshot (with highlight annotations stripped by the revert helper).\nimport paymentsBillingPageServerTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.server.ts?raw\";\nimport paymentsBillingPageSvelteTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.svelte?raw\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n unmodifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyAppLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n unmodifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n unmodifyBillingPageServer(\n billingPageServerPath,\n paymentsBillingPageServerTemplate,\n ),\n ),\n );\n\n logger.info(\"Reverting billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n unmodifyBillingPageSvelte(\n billingPageSveltePath,\n paymentsBillingPageSvelteTemplate,\n ),\n ),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"stripe_subscriptions\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAMgB,oBAA2B,IAAI,IAAI;CACvC;CACA;CACA;AACF,CAAC;AAED,SAAgBC,EAAsB,GAAiC;CACrE,IAAI,CAACH,EAAG,WAAWI,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAMC,IAAWL,EAAG,aAAaI,GAAU,MAAM;CACjD,IAAI,CAACC,EAAS,SAAS,2BAA2B,GAChD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,EAA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A,cACA,oBACF;CAKA,AAJAE,EACElE,EAAoBsE,GAAgB9B,EAAmB8B,CAAc,CAAC,CACxE,GAEAP,EAAO,KAAK,2BAA2B;CACvC,IAAMQ,IAAcjE,EAAK,KACvB0D,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAWlE,EAAoBuE,GAAatB,EAAgBsB,CAAW,CAAC,CAAC,GAEzER,EAAO,KAAK,mCAAmC;CAC/C,IAAMS,IAAwBlE,EAAK,KACjC0D,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACElE,EACEwE,GACAd,EACEc,GACAjF,CACF,CACF,CACF,GAEAwE,EAAO,KAAK,gCAAgC;CAC5C,IAAMU,IAAwBnE,EAAK,KACjC0D,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAgBA,OAfAE,EACElE,EACEyE,GACAb,EACEa,GACAjF,CACF,CACF,CACF,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BI,EAC5B,CAAC,sBAAsB,GACvBoE,CACF;CAWA;AACF"}
@@ -1,7 +1,7 @@
1
- import { n as e } from "./rolldown-runtime-DArdT4gl.js";
1
+ import { n as e } from "./rolldown-runtime-5HNE8Q1r.js";
2
2
  import { a as t } from "./util-BLYliuUK.js";
3
- import { n } from "./shared-D5GOS97l.js";
4
- import { _ as r, s as i } from "./ts-morph-helpers-Bepc-Es2.js";
3
+ import { n } from "./shared-C_Fr8wph.js";
4
+ import { _ as r, s as i } from "./ts-morph-helpers-CHI9wAil.js";
5
5
  import a from "node:fs";
6
6
  import o from "node:path";
7
7
  //#region src/runtime/modify-file.ts
@@ -50,4 +50,4 @@ function d(e, t) {
50
50
  //#endregion
51
51
  export { l as a, s as i, d as n, c as r, u as t };
52
52
 
53
- //# sourceMappingURL=modify-file-Bbhyfiy_.js.map
53
+ //# sourceMappingURL=modify-file-COBp4eCh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"modify-file-Bbhyfiy_.js","names":["__exportAll","languageFromPath","withInMemoryScript","isEffectivelyEmpty","fs","path","modify_file_exports","envRevertOutcomeToFile","keepMissing","modifyOutcomeToFile","revertOutcomeToFile","language","filePath","outcome","toDeleteEntry","envPath","creates","root","file"],"sources":["../../src/runtime/modify-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { isEffectivelyEmpty, withInMemoryScript } from \"./ts-morph-helpers\";\n\nexport function modifyOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): File | null {\n const language = languageFromPath(filePath);\n\n if (outcome.status === \"success\") {\n if (!outcome.changed) return null;\n return {\n path: filePath,\n language,\n content: fs.readFileSync(filePath, \"utf8\"),\n status: \"success\",\n };\n }\n\n const content =\n outcome.status === \"failed\" && fs.existsSync(filePath)\n ? fs.readFileSync(filePath, \"utf8\")\n : \"\";\n\n return {\n path: filePath,\n language,\n content,\n status: outcome.status,\n message: outcome.message,\n };\n}\n\n/**\n * `modifyOutcomeToFile` for a revert that may have taken out everything the\n * file held: a script left with no statements, only comments and whitespace,\n * is reported as a delete. For hooks files a pattern created, or that ended\n * up holding nothing but what patterns put there.\n */\nexport function revertOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(filePath) &&\n withInMemoryScript(fs.readFileSync(filePath, \"utf8\"), isEffectivelyEmpty)\n .result\n ) {\n return { modify: null, delete: toDeleteEntry(filePath) };\n }\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * `modifyOutcomeToFile` for a `.env` revert: a file the revert left empty is\n * reported as a delete. The enable pattern most likely created it, and an\n * empty `.env` holds nothing worth keeping.\n */\nexport function envRevertOutcomeToFile(\n envPath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(envPath) &&\n fs.readFileSync(envPath, \"utf8\").trim() === \"\"\n ) {\n return { modify: null, delete: toDeleteEntry(envPath) };\n }\n return { modify: modifyOutcomeToFile(envPath, outcome), delete: null };\n}\n\n/**\n * Drop any create that already exists on disk.\n *\n * `writeResult` overwrites an existing create whose content differs and\n * reports it as a modify, which would mean a re-run silently resetting a\n * developer's edits, or a create clobbering a file other patterns have\n * already written to. The file is theirs once it exists; a pattern that has\n * something to add to it does so with a modifier.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n"],"mappings":";;;;;;;;;;;;;AAOA,SAAgBS,EACd,GACA,GACa;CACb,IAAME,IAAWV,EAAiBW,CAAQ;CAiB1C,OAfIC,EAAQ,WAAW,YAChBA,EAAQ,UACN;EACL,MAAMD;EACN;EACA,SAASR,EAAG,aAAaQ,GAAU,MAAM;EACzC,QAAQ;CACV,IAN6B,OAcxB;EACL,MAAMA;EACN;EACA,SAPAC,EAAQ,WAAW,YAAYT,EAAG,WAAWQ,CAAQ,IACjDR,EAAG,aAAaQ,GAAU,MAAM,IAChC;EAMJ,QAAQC,EAAQ;EAChB,SAASA,EAAQ;CACnB;AACF;AAQA,SAAgBH,EACd,GACA,GAC8C;CAU9C,OAREG,EAAQ,WAAW,aACnBA,EAAQ,WACRT,EAAG,WAAWQ,CAAQ,KACtBV,EAAmBE,EAAG,aAAaQ,GAAU,MAAM,GAAGT,CAAkB,CAAC,CACtE,SAEI;EAAE,QAAQ;EAAM,QAAQW,EAAcF,CAAQ;CAAE,IAElD;EAAE,QAAQH,EAAoBG,GAAUC,CAAO;EAAG,QAAQ;CAAK;AACxE;AAOA,SAAgBN,EACd,GACA,GAC8C;CAS9C,OAPEM,EAAQ,WAAW,aACnBA,EAAQ,WACRT,EAAG,WAAWW,CAAO,KACrBX,EAAG,aAAaW,GAAS,MAAM,CAAC,CAAC,KAAK,MAAM,KAErC;EAAE,QAAQ;EAAM,QAAQD,EAAcC,CAAO;CAAE,IAEjD;EAAE,QAAQN,EAAoBM,GAASF,CAAO;EAAG,QAAQ;CAAK;AACvE;AAWA,SAAgBL,EAAY,GAAiB,GAAsB;CACjE,OAAOQ,EAAQ,QAAQ,MAAS,CAACZ,EAAG,WAAWC,EAAK,KAAKY,GAAMC,EAAK,IAAI,CAAC,CAAC;AAC5E"}
1
+ {"version":3,"file":"modify-file-COBp4eCh.js","names":["__exportAll","languageFromPath","withInMemoryScript","isEffectivelyEmpty","fs","path","modify_file_exports","envRevertOutcomeToFile","keepMissing","modifyOutcomeToFile","revertOutcomeToFile","language","filePath","outcome","toDeleteEntry","envPath","creates","root","file"],"sources":["../../src/runtime/modify-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { isEffectivelyEmpty, withInMemoryScript } from \"./ts-morph-helpers\";\n\nexport function modifyOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): File | null {\n const language = languageFromPath(filePath);\n\n if (outcome.status === \"success\") {\n if (!outcome.changed) return null;\n return {\n path: filePath,\n language,\n content: fs.readFileSync(filePath, \"utf8\"),\n status: \"success\",\n };\n }\n\n const content =\n outcome.status === \"failed\" && fs.existsSync(filePath)\n ? fs.readFileSync(filePath, \"utf8\")\n : \"\";\n\n return {\n path: filePath,\n language,\n content,\n status: outcome.status,\n message: outcome.message,\n };\n}\n\n/**\n * `modifyOutcomeToFile` for a revert that may have taken out everything the\n * file held: a script left with no statements, only comments and whitespace,\n * is reported as a delete. For hooks files a pattern created, or that ended\n * up holding nothing but what patterns put there.\n */\nexport function revertOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(filePath) &&\n withInMemoryScript(fs.readFileSync(filePath, \"utf8\"), isEffectivelyEmpty)\n .result\n ) {\n return { modify: null, delete: toDeleteEntry(filePath) };\n }\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * `modifyOutcomeToFile` for a `.env` revert: a file the revert left empty is\n * reported as a delete. The enable pattern most likely created it, and an\n * empty `.env` holds nothing worth keeping.\n */\nexport function envRevertOutcomeToFile(\n envPath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(envPath) &&\n fs.readFileSync(envPath, \"utf8\").trim() === \"\"\n ) {\n return { modify: null, delete: toDeleteEntry(envPath) };\n }\n return { modify: modifyOutcomeToFile(envPath, outcome), delete: null };\n}\n\n/**\n * Drop any create that already exists on disk.\n *\n * `writeResult` overwrites an existing create whose content differs and\n * reports it as a modify, which would mean a re-run silently resetting a\n * developer's edits, or a create clobbering a file other patterns have\n * already written to. The file is theirs once it exists; a pattern that has\n * something to add to it does so with a modifier.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n"],"mappings":";;;;;;;;;;;;;AAOA,SAAgBS,EACd,GACA,GACa;CACb,IAAME,IAAWV,EAAiBW,CAAQ;CAiB1C,OAfIC,EAAQ,WAAW,YAChBA,EAAQ,UACN;EACL,MAAMD;EACN;EACA,SAASR,EAAG,aAAaQ,GAAU,MAAM;EACzC,QAAQ;CACV,IAN6B,OAcxB;EACL,MAAMA;EACN;EACA,SAPAC,EAAQ,WAAW,YAAYT,EAAG,WAAWQ,CAAQ,IACjDR,EAAG,aAAaQ,GAAU,MAAM,IAChC;EAMJ,QAAQC,EAAQ;EAChB,SAASA,EAAQ;CACnB;AACF;AAQA,SAAgBH,EACd,GACA,GAC8C;CAU9C,OAREG,EAAQ,WAAW,aACnBA,EAAQ,WACRT,EAAG,WAAWQ,CAAQ,KACtBV,EAAmBE,EAAG,aAAaQ,GAAU,MAAM,GAAGT,CAAkB,CAAC,CACtE,SAEI;EAAE,QAAQ;EAAM,QAAQW,EAAcF,CAAQ;CAAE,IAElD;EAAE,QAAQH,EAAoBG,GAAUC,CAAO;EAAG,QAAQ;CAAK;AACxE;AAOA,SAAgBN,EACd,GACA,GAC8C;CAS9C,OAPEM,EAAQ,WAAW,aACnBA,EAAQ,WACRT,EAAG,WAAWW,CAAO,KACrBX,EAAG,aAAaW,GAAS,MAAM,CAAC,CAAC,KAAK,MAAM,KAErC;EAAE,QAAQ;EAAM,QAAQD,EAAcC,CAAO;CAAE,IAEjD;EAAE,QAAQN,EAAoBM,GAASF,CAAO;EAAG,QAAQ;CAAK;AACvE;AAWA,SAAgBL,EAAY,GAAiB,GAAsB;CACjE,OAAOQ,EAAQ,QAAQ,MAAS,CAACZ,EAAG,WAAWC,EAAK,KAAKY,GAAMC,EAAK,IAAI,CAAC,CAAC;AAC5E"}
@@ -1,4 +1,4 @@
1
- import { _ as e } from "./ts-morph-helpers-Bepc-Es2.js";
1
+ import { _ as e } from "./ts-morph-helpers-CHI9wAil.js";
2
2
  import { t } from "./svelte-file-Dv5-bl79.js";
3
3
  import n from "node:fs";
4
4
  import { SyntaxKind as r } from "ts-morph";
@@ -68,4 +68,4 @@ function f(r) {
68
68
  //#endregion
69
69
  export { f as n, l as r, u as t };
70
70
 
71
- //# sourceMappingURL=modify-nav-user-B8h8WTrM.js.map
71
+ //# sourceMappingURL=modify-nav-user-CJ1LevSU.js.map
@@ -1 +1 @@
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,CACJ;AACJ;AAGA,SAAgBC,EAAY,GAAiB,GAAyB;CACpE,IAAI,CAACC,EAAQ,SAAS,IAAI,GAAG,OAAO,KAAKC,EAAM,KAAK,IAAI,EAAE;CAC1D,IAAMC,IAASF,EAAQ,MAAM,cAAc,CAAC,GAAG,MAAM,KAC/CG,IAAQH,EAAQ,MAAM,eAAe,CAAC,GAAG,MAAM;CACrD,OAAO,MAAMC,EAAM,KAAK,MAAMC,IAASE,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE,IAAID,EAAM;AAClE;AAEA,SAASE,EAAoB,GAAyB;CACpD,IAAMC,IAAYZ,EAAeC,CAAE,GAC7BY,IAAOD,GAAW,gBAAgB,CAAC,CAAC,IACpCE,IAAU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;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
+ {"version":3,"file":"modify-nav-user-CJ1LevSU.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,oGAC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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,4 +1,4 @@
1
- import { i as e, n as t, r as n } from "./config-target-rHgjaA8u.js";
1
+ import { i as e, n as t, r as n } from "./config-target-BgyFkbFL.js";
2
2
  //#region src/runtime/modify-svelte-config-remote.ts
3
3
  var r = [
4
4
  "Enable SvelteKit remote functions and Svelte async in your config",
@@ -39,4 +39,4 @@ function a(a) {
39
39
  //#endregion
40
40
  export { a as modifySvelteConfigRemote };
41
41
 
42
- //# sourceMappingURL=modify-svelte-config-remote-DhuRX4FI.js.map
42
+ //# sourceMappingURL=modify-svelte-config-remote-CEyYydL7.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"modify-svelte-config-remote-DhuRX4FI.js","names":["modifyConfig","ensureBooleanTrue","getOrCreateObjectLiteralProperty","FAILURE_HINT","NOT_FOUND_HINT","modifySvelteConfigRemote","root","kitExperimental","target","compilerObj","compilerExperimental"],"sources":["../../src/runtime/modify-svelte-config-remote.ts"],"sourcesContent":["import {\n ensureBooleanTrue,\n getOrCreateObjectLiteralProperty,\n modifyConfig,\n type ConfigModifyResult,\n} from \"./config-target\";\n\nconst FAILURE_HINT = [\n \"Enable SvelteKit remote functions and Svelte async in your config\",\n \"(the sveltekit() plugin arg in vite.config):\",\n \"\",\n \"experimental: { remoteFunctions: true },\",\n \"compilerOptions: { experimental: { async: true } },\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Enable SvelteKit remote functions and Svelte async by passing config to the\",\n \"sveltekit() plugin in vite.config.ts:\",\n \"\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { defineConfig } from 'vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [\",\n \" sveltekit({\",\n \" experimental: { remoteFunctions: true },\",\n \" compilerOptions: { experimental: { async: true } },\",\n \" }),\",\n \" ],\",\n \"});\",\n].join(\"\\n\");\n\n/**\n * Enable SvelteKit remote functions (`experimental.remoteFunctions`) and Svelte\n * async (`compilerOptions.experimental.async`) in the inline `sveltekit()` arg\n * in vite.config, where both sit at the top level.\n */\nexport function modifySvelteConfigRemote(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n const kitExperimental = getOrCreateObjectLiteralProperty(\n target.configObject,\n \"experimental\",\n \"{}\",\n );\n if (!kitExperimental) return false;\n ensureBooleanTrue(kitExperimental, \"remoteFunctions\");\n\n const compilerObj = getOrCreateObjectLiteralProperty(\n target.configObject,\n \"compilerOptions\",\n \"{}\",\n );\n if (!compilerObj) return false;\n const compilerExperimental = getOrCreateObjectLiteralProperty(\n compilerObj,\n \"experimental\",\n \"{}\",\n );\n if (!compilerExperimental) return false;\n ensureBooleanTrue(compilerExperimental, \"async\");\n\n return true;\n },\n );\n}\n"],"mappings":";;AAOA,IAAMG,IAAe;CACnB;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAOX,SAAgBC,EAAyB,GAAkC;CACzE,OAAOL,EACLM,GACA;EAAE,UAAUF;EAAgB,QAAQD;CAAa,IAChD,MAAW;EACV,IAAMI,IAAkBL,EACtBM,EAAO,cACP,gBACA,IACF;EACA,IAAI,CAACD,GAAiB,OAAO;EAC7B,EAAkBA,GAAiB,iBAAiB;EAEpD,IAAME,IAAcP,EAClBM,EAAO,cACP,mBACA,IACF;EACA,IAAI,CAACC,GAAa,OAAO;EACzB,IAAMC,IAAuBR,EAC3BO,GACA,gBACA,IACF;EAIA,OAHKC,KACLT,EAAkBS,GAAsB,OAAO,GAExC,MAH2B;CAIpC,CACF;AACF"}
1
+ {"version":3,"file":"modify-svelte-config-remote-CEyYydL7.js","names":["modifyConfig","ensureBooleanTrue","getOrCreateObjectLiteralProperty","FAILURE_HINT","NOT_FOUND_HINT","modifySvelteConfigRemote","root","kitExperimental","target","compilerObj","compilerExperimental"],"sources":["../../src/runtime/modify-svelte-config-remote.ts"],"sourcesContent":["import {\n ensureBooleanTrue,\n getOrCreateObjectLiteralProperty,\n modifyConfig,\n type ConfigModifyResult,\n} from \"./config-target\";\n\nconst FAILURE_HINT = [\n \"Enable SvelteKit remote functions and Svelte async in your config\",\n \"(the sveltekit() plugin arg in vite.config):\",\n \"\",\n \"experimental: { remoteFunctions: true },\",\n \"compilerOptions: { experimental: { async: true } },\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Enable SvelteKit remote functions and Svelte async by passing config to the\",\n \"sveltekit() plugin in vite.config.ts:\",\n \"\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { defineConfig } from 'vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [\",\n \" sveltekit({\",\n \" experimental: { remoteFunctions: true },\",\n \" compilerOptions: { experimental: { async: true } },\",\n \" }),\",\n \" ],\",\n \"});\",\n].join(\"\\n\");\n\n/**\n * Enable SvelteKit remote functions (`experimental.remoteFunctions`) and Svelte\n * async (`compilerOptions.experimental.async`) in the inline `sveltekit()` arg\n * in vite.config, where both sit at the top level.\n */\nexport function modifySvelteConfigRemote(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n const kitExperimental = getOrCreateObjectLiteralProperty(\n target.configObject,\n \"experimental\",\n \"{}\",\n );\n if (!kitExperimental) return false;\n ensureBooleanTrue(kitExperimental, \"remoteFunctions\");\n\n const compilerObj = getOrCreateObjectLiteralProperty(\n target.configObject,\n \"compilerOptions\",\n \"{}\",\n );\n if (!compilerObj) return false;\n const compilerExperimental = getOrCreateObjectLiteralProperty(\n compilerObj,\n \"experimental\",\n \"{}\",\n );\n if (!compilerExperimental) return false;\n ensureBooleanTrue(compilerExperimental, \"async\");\n\n return true;\n },\n );\n}\n"],"mappings":";;AAOA,IAAMG,IAAe;CACnB;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAOX,SAAgBC,EAAyB,GAAkC;CACzE,OAAOL,EACLM,GACA;EAAE,UAAUF;EAAgB,QAAQD;CAAa,IAChD,MAAW;EACV,IAAMI,IAAkBL,EACtBM,EAAO,cACP,gBACA,IACF;EACA,IAAI,CAACD,GAAiB,OAAO;EAC7B,EAAkBA,GAAiB,iBAAiB;EAEpD,IAAME,IAAcP,EAClBM,EAAO,cACP,mBACA,IACF;EACA,IAAI,CAACC,GAAa,OAAO;EACzB,IAAMC,IAAuBR,EAC3BO,GACA,gBACA,IACF;EAIA,OAHKC,KACLT,EAAkBS,GAAsB,OAAO,GAExC,MAH2B;CAIpC,CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
- import { o as t } from "./ts-morph-helpers-Bepc-Es2.js";
2
+ import { o as t } from "./ts-morph-helpers-CHI9wAil.js";
3
3
  import n from "node:fs";
4
4
  import { Project as r, QuoteKind as i, SyntaxKind as a } from "ts-morph";
5
5
  //#region src/patterns/enable/payments/modifies/modify-user-signup.ts
@@ -51,4 +51,4 @@ function u(e) {
51
51
  //#endregion
52
52
  export { u as t };
53
53
 
54
- //# sourceMappingURL=modify-user-signup-BbqTiUuA.js.map
54
+ //# sourceMappingURL=modify-user-signup-DLtopazD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"modify-user-signup-BbqTiUuA.js","names":["dedent","formatLikeSource","fs","WORKFLOW_MODULE","RUN_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","modifyUserSignup","userSignupPath","originalSource","sourceFile","Project","QuoteKind","requestVerificationCall","SyntaxKind","expr","ce","statement"],"sources":["../../src/patterns/enable/payments/modifies/modify-user-signup.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst WORKFLOW_MODULE = \"#lib/workflows/link-stripe-customer.js\";\n\nconst RUN_SNIPPET = dedent`\n // Queued here, done in the background: the Stripe calls retry on their own,\n // and the key means a retry never makes a second customer for this user.\n await linkStripeCustomer.run(\n { userId: user.id, email: form.data.email },\n { idempotencyKey: user.id }\n );\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Start the workflow once the user exists:\",\n \"\",\n `import { linkStripeCustomer } from '${WORKFLOW_MODULE}';`,\n \"\",\n RUN_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\n/**\n * Starts the link-stripe-customer workflow right after the user is created.\n * The work itself lives in src/lib/workflows/link-stripe-customer.ts.\n */\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addImportDeclaration({\n namedImports: [\"linkStripeCustomer\"],\n moduleSpecifier: WORKFLOW_MODULE,\n });\n\n statement.replaceWithText(RUN_SNIPPET + \"\\n\\n\" + statement.getText());\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n"],"mappings":";;;;;AAMA,IAAMG,IAAkB,0CAElBC,IAAc,CAAM;;;;;;;GASpBC,IAAe;CACnB;CACA;CACA;CACA,uCAAuCF,EAAgB;CACvD;CACAC;AACF,CAAC,CAAC,KAAK,IAAI,GAELE,IAAiB,CACrB,oFACF,CAAC,CAAC,KAAK,IAAI;AAMX,SAAgBC,EAAiB,GAAuC;CACtE,IAAI,CAACL,EAAG,WAAWM,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAASF;CAAe;CAGxD,IAAMG,IAAiBP,EAAG,aAAaM,GAAgB,MAAM;CAC7D,IAAIC,EAAe,SAAS,oBAAoB,GAC9C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAM7C,IAAMC,IAAa,IAHCC,EAAQ,EAC1B,sBAAsB,EAAE,WAAWC,EAAU,OAAO,EACtD,CACmB,CAAA,CAAQ,oBAAoBJ,CAAc,GAEvDK,IAA0BH,EAC7B,qBAAqBI,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO;EACZ,IAAMC,IAAOC,EAAG,cAAc;EAC9B,OACED,EAAK,QAAQ,MAAMD,EAAW,4BAC9BC,EAAK,QAAQ,CAAC,CAAC,SAAS,qBAAqB;CAEjD,CAAC;CAEH,IAAI,CAACF,GACH,OAAO;EAAE,QAAQ;EAAU,SAASR;CAAa;CAGnD,IAAMY,IAAYJ,EAAwB,uBACxCC,EAAW,mBACb;CAgBA,OAdKG,KAILP,EAAW,qBAAqB;EAC9B,cAAc,CAAC,oBAAoB;EACnC,iBAAiBP;CACnB,CAAC,GAEDc,EAAU,gBAAgBb,IAAc,SAASa,EAAU,QAAQ,CAAC,GAEpEhB,EAAiBS,CAAU,GAC3BA,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAASA,EAAW,YAAY,MAAMD;CACxC,KAhBS;EAAE,QAAQ;EAAU,SAASJ;CAAa;AAiBrD"}
1
+ {"version":3,"file":"modify-user-signup-DLtopazD.js","names":["dedent","formatLikeSource","fs","WORKFLOW_MODULE","RUN_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","modifyUserSignup","userSignupPath","originalSource","sourceFile","Project","QuoteKind","requestVerificationCall","SyntaxKind","expr","ce","statement"],"sources":["../../src/patterns/enable/payments/modifies/modify-user-signup.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst WORKFLOW_MODULE = \"#lib/workflows/link-stripe-customer.js\";\n\nconst RUN_SNIPPET = dedent`\n // Queued here, done in the background: the Stripe calls retry on their own,\n // and the key means a retry never makes a second customer for this user.\n await linkStripeCustomer.run(\n { userId: user.id, email: form.data.email },\n { idempotencyKey: user.id }\n );\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Start the workflow once the user exists:\",\n \"\",\n `import { linkStripeCustomer } from '${WORKFLOW_MODULE}';`,\n \"\",\n RUN_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\n/**\n * Starts the link-stripe-customer workflow right after the user is created.\n * The work itself lives in src/lib/workflows/link-stripe-customer.ts.\n */\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addImportDeclaration({\n namedImports: [\"linkStripeCustomer\"],\n moduleSpecifier: WORKFLOW_MODULE,\n });\n\n statement.replaceWithText(RUN_SNIPPET + \"\\n\\n\" + statement.getText());\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n"],"mappings":";;;;;AAMA,IAAMG,IAAkB,0CAElBC,IAAc,CAAM;;;;;;;GASpBC,IAAe;CACnB;CACA;CACA;CACA,uCAAuCF,EAAgB;CACvD;CACAC;AACF,CAAC,CAAC,KAAK,IAAI,GAELE,IAAiB,CACrB,oFACF,CAAC,CAAC,KAAK,IAAI;AAMX,SAAgBC,EAAiB,GAAuC;CACtE,IAAI,CAACL,EAAG,WAAWM,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAASF;CAAe;CAGxD,IAAMG,IAAiBP,EAAG,aAAaM,GAAgB,MAAM;CAC7D,IAAIC,EAAe,SAAS,oBAAoB,GAC9C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAM7C,IAAMC,IAAa,IAHCC,EAAQ,EAC1B,sBAAsB,EAAE,WAAWC,EAAU,OAAO,EACtD,CACmB,CAAA,CAAQ,oBAAoBJ,CAAc,GAEvDK,IAA0BH,EAC7B,qBAAqBI,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO;EACZ,IAAMC,IAAOC,EAAG,cAAc;EAC9B,OACED,EAAK,QAAQ,MAAMD,EAAW,4BAC9BC,EAAK,QAAQ,CAAC,CAAC,SAAS,qBAAqB;CAEjD,CAAC;CAEH,IAAI,CAACF,GACH,OAAO;EAAE,QAAQ;EAAU,SAASR;CAAa;CAGnD,IAAMY,IAAYJ,EAAwB,uBACxCC,EAAW,mBACb;CAgBA,OAdKG,KAILP,EAAW,qBAAqB;EAC9B,cAAc,CAAC,oBAAoB;EACnC,iBAAiBP;CACnB,CAAC,GAEDc,EAAU,gBAAgBb,IAAc,SAASa,EAAU,QAAQ,CAAC,GAEpEhB,EAAiBS,CAAU,GAC3BA,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAASA,EAAW,YAAY,MAAMD;CACxC,KAhBS;EAAE,QAAQ;EAAU,SAASJ;CAAa;AAiBrD"}
@@ -1,4 +1,4 @@
1
- import { n as e } from "./rolldown-runtime-DArdT4gl.js";
1
+ import { n as e } from "./rolldown-runtime-5HNE8Q1r.js";
2
2
  import t from "node:fs";
3
3
  import n from "node:path";
4
4
  //#region src/runtime/package-imports.ts
@@ -170,4 +170,4 @@ function f(e, t, n, r) {
170
170
  //#endregion
171
171
  export { u as i, d as n, r, l as t };
172
172
 
173
- //# sourceMappingURL=package-imports-Bbw3iMPg.js.map
173
+ //# sourceMappingURL=package-imports-Dx05A-4S.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"package-imports-Bbw3iMPg.js","names":["__exportAll","fs","path","package_imports_exports","ensurePackageImports","ensurePackageOverrides","removePackageImports","isObject","value","readPackage","filePath","root","text","pkg","indent","eol","trailing","writePackage","next","file","insertKey","anchor","after","name","key","existing","finish","outcome","conflicts","field","line","current","entries","imports","keys","expected","_","rest","overrides","merged","mergeOverrides","out","target","wanted","source","have","where","trail"],"sources":["../../src/runtime/package-imports.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../core/types\";\n\n/**\n * Edits to the project's `package.json` that npm has no command for: the\n * `imports` map SvelteKit 3 resolves `#lib` (and `#locales`) through, and\n * `overrides`. The file is rewritten with the indentation and trailing\n * newline it had, and a key that already holds a different value is never\n * overwritten: it is the project's, and the outcome says what to change.\n */\n\nexport interface PackageJsonEditResult {\n filePath: string;\n outcome: ModifyOutcome;\n}\n\ntype Json = string | number | boolean | null | Json[] | { [key: string]: Json };\ntype JsonObject = { [key: string]: Json };\n\n/** An `overrides` value: a version, or nested overrides (npm's `\".\"` is the package itself). */\nexport type OverrideValue = string | { [key: string]: OverrideValue };\n\ninterface PackageFile {\n filePath: string;\n text: string;\n pkg: JsonObject;\n indent: string;\n eol: string;\n trailing: string;\n}\n\nfunction isObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readPackage(root: string): PackageFile | PackageJsonEditResult {\n const filePath = path.join(root, \"package.json\");\n if (!fs.existsSync(filePath)) {\n return {\n filePath,\n outcome: { status: \"not-found\", message: \"No package.json to edit.\" },\n };\n }\n const text = fs.readFileSync(filePath, \"utf8\");\n let pkg: unknown;\n try {\n pkg = JSON.parse(text);\n } catch {\n return {\n filePath,\n outcome: { status: \"failed\", message: \"package.json is not valid JSON.\" },\n };\n }\n if (!isObject(pkg)) {\n return {\n filePath,\n outcome: { status: \"failed\", message: \"package.json is not an object.\" },\n };\n }\n const indent = text.match(/^[{[][^\\S\\n]*\\r?\\n([\\t ]+)\\S/)?.[1] ?? \"\\t\";\n const eol = text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const trailing = text.match(/(\\r?\\n)*$/)?.[0] ?? \"\";\n return { filePath, text, pkg, indent, eol, trailing };\n}\n\nfunction writePackage(file: PackageFile): ModifyOutcome {\n const body = JSON.stringify(file.pkg, null, file.indent).replace(\n /\\n/g,\n file.eol,\n );\n const next = body + file.trailing;\n if (next === file.text) return { status: \"success\", changed: false };\n fs.writeFileSync(file.filePath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/**\n * Add `key` to `pkg` right after the first of `after` it has, else at the end.\n * JSON object key order is insertion order, so this rebuilds the object.\n */\nfunction insertKey(\n pkg: JsonObject,\n key: string,\n value: Json,\n after: string[],\n): JsonObject {\n const anchor = after.find((name) => name in pkg);\n if (!anchor) return { ...pkg, [key]: value };\n const next: JsonObject = {};\n for (const [name, existing] of Object.entries(pkg)) {\n next[name] = existing;\n if (name === anchor) next[key] = value;\n }\n return next;\n}\n\nfunction finish(\n file: PackageFile,\n conflicts: string[],\n field: string,\n): PackageJsonEditResult {\n const outcome = writePackage(file);\n if (conflicts.length === 0) return { filePath: file.filePath, outcome };\n return {\n filePath: file.filePath,\n outcome: {\n status: \"failed\",\n message: [\n `package.json \\`${field}\\` already has a different value for:`,\n ...conflicts.map((line) => ` ${line}`),\n \"Change these by hand if vela's value is the one you want.\",\n ].join(\"\\n\"),\n },\n };\n}\n\n/**\n * Add the subpath `imports` (`{ \"#lib/*\": \"./src/lib/*\" }`) that are missing.\n * Creates `imports` after `type` when the project has none.\n */\nexport function ensurePackageImports(\n root: string,\n entries: Record<string, string>,\n): PackageJsonEditResult {\n const file = readPackage(root);\n if (!(\"pkg\" in file)) return file;\n\n const current = file.pkg.imports;\n if (current !== undefined && !isObject(current)) {\n return {\n filePath: file.filePath,\n outcome: {\n status: \"failed\",\n message: [\n \"package.json `imports` is not an object. Add these entries to it by hand:\",\n ...Object.entries(entries).map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n ),\n ].join(\"\\n\"),\n },\n };\n }\n\n const imports: JsonObject = { ...(current ?? {}) };\n const conflicts: string[] = [];\n for (const [key, value] of Object.entries(entries)) {\n if (!(key in imports)) {\n imports[key] = value;\n } else if (imports[key] !== value) {\n conflicts.push(\n `${JSON.stringify(key)}: ${JSON.stringify(imports[key])} (vela uses ${JSON.stringify(value)})`,\n );\n }\n }\n file.pkg =\n current === undefined\n ? Object.keys(imports).length > 0\n ? insertKey(file.pkg, \"imports\", imports, [\"type\", \"version\", \"name\"])\n : file.pkg\n : { ...file.pkg, imports };\n return finish(file, conflicts, \"imports\");\n}\n\n/**\n * Remove subpath `imports` keys. With `expected`, a key is removed only while\n * it still maps to the value vela wrote, so one the developer repointed stays.\n * An `imports` left empty is removed too.\n */\nexport function removePackageImports(\n root: string,\n keys: string[],\n expected?: Record<string, string>,\n): PackageJsonEditResult {\n const file = readPackage(root);\n if (!(\"pkg\" in file)) {\n // Nothing to revert in a project without a package.json.\n return file.outcome.status === \"not-found\"\n ? {\n filePath: file.filePath,\n outcome: { status: \"success\", changed: false },\n }\n : file;\n }\n const current = file.pkg.imports;\n if (!isObject(current)) {\n return {\n filePath: file.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n const imports: JsonObject = { ...current };\n for (const key of keys) {\n if (!(key in imports)) continue;\n if (expected && key in expected && imports[key] !== expected[key]) continue;\n delete imports[key];\n }\n if (Object.keys(imports).length === 0) {\n const { imports: _, ...rest } = file.pkg;\n file.pkg = rest;\n } else {\n file.pkg = { ...file.pkg, imports };\n }\n return { filePath: file.filePath, outcome: writePackage(file) };\n}\n\n/**\n * Deep-merge `overrides` into package.json's `overrides`, created at the end\n * when missing. A version already there that differs is left as it is and\n * reported. A package overridden with a bare version that now needs nested\n * overrides keeps that version as npm's `\".\"`.\n */\nexport function ensurePackageOverrides(\n root: string,\n overrides: Record<string, OverrideValue>,\n): PackageJsonEditResult {\n const file = readPackage(root);\n if (!(\"pkg\" in file)) return file;\n\n const current = file.pkg.overrides;\n if (current !== undefined && !isObject(current)) {\n return {\n filePath: file.filePath,\n outcome: {\n status: \"failed\",\n message: `package.json \\`overrides\\` is not an object. Add this to it by hand:\\n${JSON.stringify(overrides, null, 2)}`,\n },\n };\n }\n const conflicts: string[] = [];\n const merged = mergeOverrides(current ?? {}, overrides, [], conflicts);\n file.pkg = { ...file.pkg, overrides: merged };\n return finish(file, conflicts, \"overrides\");\n}\n\nfunction mergeOverrides(\n target: JsonObject,\n source: Record<string, OverrideValue>,\n trail: string[],\n conflicts: string[],\n): JsonObject {\n const out: JsonObject = { ...target };\n for (const [key, wanted] of Object.entries(source)) {\n const have = out[key];\n const where = [...trail, key].join(\" > \");\n if (have === undefined) {\n out[key] = wanted as Json;\n } else if (typeof wanted === \"string\") {\n if (have === wanted) continue;\n if (isObject(have) && have[\".\"] === wanted) continue;\n conflicts.push(\n `${where}: ${JSON.stringify(have)} (vela uses ${JSON.stringify(wanted)})`,\n );\n } else if (isObject(have)) {\n out[key] = mergeOverrides(have, wanted, [...trail, key], conflicts);\n } else if (typeof have === \"string\") {\n out[key] = mergeOverrides(\n { \".\": have },\n wanted,\n [...trail, key],\n conflicts,\n );\n } else {\n conflicts.push(\n `${where}: ${JSON.stringify(have)} (vela uses ${JSON.stringify(wanted)})`,\n );\n }\n }\n return out;\n}\n"],"mappings":";;;;;;;;;AAgCA,SAASO,EAAS,GAAqC;CACrD,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;AAEA,SAASC,EAAY,GAAmD;CACtE,IAAMC,IAAWR,EAAK,KAAKS,GAAM,cAAc;CAC/C,IAAI,CAACV,EAAG,WAAWS,CAAQ,GACzB,OAAO;EACL;EACA,SAAS;GAAE,QAAQ;GAAa,SAAS;EAA2B;CACtE;CAEF,IAAME,IAAOX,EAAG,aAAaS,GAAU,MAAM,GACzCG;CACJ,IAAI;EACF,IAAM,KAAK,MAAMD,CAAI;CACvB,QAAQ;EACN,OAA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C,CAAM,GAAG;EAClD,IAAMC,IAAOJ,EAAIjB,IACXsB,IAAQ,CAAC,GAAGC,GAAOvB,CAAG,CAAC,CAAC,KAAK,KAAK;EACxC,IAAIqB,MAAS,KAAA,GACX,EAAIrB,KAAOmB;OACN,IAAI,OAAOA,KAAW,UAAU;GAErC,IADIE,MAASF,KACTpC,EAASsC,CAAI,KAAKA,EAAK,SAASF,GAAQ;GAC5C,EAAU,KACR,GAAGG,EAAM,IAAI,KAAK,UAAUD,CAAI,EAAE,cAAc,KAAK,UAAUF,CAAM,EAAE,EACzE;EACF,OAAO,AAAIpC,EAASsC,CAAI,IACtB,EAAIrB,KAAOgB,EAAeK,GAAMF,GAAQ,CAAC,GAAGI,GAAOvB,CAAG,GAAGI,CAAS,IACzD,OAAOiB,KAAS,WACzB,EAAIrB,KAAOgB,EACT,EAAE,KAAKK,EAAK,GACZF,GACA,CAAC,GAAGI,GAAOvB,CAAG,GACdI,CACF,IAEAA,EAAU,KACR,GAAGkB,EAAM,IAAI,KAAK,UAAUD,CAAI,EAAE,cAAc,KAAK,UAAUF,CAAM,EAAE,EACzE;CAEJ;CACA,OAAOF;AACT"}
1
+ {"version":3,"file":"package-imports-Dx05A-4S.js","names":["__exportAll","fs","path","package_imports_exports","ensurePackageImports","ensurePackageOverrides","removePackageImports","isObject","value","readPackage","filePath","root","text","pkg","indent","eol","trailing","writePackage","next","file","insertKey","anchor","after","name","key","existing","finish","outcome","conflicts","field","line","current","entries","imports","keys","expected","_","rest","overrides","merged","mergeOverrides","out","target","wanted","source","have","where","trail"],"sources":["../../src/runtime/package-imports.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../core/types\";\n\n/**\n * Edits to the project's `package.json` that npm has no command for: the\n * `imports` map SvelteKit 3 resolves `#lib` (and `#locales`) through, and\n * `overrides`. The file is rewritten with the indentation and trailing\n * newline it had, and a key that already holds a different value is never\n * overwritten: it is the project's, and the outcome says what to change.\n */\n\nexport interface PackageJsonEditResult {\n filePath: string;\n outcome: ModifyOutcome;\n}\n\ntype Json = string | number | boolean | null | Json[] | { [key: string]: Json };\ntype JsonObject = { [key: string]: Json };\n\n/** An `overrides` value: a version, or nested overrides (npm's `\".\"` is the package itself). */\nexport type OverrideValue = string | { [key: string]: OverrideValue };\n\ninterface PackageFile {\n filePath: string;\n text: string;\n pkg: JsonObject;\n indent: string;\n eol: string;\n trailing: string;\n}\n\nfunction isObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readPackage(root: string): PackageFile | PackageJsonEditResult {\n const filePath = path.join(root, \"package.json\");\n if (!fs.existsSync(filePath)) {\n return {\n filePath,\n outcome: { status: \"not-found\", message: \"No package.json to edit.\" },\n };\n }\n const text = fs.readFileSync(filePath, \"utf8\");\n let pkg: unknown;\n try {\n pkg = JSON.parse(text);\n } catch {\n return {\n filePath,\n outcome: { status: \"failed\", message: \"package.json is not valid JSON.\" },\n };\n }\n if (!isObject(pkg)) {\n return {\n filePath,\n outcome: { status: \"failed\", message: \"package.json is not an object.\" },\n };\n }\n const indent = text.match(/^[{[][^\\S\\n]*\\r?\\n([\\t ]+)\\S/)?.[1] ?? \"\\t\";\n const eol = text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const trailing = text.match(/(\\r?\\n)*$/)?.[0] ?? \"\";\n return { filePath, text, pkg, indent, eol, trailing };\n}\n\nfunction writePackage(file: PackageFile): ModifyOutcome {\n const body = JSON.stringify(file.pkg, null, file.indent).replace(\n /\\n/g,\n file.eol,\n );\n const next = body + file.trailing;\n if (next === file.text) return { status: \"success\", changed: false };\n fs.writeFileSync(file.filePath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/**\n * Add `key` to `pkg` right after the first of `after` it has, else at the end.\n * JSON object key order is insertion order, so this rebuilds the object.\n */\nfunction insertKey(\n pkg: JsonObject,\n key: string,\n value: Json,\n after: string[],\n): JsonObject {\n const anchor = after.find((name) => name in pkg);\n if (!anchor) return { ...pkg, [key]: value };\n const next: JsonObject = {};\n for (const [name, existing] of Object.entries(pkg)) {\n next[name] = existing;\n if (name === anchor) next[key] = value;\n }\n return next;\n}\n\nfunction finish(\n file: PackageFile,\n conflicts: string[],\n field: string,\n): PackageJsonEditResult {\n const outcome = writePackage(file);\n if (conflicts.length === 0) return { filePath: file.filePath, outcome };\n return {\n filePath: file.filePath,\n outcome: {\n status: \"failed\",\n message: [\n `package.json \\`${field}\\` already has a different value for:`,\n ...conflicts.map((line) => ` ${line}`),\n \"Change these by hand if vela's value is the one you want.\",\n ].join(\"\\n\"),\n },\n };\n}\n\n/**\n * Add the subpath `imports` (`{ \"#lib/*\": \"./src/lib/*\" }`) that are missing.\n * Creates `imports` after `type` when the project has none.\n */\nexport function ensurePackageImports(\n root: string,\n entries: Record<string, string>,\n): PackageJsonEditResult {\n const file = readPackage(root);\n if (!(\"pkg\" in file)) return file;\n\n const current = file.pkg.imports;\n if (current !== undefined && !isObject(current)) {\n return {\n filePath: file.filePath,\n outcome: {\n status: \"failed\",\n message: [\n \"package.json `imports` is not an object. Add these entries to it by hand:\",\n ...Object.entries(entries).map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n ),\n ].join(\"\\n\"),\n },\n };\n }\n\n const imports: JsonObject = { ...(current ?? {}) };\n const conflicts: string[] = [];\n for (const [key, value] of Object.entries(entries)) {\n if (!(key in imports)) {\n imports[key] = value;\n } else if (imports[key] !== value) {\n conflicts.push(\n `${JSON.stringify(key)}: ${JSON.stringify(imports[key])} (vela uses ${JSON.stringify(value)})`,\n );\n }\n }\n file.pkg =\n current === undefined\n ? Object.keys(imports).length > 0\n ? insertKey(file.pkg, \"imports\", imports, [\"type\", \"version\", \"name\"])\n : file.pkg\n : { ...file.pkg, imports };\n return finish(file, conflicts, \"imports\");\n}\n\n/**\n * Remove subpath `imports` keys. With `expected`, a key is removed only while\n * it still maps to the value vela wrote, so one the developer repointed stays.\n * An `imports` left empty is removed too.\n */\nexport function removePackageImports(\n root: string,\n keys: string[],\n expected?: Record<string, string>,\n): PackageJsonEditResult {\n const file = readPackage(root);\n if (!(\"pkg\" in file)) {\n // Nothing to revert in a project without a package.json.\n return file.outcome.status === \"not-found\"\n ? {\n filePath: file.filePath,\n outcome: { status: \"success\", changed: false },\n }\n : file;\n }\n const current = file.pkg.imports;\n if (!isObject(current)) {\n return {\n filePath: file.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n const imports: JsonObject = { ...current };\n for (const key of keys) {\n if (!(key in imports)) continue;\n if (expected && key in expected && imports[key] !== expected[key]) continue;\n delete imports[key];\n }\n if (Object.keys(imports).length === 0) {\n const { imports: _, ...rest } = file.pkg;\n file.pkg = rest;\n } else {\n file.pkg = { ...file.pkg, imports };\n }\n return { filePath: file.filePath, outcome: writePackage(file) };\n}\n\n/**\n * Deep-merge `overrides` into package.json's `overrides`, created at the end\n * when missing. A version already there that differs is left as it is and\n * reported. A package overridden with a bare version that now needs nested\n * overrides keeps that version as npm's `\".\"`.\n */\nexport function ensurePackageOverrides(\n root: string,\n overrides: Record<string, OverrideValue>,\n): PackageJsonEditResult {\n const file = readPackage(root);\n if (!(\"pkg\" in file)) return file;\n\n const current = file.pkg.overrides;\n if (current !== undefined && !isObject(current)) {\n return {\n filePath: file.filePath,\n outcome: {\n status: \"failed\",\n message: `package.json \\`overrides\\` is not an object. Add this to it by hand:\\n${JSON.stringify(overrides, null, 2)}`,\n },\n };\n }\n const conflicts: string[] = [];\n const merged = mergeOverrides(current ?? {}, overrides, [], conflicts);\n file.pkg = { ...file.pkg, overrides: merged };\n return finish(file, conflicts, \"overrides\");\n}\n\nfunction mergeOverrides(\n target: JsonObject,\n source: Record<string, OverrideValue>,\n trail: string[],\n conflicts: string[],\n): JsonObject {\n const out: JsonObject = { ...target };\n for (const [key, wanted] of Object.entries(source)) {\n const have = out[key];\n const where = [...trail, key].join(\" > \");\n if (have === undefined) {\n out[key] = wanted as Json;\n } else if (typeof wanted === \"string\") {\n if (have === wanted) continue;\n if (isObject(have) && have[\".\"] === wanted) continue;\n conflicts.push(\n `${where}: ${JSON.stringify(have)} (vela uses ${JSON.stringify(wanted)})`,\n );\n } else if (isObject(have)) {\n out[key] = mergeOverrides(have, wanted, [...trail, key], conflicts);\n } else if (typeof have === \"string\") {\n out[key] = mergeOverrides(\n { \".\": have },\n wanted,\n [...trail, key],\n conflicts,\n );\n } else {\n conflicts.push(\n `${where}: ${JSON.stringify(have)} (vela uses ${JSON.stringify(wanted)})`,\n );\n }\n }\n return out;\n}\n"],"mappings":";;;;;;;;;AAgCA,SAASO,EAAS,GAAqC;CACrD,OAAO,OAAOC,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;AAEA,SAASC,EAAY,GAAmD;CACtE,IAAMC,IAAWR,EAAK,KAAKS,GAAM,cAAc;CAC/C,IAAI,CAACV,EAAG,WAAWS,CAAQ,GACzB,OAAO;EACL;EACA,SAAS;GAAE,QAAQ;GAAa,SAAS;EAA2B;CACtE;CAEF,IAAME,IAAOX,EAAG,aAAaS,GAAU,MAAM,GACzCG;CACJ,IAAI;EACF,IAAM,KAAK,MAAMD,CAAI;CACvB,QAAQ;EACN,OAAO;GACL;GACA,SAAS;IAAE,QAAQ;IAAU,SAAS;GAAkC;EAC1E;CACF;CACA,IAAI,CAACL,EAASM,CAAG,GACf,OAAO;EACL;EACA,SAAS;GAAE,QAAQ;GAAU,SAAS;EAAiC;CACzE;CAEF,IAAMC,IAASF,EAAK,MAAM,8BAA8B,CAAC,GAAG,MAAM,KAC5DG,IAAMH,EAAK,SAAS,MAAM,IAAI,SAAS,MACvCI,IAAWJ,EAAK,MAAM,WAAW,CAAC,GAAG,MAAM;CACjD,OAAO;EAAE;EAAU;EAAM;EAAK;EAAQ;EAAK;CAAS;AACtD;AAEA,SAASK,EAAa,GAAkC;CAKtD,IAAMC,IAJO,KAAK,UAAUC,EAAK,KAAK,MAAMA,EAAK,MAA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AGI,CAAS,IACzD,OAAOiB,KAAS,WACzB,EAAIrB,KAAOgB,EACT,EAAE,KAAKK,EAAK,GACZF,GACA,CAAC,GAAGI,GAAOvB,CAAG,GACdI,CACF,IAEAA,EAAU,KACR,GAAGkB,EAAM,IAAI,KAAK,UAAUD,CAAI,EAAE,cAAc,KAAK,UAAUF,CAAM,EAAE,EACzE;CAEJ;CACA,OAAOF;AACT"}
@@ -1,5 +1,5 @@
1
- import { n as e } from "./rolldown-runtime-DArdT4gl.js";
2
- import { c as t, i as n } from "./constants-Rq8SCXwH.js";
1
+ import { n as e } from "./rolldown-runtime-5HNE8Q1r.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";
@@ -113,11 +113,7 @@ function h(e, t, n = 60) {
113
113
  a++;
114
114
  let s = new d.Socket();
115
115
  s.once("error", () => {
116
- if (s.destroy(), a === n) {
117
- i(/* @__PURE__ */ Error(`Timed out waiting for port ${e} to be available`));
118
- return;
119
- }
120
- setTimeout(o, 500);
116
+ s.destroy(), a === n ? i(/* @__PURE__ */ Error(`Timed out waiting for port ${e} to be available`)) : setTimeout(o, 500);
121
117
  }), s.connect(e, t, () => {
122
118
  s.destroy(), r();
123
119
  });
@@ -144,11 +140,7 @@ function _(e, t = 60) {
144
140
  } catch (e) {
145
141
  a = g(e);
146
142
  }
147
- if (i === t) {
148
- r(/* @__PURE__ */ Error(`Timed out waiting for health check at ${e}/api/health (last attempt: ${a})`));
149
- return;
150
- }
151
- setTimeout(o, 500);
143
+ i === t ? r(/* @__PURE__ */ Error(`Timed out waiting for health check at ${e}/api/health (last attempt: ${a})`)) : setTimeout(o, 500);
152
144
  };
153
145
  o();
154
146
  });
@@ -232,4 +224,4 @@ function T(e, t) {
232
224
  //#endregion
233
225
  export { w as i, b as n, v as r, x as t };
234
226
 
235
- //# sourceMappingURL=pocketbase-CgwbH1gI.js.map
227
+ //# sourceMappingURL=pocketbase-DL02rq73.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;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CACxE;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CACxE;CAAM;CAAM;AACd,CAAC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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-DL02rq73.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;CAA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F,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"}
@@ -1,5 +1,5 @@
1
1
  import { n as e, s as t } from "./providers-CL9kQ4hp.js";
2
- import { readEnvVarNames as n } from "./env-vars-Bj41Nccm.js";
2
+ import { readEnvVarNames as n } from "./env-vars-CdarYsrc.js";
3
3
  import r from "node:fs";
4
4
  import i from "node:path";
5
5
  //#region src/runtime/providers.ts
@@ -35,4 +35,4 @@ function s(e) {
35
35
  //#endregion
36
36
  export { a as detectProviders };
37
37
 
38
- //# sourceMappingURL=providers-DwbwccSW.js.map
38
+ //# sourceMappingURL=providers-CAehyySB.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"providers-DwbwccSW.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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I,mBAAmB,CAAC,CAAC,CAC1C,CAAC;CACH,QAAQ;EACN,uBAAO,IAAI,IAAI;CACjB;AACF"}
1
+ {"version":3,"file":"providers-CAehyySB.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"}
@@ -1,5 +1,5 @@
1
1
  //#region \0rolldown/runtime.js
2
- var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, n) => {
2
+ var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t, t.exports), e = null), t.exports), s = (e, n) => {
3
3
  let r = {};
4
4
  for (var i in e) t(r, i, {
5
5
  get: e[i],