@velastack/patterns 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -2
- package/dist/chunks/{_page-e_I-fdSR.js → _page-DoPdZgZv.js} +2 -2
- package/dist/chunks/_page-DoPdZgZv.js.map +1 -0
- package/dist/chunks/collections-Cpjo2OiQ.js +203 -0
- package/dist/chunks/collections-Cpjo2OiQ.js.map +1 -0
- package/dist/chunks/dispatch-BIvOwbKN.js +6 -0
- package/dist/chunks/dispatch-BIvOwbKN.js.map +1 -0
- package/dist/chunks/{env-vars-CcE6ODqC.js → env-vars-Bj41Nccm.js} +32 -20
- package/dist/chunks/env-vars-Bj41Nccm.js.map +1 -0
- package/dist/chunks/generate-BClgUH4J.js +137 -0
- package/dist/chunks/generate-BClgUH4J.js.map +1 -0
- package/dist/chunks/{generate-CZGHByV3.js → generate-DjBMRzsB.js} +6 -6
- package/dist/chunks/{generate-CZGHByV3.js.map → generate-DjBMRzsB.js.map} +1 -1
- package/dist/chunks/{generate-DetW_gbr.js → generate-DyV5R8NP.js} +7 -7
- package/dist/chunks/{generate-DetW_gbr.js.map → generate-DyV5R8NP.js.map} +1 -1
- package/dist/chunks/generate-ZIOVLH6Q.js +72 -0
- package/dist/chunks/generate-ZIOVLH6Q.js.map +1 -0
- package/dist/chunks/{generate-Bg0E3eWm.js → generate-dNlBII84.js} +4 -4
- package/dist/chunks/{generate-Bg0E3eWm.js.map → generate-dNlBII84.js.map} +1 -1
- package/dist/chunks/{generate-CFqpRi9D.js → generate-yi8AP3xH.js} +4 -4
- package/dist/chunks/{generate-CFqpRi9D.js.map → generate-yi8AP3xH.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CpMKXBkn.js → generate.runtime-B4QoBn5v.js} +6 -6
- package/dist/chunks/{generate.runtime-CpMKXBkn.js.map → generate.runtime-B4QoBn5v.js.map} +1 -1
- package/dist/chunks/{generate.runtime-aQnBmH8D.js → generate.runtime-BKINIJ2c.js} +3 -3
- package/dist/chunks/{generate.runtime-aQnBmH8D.js.map → generate.runtime-BKINIJ2c.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Dl6OQ7pe.js → generate.runtime-BKTkVCEm.js} +4 -4
- package/dist/chunks/{generate.runtime-Dl6OQ7pe.js.map → generate.runtime-BKTkVCEm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CAn1qIQ_.js → generate.runtime-BXZDKLbA.js} +3 -3
- package/dist/chunks/{generate.runtime-CAn1qIQ_.js.map → generate.runtime-BXZDKLbA.js.map} +1 -1
- package/dist/chunks/{generate.runtime-hTKzxH2M.js → generate.runtime-BYfyZHhs.js} +7 -7
- package/dist/chunks/{generate.runtime-hTKzxH2M.js.map → generate.runtime-BYfyZHhs.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DoZJHtZh.js → generate.runtime-BavEh01F.js} +6 -6
- package/dist/chunks/{generate.runtime-DoZJHtZh.js.map → generate.runtime-BavEh01F.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DJ9MVVPC.js → generate.runtime-BcgjZJug.js} +123 -110
- package/dist/chunks/generate.runtime-BcgjZJug.js.map +1 -0
- package/dist/chunks/generate.runtime-BdHv7Jp1.js +82 -0
- package/dist/chunks/generate.runtime-BdHv7Jp1.js.map +1 -0
- package/dist/chunks/{generate.runtime-CqncBFNg.js → generate.runtime-BdmoAVJK.js} +4 -4
- package/dist/chunks/{generate.runtime-CqncBFNg.js.map → generate.runtime-BdmoAVJK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BpMN5Uq-.js → generate.runtime-Bdpu4rX0.js} +3 -3
- package/dist/chunks/{generate.runtime-BpMN5Uq-.js.map → generate.runtime-Bdpu4rX0.js.map} +1 -1
- package/dist/chunks/{generate.runtime-uLUiPgqx.js → generate.runtime-C7s1Mx5L.js} +6 -6
- package/dist/chunks/{generate.runtime-uLUiPgqx.js.map → generate.runtime-C7s1Mx5L.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CEqLgLT9.js → generate.runtime-CCV4O6_I.js} +3 -3
- package/dist/chunks/{generate.runtime-CEqLgLT9.js.map → generate.runtime-CCV4O6_I.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CK10Mum5.js → generate.runtime-CSUnP0l-.js} +10 -10
- package/dist/chunks/{generate.runtime-CK10Mum5.js.map → generate.runtime-CSUnP0l-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-koQxLywh.js → generate.runtime-CV4soy2n.js} +6 -6
- package/dist/chunks/{generate.runtime-koQxLywh.js.map → generate.runtime-CV4soy2n.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Db0HZyj3.js → generate.runtime-CWgZhxQt.js} +2 -2
- package/dist/chunks/{generate.runtime-Db0HZyj3.js.map → generate.runtime-CWgZhxQt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-IWEhGhWY.js → generate.runtime-CcPCAEV0.js} +6 -6
- package/dist/chunks/{generate.runtime-IWEhGhWY.js.map → generate.runtime-CcPCAEV0.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DG2z6kqH.js → generate.runtime-D-qtaVdq.js} +3 -3
- package/dist/chunks/{generate.runtime-DG2z6kqH.js.map → generate.runtime-D-qtaVdq.js.map} +1 -1
- package/dist/chunks/{generate.runtime-E-zoeSKW.js → generate.runtime-DBBtYTAa.js} +7 -7
- package/dist/chunks/{generate.runtime-E-zoeSKW.js.map → generate.runtime-DBBtYTAa.js.map} +1 -1
- package/dist/chunks/{generate.runtime-5rIc-RNL.js → generate.runtime-DRRyPa-e.js} +6 -6
- package/dist/chunks/{generate.runtime-5rIc-RNL.js.map → generate.runtime-DRRyPa-e.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BK3mR0Rj.js → generate.runtime-DaRVyiSg.js} +148 -127
- package/dist/chunks/generate.runtime-DaRVyiSg.js.map +1 -0
- package/dist/chunks/{generate.runtime-DVB7uuht.js → generate.runtime-DetYynf4.js} +3 -3
- package/dist/chunks/{generate.runtime-DVB7uuht.js.map → generate.runtime-DetYynf4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-a3R4hqFy.js → generate.runtime-DjCzW3zU.js} +12 -12
- package/dist/chunks/{generate.runtime-a3R4hqFy.js.map → generate.runtime-DjCzW3zU.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Djas9UNy.js → generate.runtime-DlbG-8Xm.js} +4 -4
- package/dist/chunks/{generate.runtime-Djas9UNy.js.map → generate.runtime-DlbG-8Xm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CbE9RHcf.js → generate.runtime-DmsOEsJV.js} +5 -5
- package/dist/chunks/generate.runtime-DmsOEsJV.js.map +1 -0
- package/dist/chunks/{generate.runtime-axm9wcQv.js → generate.runtime-MjWwR2Bd.js} +3 -3
- package/dist/chunks/{generate.runtime-axm9wcQv.js.map → generate.runtime-MjWwR2Bd.js.map} +1 -1
- package/dist/chunks/generate.runtime-NaSIZlP5.js +48 -0
- package/dist/chunks/generate.runtime-NaSIZlP5.js.map +1 -0
- package/dist/chunks/{generate.runtime-CZ46nkSL.js → generate.runtime-OEgsdWRP.js} +2 -2
- package/dist/chunks/{generate.runtime-CZ46nkSL.js.map → generate.runtime-OEgsdWRP.js.map} +1 -1
- package/dist/chunks/{generate.runtime-rs1ZOIET.js → generate.runtime-QbmCPT42.js} +3 -3
- package/dist/chunks/{generate.runtime-rs1ZOIET.js.map → generate.runtime-QbmCPT42.js.map} +1 -1
- package/dist/chunks/generate.runtime-azOvp6tl.js +106 -0
- package/dist/chunks/generate.runtime-azOvp6tl.js.map +1 -0
- package/dist/chunks/{generate.runtime-kciwaXxh.js → generate.runtime-b2RtuPy4.js} +4 -4
- package/dist/chunks/{generate.runtime-kciwaXxh.js.map → generate.runtime-b2RtuPy4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Dp7SsCQG.js → generate.runtime-pMpn0Pbf.js} +3 -3
- package/dist/chunks/{generate.runtime-Dp7SsCQG.js.map → generate.runtime-pMpn0Pbf.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DHHlYfTD.js → generate.runtime-utFLS6Jz.js} +3 -3
- package/dist/chunks/{generate.runtime-DHHlYfTD.js.map → generate.runtime-utFLS6Jz.js.map} +1 -1
- package/dist/chunks/modify-file-Bbhyfiy_.js +53 -0
- package/dist/chunks/modify-file-Bbhyfiy_.js.map +1 -0
- package/dist/chunks/{modify-nav-user-BLyrW2sK.js → modify-nav-user-B8h8WTrM.js} +2 -2
- package/dist/chunks/{modify-nav-user-BLyrW2sK.js.map → modify-nav-user-B8h8WTrM.js.map} +1 -1
- package/dist/chunks/providers-CL9kQ4hp.js +98 -0
- package/dist/chunks/providers-CL9kQ4hp.js.map +1 -0
- package/dist/chunks/providers-DwbwccSW.js +38 -0
- package/dist/chunks/providers-DwbwccSW.js.map +1 -0
- package/dist/chunks/{shared-Cc_ns5-y.js → shared-D5GOS97l.js} +2 -2
- package/dist/chunks/{shared-Cc_ns5-y.js.map → shared-D5GOS97l.js.map} +1 -1
- package/dist/chunks/shopify-page-D-VFwGxI.js +11 -0
- package/dist/chunks/shopify-page-D-VFwGxI.js.map +1 -0
- package/dist/chunks/stripe-customer-B3tP8gtD.js +6 -0
- package/dist/chunks/stripe-customer-B3tP8gtD.js.map +1 -0
- package/dist/chunks/{svelte-file-B3RfgVdt.js → svelte-file-Dv5-bl79.js} +37 -2
- package/dist/chunks/svelte-file-Dv5-bl79.js.map +1 -0
- package/dist/chunks/{test-setup-B9fQ5L_-.js → test-setup-DZoyF8Ak.js} +2 -2
- package/dist/chunks/{test-setup-B9fQ5L_-.js.map → test-setup-DZoyF8Ak.js.map} +1 -1
- package/dist/chunks/{ui-CuCsupFq.js → ui-BuocThuh.js} +2 -2
- package/dist/chunks/{ui-CuCsupFq.js.map → ui-BuocThuh.js.map} +1 -1
- package/dist/chunks/{write-result-DiZsCS_y.js → write-result-Cq-9A7Zy.js} +2 -2
- package/dist/chunks/write-result-Cq-9A7Zy.js.map +1 -0
- package/dist/index.d.ts +284 -22
- package/dist/index.js +2199 -2035
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/_page-e_I-fdSR.js.map +0 -1
- package/dist/chunks/collections-zzZ_HQxB.js +0 -192
- package/dist/chunks/collections-zzZ_HQxB.js.map +0 -1
- package/dist/chunks/dispatch-D4TN9pdW.js +0 -6
- package/dist/chunks/dispatch-D4TN9pdW.js.map +0 -1
- package/dist/chunks/env-vars-CcE6ODqC.js.map +0 -1
- package/dist/chunks/env-vars-De0Xs0L2.js +0 -20
- package/dist/chunks/env-vars-De0Xs0L2.js.map +0 -1
- package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +0 -1
- package/dist/chunks/generate.runtime-CbE9RHcf.js.map +0 -1
- package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +0 -1
- package/dist/chunks/generate.runtime-EQnytCFL.js +0 -122
- package/dist/chunks/generate.runtime-EQnytCFL.js.map +0 -1
- package/dist/chunks/modify-file-DK-tCH9k.js +0 -46
- package/dist/chunks/modify-file-DK-tCH9k.js.map +0 -1
- package/dist/chunks/providers-BHR6-XZ7.js +0 -76
- package/dist/chunks/providers-BHR6-XZ7.js.map +0 -1
- package/dist/chunks/svelte-file-B3RfgVdt.js.map +0 -1
- package/dist/chunks/write-result-DiZsCS_y.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-DJ9MVVPC.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","stripeCustomerHelper","dedent","getLogger","_layout_server_default","stripe_customer_default","_page_default","_page_server_default","app_sidebar_default","dispatch_default","withInMemoryScript","formatLikeSource","ensureImports","SvelteFile","modifyNavUser","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$5","SUBSCRIPTION_CASES_SNIPPET","modifyWebhookServer","filePath","original","addedCases","sf","switchStmt","SyntaxKind","stmt","clauses","defaultClause","c","prefix","last","source","LOAD_LINE","NOT_FOUND_HINT$4","failureHint","helper","helperFrom","clean","template","start","end","findLoad","varDecl","init","fn","modifyAppLayoutServer","Project","QuoteKind","load","body","block","binding","hasLocals","el","userIndex","s","d","statements","ret","returned","text","writer","FAILURE_HINT$1","NOT_FOUND_HINT$3","modifyAppLayoutSvelte","file","SUBSCRIPTION_TYPE","FAILURE_HINT","NOT_FOUND_HINT$2","updateScript","wasAdded","out","decl","nameNode","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","scriptChanged","src","templateChanged","modifyByTemplate","notFoundHint","current","idempotencyMarker","stripped","NOT_FOUND_HINT$1","modifyBillingPageServer","NOT_FOUND_HINT","modifyBillingPageSvelte","STRIPE_CUSTOMER_HELPER","previewRaw","nav_user_default","_layout_default","content","relativePath","generate","logger","options","modifies","pushResult","webhookServerPath","modifyOutcomeToFile","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath","keepMissing"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/enable/subscriptions/modifies/modify-by-template.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/enable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wire the subscription event handlers into src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n Add imports:\n import { handleSubscriptionCreated } from \"./subscription/created\";\n import { handleSubscriptionUpdated } from \"./subscription/updated\";\n import { handleSubscriptionDeleted } from \"./subscription/deleted\";\n\n Add switch cases inside the event.type switch:\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first — src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\nconst SUBSCRIPTION_CASES_SNIPPET = dedent`\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n let addedCases = false;\n const { source } = withInMemoryScript(original, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"handleSubscriptionCreated\"],\n moduleSpecifier: \"./subscription/created\",\n },\n {\n namedImports: [\"handleSubscriptionUpdated\"],\n moduleSpecifier: \"./subscription/updated\",\n },\n {\n namedImports: [\"handleSubscriptionDeleted\"],\n moduleSpecifier: \"./subscription/deleted\",\n },\n ]);\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n const clauses = caseBlock.getClauses();\n const defaultClause = clauses.find(\n (c) => c.getKind() === SyntaxKind.DefaultClause,\n );\n\n // Prepend subscription cases in front of the default clause, or append\n // before the closing brace of the case block if there's no default.\n const prefix = `${SUBSCRIPTION_CASES_SNIPPET}\\n\\n`;\n if (defaultClause) {\n defaultClause.replaceWithText(prefix + defaultClause.getText());\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(\n last.getText() + `\\n\\n${SUBSCRIPTION_CASES_SNIPPET}`,\n );\n } else {\n return;\n }\n\n formatLikeSource(sf);\n addedCases = true;\n });\n\n if (!addedCases) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst LOAD_LINE =\n \"const subscription = await loadActiveSubscription(locals, user.id);\";\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.server.ts before enabling subscriptions.\",\n \"Enable auth first — the (app) layout is provided by the velastack-auth baseline.\",\n].join(\"\\n\");\n\nconst failureHint = (helper: string) =>\n [\n \"Could not find the user and the returned object in the (app) layout load.\",\n \"Add the active subscription to it by hand:\",\n \"\",\n helper,\n \"\",\n \"// In load, once `user` is set:\",\n LOAD_LINE,\n \"// ...and return it with the rest:\",\n \"return { ..., subscription };\",\n ].join(\"\\n\");\n\n/**\n * The `loadActiveSubscription` helper, taken from the preview template so the\n * docs and what gets written stay the same.\n */\nfunction helperFrom(template: string): string {\n const clean = template.replace(\n /^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm,\n \"\",\n );\n const start = clean.indexOf(\"async function loadActiveSubscription\");\n const end = clean.indexOf(\"\\n}\\n\", start);\n if (start === -1 || end === -1) {\n throw new Error(\"No loadActiveSubscription in the layout template\");\n }\n return clean.slice(start, end + 2);\n}\n\nfunction findLoad(sf: SourceFile) {\n const varDecl = sf.getVariableDeclaration(\"load\");\n if (varDecl?.getVariableStatement()?.hasExportKeyword()) {\n const init = varDecl.getInitializer();\n const fn =\n varDecl.getInitializerIfKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.FunctionExpression);\n if (fn) return { fn, statement: varDecl.getVariableStatement()! };\n }\n const fn = sf.getFunction(\"load\");\n return fn?.isExported() ? { fn, statement: fn } : undefined;\n}\n\n/**\n * Adds the active subscription to the (app) layout's data: the\n * `loadActiveSubscription` helper, a call to it in `load`, and `subscription`\n * in what `load` returns. Edits the file rather than replacing it, so what\n * other patterns put in the load (teams' `team`/`teams`, say) stays.\n */\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): 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(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const helper = helperFrom(template);\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n const load = findLoad(sf);\n const body = load?.fn.getBody();\n if (!load || !body || body.getKind() !== SyntaxKind.Block) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n const block = body.asKindOrThrow(SyntaxKind.Block);\n\n // The call needs `locals` and `user`, and goes before the return.\n const params = load.fn.getParameters();\n const binding = params[0]?.getNameNode();\n const hasLocals =\n binding?.getKind() === SyntaxKind.ObjectBindingPattern &&\n binding\n .asKindOrThrow(SyntaxKind.ObjectBindingPattern)\n .getElements()\n .some((el) => el.getName() === \"locals\");\n const userIndex = block.getStatements().findIndex(\n (s) =>\n s.getKind() === SyntaxKind.VariableStatement &&\n s\n .asKindOrThrow(SyntaxKind.VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === \"user\"),\n );\n const statements = block.getStatements();\n const ret = [...statements]\n .reverse()\n .find((s) => s.getKind() === SyntaxKind.ReturnStatement)\n ?.asKind(SyntaxKind.ReturnStatement);\n const returned = ret\n ?.getExpression()\n ?.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!hasLocals || userIndex === -1 || !ret || !returned) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n\n block.insertStatements(statements.indexOf(ret), LOAD_LINE);\n if (!returned.getProperty(\"subscription\")) {\n const text = returned.getText();\n if (text.includes(\"\\n\")) {\n returned.addShorthandPropertyAssignment({ name: \"subscription\" });\n } else {\n // Kept on one line, as written.\n returned.replaceWithText(text.replace(/\\s*\\}$/, \", subscription }\"));\n }\n }\n if (!load.fn.isAsync()) load.fn.setIsAsync(true);\n sf.insertStatements(sf.getStatements().indexOf(load.statement), (writer) =>\n writer.write(helper).blankLine(),\n );\n\n formatLikeSource(sf);\n sf.saveSync();\n return { status: \"success\", changed: sf.getFullText() !== original };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:\",\n \"\",\n \"<AppSidebar user={data.user} subscription={data.subscription} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const appended = file.appendToAttributes(\n \"AppSidebar\",\n \" subscription={data.subscription}\",\n );\n if (!appended) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\n\nconst FAILURE_HINT = [\n \"Update src/lib/components/app-sidebar.svelte to forward a subscription prop:\",\n \"\",\n \"1. Add `subscription = null` to the destructured $props() call.\",\n `2. Add \\`subscription?: ${SUBSCRIPTION_TYPE}\\` to the props type.`,\n \"3. Pass `{subscription}` to <NavUser>.\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/lib/components/app-sidebar.svelte before enabling subscriptions.\",\n].join(\"\\n\");\n\nfunction updateScript(source: string): {\n source: string;\n wasAdded: boolean;\n} {\n let wasAdded = false;\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n if (elements.some((e) => e.getName() === \"subscription\")) {\n // Already has subscription prop — no-op.\n return;\n }\n\n // Insert subscription?: ... into the props type literal if present.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^\\s*subscription\\??\\s*:/.test(t))) {\n continue;\n }\n propTexts.push(`subscription?: ${SUBSCRIPTION_TYPE}`);\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Insert `subscription = null` before the first rest/default-only element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elementTexts.length;\n elementTexts.splice(insertIdx, 0, \"subscription = null\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n wasAdded = true;\n }\n formatLikeSource(sf);\n });\n return { source: out, wasAdded };\n}\n\nexport function modifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (\n original.includes(\"subscription?: {\") ||\n original.includes(\"subscription={subscription}\") ||\n original.includes(\"{subscription}\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n if (!file.hasElement(\"NavUser\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const scriptChanged = file.modifyScript((src) => updateScript(src).source);\n\n const templateChanged = !file.hasAttribute(\"NavUser\", \"subscription\")\n ? file.appendToAttributes(\"NavUser\", \" {subscription}\")\n : false;\n\n if (!scriptChanged && !templateChanged) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Overwrites a file with the given template content, guarded by an idempotency\n * marker: if the current file already contains the marker, the modify is a\n * no-op. Used for complex rewrites where surgical AST changes aren't worth it\n * (e.g. pages that are largely replaced).\n *\n * Strips leading `// [!code highlight:N]` and `<!-- [!code highlight:N] -->`\n * lines so the same content can be shared with preview-modifies, which uses\n * those comments for documentation highlighting.\n */\nexport function modifyByTemplate(\n filePath: string,\n template: string,\n idempotencyMarker: string,\n notFoundHint: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: notFoundHint };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (current.includes(idempotencyMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.server.ts is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"selectPlan\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.svelte is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageSvelte(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"availablePlans\", NOT_FOUND_HINT);\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { keepMissing, modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { modifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { modifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\nimport stripeCustomerHelper from \"../payments/creates-app-mode/src/lib/server/stripe-customer.ts?raw\";\n\n// The billing page imports this payments helper, which apps that enabled\n// payments before it existed do not have yet.\nconst STRIPE_CUSTOMER_HELPER = \"src/lib/server/stripe-customer.ts\";\n\n// Share the final-state files between preview (rendered as-is) and runtime\n// (used as overwrite templates for modifies that amount to full rewrites).\nconst previewRaw = import.meta.glob<string>(\"./preview-modifies/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nfunction template(relativePath: string): string {\n const key = `./preview-modifies/${relativePath}`;\n const content = previewRaw[key];\n if (content === undefined) {\n throw new Error(\n `Missing template for ${relativePath} in subscriptions preview-modifies`,\n );\n }\n return content;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n modifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyAppLayoutServer(\n appLayoutServerPath,\n template(\"src/routes/(app)/+layout.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n modifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Modifying app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n modifyBillingPageServer(\n billingPageServerPath,\n template(\"src/routes/(app)/billing/+page.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n modifyBillingPageSvelte(\n billingPageSveltePath,\n template(\"src/routes/(app)/billing/+page.svelte\"),\n ),\n ),\n );\n\n const creates = keepMissing(\n [\n {\n path: STRIPE_CUSTOMER_HELPER,\n language: \"ts\",\n content: stripeCustomerHelper,\n status: \"success\",\n },\n ],\n options.root,\n );\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result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O,KAAK,gCAAgC;CAC5C,IAAMO,IAAsBlG,EAAK,KAC/B4F,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPAE,EACEE,EACEE,GACAhD,EAAsBgD,CAAmB,CAC3C,CACF,GAEAP,EAAO,KAAK,8BAA8B;CAC1C,IAAMQ,IAAiBnG,EAAK,KAC1B4F,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJAE,EACEE,EAAoBG,GAAgB5B,EAAiB4B,CAAc,CAAC,CACtE,GAEAR,EAAO,KAAK,2BAA2B;CACvC,IAAMS,IAAcpG,EAAK,KACvB4F,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAWE,EAAoBI,GAAatG,EAAcsG,CAAW,CAAC,CAAC,GAEvET,EAAO,KAAK,mCAAmC;CAC/C,IAAMU,IAAwBrG,EAAK,KACjC4F,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACEE,EACEK,GACApB,EACEoB,GACA7E,EAAS,0CAA0C,CACrD,CACF,CACF,GAEAmE,EAAO,KAAK,gCAAgC;CAC5C,IAAMW,IAAwBtG,EAAK,KACjC4F,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAuBA,OAtBAE,EACEE,EACEM,GACAnB,EACEmB,GACA9E,EAAS,uCAAuC,CAClD,CACF,CACF,GAcO;EACL,SAbc+E,EACd,CACE;GACE,MAAMnB;GACN,UAAU;GACV,SAASnG;GACT,QAAQ;EACV,CACF,GACA2G,EAAQ,IAIR;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import { t as e } from "./lib-specifier-Cngo1zF_.js";
|
|
2
|
-
import { n as t } from "./logger-CQONztPm.js";
|
|
3
|
-
import { t as n } from "./shared-Cc_ns5-y.js";
|
|
4
|
-
import { n as r } from "./env-BPfk1VAw.js";
|
|
5
|
-
import { f as i, m as a, n as o, o as s } from "./ts-morph-helpers-Bepc-Es2.js";
|
|
6
|
-
import { modifyOutcomeToFile as c } from "./modify-file-DK-tCH9k.js";
|
|
7
|
-
import { unmodifyEnvVarsFiles as l } from "./env-vars-CcE6ODqC.js";
|
|
8
|
-
import { t as u } from "./svelte-file-B3RfgVdt.js";
|
|
9
|
-
import { n as d } from "./env-vars-De0Xs0L2.js";
|
|
10
|
-
import f from "node:fs";
|
|
11
|
-
import p from "node:path";
|
|
12
|
-
import { Project as m, QuoteKind as h, SyntaxKind as g } from "ts-morph";
|
|
13
|
-
//#region src/patterns/disable/payments/modifies/modify-nav-user.ts
|
|
14
|
-
function _(e) {
|
|
15
|
-
if (!f.existsSync(e)) return {
|
|
16
|
-
status: "success",
|
|
17
|
-
changed: !1
|
|
18
|
-
};
|
|
19
|
-
let t = f.readFileSync(e, "utf8");
|
|
20
|
-
if (!t.includes("/billing")) return {
|
|
21
|
-
status: "success",
|
|
22
|
-
changed: !1
|
|
23
|
-
};
|
|
24
|
-
let n = new u(t), r = !1, a = (e) => {
|
|
25
|
-
r || e((e) => {
|
|
26
|
-
let t = i(e, "Billing", "@lucide/svelte/icons/credit-card");
|
|
27
|
-
return t.wasRemoved && (r = !0), t.source;
|
|
28
|
-
});
|
|
29
|
-
};
|
|
30
|
-
return a((e) => n.modifyModuleScript(e)), r || a((e) => n.modifyScript(e)), r ? (f.writeFileSync(e, n.toString(), "utf8"), {
|
|
31
|
-
status: "success",
|
|
32
|
-
changed: !0
|
|
33
|
-
}) : {
|
|
34
|
-
status: "success",
|
|
35
|
-
changed: !1
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
//#endregion
|
|
39
|
-
//#region src/patterns/disable/payments/modifies/modify-user-signup.ts
|
|
40
|
-
var v = /* @__PURE__ */ new Set(["linkStripeCustomer.run", "linkStripeCustomer"]);
|
|
41
|
-
function y(t) {
|
|
42
|
-
if (!f.existsSync(t)) return {
|
|
43
|
-
status: "success",
|
|
44
|
-
changed: !1
|
|
45
|
-
};
|
|
46
|
-
let n = f.readFileSync(t, "utf8");
|
|
47
|
-
if (!n.includes("linkStripeCustomer")) return {
|
|
48
|
-
status: "success",
|
|
49
|
-
changed: !1
|
|
50
|
-
};
|
|
51
|
-
let r = new m({ manipulationSettings: { quoteKind: h.Single } }).addSourceFileAtPath(t);
|
|
52
|
-
for (let t of ["workflows/link-stripe-customer", "stripe"]) {
|
|
53
|
-
let n = r.getImportDeclarations().find((n) => e(n.getModuleSpecifierValue(), t));
|
|
54
|
-
n && n.remove();
|
|
55
|
-
}
|
|
56
|
-
let i = r.getVariableStatement((e) => e.getDeclarations().some((e) => e.getName() === "linkStripeCustomer"));
|
|
57
|
-
i && i.remove();
|
|
58
|
-
let c = r.getDescendantsOfKind(g.CallExpression).filter((e) => v.has(e.getExpression().getText()));
|
|
59
|
-
for (let e of c) {
|
|
60
|
-
let t = e.getFirstAncestorByKind(g.ExpressionStatement);
|
|
61
|
-
t && a(r, t);
|
|
62
|
-
}
|
|
63
|
-
return s(r), o(r), r.saveSync(), {
|
|
64
|
-
status: "success",
|
|
65
|
-
changed: r.getFullText() !== n
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
//#endregion
|
|
69
|
-
//#region src/patterns/disable/payments/generate.runtime.ts
|
|
70
|
-
async function b(e) {
|
|
71
|
-
let i = e.features.auth, a = t(e), o = [], s = [], u = (e) => {
|
|
72
|
-
e && o.push(e);
|
|
73
|
-
};
|
|
74
|
-
a.info("Stripping Stripe credentials from .env");
|
|
75
|
-
let f = [
|
|
76
|
-
{
|
|
77
|
-
type: "comment",
|
|
78
|
-
key: "Stripe credentials"
|
|
79
|
-
},
|
|
80
|
-
{
|
|
81
|
-
type: "var",
|
|
82
|
-
key: "STRIPE_SECRET_KEY"
|
|
83
|
-
},
|
|
84
|
-
{
|
|
85
|
-
type: "var",
|
|
86
|
-
key: "PUBLIC_STRIPE_PUBLISHABLE_KEY"
|
|
87
|
-
},
|
|
88
|
-
{
|
|
89
|
-
type: "var",
|
|
90
|
-
key: "STRIPE_WEBHOOK_SECRET"
|
|
91
|
-
}
|
|
92
|
-
], m = p.join(e.root, ".env");
|
|
93
|
-
u(c(m, r(m, f))), a.info("Removing Stripe variables from src/env.ts");
|
|
94
|
-
let h = l(e.root, d);
|
|
95
|
-
if (u(h.modify), h.delete && s.push(h.delete), i) {
|
|
96
|
-
a.info("Reverting nav-user.svelte");
|
|
97
|
-
let t = p.join(e.root, "src", "lib", "components", "nav-user.svelte");
|
|
98
|
-
u(c(t, _(t))), a.info("Reverting signup +page.server.ts");
|
|
99
|
-
let n = p.join(e.root, "src", "routes", "(public)", "(auth)", "signup", "+page.server.ts");
|
|
100
|
-
u(c(n, y(n)));
|
|
101
|
-
}
|
|
102
|
-
return {
|
|
103
|
-
creates: [],
|
|
104
|
-
modifies: o,
|
|
105
|
-
deletes: s,
|
|
106
|
-
components: [],
|
|
107
|
-
packages: [],
|
|
108
|
-
collections: [],
|
|
109
|
-
collectionPatches: [],
|
|
110
|
-
collectionDrops: await n(i ? [
|
|
111
|
-
"transactions",
|
|
112
|
-
"stripe_customers",
|
|
113
|
-
"stripe_payment_methods",
|
|
114
|
-
"stripe_prices",
|
|
115
|
-
"stripe_products"
|
|
116
|
-
] : ["stripe_prices", "stripe_products"], e)
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
//#endregion
|
|
120
|
-
export { b as generate };
|
|
121
|
-
|
|
122
|
-
//# sourceMappingURL=generate.runtime-EQnytCFL.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-EQnytCFL.js","names":["isLibSpecifier","getLogger","planDropsForCollections","modifyEnvRemove","removeNavItemFromScript","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","SvelteFile","STRIPE_ENV_VAR_NAMES","fs","path","unmodifyNavUser","navUserPath","source","file","wasRemoved","tryRemove","run","result","src","fn","CALL_EXPRESSIONS","unmodifyUserSignup","userSignupPath","originalSource","sourceFile","Project","QuoteKind","module","decl","d","linkFn","s","callStatements","SyntaxKind","ce","call","stmt","generate","isAppMode","options","logger","modifies","deletes","pushResult","envEdits","envPath","modifyOutcomeToFile","envVars","unmodifyEnvVarsFiles"],"sources":["../../src/patterns/disable/payments/modifies/modify-nav-user.ts","../../src/patterns/disable/payments/modifies/modify-user-signup.ts","../../src/patterns/disable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { removeNavItemFromScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(source);\n let wasRemoved = false;\n\n const tryRemove = (run: (fn: (s: string) => string) => boolean) => {\n if (wasRemoved) return;\n run((src) => {\n const result = removeNavItemFromScript(\n src,\n \"Billing\",\n \"@lucide/svelte/icons/credit-card\",\n );\n if (result.wasRemoved) wasRemoved = true;\n return result.source;\n });\n };\n\n tryRemove((fn) => file.modifyModuleScript(fn));\n if (!wasRemoved) tryRemove((fn) => file.modifyScript(fn));\n\n if (!wasRemoved) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(navUserPath, file.toString(), \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureBlankLineAfterImports,\n formatLikeSource,\n removeStatementWithComments,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst CALL_EXPRESSIONS = new Set([\n \"linkStripeCustomer.run\",\n // Projects from before the workflow: an inline helper called directly.\n \"linkStripeCustomer\",\n]);\n\nexport function unmodifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"success\", changed: false };\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 for (const module of [\"workflows/link-stripe-customer\", \"stripe\"]) {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => isLibSpecifier(d.getModuleSpecifierValue(), module));\n if (decl) decl.remove();\n }\n\n const linkFn = sourceFile.getVariableStatement((s) =>\n s.getDeclarations().some((d) => d.getName() === \"linkStripeCustomer\"),\n );\n if (linkFn) linkFn.remove();\n\n const callStatements = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => CALL_EXPRESSIONS.has(ce.getExpression().getText()));\n for (const call of callStatements) {\n const stmt = call.getFirstAncestorByKind(SyntaxKind.ExpressionStatement);\n // With the two comment lines enable-payments put above it: left behind,\n // they keep the file from matching the stock signup, and enable-whatsapp\n // then refuses to swap it.\n if (stmt) removeStatementWithComments(sourceFile, stmt);\n }\n\n formatLikeSource(sourceFile);\n ensureBlankLineAfterImports(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnvRemove, type EnvEdit } from \"../../../runtime/env\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { STRIPE_ENV_VAR_NAMES } from \"../../enable/payments/runtime/env-vars\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Stripping Stripe credentials from .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\" },\n { type: \"var\", key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\" },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\" },\n ];\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnvRemove(envPath, envEdits)));\n\n logger.info(\"Removing Stripe variables from src/env.ts\");\n const envVars = unmodifyEnvVarsFiles(options.root, STRIPE_ENV_VAR_NAMES);\n pushResult(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n if (isAppMode) {\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 signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, unmodifyUserSignup(userSignupPath)),\n );\n }\n\n const collectionNames = [\n \"transactions\",\n \"stripe_customers\",\n \"stripe_payment_methods\",\n \"stripe_prices\",\n \"stripe_products\",\n ];\n const collectionDrops = await planDropsForCollections(\n isAppMode ? collectionNames : [\"stripe_prices\", \"stripe_products\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes,\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n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AAO,KAAK,2CAA2C;CACvD,IAAMO,IAAUC,EAAqBT,EAAQ,MAAMhC,CAAoB;CAIvE,IAHAoC,EAAWI,EAAQ,MAAM,GACrBA,EAAQ,UAAQL,EAAQ,KAAKK,EAAQ,MAAM,GAE3CT,GAAW;EACb,EAAO,KAAK,2BAA2B;EACvC,IAAM3B,IAAcF,EAAK,KACvB8B,EAAQ,MACR,OACA,OACA,cACA,iBACF;EAGA,AAFAI,EAAWG,EAAoBnC,GAAaD,EAAgBC,CAAW,CAAC,CAAC,GAEzE6B,EAAO,KAAK,kCAAkC;EAC9C,IAAMlB,IAAiBb,EAAK,KAC1B8B,EAAQ,MACR,OACA,UACA,YACA,UACA,UACA,iBACF;EACA,EACEO,EAAoBxB,GAAgBD,EAAmBC,CAAc,CAAC,CACxE;CACF;CAcA,OAAO;EACL,SAAS,CAAC;EACV;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BtB,EAC5BsC,IAAY;GAPZ;GACA;GACA;GACA;GACA;EAGY,IAAkB,CAAC,iBAAiB,iBAAiB,GACjEC,CACF;CAWA;AACF"}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { a as e } from "./util-BLYliuUK.js";
|
|
2
|
-
import { n as t } from "./shared-Cc_ns5-y.js";
|
|
3
|
-
import { _ as n, s as r } from "./ts-morph-helpers-Bepc-Es2.js";
|
|
4
|
-
import i from "node:fs";
|
|
5
|
-
import a from "node:path";
|
|
6
|
-
//#region src/runtime/modify-file.ts
|
|
7
|
-
function o(t, n) {
|
|
8
|
-
let r = e(t);
|
|
9
|
-
return n.status === "success" ? n.changed ? {
|
|
10
|
-
path: t,
|
|
11
|
-
language: r,
|
|
12
|
-
content: i.readFileSync(t, "utf8"),
|
|
13
|
-
status: "success"
|
|
14
|
-
} : null : {
|
|
15
|
-
path: t,
|
|
16
|
-
language: r,
|
|
17
|
-
content: n.status === "failed" && i.existsSync(t) ? i.readFileSync(t, "utf8") : "",
|
|
18
|
-
status: n.status,
|
|
19
|
-
message: n.message
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
function s(e, a) {
|
|
23
|
-
return a.status === "success" && a.changed && i.existsSync(e) && n(i.readFileSync(e, "utf8"), r).result ? {
|
|
24
|
-
modify: null,
|
|
25
|
-
delete: t(e)
|
|
26
|
-
} : {
|
|
27
|
-
modify: o(e, a),
|
|
28
|
-
delete: null
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
function c(e, n) {
|
|
32
|
-
return n.status === "success" && n.changed && i.existsSync(e) && i.readFileSync(e, "utf8").trim() === "" ? {
|
|
33
|
-
modify: null,
|
|
34
|
-
delete: t(e)
|
|
35
|
-
} : {
|
|
36
|
-
modify: o(e, n),
|
|
37
|
-
delete: null
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
function l(e, t) {
|
|
41
|
-
return e.filter((e) => !i.existsSync(a.join(t, e.path)));
|
|
42
|
-
}
|
|
43
|
-
//#endregion
|
|
44
|
-
export { c as envRevertOutcomeToFile, l as keepMissing, o as modifyOutcomeToFile, s as revertOutcomeToFile };
|
|
45
|
-
|
|
46
|
-
//# sourceMappingURL=modify-file-DK-tCH9k.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"modify-file-DK-tCH9k.js","names":["languageFromPath","toDeleteEntry","withInMemoryScript","isEffectivelyEmpty","fs","path","modifyOutcomeToFile","language","filePath","outcome","revertOutcomeToFile","envRevertOutcomeToFile","envPath","keepMissing","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,SAAgBM,EACd,GACA,GACa;CACb,IAAMC,IAAWP,EAAiBQ,CAAQ;CAiB1C,OAfIC,EAAQ,WAAW,YAChBA,EAAQ,UACN;EACL,MAAMD;EACN;EACA,SAASJ,EAAG,aAAaI,GAAU,MAAM;EACzC,QAAQ;CACV,IAN6B,OAcxB;EACL,MAAMA;EACN;EACA,SAPAC,EAAQ,WAAW,YAAYL,EAAG,WAAWI,CAAQ,IACjDJ,EAAG,aAAaI,GAAU,MAAM,IAChC;EAMJ,QAAQC,EAAQ;EAChB,SAASA,EAAQ;CACnB;AACF;AAQA,SAAgBC,EACd,GACA,GAC8C;CAU9C,OARED,EAAQ,WAAW,aACnBA,EAAQ,WACRL,EAAG,WAAWI,CAAQ,KACtBN,EAAmBE,EAAG,aAAaI,GAAU,MAAM,GAAGL,CAAkB,CAAC,CACtE,SAEI;EAAE,QAAQ;EAAM,QAAQF,EAAcO,CAAQ;CAAE,IAElD;EAAE,QAAQF,EAAoBE,GAAUC,CAAO;EAAG,QAAQ;CAAK;AACxE;AAOA,SAAgBE,EACd,GACA,GAC8C;CAS9C,OAPEF,EAAQ,WAAW,aACnBA,EAAQ,WACRL,EAAG,WAAWQ,CAAO,KACrBR,EAAG,aAAaQ,GAAS,MAAM,CAAC,CAAC,KAAK,MAAM,KAErC;EAAE,QAAQ;EAAM,QAAQX,EAAcW,CAAO;CAAE,IAEjD;EAAE,QAAQN,EAAoBM,GAASH,CAAO;EAAG,QAAQ;CAAK;AACvE;AAWA,SAAgBI,EAAY,GAAiB,GAAsB;CACjE,OAAOC,EAAQ,QAAQ,MAAS,CAACV,EAAG,WAAWC,EAAK,KAAKU,GAAMC,EAAK,IAAI,CAAC,CAAC;AAC5E"}
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { t as e } from "./errors-DR3gF_7a.js";
|
|
2
|
-
import { i as t } from "./util-BLYliuUK.js";
|
|
3
|
-
//#region src/core/providers.ts
|
|
4
|
-
function n(e) {
|
|
5
|
-
return e.replace(/^enable-/, "");
|
|
6
|
-
}
|
|
7
|
-
function r(e) {
|
|
8
|
-
for (let t = 0; t < e.length; t++) {
|
|
9
|
-
let n = e[t];
|
|
10
|
-
if (n === "--provider") return e[t + 1];
|
|
11
|
-
if (n.startsWith("--provider=")) return n.slice(11);
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
function i(e, t, n) {
|
|
15
|
-
return [
|
|
16
|
-
`Unknown provider "${t}" for ${e}.`,
|
|
17
|
-
"",
|
|
18
|
-
"Available providers:",
|
|
19
|
-
...n.map((e) => ` ${e.id}`)
|
|
20
|
-
].join("\n");
|
|
21
|
-
}
|
|
22
|
-
function a(e) {
|
|
23
|
-
return `--provider <${e.map((e) => e.id).join("|")}>`;
|
|
24
|
-
}
|
|
25
|
-
function o(t, o) {
|
|
26
|
-
let s = t.providers ?? [], c = n(t.slug);
|
|
27
|
-
if (s.length === 0) throw Error(`${t.slug} declares no providers.`);
|
|
28
|
-
let l = typeof o.input.provider == "string" ? o.input.provider : r(o.argv);
|
|
29
|
-
if (l === void 0 || l === "") {
|
|
30
|
-
if (o.env === "preview") return s[0];
|
|
31
|
-
throw new e(`Choose a provider for ${c}: ${a(s)}`);
|
|
32
|
-
}
|
|
33
|
-
let u = s.find((e) => e.id === l);
|
|
34
|
-
if (!u) throw new e(i(c, l, s));
|
|
35
|
-
return u;
|
|
36
|
-
}
|
|
37
|
-
function s(e, t, n = {}) {
|
|
38
|
-
return [{
|
|
39
|
-
type: "comment",
|
|
40
|
-
key: t
|
|
41
|
-
}, ...(e.env ?? []).map((e) => ({
|
|
42
|
-
type: "var",
|
|
43
|
-
key: e.key,
|
|
44
|
-
value: n[e.key]?.trim() || e.default || ""
|
|
45
|
-
}))];
|
|
46
|
-
}
|
|
47
|
-
function c(e) {
|
|
48
|
-
return (e.env ?? []).map((e) => ({
|
|
49
|
-
name: e.key,
|
|
50
|
-
...e.public ? { public: !0 } : {},
|
|
51
|
-
description: e.label
|
|
52
|
-
}));
|
|
53
|
-
}
|
|
54
|
-
function l(e) {
|
|
55
|
-
let t = e.input.providerEnv;
|
|
56
|
-
if (!t || typeof t != "object") return {};
|
|
57
|
-
let n = {};
|
|
58
|
-
for (let [e, r] of Object.entries(t)) typeof r == "string" && (n[e] = r);
|
|
59
|
-
return n;
|
|
60
|
-
}
|
|
61
|
-
function u(e) {
|
|
62
|
-
let t = /* @__PURE__ */ new Set();
|
|
63
|
-
for (let n of Object.keys(e)) {
|
|
64
|
-
let e = n.match(/\/providers\/[^/]+\/(.+)$/);
|
|
65
|
-
e && t.add(e[1]);
|
|
66
|
-
}
|
|
67
|
-
return [...t].sort();
|
|
68
|
-
}
|
|
69
|
-
function d(e, n) {
|
|
70
|
-
let r = t(e, `./providers/${n}/`);
|
|
71
|
-
return Object.values(r).sort((e, t) => e.path.localeCompare(t.path));
|
|
72
|
-
}
|
|
73
|
-
//#endregion
|
|
74
|
-
export { r as a, i as c, c as i, d as n, o, s as r, l as s, u as t };
|
|
75
|
-
|
|
76
|
-
//# sourceMappingURL=providers-BHR6-XZ7.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"providers-BHR6-XZ7.js","names":["InvalidArgumentError","filesUnderPrefix","capabilityName","slug","providerFromArgv","i","argv","arg","unknownProviderMessage","raw","name","providers","provider","providerChoices","resolveProvider","pattern","options","candidate","providerEnvEdits","heading","variable","supplied","providerEnvVars","suppliedProviderEnv","values","key","value","allProviderPaths","paths","providersRaw","match","providerCreates","files","id","a","b"],"sources":["../../src/core/providers.ts"],"sourcesContent":["import type { EnvEdit } from \"../runtime/env\";\nimport type { EnvVarSpec } from \"../runtime/env-vars-file\";\nimport { InvalidArgumentError } from \"./errors\";\nimport type { File, Options, Pattern, Provider } from \"./types\";\nimport { filesUnderPrefix } from \"./util\";\n\ntype ProviderPattern = Pick<Pattern, \"slug\" | \"providers\">;\n\n/** `analytics` for `enable-analytics`: how the capability is named to users. */\nexport function capabilityName(slug: string): string {\n return slug.replace(/^enable-/, \"\");\n}\n\n/** `--provider <id>` or `--provider=<id>`, for callers that hand flags through in argv. */\nexport function providerFromArgv(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--provider\") return argv[i + 1];\n if (arg.startsWith(\"--provider=\")) return arg.slice(\"--provider=\".length);\n }\n return undefined;\n}\n\nexport function unknownProviderMessage(\n name: string,\n raw: string,\n providers: Provider[],\n): string {\n return [\n `Unknown provider \"${raw}\" for ${name}.`,\n \"\",\n \"Available providers:\",\n ...providers.map((provider) => ` ${provider.id}`),\n ].join(\"\\n\");\n}\n\nexport function providerChoices(providers: Provider[]): string {\n return `--provider <${providers.map((provider) => provider.id).join(\"|\")}>`;\n}\n\n/**\n * The provider a generate call should produce, from `input.provider` or\n * `--provider` in argv.\n *\n * An unknown id is rejected with the list of known ones. With no provider at\n * all, a runtime call is rejected too: the CLI always supplies one, so this\n * is a caller bug. A preview call falls back to the first declared provider,\n * because the website loads patterns with argv only.\n */\nexport function resolveProvider(\n pattern: ProviderPattern,\n options: Pick<Options, \"input\" | \"argv\" | \"env\">,\n): Provider {\n const providers = pattern.providers ?? [];\n const name = capabilityName(pattern.slug);\n if (providers.length === 0) {\n throw new Error(`${pattern.slug} declares no providers.`);\n }\n\n const raw =\n typeof options.input.provider === \"string\"\n ? options.input.provider\n : providerFromArgv(options.argv);\n\n if (raw === undefined || raw === \"\") {\n if (options.env === \"preview\") return providers[0];\n throw new InvalidArgumentError(\n `Choose a provider for ${name}: ${providerChoices(providers)}`,\n );\n }\n\n const provider = providers.find((candidate) => candidate.id === raw);\n if (!provider) {\n throw new InvalidArgumentError(\n unknownProviderMessage(name, raw, providers),\n );\n }\n return provider;\n}\n\n/**\n * The `.env` lines for a provider: `# heading`, then one `KEY=value` per\n * declared env var. `supplied` holds what the CLI collected; a blank value\n * falls back to the provider's default, else an empty assignment the\n * developer fills in later. Prompt placeholders are never written.\n */\nexport function providerEnvEdits(\n provider: Provider,\n heading: string,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return [\n { type: \"comment\", key: heading },\n ...(provider.env ?? []).map((variable): EnvEdit => ({\n type: \"var\",\n key: variable.key,\n value: supplied[variable.key]?.trim() || variable.default || \"\",\n })),\n ];\n}\n\n/**\n * The `src/env.ts` declarations for a provider's env vars: optional, so an\n * empty `.env` still builds, and public only where the provider says so.\n */\nexport function providerEnvVars(provider: Provider): EnvVarSpec[] {\n return (provider.env ?? []).map((variable) => ({\n name: variable.key,\n ...(variable.public ? { public: true } : {}),\n description: variable.label,\n }));\n}\n\n/** The string values of `input.providerEnv`, as the CLI collected them. */\nexport function suppliedProviderEnv(\n options: Pick<Options, \"input\">,\n): Record<string, string> {\n const raw = options.input.providerEnv;\n if (!raw || typeof raw !== \"object\") return {};\n const values: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw)) {\n if (typeof value === \"string\") values[key] = value;\n }\n return values;\n}\n\n/**\n * Every app-relative path any provider creates, sorted, for a disable pattern\n * that removes the files whichever provider was chosen. Works on a glob taken\n * from anywhere (`../../enable/<x>/providers/**`): only the part after\n * `providers/<id>/` counts.\n */\nexport function allProviderPaths(\n providersRaw: Record<string, string>,\n): string[] {\n const paths = new Set<string>();\n for (const key of Object.keys(providersRaw)) {\n const match = key.match(/\\/providers\\/[^/]+\\/(.+)$/);\n if (match) paths.add(match[1]);\n }\n return [...paths].sort();\n}\n\n/**\n * The files under `providers/<id>/**` of a pattern, as creates. The glob map\n * is one `import.meta.glob(\"./providers/**\")` covering every provider.\n */\nexport function providerCreates(\n providersRaw: Record<string, string>,\n id: string,\n): File[] {\n const files = filesUnderPrefix(providersRaw, `./providers/${id}/`);\n return Object.values(files).sort((a, b) => a.path.localeCompare(b.path));\n}\n"],"mappings":";;;AASA,SAAgBE,EAAe,GAAsB;CACnD,OAAOC,EAAK,QAAQ,YAAY,EAAE;AACpC;AAGA,SAAgBC,EAAiB,GAAoC;CACnE,K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G,KAAK,OAAuB;EAClD,MAAM;EACN,KAAKQ,EAAS;EACd,OAAOC,EAASD,EAAS,IAAI,EAAE,KAAK,KAAKA,EAAS,WAAW;CAC/D,EAAE,CACJ;AACF;AAMA,SAAgBE,EAAgB,GAAkC;CAChE,QAAQV,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,OAAc;EAC7C,MAAMQ,EAAS;EACf,GAAIA,EAAS,SAAS,EAAE,QAAQ,GAAK,IAAI,CAAC;EAC1C,aAAaA,EAAS;CACxB,EAAE;AACJ;AAGA,SAAgBG,EACd,GACwB;CACxB,IAAMd,IAAMO,EAAQ,MAAM;CAC1B,IAAI,CAACP,KAAO,OAAOA,KAAQ,UAAU,OAAO,CAAC;CAC7C,IAAMe,IAAiC,CAAC;CACxC,KAAK,IAAM,CAACC,GAAKC,MAAU,OAAO,QAAQjB,CAAG,GAC3C,AAAI,OAAOiB,KAAU,aAAU,EAAOD,KAAOC;CAE/C,OAAOF;AACT;AAQA,SAAgBG,EACd,GACU;CACV,IAAMC,oBAAQ,IAAI,IAAY;CAC9B,KAAK,IAAMH,KAAO,OAAO,KAAKI,CAAY,GAAG;EAC3C,IAAMC,IAAQL,EAAI,MAAM,2BAA2B;EACnD,AAAIK,KAAOF,EAAM,IAAIE,EAAM,EAAE;CAC/B;CACA,OAAO,CAAC,GAAGF,CAAK,CAAC,CAAC,KAAK;AACzB;AAMA,SAAgBG,EACd,GACA,GACQ;CACR,IAAMC,IAAQ/B,EAAiB4B,GAAc,eAAeI,EAAG,EAAE;CACjE,OAAO,OAAO,OAAOD,CAAK,CAAC,CAAC,MAAM,GAAG,MAAME,EAAE,KAAK,cAAcC,EAAE,IAAI,CAAC;AACzE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"svelte-file-B3RfgVdt.js","names":["fs","MagicString","SvelteFile","source","parse","filePath","script","start","end","fn","block","next","findNode","node","name","componentName","attr","attrName","closingTag","closingPos","content","newContent","nodes","index","trimmed","i","prev","last","insertAt","attrs","a","seen","visit","predicate","key","child","item","found","root"],"sources":["../../src/runtime/svelte-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { parse, type AST } from \"svelte/compiler\";\nimport MagicString from \"magic-string\";\n\ntype SvelteAst = AST.Root;\ntype SvelteNode = any;\n\ninterface ScriptBlock {\n content: string;\n start: number;\n end: number;\n}\n\n/**\n * Surgical, AST-aware editing of .svelte files.\n *\n * Parses the source with svelte/compiler to discover precise character offsets,\n * then applies edits via magic-string so untouched regions remain byte-for-byte\n * identical to the original. Script-block contents are exposed as plain strings\n * so callers can hand them to ts-morph.\n */\nexport class SvelteFile {\n private readonly source: string;\n private readonly ast: SvelteAst;\n private readonly s: MagicString;\n\n constructor(source: string) {\n this.source = source;\n this.ast = parse(source, { modern: true });\n this.s = new MagicString(source);\n }\n\n static fromPath(filePath: string): SvelteFile {\n return new SvelteFile(fs.readFileSync(filePath, \"utf8\"));\n }\n\n getScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).instance);\n }\n\n getModuleScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).module);\n }\n\n private scriptInner(script: SvelteNode | null): ScriptBlock | null {\n if (!script) return null;\n const start = script.content.start as number;\n const end = script.content.end as number;\n return { content: this.source.slice(start, end), start, end };\n }\n\n /**\n * Replace the inner contents of <script>. Use for ts-morph round-trips.\n * Returns true when an edit was made.\n */\n modifyScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getScript(), fn);\n }\n\n modifyModuleScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getModuleScript(), fn);\n }\n\n private modifyScriptBlock(\n block: ScriptBlock | null,\n fn: (content: string) => string,\n ): boolean {\n if (!block) return false;\n const next = fn(block.content);\n if (next === block.content) return false;\n this.s.overwrite(block.start, block.end, next);\n return true;\n }\n\n /** First Component or RegularElement node with the given name. */\n findElement(name: string): SvelteNode | null {\n return findNode(\n (this.ast as any).fragment,\n (node) =>\n (node.type === \"Component\" || node.type === \"RegularElement\") &&\n node.name === name,\n );\n }\n\n hasElement(name: string): boolean {\n return this.findElement(name) !== null;\n }\n\n hasAttribute(componentName: string, attrName: string): boolean {\n const node = this.findElement(componentName);\n if (!node) return false;\n return (node.attributes ?? []).some(\n (attr: SvelteNode) => attr.type === \"Attribute\" && attr.name === attrName,\n );\n }\n\n /**\n * Insert content at the end of <ComponentName>'s children, just before the\n * closing tag. No-op if the element is not found.\n */\n insertBeforeClosingTag(name: string, content: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const closingTag = `</${name}>`;\n const closingPos = this.source.lastIndexOf(closingTag, node.end);\n if (closingPos === -1) return false;\n this.s.appendLeft(closingPos, content);\n return true;\n }\n\n /** Replace the element entirely (start tag through close tag). */\n replaceElement(name: string, newContent: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n this.s.overwrite(node.start, node.end, newContent);\n return true;\n }\n\n /** Remove the element (start tag through close tag). */\n removeElement(name: string): boolean {\n return this.replaceElement(name, \"\");\n }\n\n /** Append raw markup to the end of the source file. */\n appendMarkup(content: string): void {\n this.s.append(content);\n }\n\n /**\n * Insert markup so it renders before the layout's children — i.e. ahead of\n * the top-level `{@render children()}` (or legacy `<slot />`). The markup\n * lands on its own line directly after the preceding sibling, so\n *\n * <Toaster />\n *\n * {@render children?.()}\n *\n * becomes `<Toaster />\\n<AdminBar />\\n\\n{@render children?.()}`. When the\n * render tag is the first node the markup goes immediately before it.\n * Returns false (and changes nothing) if no such tag exists.\n */\n insertBeforeChildren(content: string): boolean {\n const nodes: SvelteNode[] = (this.ast as any).fragment?.nodes ?? [];\n const index = nodes.findIndex(\n (node) =>\n node.type === \"RenderTag\" ||\n node.type === \"SlotElement\" ||\n (node.type === \"RegularElement\" && node.name === \"slot\"),\n );\n if (index === -1) return false;\n\n const trimmed = content.trim();\n for (let i = index - 1; i >= 0; i--) {\n const prev = nodes[i]!;\n if (prev.type === \"Text\" && prev.data.trim() === \"\") continue;\n this.s.appendLeft(prev.end as number, `\\n${trimmed}`);\n return true;\n }\n this.s.appendLeft(nodes[index]!.start as number, `${trimmed}\\n\\n`);\n return true;\n }\n\n /**\n * Append attribute text (e.g. \" team={data.team}\") just after the last\n * existing attribute on the element's start tag.\n */\n appendToAttributes(name: string, attrs: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const last = (node.attributes ?? []).at(-1) as SvelteNode | undefined;\n const insertAt = last\n ? (last.end as number)\n : (node.start as number) + `<${name}`.length;\n this.s.appendLeft(insertAt, attrs);\n return true;\n }\n\n /**\n * Remove a named attribute from a component's start tag, including the\n * leading whitespace. No-op if the element or attribute isn't present.\n */\n removeAttribute(name: string, attrName: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const attr = (node.attributes ?? []).find(\n (a: SvelteNode) => a.type === \"Attribute\" && a.name === attrName,\n );\n if (!attr) return false;\n // Extend the removal backwards over the whitespace between the previous\n // token and this attribute so the tag doesn't collapse `<Foo />`.\n let start = attr.start as number;\n while (start > 0 && /\\s/.test(this.source[start - 1]!)) start--;\n this.s.remove(start, attr.end as number);\n return true;\n }\n\n hasChanged(): boolean {\n return this.s.hasChanged();\n }\n\n toString(): string {\n return this.s.toString();\n }\n\n writeTo(filePath: string): void {\n if (this.hasChanged()) {\n fs.writeFileSync(filePath, this.toString(), \"utf8\");\n }\n }\n}\n\nfunction findNode(\n root: unknown,\n predicate: (node: any) => boolean,\n): any | null {\n const seen = new WeakSet<object>();\n function visit(node: unknown): any | null {\n if (!node || typeof node !== \"object\" || seen.has(node as object)) {\n return null;\n }\n seen.add(node as object);\n if (predicate(node as any)) return node;\n for (const key of Object.keys(node as Record<string, unknown>)) {\n if (key === \"parent\") continue;\n const child = (node as Record<string, unknown>)[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n const found = visit(item);\n if (found) return found;\n }\n } else if (\n child &&\n typeof child === \"object\" &&\n \"type\" in (child as object)\n ) {\n const found = visit(child);\n if (found) return found;\n }\n }\n return null;\n }\n return visit(root);\n}\n"],"mappings":";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ME,IAAQL,EAAMI,CAAI;IACxB,IAAIC,GAAO,OAAOA;GACpB;QACK,IACLF,KACA,OAAOA,KAAU,YACjB,UAAWA,GACX;IACA,IAAME,IAAQL,EAAMG,CAAK;IACzB,IAAIE,GAAO,OAAOA;GACpB;EACF;EACA,OAAO;CACT;CACA,OAAOL,EAAMM,CAAI;AACnB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"write-result-DiZsCS_y.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","__import_glob__0_7_","__import_glob__0_8_","__import_glob__0_9_","__import_glob__0_10_","__import_glob__0_11_","__import_glob__0_12_","__import_glob__0_13_","__import_glob__0_14_","__import_glob__0_15_","__import_glob__0_16_","__import_glob__0_17_","__import_glob__0_18_","__import_glob__0_19_","__import_glob__0_20_","__import_glob__0_21_","__import_glob__0_22_","__import_glob__0_23_","__import_glob__0_24_","__import_glob__0_25_","__import_glob__0_26_","__import_glob__0_27_","__import_glob__0_28_","__import_glob__0_29_","__import_glob__0_30_","__import_glob__0_31_","__import_glob__0_32_","__import_glob__0_33_","__import_glob__0_34_","__import_glob__0_35_","__import_glob__0_36_","__import_glob__0_37_","__import_glob__0_38_","__import_glob__0_39_","__import_glob__0_40_","__import_glob__0_41_","__import_glob__0_42_","__import_glob__0_43_","__import_glob__0_44_","__import_glob__0_45_","__import_glob__0_46_","__import_glob__0_47_","__import_glob__0_48_","__import_glob__0_49_","__import_glob__0_50_","__import_glob__0_51_","__import_glob__0_52_","__import_glob__0_53_","__import_glob__0_54_","__import_glob__0_55_","__exportAll","MissingShadcnError","RegistryUnavailableError","InvalidArgumentError","FORMSNAP","TANSTACK_TABLE_CORE","FORMSNAP_OVERRIDES","formatSource","getLogger","NOOP_LOGGER","resolveUiDir","readComponentsConfig","fetchRegistryIndex","assertTableCorePackage","ensurePackageOverrides","path","spawn","os","auth_menu_content_default","auth_menu_group_default","auth_menu_item_default","auth_menu_label_default","auth_menu_separator_default","auth_menu_trigger_default","auth_menu_default$1","context_default","auth_menu_default","autodate_default","bool_default","date_default","editor_default","email_default","file_default","geoPoint_default","cells_default","json_default","number_default","password_default","relation_default","select_default","text_default","url_default","column_header_default$1","column_header_default","data_table_svelte_default","flex_render_default","data_table_default","render_helpers_default","faceted_filter_default$1","faceted_filter_default","file_field_default","file_input_default","file_multiple_default","file_single_default","file_thumb_default","file_form_default","shared_default","coordinate_default","geopoint_default","input_default$1","toggle_map_default","leaflet_default$1","leaflet_default","chip_default","content_default","field_default","multiselect_default","input_default","item_default","trigger_default","pagination_default$1","pagination_default","row_actions_default$1","row_actions_default","write_result_exports","ensureSvelteKitSync","executeCommand","formatPaths","getAllCustomComponents","installComponents","installedComponents","installedPackagesFromProject","isCustomComponent","isExactSpec","packageName","restoreDowngradedDependencies","writeResult","customDependencies","customNpmPackages","customComponentAssets","componentNameFromAssetPath","parts","assetPath","componentRelativeAssetPath","index","toTargetPath","filePath","root","toRelativePath","writeFile","mkdirSync","writeFileSync","content","removeFile","existsSync","rmSync","pruneEmptyDirectories","stop","current","dir","readdirSync","EXACT_FLAG","executeWithDetectedPackageManager","packageManager","detect","resolved","resolveCommand","operation","args","commandArgs","exactFlag","options","child","reject","code","restoreTypes","preserveSvelteKitTypes","cwd","runtime","packageJsonPath","packageJson","readFileSync","at","spec","name","ensureFormsnapOverride","names","toInstall","formsnap","installed","touched","outcome","logger","appDir","saved","mkdtempSync","cpSync","error","DEPENDENCY_BLOCKS","rangeFloor","match","part","value","compareFloors","i","a","b","pkg","after","restored","previous","block","before","entries","old","oldFloor","newFloor","readPackageJson","file","installPackages","packages","exact","ranged","uninstallPackages","toRemove","component","customNpmPackagesFor","components","copyCustomComponent","targetDir","targetComponentsDir","relativePath","outputPath","FORMATTABLE_EXTENSIONS","filesUnder","target","statSync","entry","context","changed","paths","formatted","uiDir","BARE_ITEM_NAME","assertKnownRegistryItems","bare","known","item","unknown","style","requested","componentsDir","isPresent","skipped","overwrite","customToInstall","publicToInstall","dependency","customList","publicList","indent","recorded","had","installedList","writtenResult","dropMigrationCreates","result","dropCollections","isPackageJson","packageInstalls","componentInstalls","packageUninstalls"],"sources":["../../src/runtime/write-result.ts"],"sourcesContent":["import {\n cpSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport type {\n Component,\n ExecuteCommandOptions,\n InstallComponentsOptions,\n InstallComponentsResult,\n Options,\n PackageManagerOperation,\n Result,\n WriteResultRuntime,\n} from \"../core/types\";\nimport {\n InvalidArgumentError,\n MissingShadcnError,\n RegistryUnavailableError,\n} from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { formatSource } from \"../core/format-result\";\nimport {\n FORMSNAP,\n FORMSNAP_OVERRIDES,\n TANSTACK_TABLE_CORE,\n} from \"../core/constants\";\nimport {\n fetchRegistryIndex,\n readComponentsConfig,\n resolveUiDir,\n} from \"./registry\";\nimport { assertTableCorePackage } from \"./table-core\";\nimport { ensurePackageOverrides } from \"./package-imports\";\n\nexport { resolveUiDir };\n\ntype CustomNpmPackages = Record<string, string[]>;\n\n/**\n * The components under `src/ui/components` are copied into a project rather\n * than fetched from the shadcn-svelte registry, so their dependencies have to\n * be declared here: every shadcn-svelte component a bundled one imports\n * (`#lib/components/ui/<x>/index.js`) must appear in `customDependencies`, and\n * every npm package that no shadcn item installs for it must appear in\n * `customNpmPackages`.\n */\nconst customDependencies: Record<string, string[]> = {\n \"file-form\": [\"input\"],\n multiselect: [\"command\", \"popover\", \"button\"],\n geopoint: [\"button\", \"leaflet\"],\n cells: [\"badge\"],\n \"data-table\": [],\n \"column-header\": [\"dropdown-menu\", \"button\"],\n \"faceted-filter\": [\"command\", \"popover\", \"button\", \"separator\", \"badge\"],\n pagination: [\"button\", \"select\"],\n \"row-actions\": [\"dropdown-menu\", \"button\"],\n leaflet: [],\n \"auth-menu\": [\"dropdown-menu\", \"button\"],\n};\n\nconst customNpmPackages: CustomNpmPackages = {\n \"file-form\": [FORMSNAP],\n multiselect: [FORMSNAP],\n geopoint: [],\n cells: [],\n // shadcn-svelte >= 1.2.0 resolves items from the style-scoped registry\n // (/registry/styles/<style>/), which has no `data-table` item, so the\n // TanStack helpers ship from here instead.\n \"data-table\": [TANSTACK_TABLE_CORE],\n \"column-header\": [TANSTACK_TABLE_CORE],\n \"faceted-filter\": [TANSTACK_TABLE_CORE],\n pagination: [TANSTACK_TABLE_CORE],\n \"row-actions\": [],\n leaflet: [\"leaflet\", \"@types/leaflet\"],\n};\n\nconst customComponentAssets = import.meta.glob<string>(\"../ui/components/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The components this package ships, by directory name, sorted. */\nexport function getAllCustomComponents(): Component[] {\n return [\n ...new Set(\n Object.keys(customComponentAssets).map(componentNameFromAssetPath),\n ),\n ]\n .filter(Boolean)\n .sort();\n}\n\nfunction componentNameFromAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts[index + 1] ?? \"\";\n}\n\nfunction componentRelativeAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts.slice(index + 2).join(\"/\");\n}\n\nfunction toTargetPath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n return path.join(root, filePath);\n}\n\nfunction toRelativePath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return path.relative(root, filePath);\n }\n return filePath;\n}\n\nfunction writeFile(filePath: string, content: string): void {\n mkdirSync(path.dirname(filePath), { recursive: true });\n writeFileSync(filePath, content, \"utf8\");\n}\n\nfunction removeFile(filePath: string, root: string): void {\n if (!existsSync(filePath)) {\n return;\n }\n\n rmSync(filePath, { force: true, recursive: true });\n pruneEmptyDirectories(path.dirname(filePath), root);\n}\n\n/**\n * Deleting a feature's files must also delete the directories it added, up\n * to the first one that still has content. The CLI detects features by\n * directory (`src/routes/(app)` means auth is on), so an empty leftover\n * directory keeps a disabled feature \"enabled\".\n */\nfunction pruneEmptyDirectories(dir: string, root: string): void {\n const stop = path.resolve(root);\n let current = path.resolve(dir);\n while (current !== stop && current.startsWith(stop)) {\n if (!existsSync(current) || readdirSync(current).length > 0) {\n return;\n }\n rmSync(current, { recursive: true, force: true });\n current = path.dirname(current);\n }\n}\n\n/** Each package manager's flag for saving the exact version instead of a range. */\nconst EXACT_FLAG: Record<string, string> = {\n npm: \"--save-exact\",\n pnpm: \"--save-exact\",\n yarn: \"--exact\",\n bun: \"--exact\",\n};\n\nasync function executeWithDetectedPackageManager(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n options: ExecuteCommandOptions = {},\n): Promise<void> {\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n // Adding named packages is `add` (`npm i`, `pnpm add`, `yarn add`):\n // `yarn install <pkg>` is an error.\n const resolved = resolveCommand(\n packageManager,\n operation === \"install\" && args.length > 0 ? \"add\" : operation,\n args,\n );\n if (!resolved) {\n throw new Error(\n `Unable to resolve ${operation} command for ${packageManager}`,\n );\n }\n\n const commandArgs = [...resolved.args];\n if (packageManager === \"npm\") {\n commandArgs.unshift(\"--yes\");\n }\n const exactFlag = EXACT_FLAG[packageManager];\n if (options.exact && exactFlag) {\n commandArgs.push(exactFlag);\n }\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(resolved.command, commandArgs, {\n cwd,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(`${resolved.command} exited with code ${code ?? \"unknown\"}`),\n );\n });\n });\n}\n\nexport async function executeCommand(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n runtime?: WriteResultRuntime,\n options?: ExecuteCommandOptions,\n): Promise<void> {\n const restoreTypes =\n operation === \"execute\" ? null : preserveSvelteKitTypes(cwd);\n try {\n if (runtime?.executeCommand) {\n await (options\n ? runtime.executeCommand(cwd, operation, args, options)\n : runtime.executeCommand(cwd, operation, args));\n return;\n }\n\n await executeWithDetectedPackageManager(cwd, operation, args, options);\n } finally {\n restoreTypes?.();\n }\n}\n\n/** Package names `package.json` records, whichever dependency block they sit in. */\nexport function installedPackagesFromProject(root: string): Set<string> {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n return new Set();\n }\n\n const packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n\n return new Set([\n ...Object.keys(packageJson.dependencies ?? {}),\n ...Object.keys(packageJson.devDependencies ?? {}),\n ...Object.keys(packageJson.optionalDependencies ?? {}),\n ...Object.keys(packageJson.peerDependencies ?? {}),\n ]);\n}\n\n/**\n * Splits an npm install spec into its package name, dropping any range.\n * `wuchale@^0.26.3` -> `wuchale`, `@wuchale/svelte@^0.21.1` -> `@wuchale/svelte`.\n *\n * The name is what `package.json` records, so it -- not the full spec -- is what\n * the already-installed check has to compare against.\n */\nexport function packageName(spec: string): string {\n const at = spec.indexOf(\"@\", spec.startsWith(\"@\") ? 1 : 0);\n return at === -1 ? spec : spec.slice(0, at);\n}\n\n/**\n * A spec naming one exact version (`sveltekit-superforms@3.0.0-next.1`),\n * which is saved as written. Package managers otherwise save a caret, and a\n * caret on a prerelease follows every later `next` build.\n */\nexport function isExactSpec(spec: string): boolean {\n const name = packageName(spec);\n return /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(\n spec.slice(name.length + 1),\n );\n}\n\n/**\n * formsnap 2 peers superforms ^2 and projects run superforms 3, so the\n * override has to be in package.json before an install that brings either in\n * next to formsnap, or npm stops with ERESOLVE.\n */\nfunction ensureFormsnapOverride(\n root: string,\n installed: Set<string>,\n toInstall: string[],\n logger: Logger,\n): void {\n const names = new Set(toInstall.map(packageName));\n const formsnap = names.has(\"formsnap\") || installed.has(\"formsnap\");\n const touched = names.has(\"formsnap\") || names.has(\"sveltekit-superforms\");\n if (!formsnap || !touched) {\n return;\n }\n const { outcome } = ensurePackageOverrides(root, FORMSNAP_OVERRIDES);\n if (outcome.status === \"failed\") {\n logger.info(outcome.message);\n } else if (outcome.status === \"success\" && outcome.changed) {\n logger.info(\"Added the formsnap override for sveltekit-superforms\");\n }\n}\n\n/**\n * SvelteKit 3's tsconfig extends `$app/tsconfig`, which `svelte-kit sync`\n * writes to `node_modules/$app`. A package-manager install prunes that folder\n * (it is no package) and only an argument-less npm install's `prepare` writes\n * it back, so after `npm install <pkg>` every tool that reads the tsconfig\n * (shadcn-svelte, svelte-check without sync, the editor) fails on the missing\n * `extends`. Syncing again is no fix mid-pattern: it loads vite.config, which\n * may already name a plugin whose own config the pattern has not written yet.\n * So the folder is copied aside before an install and put back after.\n */\nfunction preserveSvelteKitTypes(root: string): (() => void) | null {\n const appDir = path.join(root, \"node_modules\", \"$app\");\n if (!existsSync(appDir)) {\n return null;\n }\n const saved = mkdtempSync(path.join(os.tmpdir(), \"vela-app-types-\"));\n cpSync(appDir, path.join(saved, \"$app\"), { recursive: true });\n return () => {\n try {\n if (!existsSync(appDir) && existsSync(path.join(root, \"node_modules\"))) {\n cpSync(path.join(saved, \"$app\"), appDir, { recursive: true });\n }\n } finally {\n rmSync(saved, { recursive: true, force: true });\n }\n };\n}\n\n/**\n * Run `svelte-kit sync` when SvelteKit is installed but `node_modules/$app`\n * is missing (a fresh copy of `node_modules`, or an install made outside\n * vela), so shadcn-svelte can read the tsconfig. Best effort: a sync that\n * fails is reported and left to shadcn-svelte to complain about.\n */\nexport async function ensureSvelteKitSync(\n root: string,\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<boolean> {\n if (!existsSync(path.join(root, \"node_modules\", \"@sveltejs\", \"kit\"))) {\n return false;\n }\n if (existsSync(path.join(root, \"node_modules\", \"$app\", \"tsconfig.json\"))) {\n return false;\n }\n try {\n await executeCommand(root, \"execute\", [\"svelte-kit\", \"sync\"], runtime);\n return true;\n } catch (error) {\n logger.info(\n `svelte-kit sync failed (${error instanceof Error ? error.message : String(error)}); node_modules/$app is missing`,\n );\n return false;\n }\n}\n\ntype DependencyBlocks = Record<string, Record<string, string> | undefined>;\n\nconst DEPENDENCY_BLOCKS = [\n \"dependencies\",\n \"devDependencies\",\n \"optionalDependencies\",\n] as const;\n\n/** The lowest version a range names, as numbers, or null when it is no semver range. */\nfunction rangeFloor(spec: string): number[] | null {\n const match = spec\n .trim()\n .match(\n /^(?:[\\^~=v]|>=?)?\\s*(\\d+)(?:\\.(\\d+|[xX*]))?(?:\\.(\\d+|[xX*]))?(-[0-9A-Za-z.-]+)?$/,\n );\n if (!match) {\n return null;\n }\n const part = (value: string | undefined) =>\n value === undefined || /[xX*]/.test(value) ? 0 : Number(value);\n // A prerelease sorts below its release.\n return [part(match[1]), part(match[2]), part(match[3]), match[4] ? 0 : 1];\n}\n\nfunction compareFloors(a: number[], b: number[]): number {\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return a[i]! - b[i]!;\n }\n }\n return 0;\n}\n\n/**\n * The dependency entries `shadcn-svelte add` changed that have to go back:\n * shadcn replaces any range its registry item's own range does not cover,\n * downgrades included. The form item still asks for `sveltekit-superforms`\n * ^2, which SvelteKit 3 cannot install, over the project's 3.x pin. So an\n * entry the project already had is restored when shadcn moved it below\n * where it was, or when it is not a semver range at all (file:, git,\n * workspace:). A raised floor and every new entry are kept.\n */\nexport function restoreDowngradedDependencies(\n before: DependencyBlocks,\n after: DependencyBlocks,\n): { pkg: DependencyBlocks; restored: string[] } {\n const pkg: DependencyBlocks = { ...after };\n const restored: string[] = [];\n const previous = new Map<string, string>();\n for (const block of DEPENDENCY_BLOCKS) {\n for (const [name, spec] of Object.entries(before[block] ?? {})) {\n previous.set(name, spec);\n }\n }\n for (const block of DEPENDENCY_BLOCKS) {\n const entries = after[block];\n if (!entries) {\n continue;\n }\n for (const [name, spec] of Object.entries(entries)) {\n const old = previous.get(name);\n if (old === undefined || old === spec) {\n continue;\n }\n const oldFloor = rangeFloor(old);\n const newFloor = rangeFloor(spec);\n const keep =\n oldFloor !== null &&\n newFloor !== null &&\n compareFloors(newFloor, oldFloor) >= 0;\n if (keep) {\n continue;\n }\n pkg[block] = { ...(pkg[block] as Record<string, string>), [name]: old };\n restored.push(`${name}@${old}`);\n }\n }\n return { pkg, restored };\n}\n\nfunction readPackageJson(root: string): Record<string, unknown> | null {\n const file = path.join(root, \"package.json\");\n if (!existsSync(file)) {\n return null;\n }\n return JSON.parse(readFileSync(file, \"utf8\")) as Record<string, unknown>;\n}\n\nasync function installPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toInstall = [...new Set(packages)].filter(\n (pkg) => !installed.has(packageName(pkg)),\n );\n if (toInstall.length === 0) {\n return [];\n }\n\n ensureFormsnapOverride(root, installed, toInstall, logger);\n\n logger.info(`Installing packages: ${toInstall.join(\", \")}`);\n // `--save-exact` applies to a whole command, so exact pins go in their own.\n const exact = toInstall.filter(isExactSpec);\n const ranged = toInstall.filter((spec) => !isExactSpec(spec));\n if (exact.length > 0) {\n await executeCommand(root, \"install\", exact, runtime, { exact: true });\n }\n if (ranged.length > 0) {\n await executeCommand(root, \"install\", ranged, runtime);\n }\n return toInstall;\n}\n\n/**\n * `npm uninstall` for the listed packages that `package.json` records. The\n * inverse of `installPackages`: names not present are skipped, so a disable\n * pattern can name everything its enable counterpart installed.\n */\nasync function uninstallPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toRemove = [...new Set(packages.map(packageName))].filter((pkg) =>\n installed.has(pkg),\n );\n if (toRemove.length === 0) {\n return [];\n }\n\n logger.info(`Removing packages: ${toRemove.join(\", \")}`);\n await executeCommand(root, \"uninstall\", toRemove, runtime);\n return toRemove;\n}\n\nexport function isCustomComponent(component: string): boolean {\n return getAllCustomComponents().includes(component);\n}\n\nfunction customNpmPackagesFor(components: string[]): string[] {\n return [\n ...new Set(\n components.flatMap((component) => customNpmPackages[component] ?? []),\n ),\n ];\n}\n\nfunction copyCustomComponent(\n component: string,\n targetComponentsDir: string,\n): void {\n const targetDir = path.join(targetComponentsDir, component);\n mkdirSync(targetDir, { recursive: true });\n\n for (const [assetPath, content] of Object.entries(customComponentAssets)) {\n if (componentNameFromAssetPath(assetPath) !== component) {\n continue;\n }\n const relativePath = componentRelativeAssetPath(assetPath);\n if (!relativePath) {\n continue;\n }\n\n const outputPath = path.join(targetDir, relativePath);\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, content, \"utf8\");\n }\n}\n\nconst FORMATTABLE_EXTENSIONS = new Set([\n \".ts\",\n \".js\",\n \".svelte\",\n \".json\",\n \".css\",\n]);\n\nfunction* filesUnder(target: string): Generator<string> {\n if (!existsSync(target)) {\n return;\n }\n if (statSync(target).isFile()) {\n yield target;\n return;\n }\n const entries = readdirSync(target, { recursive: true, withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n yield path.join(entry.parentPath, entry.name);\n }\n }\n}\n\n/**\n * `shadcn-svelte add` and `apply` write files in the registry's style and the\n * bundled components carry this repo's; the project's `npm run lint` expects\n * its own. Runs the project's prettier over the given files and directories\n * (relative to the root or absolute) and returns the relative paths it\n * changed. Paths that do not exist are skipped.\n */\nexport async function formatPaths(\n root: string,\n paths: string[],\n): Promise<string[]> {\n const context = { env: \"runtime\" as const, root };\n const changed: string[] = [];\n for (const target of paths) {\n for (const filePath of filesUnder(toTargetPath(root, target))) {\n if (!FORMATTABLE_EXTENSIONS.has(path.extname(filePath))) {\n continue;\n }\n const content = readFileSync(filePath, \"utf8\");\n const formatted = await formatSource(content, filePath, context);\n if (formatted !== content) {\n writeFileSync(filePath, formatted, \"utf8\");\n changed.push(path.relative(root, filePath));\n }\n }\n }\n return changed;\n}\n\n/** The component directories a project has, sorted. */\nexport function installedComponents(root: string): Component[] {\n const uiDir = resolveUiDir(root);\n if (!existsSync(uiDir)) {\n return [];\n }\n return readdirSync(uiDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n}\n\n/** Bare item names are checked against the index; URLs and `@scope/item` are shadcn's to resolve. */\nconst BARE_ITEM_NAME = /^[a-z0-9][a-z0-9-]*$/i;\n\n/**\n * A name the style's registry does not list would otherwise reach\n * `shadcn-svelte add`, which fails after a fetch with a message that never\n * mentions the style. Skipped when the registry cannot be read: shadcn will\n * report that itself.\n */\nasync function assertKnownRegistryItems(\n root: string,\n components: Component[],\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<void> {\n const bare = components.filter((component) => BARE_ITEM_NAME.test(component));\n if (bare.length === 0) {\n return;\n }\n let known: Set<string>;\n try {\n const index = await fetchRegistryIndex(root, { runtime });\n known = new Set(index.map((item) => item.name));\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n logger.info(`${error.message}; leaving component names to shadcn-svelte`);\n return;\n }\n const unknown = bare.filter((component) => !known.has(component));\n if (unknown.length === 0) {\n return;\n }\n const { style } = readComponentsConfig(root);\n const names = unknown.map((component) => `\"${component}\"`).join(\", \");\n throw new InvalidArgumentError(\n `Unknown component${unknown.length > 1 ? \"s\" : \"\"} ${names} for style ${style}. Run \\`vela ui list\\` to see what is available.`,\n );\n}\n\nexport async function installComponents(\n options: InstallComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<InstallComponentsResult> {\n const { root, components, overwrite = false } = options;\n const logger = getLogger(options);\n\n const requested = [...new Set(components)];\n if (requested.length === 0) {\n return { installed: [], skipped: [], packages: [] };\n }\n\n // `shadcn-svelte add` exits 1 without a `components.json`, after the custom\n // components and their packages are already in. Checked first, so a project\n // without shadcn-svelte is refused whole rather than left half-written.\n if (!existsSync(path.join(root, \"components.json\"))) {\n throw new MissingShadcnError(\n `Adding ${requested.length > 1 ? \"components\" : \"a component\"} (${requested.join(\", \")})`,\n );\n }\n\n const componentsDir = resolveUiDir(root);\n mkdirSync(componentsDir, { recursive: true });\n const isPresent = (component: string) =>\n existsSync(path.join(componentsDir, component));\n\n const skipped = overwrite ? [] : requested.filter(isPresent);\n const toInstall = requested.filter(\n (component) => !skipped.includes(component),\n );\n if (skipped.length > 0) {\n logger.info(`Already present: ${skipped.join(\", \")}`);\n }\n if (toInstall.length === 0) {\n return { installed: [], skipped, packages: [] };\n }\n\n const customToInstall = new Set(toInstall.filter(isCustomComponent));\n const publicToInstall = new Set(\n toInstall.filter((component) => !isCustomComponent(component)),\n );\n\n // Dependencies are added only when missing, even under `overwrite`:\n // re-adding `button` because `pagination` was re-added would clobber edits\n // the user never asked to lose.\n for (const component of [...customToInstall]) {\n for (const dependency of customDependencies[component] ?? []) {\n if (isPresent(dependency)) {\n continue;\n }\n if (isCustomComponent(dependency)) {\n customToInstall.add(dependency);\n } else {\n publicToInstall.add(dependency);\n }\n }\n }\n\n // `installPackages` keeps an existing @tanstack/table-core whatever its range.\n assertTableCorePackage(root, [...customToInstall]);\n\n const installed: string[] = [];\n const customList = [...customToInstall].sort();\n if (customList.length > 0) {\n logger.info(`Installing custom components: ${customList.join(\", \")}`);\n }\n for (const component of customList) {\n copyCustomComponent(component, componentsDir);\n installed.push(component);\n publicToInstall.delete(component);\n }\n\n const packages = await installPackages(\n root,\n customNpmPackagesFor(customList),\n runtime,\n logger,\n );\n\n const publicList = [...publicToInstall].sort();\n if (publicList.length > 0) {\n await assertKnownRegistryItems(root, publicList, runtime, logger);\n logger.info(\n `Installing shadcn-svelte components: ${publicList.join(\", \")}`,\n );\n // shadcn-svelte reads the tsconfig, whose `extends` an install may have pruned.\n await ensureSvelteKitSync(root, runtime, logger);\n // shadcn only records its packages; they are installed below, once any\n // pin it moved backwards is put back.\n const before = readPackageJson(root);\n await executeCommand(\n root,\n \"execute\",\n [\n \"shadcn-svelte\",\n \"add\",\n \"--yes\",\n \"--overwrite\",\n \"--no-deps-install\",\n ...publicList,\n ],\n runtime,\n );\n installed.push(...publicList);\n const after = readPackageJson(root);\n if (before && after && JSON.stringify(before) !== JSON.stringify(after)) {\n const { pkg, restored } = restoreDowngradedDependencies(\n before as DependencyBlocks,\n after as DependencyBlocks,\n );\n if (restored.length > 0) {\n logger.info(\n `Kept ${restored.join(\", \")} (shadcn-svelte asked for an older range)`,\n );\n const file = path.join(root, \"package.json\");\n const indent =\n readFileSync(file, \"utf8\").match(/^[{]\\s*\\n([\\t ]+)/)?.[1] ?? \"\\t\";\n writeFileSync(file, `${JSON.stringify(pkg, null, indent)}\\n`, \"utf8\");\n }\n const recorded = (pkg: Record<string, unknown>) =>\n new Set(\n DEPENDENCY_BLOCKS.flatMap((block) =>\n Object.keys((pkg[block] as Record<string, string>) ?? {}),\n ),\n );\n const had = recorded(before);\n const added = [...recorded(after)].filter((name) => !had.has(name));\n ensureFormsnapOverride(root, had, added, logger);\n await executeCommand(root, \"install\", [], runtime);\n }\n }\n\n const installedList = [...new Set(installed)].sort();\n await formatPaths(\n root,\n installedList.map((component) => path.join(componentsDir, component)),\n );\n\n return { installed: installedList, skipped, packages };\n}\n\nexport async function writeResult(\n result: Result,\n options: Options,\n runtime?: WriteResultRuntime,\n): Promise<Result> {\n const logger = getLogger(options);\n\n const writtenResult: Result = {\n creates: [],\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n let dropMigrationCreates: Result[\"creates\"] = [];\n if (result.collectionDrops.length > 0) {\n const { dropCollections } = await import(\"./collections\");\n dropMigrationCreates = await dropCollections(\n result.collectionDrops,\n options,\n );\n }\n\n // A package.json edit lands before the package manager runs, so the install\n // builds on it. Written after, its content (read before the install) would\n // take back every dependency the install just recorded.\n const packageJsonPath = path.resolve(options.root, \"package.json\");\n const isPackageJson = (file: Result[\"modifies\"][number]) =>\n file.status === \"success\" &&\n path.resolve(toTargetPath(options.root, file.path)) === packageJsonPath;\n for (const file of result.modifies.filter(isPackageJson)) {\n writeFile(packageJsonPath, file.content);\n }\n\n const packageInstalls = await installPackages(\n options.root,\n result.packages,\n runtime,\n logger,\n );\n\n const componentInstalls = await installComponents(\n { root: options.root, components: result.components, logger },\n runtime,\n );\n\n const packageUninstalls = await uninstallPackages(\n options.root,\n result.uninstalls ?? [],\n runtime,\n logger,\n );\n\n for (const file of [...result.creates, ...dropMigrationCreates]) {\n if (file.status !== \"success\") {\n // A modifier that could not recognise the file it was asked to edit\n // reports `failed` / `not-found` with a paste-ready remediation snippet.\n // Nothing is written, but the entry has to survive into the result: this\n // loop used to `continue` before pushing, so the entry never reached the\n // caller at all and the snippet was lost. The pattern reported success\n // and simply said nothing about the file it had given up on.\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n const target = toTargetPath(options.root, file.path);\n if (!existsSync(target)) {\n writeFile(target, file.content);\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (readFileSync(target, \"utf8\") !== file.content) {\n writeFile(target, file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n for (const file of result.modifies) {\n if (isPackageJson(file)) {\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (file.status !== \"success\") {\n // Carried through unwritten, so the caller can report the failure. See\n // the note in the creates loop above.\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n writeFile(toTargetPath(options.root, file.path), file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n\n for (const file of result.deletes) {\n if (file.status !== \"success\") {\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (existsSync(toTargetPath(options.root, file.path))) {\n removeFile(toTargetPath(options.root, file.path), options.root);\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n return {\n ...result,\n creates: writtenResult.creates,\n modifies: writtenResult.modifies,\n deletes: writtenResult.deletes,\n components: componentInstalls.installed,\n packages: [...new Set([...packageInstalls, ...componentInstalls.packages])],\n ...(packageUninstalls.length > 0 ? { uninstalls: packageUninstalls } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IA0DM+I,KAA+C;CACnD,aAAa,CAAC,OAAO;CACrB,aAAa;EAAC;EAAW;EAAW;CAAQ;CAC5C,UAAU,CAAC,UAAU,SAAS;CAC9B,OAAO,CAAC,OAAO;CACf,cAAc,CAAC;CACf,iBAAiB,CAAC,iBAAiB,QAAQ;CAC3C,kBAAkB;EAAC;EAAW;EAAW;EAAU;EAAa;CAAO;CACvE,YAAY,CAAC,UAAU,QAAQ;CAC/B,eAAe,CAAC,iBAAiB,QAAQ;CACzC,SAAS,CAAC;CACV,aAAa,CAAC,iBAAiB,QAAQ;AACzC,GAEMC,KAAuC;CAC3C,aAAa,CAACpF,CAAQ;CACtB,aAAa,CAACA,CAAQ;CACtB,UAAU,CAAC;CACX,OAAO,CAAC;CAIR,cAAc,CAACC,CAAmB;CAClC,iBAAiB,CAACA,CAAmB;CACrC,kBAAkB,CAACA,CAAmB;CACtC,YAAY,CAACA,CAAmB;CAChC,eAAe,CAAC;CAChB,SAAS,CAAC,WAAW,gBAAgB;AACvC,GAEMoF,IAAwB,uBAAA,OAAA;CAAA,uDAAAjJ;CAAA,qDAAAC;CAAA,oDAAAC;CAAA,q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