@velastack/patterns 0.1.10 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +22 -0
  2. package/dist/chunks/{collections-C1SaNdMd.js → collections-wIKcIKzY.js} +3 -3
  3. package/dist/chunks/{collections-C1SaNdMd.js.map → collections-wIKcIKzY.js.map} +1 -1
  4. package/dist/chunks/constants-PBCzh8eY.js +6 -0
  5. package/dist/chunks/constants-PBCzh8eY.js.map +1 -0
  6. package/dist/chunks/errors-D6gyegUK.js +14 -0
  7. package/dist/chunks/errors-D6gyegUK.js.map +1 -0
  8. package/dist/chunks/format-result-BdAy5M8C.js +50 -0
  9. package/dist/chunks/format-result-BdAy5M8C.js.map +1 -0
  10. package/dist/chunks/{generate-3QOmCHGZ.js → generate-vRi-W3rL.js} +2 -2
  11. package/dist/chunks/{generate-3QOmCHGZ.js.map → generate-vRi-W3rL.js.map} +1 -1
  12. package/dist/chunks/{generate.runtime-eojYS75G.js → generate.runtime-4QI3es6J.js} +2 -2
  13. package/dist/chunks/{generate.runtime-eojYS75G.js.map → generate.runtime-4QI3es6J.js.map} +1 -1
  14. package/dist/chunks/{generate.runtime-CKW5vPzA.js → generate.runtime-BX0QcpGg.js} +2 -2
  15. package/dist/chunks/{generate.runtime-CKW5vPzA.js.map → generate.runtime-BX0QcpGg.js.map} +1 -1
  16. package/dist/chunks/{generate.runtime-DnFdGn1e.js → generate.runtime-BlK7yHff.js} +2 -2
  17. package/dist/chunks/{generate.runtime-DnFdGn1e.js.map → generate.runtime-BlK7yHff.js.map} +1 -1
  18. package/dist/chunks/{generate.runtime-C2DgLTi8.js → generate.runtime-BmW0th7X.js} +2 -2
  19. package/dist/chunks/{generate.runtime-C2DgLTi8.js.map → generate.runtime-BmW0th7X.js.map} +1 -1
  20. package/dist/chunks/{generate.runtime-B08p7DoC.js → generate.runtime-C4wcEIc9.js} +3 -3
  21. package/dist/chunks/{generate.runtime-B08p7DoC.js.map → generate.runtime-C4wcEIc9.js.map} +1 -1
  22. package/dist/chunks/{generate.runtime-CWA_i6Ch.js → generate.runtime-CAzHPuHk.js} +2 -2
  23. package/dist/chunks/{generate.runtime-CWA_i6Ch.js.map → generate.runtime-CAzHPuHk.js.map} +1 -1
  24. package/dist/chunks/{generate.runtime-CK1ApRFh.js → generate.runtime-CNrtLDCf.js} +2 -2
  25. package/dist/chunks/{generate.runtime-CK1ApRFh.js.map → generate.runtime-CNrtLDCf.js.map} +1 -1
  26. package/dist/chunks/{generate.runtime-D33zutDr.js → generate.runtime-CQ0Veyk4.js} +3 -3
  27. package/dist/chunks/{generate.runtime-D33zutDr.js.map → generate.runtime-CQ0Veyk4.js.map} +1 -1
  28. package/dist/chunks/{generate.runtime-YwrRBYSg.js → generate.runtime-CQWygx-F.js} +2 -2
  29. package/dist/chunks/{generate.runtime-YwrRBYSg.js.map → generate.runtime-CQWygx-F.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-BS0FFasX.js → generate.runtime-DOBfTVW3.js} +3 -3
  31. package/dist/chunks/{generate.runtime-BS0FFasX.js.map → generate.runtime-DOBfTVW3.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-B3IKmGyV.js → generate.runtime-DpgPAnEd.js} +2 -2
  33. package/dist/chunks/{generate.runtime-B3IKmGyV.js.map → generate.runtime-DpgPAnEd.js.map} +1 -1
  34. package/dist/chunks/{pocketbase-C4NoNrnW.js → pocketbase-fERkp8b8.js} +6 -6
  35. package/dist/chunks/{pocketbase-C4NoNrnW.js.map → pocketbase-fERkp8b8.js.map} +1 -1
  36. package/dist/chunks/{shared--GUUivGs.js → shared-BZlvCHX8.js} +2 -2
  37. package/dist/chunks/{shared--GUUivGs.js.map → shared-BZlvCHX8.js.map} +1 -1
  38. package/dist/chunks/ui-DZS2SAQg.js +173 -0
  39. package/dist/chunks/ui-DZS2SAQg.js.map +1 -0
  40. package/dist/chunks/write-result-Cb3r0sCO.js +445 -0
  41. package/dist/chunks/write-result-Cb3r0sCO.js.map +1 -0
  42. package/dist/index.d.ts +161 -2
  43. package/dist/index.js +2097 -2103
  44. package/dist/index.js.map +1 -1
  45. package/package.json +3 -1
  46. package/dist/chunks/constants-qmioN-7W.js +0 -6
  47. package/dist/chunks/constants-qmioN-7W.js.map +0 -1
  48. package/dist/chunks/errors-D3Zy3wCg.js +0 -10
  49. package/dist/chunks/errors-D3Zy3wCg.js.map +0 -1
  50. package/dist/chunks/write-result-Hq8bafvV.js +0 -296
  51. package/dist/chunks/write-result-Hq8bafvV.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-YwrRBYSg.js","names":[],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-stripe-hooks.ts","../../src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/disable/subscriptions/modifies/revert-by-template.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/disable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Matches the entire cronAdd(\"stripe-subscriptions\", ...) {...}); block with\n// optional surrounding blank lines. Tolerates single- or double-quoted name\n// and trailing semicolon variants.\nconst SUBSCRIPTION_CRON_RE =\n /\\n*cronAdd\\(\\s*[\"']stripe-subscriptions[\"'][\\s\\S]*?\\}\\s*\\)\\s*;?\\s*\\n?/m;\n\nexport function unmodifyStripeHooks(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"stripe-subscriptions\")) {\n return { status: \"success\", changed: false };\n }\n const next = original.replace(SUBSCRIPTION_CRON_RE, \"\\n\");\n if (next === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst SUBSCRIPTION_CASE_VALUES = new Set([\n \"customer.subscription.created\",\n \"customer.subscription.updated\",\n \"customer.subscription.deleted\",\n]);\n\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n removeImportByModuleSpecifier(sf, \"./handlers/subscription/created\");\n removeImportByModuleSpecifier(sf, \"./handlers/subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./handlers/subscription/deleted\");\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n // Collect matching case clauses first — removing invalidates node refs.\n const toRemove = caseBlock\n .getClauses()\n .filter((clause) => {\n if (clause.getKind() !== SyntaxKind.CaseClause) return false;\n const caseClause = clause.asKindOrThrow(SyntaxKind.CaseClause);\n const expr = caseClause.getExpression();\n const literal =\n expr.asKind(SyntaxKind.StringLiteral) ??\n expr.asKind(SyntaxKind.NoSubstitutionTemplateLiteral);\n if (!literal) return false;\n return SUBSCRIPTION_CASE_VALUES.has(literal.getLiteralValue());\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n sf.formatText();\n });\n\n if (source === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const removed = file.removeAttribute(\"AppSidebar\", \"subscription\");\n if (!removed) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction updateScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const hasSub = elements.some((e) => e.getName() === \"subscription\");\n\n // Strip subscription from the props type literal (the specific type\n // added by enable-subscriptions — leave unrelated `subscription` props\n // alone).\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"))\n .filter((t) => !/^\\s*subscription\\??\\s*:/.test(t));\n lit.replaceWithText(\n propTexts.length ? `{ ${propTexts.join(\"; \")}; }` : \"{}\",\n );\n break;\n }\n }\n\n if (hasSub) {\n const remaining = elements\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n pattern.replaceWithText(`{ ${remaining.join(\", \")} }`);\n }\n }\n sf.formatText();\n });\n return out;\n}\n\nexport function unmodifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(filePath, \"utf8\");\n const hasSubPropType = /subscription\\??\\s*:\\s*\\{/.test(source);\n const hasSubProp = /\\bsubscription\\s*=\\s*null\\b/.test(source);\n\n const file = new SvelteFile(source);\n const hasNavUserSubAttr =\n file.hasElement(\"NavUser\") && file.hasAttribute(\"NavUser\", \"subscription\");\n\n if (!hasSubPropType && !hasSubProp && !hasNavUserSubAttr) {\n return { status: \"success\", changed: false };\n }\n\n if (hasSubPropType || hasSubProp) {\n file.modifyScript(updateScript);\n }\n if (hasNavUserSubAttr) {\n file.removeAttribute(\"NavUser\", \"subscription\");\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Rewrites a file to the given `template` if the current content still shows\n * the `enabledMarker` (meaning enable-subscriptions is applied). If the marker\n * is absent (already reverted or never applied), it's a no-op.\n *\n * Strips leading `// [!code highlight:N]` / `<!-- [!code highlight:N] -->`\n * lines so templates can be pulled from `preview-modifies/` directories which\n * use those for documentation highlighting.\n */\nexport function revertByTemplate(\n filePath: string,\n template: string,\n enabledMarker: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (!current.includes(enabledMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import dedent from \"dedent\";\nimport { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Baseline velastack-auth (app)/+layout.server.ts — the state of the file\n// before enable-subscriptions wrapped it with loadActiveSubscription.\nconst BASELINE =\n dedent`\n export const load = ({ locals }) => {\n \\tconst user = locals.pb.authStore.record!;\n \\tconst breadcrumbs = [{ title: 'Home', url: '/dashboard' }];\n\n \\treturn { user, breadcrumbs };\n };\n` + \"\\n\";\n\nexport function unmodifyAppLayoutServer(filePath: string): ModifyOutcome {\n return revertByTemplate(filePath, BASELINE, \"loadActiveSubscription\");\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(\n filePath: string,\n paymentsNavUserTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(filePath, paymentsNavUserTemplate, \"planLabel\");\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageServer(\n filePath: string,\n paymentsBillingPageServerTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageServerTemplate,\n \"selectPlan\",\n );\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageSvelte(\n filePath: string,\n paymentsBillingPageSvelteTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageSvelteTemplate,\n \"availablePlans\",\n );\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyStripeHooks } from \"./modifies/modify-stripe-hooks\";\nimport { unmodifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { unmodifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { unmodifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Pull the \"post-payments\" state of files that enable-subscriptions fully\n// overwrote. For the billing pages, that's exactly what enable-payments\n// writes in creates-app-mode; for nav-user it's the payments preview-modifies\n// snapshot (with highlight annotations stripped by the revert helper).\nimport paymentsNavUserTemplate from \"../../enable/payments/preview-modifies/src/lib/components/nav-user.svelte?raw\";\nimport paymentsBillingPageServerTemplate from \"../../enable/payments/creates-app-mode/src/routes/(app)/billing/+page.server.ts?raw\";\nimport paymentsBillingPageSvelteTemplate from \"../../enable/payments/creates-app-mode/src/routes/(app)/billing/+page.svelte?raw\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting data/hooks/stripe.pb.js\");\n const stripeHooksPath = path.join(\n options.root,\n \"data\",\n \"hooks\",\n \"stripe.pb.js\",\n );\n pushResult(\n modifyOutcomeToFile(stripeHooksPath, unmodifyStripeHooks(stripeHooksPath)),\n );\n\n logger.info(\"Reverting webhooks/stripe/+server.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"+server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n unmodifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyAppLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n unmodifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n navUserPath,\n unmodifyNavUser(navUserPath, paymentsNavUserTemplate),\n ),\n );\n\n logger.info(\"Reverting billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n unmodifyBillingPageServer(\n billingPageServerPath,\n paymentsBillingPageServerTemplate,\n ),\n ),\n );\n\n logger.info(\"Reverting billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n unmodifyBillingPageSvelte(\n billingPageSveltePath,\n paymentsBillingPageSvelteTemplate,\n ),\n ),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"stripe_subscriptions\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAMA,IAAM,IACJ;AAEF,SAAgB,EAAoB,GAAiC;CACnE,IAAI,CAAC,EAAG,WAAW,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAM,IAAW,EAAG,aAAa,GAAU,MAAM;CACjD,IAAI,CAAC,EAAS,SAAS,sBAAsB,GAC3C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAM,IAAO,EAAS,QAAQ,GAAsB,IAAI;CAKxD,OAJI,MAAS,IACJ;EAAE,QAAQ;EAAW,SAAS;CAAM,KAE7C,EAAG,cAAc,GAAU,GAAM,MAAM,GAChC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;;;ACfA,IAAM,oBAA2B,IAAI,IAAI;CACvC;CACA;CACA;AACF,CAAC;AAED,SAAgB,EAAsB,GAAiC;CACrE,IAAI,CAAC,EAAG,WAAW,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAM,IAAW,EAAG,aAAa,GAAU,MAAM;CACjD,IAAI,CAAC,EAAS,SAAS,2BAA2B,GAChD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,EAAE,cAAW,EAAmB,IAAW,MAAO;EAGtD,AAFA,EAA8B,GAAI,iCAAiC,GACnE,EAA8B,GAAI,iCAAiC,GACnE,EAA8B,GAAI,iCAAiC;EAEnE,IAAM,IAAa,EAChB,qBAAqB,EAAW,eAAe,CAAC,CAChD,MAAM,MA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,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4B,EAC5B,CAAC,sBAAsB,GACvB,CACF;CAWA;AACF"}
1
+ {"version":3,"file":"generate.runtime-CQWygx-F.js","names":[],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-stripe-hooks.ts","../../src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/disable/subscriptions/modifies/revert-by-template.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/disable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Matches the entire cronAdd(\"stripe-subscriptions\", ...) {...}); block with\n// optional surrounding blank lines. Tolerates single- or double-quoted name\n// and trailing semicolon variants.\nconst SUBSCRIPTION_CRON_RE =\n /\\n*cronAdd\\(\\s*[\"']stripe-subscriptions[\"'][\\s\\S]*?\\}\\s*\\)\\s*;?\\s*\\n?/m;\n\nexport function unmodifyStripeHooks(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"stripe-subscriptions\")) {\n return { status: \"success\", changed: false };\n }\n const next = original.replace(SUBSCRIPTION_CRON_RE, \"\\n\");\n if (next === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst SUBSCRIPTION_CASE_VALUES = new Set([\n \"customer.subscription.created\",\n \"customer.subscription.updated\",\n \"customer.subscription.deleted\",\n]);\n\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n removeImportByModuleSpecifier(sf, \"./handlers/subscription/created\");\n removeImportByModuleSpecifier(sf, \"./handlers/subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./handlers/subscription/deleted\");\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n // Collect matching case clauses first — removing invalidates node refs.\n const toRemove = caseBlock\n .getClauses()\n .filter((clause) => {\n if (clause.getKind() !== SyntaxKind.CaseClause) return false;\n const caseClause = clause.asKindOrThrow(SyntaxKind.CaseClause);\n const expr = caseClause.getExpression();\n const literal =\n expr.asKind(SyntaxKind.StringLiteral) ??\n expr.asKind(SyntaxKind.NoSubstitutionTemplateLiteral);\n if (!literal) return false;\n return SUBSCRIPTION_CASE_VALUES.has(literal.getLiteralValue());\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n sf.formatText();\n });\n\n if (source === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const removed = file.removeAttribute(\"AppSidebar\", \"subscription\");\n if (!removed) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction updateScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const hasSub = elements.some((e) => e.getName() === \"subscription\");\n\n // Strip subscription from the props type literal (the specific type\n // added by enable-subscriptions — leave unrelated `subscription` props\n // alone).\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"))\n .filter((t) => !/^\\s*subscription\\??\\s*:/.test(t));\n lit.replaceWithText(\n propTexts.length ? `{ ${propTexts.join(\"; \")}; }` : \"{}\",\n );\n break;\n }\n }\n\n if (hasSub) {\n const remaining = elements\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n pattern.replaceWithText(`{ ${remaining.join(\", \")} }`);\n }\n }\n sf.formatText();\n });\n return out;\n}\n\nexport function unmodifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(filePath, \"utf8\");\n const hasSubPropType = /subscription\\??\\s*:\\s*\\{/.test(source);\n const hasSubProp = /\\bsubscription\\s*=\\s*null\\b/.test(source);\n\n const file = new SvelteFile(source);\n const hasNavUserSubAttr =\n file.hasElement(\"NavUser\") && file.hasAttribute(\"NavUser\", \"subscription\");\n\n if (!hasSubPropType && !hasSubProp && !hasNavUserSubAttr) {\n return { status: \"success\", changed: false };\n }\n\n if (hasSubPropType || hasSubProp) {\n file.modifyScript(updateScript);\n }\n if (hasNavUserSubAttr) {\n file.removeAttribute(\"NavUser\", \"subscription\");\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Rewrites a file to the given `template` if the current content still shows\n * the `enabledMarker` (meaning enable-subscriptions is applied). If the marker\n * is absent (already reverted or never applied), it's a no-op.\n *\n * Strips leading `// [!code highlight:N]` / `<!-- [!code highlight:N] -->`\n * lines so templates can be pulled from `preview-modifies/` directories which\n * use those for documentation highlighting.\n */\nexport function revertByTemplate(\n filePath: string,\n template: string,\n enabledMarker: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (!current.includes(enabledMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import dedent from \"dedent\";\nimport { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Baseline velastack-auth (app)/+layout.server.ts — the state of the file\n// before enable-subscriptions wrapped it with loadActiveSubscription.\nconst BASELINE =\n dedent`\n export const load = ({ locals }) => {\n \\tconst user = locals.pb.authStore.record!;\n \\tconst breadcrumbs = [{ title: 'Home', url: '/dashboard' }];\n\n \\treturn { user, breadcrumbs };\n };\n` + \"\\n\";\n\nexport function unmodifyAppLayoutServer(filePath: string): ModifyOutcome {\n return revertByTemplate(filePath, BASELINE, \"loadActiveSubscription\");\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(\n filePath: string,\n paymentsNavUserTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(filePath, paymentsNavUserTemplate, \"planLabel\");\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageServer(\n filePath: string,\n paymentsBillingPageServerTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageServerTemplate,\n \"selectPlan\",\n );\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageSvelte(\n filePath: string,\n paymentsBillingPageSvelteTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageSvelteTemplate,\n \"availablePlans\",\n );\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyStripeHooks } from \"./modifies/modify-stripe-hooks\";\nimport { unmodifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { unmodifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { unmodifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Pull the \"post-payments\" state of files that enable-subscriptions fully\n// overwrote. For the billing pages, that's exactly what enable-payments\n// writes in creates-app-mode; for nav-user it's the payments preview-modifies\n// snapshot (with highlight annotations stripped by the revert helper).\nimport paymentsNavUserTemplate from \"../../enable/payments/preview-modifies/src/lib/components/nav-user.svelte?raw\";\nimport paymentsBillingPageServerTemplate from \"../../enable/payments/creates-app-mode/src/routes/(app)/billing/+page.server.ts?raw\";\nimport paymentsBillingPageSvelteTemplate from \"../../enable/payments/creates-app-mode/src/routes/(app)/billing/+page.svelte?raw\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting data/hooks/stripe.pb.js\");\n const stripeHooksPath = path.join(\n options.root,\n \"data\",\n \"hooks\",\n \"stripe.pb.js\",\n );\n pushResult(\n modifyOutcomeToFile(stripeHooksPath, unmodifyStripeHooks(stripeHooksPath)),\n );\n\n logger.info(\"Reverting webhooks/stripe/+server.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"+server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n unmodifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyAppLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n unmodifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n navUserPath,\n unmodifyNavUser(navUserPath, paymentsNavUserTemplate),\n ),\n );\n\n logger.info(\"Reverting billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n unmodifyBillingPageServer(\n billingPageServerPath,\n paymentsBillingPageServerTemplate,\n ),\n ),\n );\n\n logger.info(\"Reverting billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n unmodifyBillingPageSvelte(\n billingPageSveltePath,\n paymentsBillingPageSvelteTemplate,\n ),\n ),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"stripe_subscriptions\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\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K,mCAAmC;CAC/C,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAQA,AAPA,EACE,EACE,GACA,EAAwB,CAAmB,CAC7C,CACF,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPA,EACE,EACE,GACA,EAAwB,CAAmB,CAC7C,CACF,GAEA,EAAO,KAAK,8BAA8B;CAC1C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJA,EACE,EAAoB,GAAgB,EAAmB,CAAc,CAAC,CACxE,GAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAQA,AAPA,EACE,EACE,GACA,EAAgB,GAAa,CAAuB,CACtD,CACF,GAEA,EAAO,KAAK,mCAAmC;CAC/C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVA,EACE,EACE,GACA,EACE,GACA,CACF,CACF,CACF,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAgBA,OAfA,EACE,EACE,GACA,EACE,GACA,CACF,CACF,CACF,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4B,EAC5B,CAAC,sBAAsB,GACvB,CACF;CAWA;AACF"}
@@ -4,8 +4,8 @@ import { n } from "./logger-CQONztPm.js";
4
4
  import { t as r } from "./pocketbase-C5GS-Dh5.js";
5
5
  import { modifyOutcomeToFile as i } from "./modify-file-PVKmDJHk.js";
6
6
  import { a, n as o, o as s, t as c } from "./ts-morph-helpers-Bk82Z2n7.js";
7
- import { getMigrationFile as l, migrationDelay as u, withPocketbase as d } from "./pocketbase-C4NoNrnW.js";
8
- import { applyCollectionRulePatches as f, createCollectionIdempotent as p } from "./collections-C1SaNdMd.js";
7
+ import { getMigrationFile as l, migrationDelay as u, withPocketbase as d } from "./pocketbase-fERkp8b8.js";
8
+ import { applyCollectionRulePatches as f, createCollectionIdempotent as p } from "./collections-wIKcIKzY.js";
9
9
  import m from "node:path";
10
10
  import h from "node:fs";
11
11
  import { Project as g, SyntaxKind as _ } from "ts-morph";
@@ -616,4 +616,4 @@ async function P(e) {
616
616
  //#endregion
617
617
  export { P as generate };
618
618
 
619
- //# sourceMappingURL=generate.runtime-BS0FFasX.js.map
619
+ //# sourceMappingURL=generate.runtime-DOBfTVW3.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-BS0FFasX.js","names":[],"sources":["../../src/patterns/enable/teams/modifies/modify-app-layout.ts","../../src/patterns/enable/teams/modifies/modify-app-sidebar.ts","../../src/patterns/enable/teams/modifies/+layout.server.ts","../../src/patterns/enable/teams/modifies/modify-nav-user.ts","../../src/patterns/enable/teams/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass team props to <AppSidebar> in your app layout:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app layout that renders <AppSidebar> with team props:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"teams\")) {\n return { status: \"success\", changed: false };\n }\n\n file.appendToAttributes(\n \"AppSidebar\",\n \" team={data.team} teams={data.teams ?? []}\",\n );\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEW_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<TeamSwitcher {teams}>\n\t\t\t\t{#snippet children()}\n\t\t\t\t\t{@const activeTeam = teams.find((t) => t.id === team)}\n\t\t\t\t\t{#if activeTeam}\n\t\t\t\t\t\t<Avatar.Root class=\"size-8 rounded-lg\">\n\t\t\t\t\t\t\t<Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{:else}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<img src={favicon} alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{meta.appName}</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t\t<ChevronsUpDownIcon class=\"ml-auto\" />\n\t\t\t\t{/snippet}\n\t\t\t</TeamSwitcher>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\nconst IMPORT_SNIPPET = [\n \"import favicon from '$lib/assets/favicon.svg';\",\n \"import TeamSwitcher from '$lib/components/team-switcher.svelte';\",\n \"import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\",\n \"import * as Avatar from '$lib/components/ui/avatar';\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Replace the <Sidebar.Header> in your app sidebar with the team switcher.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Props to destructure in $props(): team, teams = []\",\n \"\",\n \"Markup to use as the header:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app sidebar with a <Sidebar.Header> containing the team switcher.\",\n \"\",\n \"Imports:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Header markup:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nfunction updateAppSidebarScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"favicon\",\n moduleSpecifier: \"$lib/assets/favicon.svg\",\n },\n {\n defaultImport: \"TeamSwitcher\",\n moduleSpecifier: \"$lib/components/team-switcher.svelte\",\n },\n {\n defaultImport: \"ChevronsUpDownIcon\",\n moduleSpecifier: \"@lucide/svelte/icons/chevrons-up-down\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\n },\n ]);\n\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n\n if (elements.some((e) => e.getName() === \"team\")) continue;\n\n // Type changes first — name change can shift positions and invalidate type node refs.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^team\\b/.test(t))) break;\n propTexts.push(\n \"team?: string | undefined\",\n \"teams?: { id: string; name: string }[]\",\n );\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Rebuild binding pattern: insert team, teams = [] before first rest/initializer element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elements.length;\n elementTexts.splice(insertIdx, 0, \"team\", \"teams = []\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n }\n sf.formatText();\n });\n return out;\n}\n\nexport function modifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasElement(\"Sidebar.Header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript(updateAppSidebarScript);\n file.replaceElement(\"Sidebar.Header\", NEW_HEADER);\n file.writeTo(appSidebarPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n const team = locals.team;\n const teams = await locals.pb.collection(\"teams\").getFullList();\n depends(\"app:team\");\n\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n return { user, team, teams, breadcrumbs };\n };\n `;\n\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n const hasProperty = !!obj.getProperty(name);\n if (!hasProperty) {\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n \"const user = locals.pb.authStore.record!;\",\n \"const team = locals.team;\",\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n 'depends(\"app:team\");',\n \"\",\n 'const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];',\n \"return { user, team, teams, breadcrumbs };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasDepends = obp\n .getElements()\n .some((el) => el.getName() === \"depends\");\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n\n if (!hasDepends) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n\n if (hasLocals) {\n first.set({\n name: `{ depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) {\n loadArrow.setIsAsync(true);\n } else if (loadFn && !loadFn.isAsync()) {\n loadFn.setIsAsync(true);\n }\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const hasTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id: import(\"ts-morph\").Identifier) => id.getText() === \"team\"),\n );\n\n const hasTeams = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id: import(\"ts-morph\").Identifier) => id.getText() === \"teams\",\n ),\n );\n\n const hasDependsTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((ce: import(\"ts-morph\").CallExpression) => {\n const expr = ce.getExpression();\n if (expr.getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:team'\" || argText === '\"app:team\"')\n );\n }),\n );\n\n if (!hasTeam) {\n blockBody.insertStatements(1, \"const team = locals.team;\");\n }\n\n if (!hasTeams) {\n blockBody.insertStatements(\n 2,\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n );\n }\n\n if (!hasDependsTeam) {\n blockBody.insertStatements(3, 'depends(\"app:team\");');\n }\n }\n\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n } else {\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = bodyExpr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) {\n const returns = fnBody.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst TEAMS_NAV_SNIPPET = [\n \"import UsersIcon from '@lucide/svelte/icons/users';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Teams', url: '/teams', icon: UsersIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Teams nav item to nav-user.svelte:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Teams entry:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/teams\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Teams\",\n \"/teams\",\n \"UsersIcon\",\n \"@lucide/svelte/icons/users\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { TEAM_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n // Wait so the next schema op lands in a different PocketBase timestamp second.\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) {\n return;\n }\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating teams collection\");\n const teamsResult = await create({\n name: \"teams\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"name\",\n type: \"text\",\n required: true,\n },\n {\n name: \"owner\",\n type: \"relation\",\n cascadeDelete: false,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n });\n const teamsCollection = teamsResult.collection;\n await pushMigrationCreates(creates, \"teams\", options, teamsResult.created);\n\n logger.info(\"Creating team_memberships collection\");\n const teamMembershipsResult = await create({\n name: \"team_memberships\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"user\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const teamMembershipsCollection = teamMembershipsResult.collection;\n await pushMigrationCreates(\n creates,\n \"team_memberships\",\n options,\n teamMembershipsResult.created,\n );\n\n logger.info(\"Creating team_users view\");\n const teamUsersResult = await create({\n name: \"team_users\",\n type: \"view\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"email\",\n exceptDomains: null,\n onlyDomains: null,\n required: true,\n type: \"email\",\n },\n {\n name: \"name\",\n max: 255,\n required: false,\n type: \"text\",\n },\n {\n name: \"membership_id\",\n cascadeDelete: false,\n collectionId: teamMembershipsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: false,\n type: \"relation\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n ],\n viewQuery:\n \"select users.id, users.email, users.name, team_memberships.id as membership_id, team_memberships.team, team_memberships.role from users join team_memberships on team_memberships.user = users.id;\",\n });\n await pushMigrationCreates(\n creates,\n \"team_users\",\n options,\n teamUsersResult.created,\n );\n\n logger.info(\"Creating team_invites collection\");\n const teamInvitesResult = await create({\n name: \"team_invites\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"team\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"email\",\n type: \"email\",\n required: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invites\",\n options,\n teamInvitesResult.created,\n );\n\n logger.info(\"Creating team_invite_links collection\");\n const teamInviteLinksResult = await create({\n name: \"team_invite_links\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n indexes: [\n \"CREATE UNIQUE INDEX `idx_9y3Oz1KVzz` ON `team_invite_links` (`team`)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invite_links\",\n options,\n teamInviteLinksResult.created,\n );\n\n logger.info(\"Applying team rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n TEAM_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerPath, modifyLayoutServer(layoutServerPath)),\n );\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Modifying app-sidebar\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mapp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ACA,oBACF;CAKA,AAJA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,OAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEhE;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-DOBfTVW3.js","names":[],"sources":["../../src/patterns/enable/teams/modifies/modify-app-layout.ts","../../src/patterns/enable/teams/modifies/modify-app-sidebar.ts","../../src/patterns/enable/teams/modifies/+layout.server.ts","../../src/patterns/enable/teams/modifies/modify-nav-user.ts","../../src/patterns/enable/teams/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass team props to <AppSidebar> in your app layout:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app layout that renders <AppSidebar> with team props:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"teams\")) {\n return { status: \"success\", changed: false };\n }\n\n file.appendToAttributes(\n \"AppSidebar\",\n \" team={data.team} teams={data.teams ?? []}\",\n );\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEW_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<TeamSwitcher {teams}>\n\t\t\t\t{#snippet children()}\n\t\t\t\t\t{@const activeTeam = teams.find((t) => t.id === team)}\n\t\t\t\t\t{#if activeTeam}\n\t\t\t\t\t\t<Avatar.Root class=\"size-8 rounded-lg\">\n\t\t\t\t\t\t\t<Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{:else}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<img src={favicon} alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{meta.appName}</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t\t<ChevronsUpDownIcon class=\"ml-auto\" />\n\t\t\t\t{/snippet}\n\t\t\t</TeamSwitcher>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\nconst IMPORT_SNIPPET = [\n \"import favicon from '$lib/assets/favicon.svg';\",\n \"import TeamSwitcher from '$lib/components/team-switcher.svelte';\",\n \"import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\",\n \"import * as Avatar from '$lib/components/ui/avatar';\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Replace the <Sidebar.Header> in your app sidebar with the team switcher.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Props to destructure in $props(): team, teams = []\",\n \"\",\n \"Markup to use as the header:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app sidebar with a <Sidebar.Header> containing the team switcher.\",\n \"\",\n \"Imports:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Header markup:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nfunction updateAppSidebarScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"favicon\",\n moduleSpecifier: \"$lib/assets/favicon.svg\",\n },\n {\n defaultImport: \"TeamSwitcher\",\n moduleSpecifier: \"$lib/components/team-switcher.svelte\",\n },\n {\n defaultImport: \"ChevronsUpDownIcon\",\n moduleSpecifier: \"@lucide/svelte/icons/chevrons-up-down\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\n },\n ]);\n\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n\n if (elements.some((e) => e.getName() === \"team\")) continue;\n\n // Type changes first — name change can shift positions and invalidate type node refs.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^team\\b/.test(t))) break;\n propTexts.push(\n \"team?: string | undefined\",\n \"teams?: { id: string; name: string }[]\",\n );\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Rebuild binding pattern: insert team, teams = [] before first rest/initializer element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elements.length;\n elementTexts.splice(insertIdx, 0, \"team\", \"teams = []\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n }\n sf.formatText();\n });\n return out;\n}\n\nexport function modifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasElement(\"Sidebar.Header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript(updateAppSidebarScript);\n file.replaceElement(\"Sidebar.Header\", NEW_HEADER);\n file.writeTo(appSidebarPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n const team = locals.team;\n const teams = await locals.pb.collection(\"teams\").getFullList();\n depends(\"app:team\");\n\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n return { user, team, teams, breadcrumbs };\n };\n `;\n\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n const hasProperty = !!obj.getProperty(name);\n if (!hasProperty) {\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n \"const user = locals.pb.authStore.record!;\",\n \"const team = locals.team;\",\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n 'depends(\"app:team\");',\n \"\",\n 'const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];',\n \"return { user, team, teams, breadcrumbs };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasDepends = obp\n .getElements()\n .some((el) => el.getName() === \"depends\");\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n\n if (!hasDepends) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n\n if (hasLocals) {\n first.set({\n name: `{ depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) {\n loadArrow.setIsAsync(true);\n } else if (loadFn && !loadFn.isAsync()) {\n loadFn.setIsAsync(true);\n }\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const hasTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id: import(\"ts-morph\").Identifier) => id.getText() === \"team\"),\n );\n\n const hasTeams = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id: import(\"ts-morph\").Identifier) => id.getText() === \"teams\",\n ),\n );\n\n const hasDependsTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((ce: import(\"ts-morph\").CallExpression) => {\n const expr = ce.getExpression();\n if (expr.getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:team'\" || argText === '\"app:team\"')\n );\n }),\n );\n\n if (!hasTeam) {\n blockBody.insertStatements(1, \"const team = locals.team;\");\n }\n\n if (!hasTeams) {\n blockBody.insertStatements(\n 2,\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n );\n }\n\n if (!hasDependsTeam) {\n blockBody.insertStatements(3, 'depends(\"app:team\");');\n }\n }\n\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n } else {\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = bodyExpr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) {\n const returns = fnBody.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst TEAMS_NAV_SNIPPET = [\n \"import UsersIcon from '@lucide/svelte/icons/users';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Teams', url: '/teams', icon: UsersIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Teams nav item to nav-user.svelte:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Teams entry:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/teams\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Teams\",\n \"/teams\",\n \"UsersIcon\",\n \"@lucide/svelte/icons/users\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { TEAM_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n // Wait so the next schema op lands in a different PocketBase timestamp second.\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) {\n return;\n }\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating teams collection\");\n const teamsResult = await create({\n name: \"teams\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"name\",\n type: \"text\",\n required: true,\n },\n {\n name: \"owner\",\n type: \"relation\",\n cascadeDelete: false,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n });\n const teamsCollection = teamsResult.collection;\n await pushMigrationCreates(creates, \"teams\", options, teamsResult.created);\n\n logger.info(\"Creating team_memberships collection\");\n const teamMembershipsResult = await create({\n name: \"team_memberships\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"user\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const teamMembershipsCollection = teamMembershipsResult.collection;\n await pushMigrationCreates(\n creates,\n \"team_memberships\",\n options,\n teamMembershipsResult.created,\n );\n\n logger.info(\"Creating team_users view\");\n const teamUsersResult = await create({\n name: \"team_users\",\n type: \"view\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"email\",\n exceptDomains: null,\n onlyDomains: null,\n required: true,\n type: \"email\",\n },\n {\n name: \"name\",\n max: 255,\n required: false,\n type: \"text\",\n },\n {\n name: \"membership_id\",\n cascadeDelete: false,\n collectionId: teamMembershipsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: false,\n type: \"relation\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n ],\n viewQuery:\n \"select users.id, users.email, users.name, team_memberships.id as membership_id, team_memberships.team, team_memberships.role from users join team_memberships on team_memberships.user = users.id;\",\n });\n await pushMigrationCreates(\n creates,\n \"team_users\",\n options,\n teamUsersResult.created,\n );\n\n logger.info(\"Creating team_invites collection\");\n const teamInvitesResult = await create({\n name: \"team_invites\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"team\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"email\",\n type: \"email\",\n required: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invites\",\n options,\n teamInvitesResult.created,\n );\n\n logger.info(\"Creating team_invite_links collection\");\n const teamInviteLinksResult = await create({\n name: \"team_invite_links\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n indexes: [\n \"CREATE UNIQUE INDEX `idx_9y3Oz1KVzz` ON `team_invite_links` (`team`)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invite_links\",\n options,\n teamInviteLinksResult.created,\n );\n\n logger.info(\"Applying team rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n TEAM_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerPath, modifyLayoutServer(layoutServerPath)),\n );\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Modifying app-sidebar\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAIA,IAAM,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;A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,OACA,cACA,iBACF;CAGA,OAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEhE;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
- import { n } from "./generate-3QOmCHGZ.js";
3
+ import { n } from "./generate-vRi-W3rL.js";
4
4
  import { modifyOutcomeToFile as r } from "./modify-file-PVKmDJHk.js";
5
5
  import { a as i, n as a, o } from "./ts-morph-helpers-Bk82Z2n7.js";
6
6
  import { a as s, t as c } from "./config-target-DOi8kI_f.js";
@@ -399,4 +399,4 @@ async function q(e) {
399
399
  //#endregion
400
400
  export { q as generate, W as keepMissing };
401
401
 
402
- //# sourceMappingURL=generate.runtime-B3IKmGyV.js.map
402
+ //# sourceMappingURL=generate.runtime-DpgPAnEd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-B3IKmGyV.js","names":[],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/load-function.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n sourceFile.formatText();\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type Block,\n type FunctionDeclaration,\n type FunctionExpression,\n type ObjectLiteralExpression,\n type ParameterDeclaration,\n type ReturnStatement,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * What the two layout modifiers have in common: finding a SvelteKit `load`,\n * working out how it receives its event, and locating the object it returns.\n */\n\nexport type LoadFunction =\n ArrowFunction | FunctionExpression | FunctionDeclaration;\n\nexport function newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\nexport function ensureNamedImports(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n names: string[],\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({ namedImports: names, moduleSpecifier });\n return;\n }\n for (const name of names) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n }\n}\n\nexport function ensureImportSpec(sourceFile: SourceFile, spec: ImportSpec) {\n if (spec.namedImports?.length) {\n ensureNamedImports(sourceFile, spec.moduleSpecifier, spec.namedImports);\n }\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({\n moduleSpecifier: spec.moduleSpecifier,\n defaultImport: spec.defaultImport,\n namespaceImport: spec.namespaceImport,\n });\n}\n\n/** Peel wrappers (`loadFlash(fn)`, `(fn)`, `fn satisfies X`) down to the function. */\nfunction unwrapFunction(node: Node): ArrowFunction | FunctionExpression | null {\n if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) {\n return node;\n }\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node)\n ) {\n return unwrapFunction(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n for (const arg of node.getArguments()) {\n const fn = unwrapFunction(arg);\n if (fn) return fn;\n }\n }\n return null;\n}\n\n/** The exported `load`, whether declared as a function or wrapped in a const. */\nexport function findLoadFunction(sourceFile: SourceFile): LoadFunction | null {\n const declaration = sourceFile.getFunction(\"load\");\n if (declaration) {\n return declaration.isExported() ? declaration : null;\n }\n\n const variable = sourceFile.getVariableDeclaration(\"load\");\n if (!variable) return null;\n if (!variable.getVariableStatement()?.isExported()) return null;\n\n const initializer = variable.getInitializer();\n return initializer ? unwrapFunction(initializer) : null;\n}\n\nfunction isFunctionNode(node: Node): boolean {\n return (\n Node.isArrowFunction(node) ||\n Node.isFunctionExpression(node) ||\n Node.isFunctionDeclaration(node) ||\n Node.isMethodDeclaration(node)\n );\n}\n\n/**\n * The single, final `return <expression>` of the load body, or null when the\n * body has early returns — those would need any insertion hoisted above them,\n * and guessing where is worse than refusing.\n */\nexport function findFinalReturn(\n fn: LoadFunction,\n body: Block,\n): ReturnStatement | null {\n const statements = body.getStatements();\n const last = statements[statements.length - 1];\n if (!last || !Node.isReturnStatement(last)) return null;\n\n const returns = body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .filter((r) => r.getFirstAncestor(isFunctionNode) === fn);\n if (returns.length !== 1) return null;\n\n return last;\n}\n\n/** The object literal a return statement yields, unwrapping parentheses. */\nexport function returnedObject(\n statement: ReturnStatement,\n): ObjectLiteralExpression | null {\n let expression = statement.getExpression();\n while (expression && Node.isParenthesizedExpression(expression)) {\n expression = expression.getExpression();\n }\n if (!expression || !Node.isObjectLiteralExpression(expression)) return null;\n return expression;\n}\n\nexport function hasProperty(\n object: ObjectLiteralExpression,\n name: string,\n): boolean {\n return object.getProperties().some((property) => {\n if (\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ) {\n return property.getName() === name;\n }\n return false;\n });\n}\n\nexport function hasSpreadOf(\n object: ObjectLiteralExpression,\n expressionText: string,\n): boolean {\n return object\n .getProperties()\n .some(\n (property) =>\n Node.isSpreadAssignment(property) &&\n property.getExpression().getText() === expressionText,\n );\n}\n\n/** How a load receives its event: not at all, by name, or destructured. */\nexport type EventParameter =\n | { kind: \"none\" }\n | { kind: \"identifier\"; name: string; param: ParameterDeclaration }\n | {\n kind: \"binding\";\n pattern: import(\"ts-morph\").ObjectBindingPattern;\n param: ParameterDeclaration;\n }\n | { kind: \"unsupported\" };\n\nexport function inspectEventParameter(fn: LoadFunction): EventParameter {\n const params = fn.getParameters();\n if (params.length === 0) return { kind: \"none\" };\n if (params.length > 1) return { kind: \"unsupported\" };\n\n const param = params[0];\n if (param.getInitializer() || param.isRestParameter()) {\n return { kind: \"unsupported\" };\n }\n const nameNode = param.getNameNode();\n if (Node.isIdentifier(nameNode)) {\n return { kind: \"identifier\", name: nameNode.getText(), param };\n }\n if (Node.isObjectBindingPattern(nameNode)) {\n return { kind: \"binding\", pattern: nameNode, param };\n }\n return { kind: \"unsupported\" };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/** A wuchale site: the locale enable-i18n's reroute already resolved from the URL. */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"$locales/main.url\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '$lib/cms';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n const returnIndex = body.getStatements().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"$lib/cms\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/** Mounts `<AdminBar />` at the top level of the root layout. */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n file.appendMarkup(MARKUP_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\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 for these files would mean a re-run silently\n * resetting a developer's edits to `$lib/cms.ts` or the backend config. The\n * wiring is theirs once it has been written; a re-run only fills in what is\n * missing.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const locale = i18n ? WUCHALE_LOCALE : DEFAULT_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAS,EAAY,GAAsB;CACzC,OAAO,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgB,EACd,GACA,IAAa,IACE;CACf,IAAM,IA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
1
+ {"version":3,"file":"generate.runtime-DpgPAnEd.js","names":[],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/load-function.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n sourceFile.formatText();\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type Block,\n type FunctionDeclaration,\n type FunctionExpression,\n type ObjectLiteralExpression,\n type ParameterDeclaration,\n type ReturnStatement,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * What the two layout modifiers have in common: finding a SvelteKit `load`,\n * working out how it receives its event, and locating the object it returns.\n */\n\nexport type LoadFunction =\n ArrowFunction | FunctionExpression | FunctionDeclaration;\n\nexport function newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\nexport function ensureNamedImports(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n names: string[],\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({ namedImports: names, moduleSpecifier });\n return;\n }\n for (const name of names) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n }\n}\n\nexport function ensureImportSpec(sourceFile: SourceFile, spec: ImportSpec) {\n if (spec.namedImports?.length) {\n ensureNamedImports(sourceFile, spec.moduleSpecifier, spec.namedImports);\n }\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({\n moduleSpecifier: spec.moduleSpecifier,\n defaultImport: spec.defaultImport,\n namespaceImport: spec.namespaceImport,\n });\n}\n\n/** Peel wrappers (`loadFlash(fn)`, `(fn)`, `fn satisfies X`) down to the function. */\nfunction unwrapFunction(node: Node): ArrowFunction | FunctionExpression | null {\n if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) {\n return node;\n }\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node)\n ) {\n return unwrapFunction(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n for (const arg of node.getArguments()) {\n const fn = unwrapFunction(arg);\n if (fn) return fn;\n }\n }\n return null;\n}\n\n/** The exported `load`, whether declared as a function or wrapped in a const. */\nexport function findLoadFunction(sourceFile: SourceFile): LoadFunction | null {\n const declaration = sourceFile.getFunction(\"load\");\n if (declaration) {\n return declaration.isExported() ? declaration : null;\n }\n\n const variable = sourceFile.getVariableDeclaration(\"load\");\n if (!variable) return null;\n if (!variable.getVariableStatement()?.isExported()) return null;\n\n const initializer = variable.getInitializer();\n return initializer ? unwrapFunction(initializer) : null;\n}\n\nfunction isFunctionNode(node: Node): boolean {\n return (\n Node.isArrowFunction(node) ||\n Node.isFunctionExpression(node) ||\n Node.isFunctionDeclaration(node) ||\n Node.isMethodDeclaration(node)\n );\n}\n\n/**\n * The single, final `return <expression>` of the load body, or null when the\n * body has early returns — those would need any insertion hoisted above them,\n * and guessing where is worse than refusing.\n */\nexport function findFinalReturn(\n fn: LoadFunction,\n body: Block,\n): ReturnStatement | null {\n const statements = body.getStatements();\n const last = statements[statements.length - 1];\n if (!last || !Node.isReturnStatement(last)) return null;\n\n const returns = body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .filter((r) => r.getFirstAncestor(isFunctionNode) === fn);\n if (returns.length !== 1) return null;\n\n return last;\n}\n\n/** The object literal a return statement yields, unwrapping parentheses. */\nexport function returnedObject(\n statement: ReturnStatement,\n): ObjectLiteralExpression | null {\n let expression = statement.getExpression();\n while (expression && Node.isParenthesizedExpression(expression)) {\n expression = expression.getExpression();\n }\n if (!expression || !Node.isObjectLiteralExpression(expression)) return null;\n return expression;\n}\n\nexport function hasProperty(\n object: ObjectLiteralExpression,\n name: string,\n): boolean {\n return object.getProperties().some((property) => {\n if (\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ) {\n return property.getName() === name;\n }\n return false;\n });\n}\n\nexport function hasSpreadOf(\n object: ObjectLiteralExpression,\n expressionText: string,\n): boolean {\n return object\n .getProperties()\n .some(\n (property) =>\n Node.isSpreadAssignment(property) &&\n property.getExpression().getText() === expressionText,\n );\n}\n\n/** How a load receives its event: not at all, by name, or destructured. */\nexport type EventParameter =\n | { kind: \"none\" }\n | { kind: \"identifier\"; name: string; param: ParameterDeclaration }\n | {\n kind: \"binding\";\n pattern: import(\"ts-morph\").ObjectBindingPattern;\n param: ParameterDeclaration;\n }\n | { kind: \"unsupported\" };\n\nexport function inspectEventParameter(fn: LoadFunction): EventParameter {\n const params = fn.getParameters();\n if (params.length === 0) return { kind: \"none\" };\n if (params.length > 1) return { kind: \"unsupported\" };\n\n const param = params[0];\n if (param.getInitializer() || param.isRestParameter()) {\n return { kind: \"unsupported\" };\n }\n const nameNode = param.getNameNode();\n if (Node.isIdentifier(nameNode)) {\n return { kind: \"identifier\", name: nameNode.getText(), param };\n }\n if (Node.isObjectBindingPattern(nameNode)) {\n return { kind: \"binding\", pattern: nameNode, param };\n }\n return { kind: \"unsupported\" };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/** A wuchale site: the locale enable-i18n's reroute already resolved from the URL. */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"$locales/main.url\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '$lib/cms';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n const returnIndex = body.getStatements().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"$lib/cms\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/** Mounts `<AdminBar />` at the top level of the root layout. */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n file.appendMarkup(MARKUP_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\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 for these files would mean a re-run silently\n * resetting a developer's edits to `$lib/cms.ts` or the backend config. The\n * wiring is theirs once it has been written; a re-run only fills in what is\n * missing.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const locale = i18n ? WUCHALE_LOCALE : DEFAULT_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAS,EAAY,GAAsB;CACzC,OAAO,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgB,EACd,GACA,IAAa,IACE;CACf,IAAM,IAAO,OAAO,EAAW;CAC/B,IAAI,CAAC,EAAG,WAAW,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAOxD,IAAM,IAAa,IAJC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoB,CAAc,GAEzD,IAAU,IACV,IAAS;CAMb,AAJkB,EACf,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAE1C,MACH,EAAW,wBAAwB,GAAG;EACpC,cAAc,CAAC,KAAK;EACpB,iBAAiB;CACnB,CAAC,GACD,IAAU;CAOZ,IAAM,IAJmB,EACtB,qBAAqB,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,cAE/B,CAAA,EAAkB,aAAa,CAAC,GAAG,IAC/C,IACJ,GAAW,QAAQ,MAAM,EAAW,0BAC/B,IACD;CAEN,IAAI,CAAC,GACH,IAAS;MACJ;EACL,I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D,IAAM,IAAmB,EAAK,KAC5B,EAAQ,MACR,OACA,UACA,mBACF;CAWA,AATA,EACE,EACE,GACA,EAAmB,GAJR,IAAO,IAAiB,CAIQ,CAC7C,CACF,GAIA,EAAO,KAAK,iCAAiC;CAC7C,IAAM,IAAsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,YACF;CAQA,AAPA,EACE,EACE,GACA,EAAsB,CAAmB,CAC3C,CACF,GAEA,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAmB,EAAK,KAC5B,EAAQ,MACR,OACA,UACA,gBACF;CAKA,OAJA,EACE,EAAoB,GAAkB,EAAmB,CAAgB,CAAC,CAC5E,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,4 +1,4 @@
1
- import { n as e, r as t } from "./constants-qmioN-7W.js";
1
+ import { i as e, n as t } from "./constants-PBCzh8eY.js";
2
2
  import n from "node:path";
3
3
  import { existsSync as r, readFileSync as i, readdirSync as a } from "node:fs";
4
4
  import o from "pocketbase";
@@ -53,9 +53,9 @@ var m = 1100;
53
53
  function h() {
54
54
  return new Promise((e) => setTimeout(e, m));
55
55
  }
56
- function g(e, r, i) {
57
- let o = `${r}_${e}.js`, s = a(n.join(i.root, t)).filter((e) => e.endsWith(o)).sort().pop();
58
- if (s) return n.join(i.root, t, s);
56
+ function g(t, r, i) {
57
+ let o = `${r}_${t}.js`, s = a(n.join(i.root, e)).filter((e) => e.endsWith(o)).sort().pop();
58
+ if (s) return n.join(i.root, e, s);
59
59
  }
60
60
  function _(e) {
61
61
  let t = n.join(e, "node_modules", ".vite", "_pocketbase_metadata.json");
@@ -72,7 +72,7 @@ async function v(e, t, n) {
72
72
  if (!r) throw Error("Failed to authenticate with PocketBase. Check your superuser credentials.");
73
73
  }
74
74
  async function y(i, a) {
75
- let u = n.join(i, e), m = n.join(i, t), h = "localhost";
75
+ let u = n.join(i, t), m = n.join(i, e), h = "localhost";
76
76
  if (!r(u)) throw Error("PocketBase data directory does not exist");
77
77
  let g = _(i);
78
78
  if (g && g.pocketbaseUrl) {
@@ -120,4 +120,4 @@ function b(e, t) {
120
120
  //#endregion
121
121
  export { g as getMigrationFile, h as migrationDelay, y as withPocketbase };
122
122
 
123
- //# sourceMappingURL=pocketbase-C4NoNrnW.js.map
123
+ //# sourceMappingURL=pocketbase-fERkp8b8.js.map