@velastack/patterns 0.0.58 → 0.0.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -12
- package/dist/chunks/{_server-Cv3bTkG0.js → _server-Cie287JZ.js} +1 -1
- package/dist/chunks/_server-Cie287JZ.js.map +1 -0
- package/dist/chunks/{collections-CkCADMyb.js → collections-DZOoJLVj.js} +5 -5
- package/dist/chunks/{collections-CkCADMyb.js.map → collections-DZOoJLVj.js.map} +1 -1
- package/dist/chunks/{config-target-C1u-fbTo.js → config-target-Co-ij8p3.js} +1 -1
- package/dist/chunks/{config-target-C1u-fbTo.js.map → config-target-Co-ij8p3.js.map} +1 -1
- package/dist/chunks/{constants-BMZmCRiI.js → constants-qmioN-7W.js} +1 -1
- package/dist/chunks/{constants-BMZmCRiI.js.map → constants-qmioN-7W.js.map} +1 -1
- package/dist/chunks/{dedent-C4qKBQXh.js → dedent-Gq6Krl4n.js} +1 -1
- package/dist/chunks/{dedent-C4qKBQXh.js.map → dedent-Gq6Krl4n.js.map} +1 -1
- package/dist/chunks/{env-BqHJ-kSa.js → env-BPfk1VAw.js} +1 -1
- package/dist/chunks/{env-BqHJ-kSa.js.map → env-BPfk1VAw.js.map} +1 -1
- package/dist/chunks/{env.preview-DoY1CJwL.js → env.preview-uMRKT5Pc.js} +1 -1
- package/dist/chunks/{env.preview-DoY1CJwL.js.map → env.preview-uMRKT5Pc.js.map} +1 -1
- package/dist/chunks/{env.runtime-D46GCIKe.js → env.runtime-BVage9Kk.js} +1 -1
- package/dist/chunks/{env.runtime-D46GCIKe.js.map → env.runtime-BVage9Kk.js.map} +1 -1
- package/dist/chunks/{errors-Co77I4oK.js → errors-D3Zy3wCg.js} +1 -1
- package/dist/chunks/{errors-Co77I4oK.js.map → errors-D3Zy3wCg.js.map} +1 -1
- package/dist/chunks/{generate2.runtime-DLe5zNsJ.js → generate.runtime-6TJoTPg9.js} +21 -15
- package/dist/chunks/generate.runtime-6TJoTPg9.js.map +1 -0
- package/dist/chunks/{generate.runtime-BWDfruiV.js → generate.runtime-6qpoLA04.js} +10 -8
- package/dist/chunks/{generate.runtime-BWDfruiV.js.map → generate.runtime-6qpoLA04.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CUR-kles.js → generate.runtime-AmiNbSR3.js} +10 -10
- package/dist/chunks/{generate.runtime-CUR-kles.js.map → generate.runtime-AmiNbSR3.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C22xL49X.js → generate.runtime-BT_bwAtt.js} +7 -7
- package/dist/chunks/{generate.runtime-C22xL49X.js.map → generate.runtime-BT_bwAtt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BlW1FmJq.js → generate.runtime-BnnsaLsg.js} +5 -5
- package/dist/chunks/{generate.runtime-BlW1FmJq.js.map → generate.runtime-BnnsaLsg.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CYp6zwqL.js → generate.runtime-CGtKTfYU.js} +4 -4
- package/dist/chunks/{generate.runtime-CYp6zwqL.js.map → generate.runtime-CGtKTfYU.js.map} +1 -1
- package/dist/chunks/{generate.runtime-cLVzf30y.js → generate.runtime-CINxHRnJ.js} +5 -5
- package/dist/chunks/{generate.runtime-cLVzf30y.js.map → generate.runtime-CINxHRnJ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CRovTioN.js → generate.runtime-CNxgU9v1.js} +6 -6
- package/dist/chunks/{generate.runtime-CRovTioN.js.map → generate.runtime-CNxgU9v1.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BlAf07l8.js → generate.runtime-CRS9C9xX.js} +18 -16
- package/dist/chunks/{generate.runtime-BlAf07l8.js.map → generate.runtime-CRS9C9xX.js.map} +1 -1
- package/dist/chunks/{generate.runtime-HV5Dqu9a.js → generate.runtime-CYmjlSQp.js} +3 -3
- package/dist/chunks/{generate.runtime-HV5Dqu9a.js.map → generate.runtime-CYmjlSQp.js.map} +1 -1
- package/dist/chunks/{generate.runtime-t6rqiv36.js → generate.runtime-CtS6qa_1.js} +7 -7
- package/dist/chunks/{generate.runtime-t6rqiv36.js.map → generate.runtime-CtS6qa_1.js.map} +1 -1
- package/dist/chunks/{generate2.runtime-Dm_sXXFY.js → generate.runtime-CtzHFod-.js} +8 -8
- package/dist/chunks/generate.runtime-CtzHFod-.js.map +1 -0
- package/dist/chunks/{generate.runtime-0SzpMzxU.js → generate.runtime-D9t6eaQd.js} +5 -5
- package/dist/chunks/{generate.runtime-0SzpMzxU.js.map → generate.runtime-D9t6eaQd.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ByLGQwE6.js → generate.runtime-DBG6kEKb.js} +6 -6
- package/dist/chunks/{generate.runtime-ByLGQwE6.js.map → generate.runtime-DBG6kEKb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bkg4iGwz.js → generate.runtime-DfqzMG8Z.js} +4 -4
- package/dist/chunks/{generate.runtime-Bkg4iGwz.js.map → generate.runtime-DfqzMG8Z.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DdjZK-Sk.js → generate.runtime-Di0p-J8l.js} +4 -4
- package/dist/chunks/{generate.runtime-DdjZK-Sk.js.map → generate.runtime-Di0p-J8l.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B2Er8H7-.js → generate.runtime-DsLlDfIo.js} +8 -8
- package/dist/chunks/{generate.runtime-B2Er8H7-.js.map → generate.runtime-DsLlDfIo.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BitkLnIB.js → generate.runtime-EokncTLy.js} +6 -6
- package/dist/chunks/{generate.runtime-BitkLnIB.js.map → generate.runtime-EokncTLy.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CMdKTf_0.js → generate.runtime-P8IVwJLB.js} +23 -17
- package/dist/chunks/{generate.runtime-CMdKTf_0.js.map → generate.runtime-P8IVwJLB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CZALdXt6.js → generate.runtime-a5PXS1Kd.js} +3 -3
- package/dist/chunks/{generate.runtime-CZALdXt6.js.map → generate.runtime-a5PXS1Kd.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CFOYi6Sf.js → generate.runtime-qZhYdFI1.js} +9 -9
- package/dist/chunks/{generate.runtime-CFOYi6Sf.js.map → generate.runtime-qZhYdFI1.js.map} +1 -1
- package/dist/chunks/{logger-BpgCb-ZG.js → logger-CQONztPm.js} +1 -1
- package/dist/chunks/{logger-BpgCb-ZG.js.map → logger-CQONztPm.js.map} +1 -1
- package/dist/chunks/{modify-file-DE7tPADZ.js → modify-file-PVKmDJHk.js} +2 -2
- package/dist/chunks/{modify-file-DE7tPADZ.js.map → modify-file-PVKmDJHk.js.map} +1 -1
- package/dist/chunks/{modify-svelte-config-remote-DvpeGxB-.js → modify-svelte-config-remote-CDKs_Qi0.js} +2 -2
- package/dist/chunks/{modify-svelte-config-remote-DvpeGxB-.js.map → modify-svelte-config-remote-CDKs_Qi0.js.map} +1 -1
- package/dist/chunks/{modify-utils-D5W--csL.js → modify-utils-Cw-on_cL.js} +13 -13
- package/dist/chunks/{modify-utils-D5W--csL.js.map → modify-utils-Cw-on_cL.js.map} +1 -1
- package/dist/chunks/{nav-user-_VheJA6n.js → nav-user-CndUO69x.js} +1 -1
- package/dist/chunks/nav-user-CndUO69x.js.map +1 -0
- package/dist/chunks/{pocketbase--poMYyvc.js → pocketbase-BbFvZ4HI.js} +2 -2
- package/dist/chunks/{pocketbase--poMYyvc.js.map → pocketbase-BbFvZ4HI.js.map} +1 -1
- package/dist/chunks/{pocketbase-Bj-cW2Zl.js → pocketbase-C5GS-Dh5.js} +1 -1
- package/dist/chunks/{pocketbase-Bj-cW2Zl.js.map → pocketbase-C5GS-Dh5.js.map} +1 -1
- package/dist/chunks/{pocketbase-Dm2SF3vM.js → pocketbase-DpudAAmd.js} +1 -1
- package/dist/chunks/{pocketbase-Dm2SF3vM.js.map → pocketbase-DpudAAmd.js.map} +1 -1
- package/dist/chunks/{shared-C_Bl1V62.js → shared-C4-NNykV.js} +3 -3
- package/dist/chunks/{shared-C_Bl1V62.js.map → shared-C4-NNykV.js.map} +1 -1
- package/dist/chunks/{taggedTemplateLiteral-Bfbldyfk.js → taggedTemplateLiteral-CPUMuLtk.js} +1 -1
- package/dist/chunks/{test-setup-BQFmAjD0.js → test-setup-CcD8wSRD.js} +3 -3
- package/dist/chunks/{test-setup-BQFmAjD0.js.map → test-setup-CcD8wSRD.js.map} +1 -1
- package/dist/chunks/{ts-morph-helpers-bR0-x04t.js → ts-morph-helpers-Bk82Z2n7.js} +3 -3
- package/dist/chunks/{ts-morph-helpers-bR0-x04t.js.map → ts-morph-helpers-Bk82Z2n7.js.map} +1 -1
- package/dist/chunks/{util-BNtpm1tP.js → util-Bk7aQQJR.js} +1 -1
- package/dist/chunks/{util-BNtpm1tP.js.map → util-Bk7aQQJR.js.map} +1 -1
- package/dist/chunks/{write-result-B2ucfJ6m.js → write-result-DtTqt0Cs.js} +6 -6
- package/dist/chunks/write-result-DtTqt0Cs.js.map +1 -0
- package/dist/index.js +398 -352
- package/dist/index.js.map +1 -1
- package/package.json +8 -8
- package/dist/chunks/_server-Cv3bTkG0.js.map +0 -1
- package/dist/chunks/generate2.runtime-DLe5zNsJ.js.map +0 -1
- package/dist/chunks/generate2.runtime-Dm_sXXFY.js.map +0 -1
- package/dist/chunks/nav-user-_VheJA6n.js.map +0 -1
- package/dist/chunks/write-result-B2ucfJ6m.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-CMdKTf_0.js","names":[],"sources":["../../src/patterns/enable/payments/modifies/modify-nav-user.ts","../../src/patterns/enable/payments/modifies/modify-user-signup.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["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 BILLING_NAV_SNIPPET = [\n \"import CreditCardIcon from '@lucide/svelte/icons/credit-card';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Billing', url: '/billing', icon: CreditCardIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Billing nav item to nav-user.svelte:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Billing entry:\",\n \"\",\n BILLING_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(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Billing\",\n \"/billing\",\n \"CreditCardIcon\",\n \"@lucide/svelte/icons/credit-card\",\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 dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst LINK_STRIPE_CUSTOMER_SNIPPET = dedent`\n const linkStripeCustomer = async (email: string, user: { id: string }, locals: App.Locals) => {\n const matchingCustomer = await stripe.customers.list({\n email: email,\n limit: 1,\n expand: ['data.invoice_settings']\n });\n\n let customer;\n let isExistingCustomer = false;\n\n if (matchingCustomer.data.length > 0) {\n isExistingCustomer = true;\n customer = matchingCustomer.data[0];\n } else {\n customer = await stripe.customers.create({\n email: email\n });\n }\n\n await locals.admin.collection('stripe_customers').create({\n id: customer.id,\n user: user.id\n });\n\n if (!isExistingCustomer) {\n return;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(customer.id, {\n type: 'card',\n allow_redisplay: 'always'\n });\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === 'unspecified') {\n continue;\n }\n\n await locals.admin.collection('stripe_payment_methods').create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year\n });\n }\n\n const defaultPaymentMethod = customer.invoice_settings?.default_payment_method;\n\n if (defaultPaymentMethod) {\n try {\n await locals.admin.collection('stripe_customers').update(customer.id, {\n default_payment_method: defaultPaymentMethod\n });\n } catch {}\n }\n };\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Add a linkStripeCustomer helper and call it before requestVerification().\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const hasStripeImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"$lib/stripe\");\n\n if (hasStripeImport) {\n return { status: \"success\", changed: false };\n }\n\n sourceFile.addImportDeclaration({\n defaultImport: \"stripe\",\n moduleSpecifier: \"$lib/stripe\",\n });\n\n const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addStatements(LINK_STRIPE_CUSTOMER_SNIPPET);\n\n const stripeCall = dedent`\n await linkStripeCustomer(form.data.email, user, locals);\n `;\n\n statement.replaceWithText(stripeCall + \"\\n\\n\" + statement.getText());\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb\n .collection(\"users\")\n .getFullList<{ id: string; email: string }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n if (!user.email) {\n logger.info(`Skipping user ${user.id} with no email`);\n result.skipped += 1;\n continue;\n }\n\n const matching = await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n });\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${user.email}`);\n } else {\n customer = await stripe.customers.create({ email: user.email });\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${user.email}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${user.email}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { createCollectionIdempotent } from \"../../../runtime/collections\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { modifyEnv, type EnvEdit } from \"./modifies/modify-env\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./runtime/stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '$lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\nexport async function generate(options: Options) {\n const {\n stripeSecretKey,\n stripePublishableKey,\n stripeWebhookSecret,\n stripePriceId,\n } = options.input as {\n stripeSecretKey: string;\n stripePublishableKey: string;\n stripeWebhookSecret: string;\n stripePriceId?: string;\n };\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Writing Stripe credentials to .env\");\n const internalJobSecret = randomBytes(16).toString(\"hex\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\", value: stripeSecretKey },\n {\n type: \"var\",\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n value: stripePublishableKey,\n },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\", value: stripeWebhookSecret },\n { type: \"var\", key: \"INTERNAL_JOB_SECRET\", value: internalJobSecret },\n ];\n\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnv(envPath, envEdits)));\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating stripe_products collection\");\n const productsResult = await create({\n name: \"stripe_products\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"active\", required: false, type: \"text\" },\n { name: \"default_price\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_products\",\n \"created\",\n options,\n productsResult.created,\n );\n\n logger.info(\"Creating stripe_prices collection\");\n const pricesResult = await create({\n name: \"stripe_prices\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"billing_scheme\", required: false, type: \"text\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"recurring\", required: false, type: \"json\" },\n { name: \"type\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"active\", required: false, type: \"bool\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_prices\",\n \"created\",\n options,\n pricesResult.created,\n );\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, modifyUserSignup(userSignupPath)),\n );\n }\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,IAAM,IAAsB;CAC1B;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK,EAEN,IAAe;CACnB;CACA;CACA;CACD,CAAC,KAAK,KAAK,EAEN,IAAiB;CACrB;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkD;CAClD,IAAM,IAAO,IAAI,EAAW,EAAe,EACvC,IAAW,IAET,KAAU,MAAgD;AAC1D,OACJ,GAAK,MAAW;GACd,IAAM,IAAS,EACb,GACA,GACA,GACA,GACA,EACD;AAED,UADI,EAAO,aAAU,IAAW,KACzB,EAAO;IACd;;AAMJ,QAHA,GAAQ,MAAO,EAAK,mBAAmB,EAAG,CAAC,EACtC,KAAU,GAAQ,MAAO,EAAK,aAAa,EAAG,CAAC,EAE7C;EAAE,mBAAmB,EAAK,UAAU;EAAE;EAAU;;AAGzD,SAAgB,EAAc,GAAoC;AAChE,KAAI,CAAC,EAAG,WAAW,EAAY,CAC7B,QAAO;EAAE,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AAS,EAAmB,EAAM,GAAG;EACrC,QAAQ;EACT,CAAC,EAEE,GAAW;AACb,IAAO,KAAK,4BAA4B;EACxC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,kBACD;AAGD,EAFA,EAAW,EAAoB,GAAa,EAAc,EAAY,CAAC,CAAC,EAExE,EAAO,KAAK,mCAAmC;EAC/C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,YACA,UACA,UACA,kBACD;AACD,IACE,EAAoB,GAAgB,EAAiB,EAAe,CAAC,CACtE;;AAGH,QAAO;EACL;EACA;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAAiB,EAAE;EACpB"}
|
|
1
|
+
{"version":3,"file":"generate.runtime-P8IVwJLB.js","names":[],"sources":["../../src/patterns/enable/payments/modifies/modify-nav-user.ts","../../src/patterns/enable/payments/modifies/modify-user-signup.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["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 BILLING_NAV_SNIPPET = [\n \"import CreditCardIcon from '@lucide/svelte/icons/credit-card';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Billing', url: '/billing', icon: CreditCardIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Billing nav item to nav-user.svelte:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Billing entry:\",\n \"\",\n BILLING_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(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Billing\",\n \"/billing\",\n \"CreditCardIcon\",\n \"@lucide/svelte/icons/credit-card\",\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 dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst LINK_STRIPE_CUSTOMER_SNIPPET = dedent`\n const linkStripeCustomer = async (email: string, user: { id: string }, locals: App.Locals) => {\n const matchingCustomer = await stripe.customers.list({\n email: email,\n limit: 1,\n expand: ['data.invoice_settings']\n });\n\n let customer;\n let isExistingCustomer = false;\n\n if (matchingCustomer.data.length > 0) {\n isExistingCustomer = true;\n customer = matchingCustomer.data[0];\n } else {\n customer = await stripe.customers.create({\n email: email\n });\n }\n\n await locals.admin.collection('stripe_customers').create({\n id: customer.id,\n user: user.id\n });\n\n if (!isExistingCustomer) {\n return;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(customer.id, {\n type: 'card',\n allow_redisplay: 'always'\n });\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === 'unspecified') {\n continue;\n }\n\n await locals.admin.collection('stripe_payment_methods').create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year\n });\n }\n\n const defaultPaymentMethod = customer.invoice_settings?.default_payment_method;\n\n if (defaultPaymentMethod) {\n try {\n await locals.admin.collection('stripe_customers').update(customer.id, {\n default_payment_method: defaultPaymentMethod\n });\n } catch {}\n }\n };\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Add a linkStripeCustomer helper and call it before requestVerification().\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const hasStripeImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"$lib/stripe\");\n\n if (hasStripeImport) {\n return { status: \"success\", changed: false };\n }\n\n sourceFile.addImportDeclaration({\n defaultImport: \"stripe\",\n moduleSpecifier: \"$lib/stripe\",\n });\n\n const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addStatements(LINK_STRIPE_CUSTOMER_SNIPPET);\n\n const stripeCall = dedent`\n await linkStripeCustomer(form.data.email, user, locals);\n `;\n\n statement.replaceWithText(stripeCall + \"\\n\\n\" + statement.getText());\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb\n .collection(\"users\")\n .getFullList<{ id: string; email: string }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n if (!user.email) {\n logger.info(`Skipping user ${user.id} with no email`);\n result.skipped += 1;\n continue;\n }\n\n const matching = await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n });\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${user.email}`);\n } else {\n customer = await stripe.customers.create({ email: user.email });\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${user.email}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${user.email}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { createCollectionIdempotent } from \"../../../runtime/collections\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { modifyEnv, type EnvEdit } from \"./modifies/modify-env\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./runtime/stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '$lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\nexport async function generate(options: Options) {\n const {\n stripeSecretKey,\n stripePublishableKey,\n stripeWebhookSecret,\n stripePriceId,\n } = options.input as {\n stripeSecretKey: string;\n stripePublishableKey: string;\n stripeWebhookSecret: string;\n stripePriceId?: string;\n };\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Writing Stripe credentials to .env\");\n const internalJobSecret = randomBytes(16).toString(\"hex\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\", value: stripeSecretKey },\n {\n type: \"var\",\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n value: stripePublishableKey,\n },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\", value: stripeWebhookSecret },\n { type: \"var\", key: \"INTERNAL_JOB_SECRET\", value: internalJobSecret },\n ];\n\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnv(envPath, envEdits)));\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating stripe_products collection\");\n const productsResult = await create({\n name: \"stripe_products\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"active\", required: false, type: \"text\" },\n { name: \"default_price\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_products\",\n \"created\",\n options,\n productsResult.created,\n );\n\n logger.info(\"Creating stripe_prices collection\");\n const pricesResult = await create({\n name: \"stripe_prices\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"billing_scheme\", required: false, type: \"text\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"recurring\", required: false, type: \"json\" },\n { name: \"type\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"active\", required: false, type: \"bool\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_prices\",\n \"created\",\n options,\n pricesResult.created,\n );\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, modifyUserSignup(userSignupPath)),\n );\n }\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,IAAM,IAAsB;CAC1B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkD;CAClD,IAAM,IAAO,IAAI,EAAW,CAAc,GACtC,IAAW,IAET,KAAU,MAAgD;EAC1D,KACJ,GAAK,MAAW;GACd,IAAM,IAAS,EACb,GACA,GACA,GACA,GACA,CACF;GAEA,OADI,EAAO,aAAU,IAAW,KACzB,EAAO;EAChB,CAAC;CACH;CAKA,OAHA,GAAQ,MAAO,EAAK,mBAAmB,CAAE,CAAC,GACrC,KAAU,GAAQ,MAAO,EAAK,aAAa,CAAE,CAAC,GAE5C;EAAE,mBAAmB,EAAK,SAAS;EAAG;CAAS;AACxD;AAEA,SAAgB,EAAc,GAAoC;CAChE,IAAI,CAAC,EAAG,WAAW,CAAW,GAC5B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAiB,EAAG,aAAa,GAAa,MAAM;CAC1D,IAAI,EAAe,SAAS,UAAU,GACpC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,EAAE,sBAAmB,gBAAa,EACtC,GACA,WACA,YACA,kBACA,kCACF;CAOA,OALK,KAIL,EAAG,cAAc,GAAa,GAAmB,MAAM,GAChD;EAAE,QAAQ;EAAW,SAAS;CAAK,KAJjC;EAAE,QAAQ;EAAU,SAAS;CAAa;AA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,MACR,OACA,OACA,cACA,iBACF;EAGA,AAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEvE,EAAO,KAAK,kCAAkC;EAC9C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,YACA,UACA,UACA,iBACF;EACA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE;CACF;CAEA,OAAO;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as e } from "./logger-
|
|
2
|
-
import { modifyOutcomeToFile as t } from "./modify-file-
|
|
1
|
+
import { n as e } from "./logger-CQONztPm.js";
|
|
2
|
+
import { modifyOutcomeToFile as t } from "./modify-file-PVKmDJHk.js";
|
|
3
3
|
import n from "node:fs";
|
|
4
4
|
import r from "node:path";
|
|
5
5
|
import { Project as i, SyntaxKind as a } from "ts-morph";
|
|
@@ -53,4 +53,4 @@ async function s(n) {
|
|
|
53
53
|
//#endregion
|
|
54
54
|
export { s as generate };
|
|
55
55
|
|
|
56
|
-
//# sourceMappingURL=generate.runtime-
|
|
56
|
+
//# sourceMappingURL=generate.runtime-a5PXS1Kd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-a5PXS1Kd.js","names":[],"sources":["../../src/patterns/disable/api/modifies/hooks.server.ts","../../src/patterns/disable/api/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"success\", changed: false };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n return { status: \"success\", changed: false };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp) {\n return { status: \"success\", changed: false };\n }\n\n apiProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\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,SAAgB,EAAoB,GAAwC;CAC1E,IAAI,CAAC,EAAG,WAAW,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAiB,MAAM,GAExD,IAAa,IADC,EACD,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-
import { a as r, o as i, r as a } from "./ts-morph-helpers-
|
|
1
|
+
import { n as e } from "./logger-CQONztPm.js";
|
|
2
|
+
import { t } from "./shared-C4-NNykV.js";
|
|
3
|
+
import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
|
|
4
|
+
import { a as r, o as i, r as a } from "./ts-morph-helpers-Bk82Z2n7.js";
|
|
5
5
|
import o from "node:fs";
|
|
6
6
|
import s from "node:path";
|
|
7
7
|
import { Project as c, SyntaxKind as l } from "ts-morph";
|
|
@@ -33,15 +33,15 @@ function d(e) {
|
|
|
33
33
|
status: "success",
|
|
34
34
|
changed: !1
|
|
35
35
|
};
|
|
36
|
-
let t =
|
|
37
|
-
return
|
|
36
|
+
let t = o.readFileSync(e, "utf8"), n = new i(t);
|
|
37
|
+
return n.hasElement("AuthMenu.Root") ? (n.removeElement("AuthMenu.Root"), n.modifyScript((e) => {
|
|
38
38
|
let { source: t } = r(e, (e) => {
|
|
39
39
|
a(e, "$lib/components/ui/auth-menu"), a(e, "$lib/components/ui/avatar");
|
|
40
40
|
});
|
|
41
41
|
return t;
|
|
42
|
-
}),
|
|
42
|
+
}), n.writeTo(e), {
|
|
43
43
|
status: "success",
|
|
44
|
-
changed:
|
|
44
|
+
changed: n.hasChanged()
|
|
45
45
|
}) : {
|
|
46
46
|
status: "success",
|
|
47
47
|
changed: !1
|
|
@@ -104,4 +104,4 @@ async function p(r) {
|
|
|
104
104
|
//#endregion
|
|
105
105
|
export { p as generate };
|
|
106
106
|
|
|
107
|
-
//# sourceMappingURL=generate.runtime-
|
|
107
|
+
//# sourceMappingURL=generate.runtime-qZhYdFI1.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-qZhYdFI1.js","names":[],"sources":["../../src/patterns/disable/auth/modifies/+layout.server.ts","../../src/patterns/disable/auth/modifies/root-layout.svelte.ts","../../src/patterns/disable/auth/modifies/hooks.server.ts","../../src/patterns/disable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n if (!originalSource.includes(\"locals.pb.authStore.record\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const literals = sourceFile.getDescendantsOfKind(\n SyntaxKind.ObjectLiteralExpression,\n );\n for (const obj of literals) {\n const userProp = obj.getProperty(\"user\");\n if (!userProp || userProp.getKind() !== SyntaxKind.PropertyAssignment) {\n continue;\n }\n const value = (userProp as import(\"ts-morph\").PropertyAssignment)\n .getInitializer()\n ?.getText();\n if (value === \"locals.pb.authStore.record\") {\n userProp.remove();\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\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 {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(layoutPath, \"utf8\");\n const file = new SvelteFile(source);\n if (!file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.removeElement(\"AuthMenu.Root\");\n\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/components/ui/auth-menu\");\n removeImportByModuleSpecifier(sf, \"$lib/components/ui/avatar\");\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n return { status: \"success\", changed: false };\n }\n\n authProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\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 +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerFile,\n unmodifyLayoutServer(layoutServerFile),\n ),\n );\n\n logger.info(\"Reverting root layout\");\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, unmodifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, unmodifyHooksServer(hooksServerFile)),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"oauth_accounts\"],\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":";;;;;;;;AAIA,SAAgB,EAAqB,GAAmC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAY,MAAM;CACzD,IAAI,CAAC,EAAe,SAAS,4BAA4B,GACvD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAM,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAU,GAEnD,IAAW,EAAW,qBAC1B,EAAW,uBACb;CACA,KAAK,IAAM,KAAO,GAAU;EAC1B,IAAM,IAAW,EAAI,YAAY,MAAM;EACnC,CAAC,KAAY,EAAS,QAAQ,MAAM,EAAW,sBAGpC,EACZ,eAAe,CAAC,EACf,Q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GACjB,CACF;CAWA;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger-
|
|
1
|
+
{"version":3,"file":"logger-CQONztPm.js","names":[],"sources":["../../src/core/logger.ts"],"sourcesContent":["export interface Logger {\n info: (message: string) => void;\n}\n\nexport const NOOP_LOGGER: Logger = {\n info: () => {},\n};\n\nexport function getLogger(options: { logger?: Logger }): Logger {\n return options.logger ?? NOOP_LOGGER;\n}\n"],"mappings":";AAIA,IAAa,IAAsB,EACjC,YAAY,CAAC,EACf;AAEA,SAAgB,EAAU,GAAsC;CAC9D,OAAO,EAAQ,UAAU;AAC3B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as e } from "./util-
|
|
1
|
+
import { i as e } from "./util-Bk7aQQJR.js";
|
|
2
2
|
import t from "node:fs";
|
|
3
3
|
//#region src/runtime/modify-file.ts
|
|
4
4
|
function n(n, r) {
|
|
@@ -19,4 +19,4 @@ function n(n, r) {
|
|
|
19
19
|
//#endregion
|
|
20
20
|
export { n as modifyOutcomeToFile };
|
|
21
21
|
|
|
22
|
-
//# sourceMappingURL=modify-file-
|
|
22
|
+
//# sourceMappingURL=modify-file-PVKmDJHk.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modify-file-
|
|
1
|
+
{"version":3,"file":"modify-file-PVKmDJHk.js","names":[],"sources":["../../src/runtime/modify-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\n\nexport function modifyOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): File | null {\n const language = languageFromPath(filePath);\n\n if (outcome.status === \"success\") {\n if (!outcome.changed) return null;\n return {\n path: filePath,\n language,\n content: fs.readFileSync(filePath, \"utf8\"),\n status: \"success\",\n };\n }\n\n const content =\n outcome.status === \"failed\" && fs.existsSync(filePath)\n ? fs.readFileSync(filePath, \"utf8\")\n : \"\";\n\n return {\n path: filePath,\n language,\n content,\n status: outcome.status,\n message: outcome.message,\n };\n}\n"],"mappings":";;;AAIA,SAAgB,EACd,GACA,GACa;CACb,IAAM,IAAW,EAAiB,CAAQ;CAiB1C,OAfI,EAAQ,WAAW,YAChB,EAAQ,UACN;EACL,MAAM;EACN;EACA,SAAS,EAAG,aAAa,GAAU,MAAM;EACzC,QAAQ;CACV,IAN6B,OAcxB;EACL,MAAM;EACN;EACA,SAPA,EAAQ,WAAW,YAAY,EAAG,WAAW,CAAQ,IACjD,EAAG,aAAa,GAAU,MAAM,IAChC;EAMJ,QAAQ,EAAQ;EAChB,SAAS,EAAQ;CACnB;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as e, n as t, r as n } from "./config-target-
|
|
1
|
+
import { i as e, n as t, r as n } from "./config-target-Co-ij8p3.js";
|
|
2
2
|
//#region src/runtime/modify-svelte-config-remote.ts
|
|
3
3
|
var r = [
|
|
4
4
|
"Enable SvelteKit remote functions and Svelte async in your config",
|
|
@@ -41,4 +41,4 @@ function a(a) {
|
|
|
41
41
|
//#endregion
|
|
42
42
|
export { a as modifySvelteConfigRemote };
|
|
43
43
|
|
|
44
|
-
//# sourceMappingURL=modify-svelte-config-remote-
|
|
44
|
+
//# sourceMappingURL=modify-svelte-config-remote-CDKs_Qi0.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modify-svelte-config-remote-
|
|
1
|
+
{"version":3,"file":"modify-svelte-config-remote-CDKs_Qi0.js","names":[],"sources":["../../src/runtime/modify-svelte-config-remote.ts"],"sourcesContent":["import {\n ensureBooleanTrue,\n getOrCreateObjectLiteralProperty,\n modifyConfig,\n type ConfigModifyResult,\n} from \"./config-target\";\n\nconst FAILURE_HINT = [\n \"Enable SvelteKit remote functions and Svelte async in your config\",\n \"(the sveltekit() plugin arg in vite.config, or svelte.config):\",\n \"\",\n \"experimental: { remoteFunctions: true },\",\n \"compilerOptions: { experimental: { async: true } },\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Enable SvelteKit remote functions and Svelte async by passing config to the\",\n \"sveltekit() plugin in vite.config.ts:\",\n \"\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { defineConfig } from 'vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [\",\n \" sveltekit({\",\n \" experimental: { remoteFunctions: true },\",\n \" compilerOptions: { experimental: { async: true } },\",\n \" }),\",\n \" ],\",\n \"});\",\n].join(\"\\n\");\n\n/**\n * Enable SvelteKit remote functions (`experimental.remoteFunctions`) and Svelte\n * async (`compilerOptions.experimental.async`) in whichever config the project\n * uses — the inline `sveltekit()` arg in vite.config, or svelte.config.\n *\n * `remoteFunctions` is kit-namespaced (→ `kitContainer()`); `async` is a\n * root-level compiler option (→ `configObject`).\n */\nexport function modifySvelteConfigRemote(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n const kit = target.kitContainer();\n if (!kit) return false;\n const kitExperimental = getOrCreateObjectLiteralProperty(\n kit,\n \"experimental\",\n \"{}\",\n );\n if (!kitExperimental) return false;\n ensureBooleanTrue(kitExperimental, \"remoteFunctions\");\n\n const compilerObj = getOrCreateObjectLiteralProperty(\n target.configObject,\n \"compilerOptions\",\n \"{}\",\n );\n if (!compilerObj) return false;\n const compilerExperimental = getOrCreateObjectLiteralProperty(\n compilerObj,\n \"experimental\",\n \"{}\",\n );\n if (!compilerExperimental) return false;\n ensureBooleanTrue(compilerExperimental, \"async\");\n\n return true;\n },\n );\n}\n"],"mappings":";;AAOA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAUX,SAAgB,EAAyB,GAAkC;CACzE,OAAO,EACL,GACA;EAAE,UAAU;EAAgB,QAAQ;CAAa,IAChD,MAAW;EACV,IAAM,IAAM,EAAO,aAAa;EAChC,IAAI,CAAC,GAAK,OAAO;EACjB,IAAM,IAAkB,EACtB,GACA,gBACA,IACF;EACA,IAAI,CAAC,GAAiB,OAAO;EAC7B,EAAkB,GAAiB,iBAAiB;EAEpD,IAAM,IAAc,EAClB,EAAO,cACP,mBACA,IACF;EACA,IAAI,CAAC,GAAa,OAAO;EACzB,IAAM,IAAuB,EAC3B,GACA,gBACA,IACF;EAIA,OAHK,KACL,EAAkB,GAAsB,OAAO,GAExC,MAH2B;CAIpC,CACF;AACF"}
|
|
@@ -1,11 +1,8 @@
|
|
|
1
|
-
import { t as e } from "./dedent-
|
|
1
|
+
import { t as e } from "./dedent-Gq6Krl4n.js";
|
|
2
2
|
import t from "node:fs";
|
|
3
3
|
import { Project as n, QuoteKind as r } from "ts-morph";
|
|
4
4
|
//#region src/runtime/modify-utils.ts
|
|
5
5
|
var i = e`
|
|
6
|
-
Create src/lib/utils.ts with a timeAgo helper:
|
|
7
|
-
|
|
8
|
-
${e`
|
|
9
6
|
const TIME_AGO_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
|
|
10
7
|
['year', 60 * 60 * 24 * 365],
|
|
11
8
|
['month', 60 * 60 * 24 * 30],
|
|
@@ -25,8 +22,11 @@ var i = e`
|
|
|
25
22
|
}
|
|
26
23
|
}
|
|
27
24
|
}
|
|
28
|
-
`}
|
|
29
25
|
`, a = e`
|
|
26
|
+
Create src/lib/utils.ts with a timeAgo helper:
|
|
27
|
+
|
|
28
|
+
${i}
|
|
29
|
+
`, o = e`
|
|
30
30
|
const TIME_AGO_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
|
|
31
31
|
['year', 60 * 60 * 24 * 365],
|
|
32
32
|
['month', 60 * 60 * 24 * 30],
|
|
@@ -35,7 +35,7 @@ var i = e`
|
|
|
35
35
|
['minute', 60],
|
|
36
36
|
['second', 1]
|
|
37
37
|
];
|
|
38
|
-
`,
|
|
38
|
+
`, s = e`
|
|
39
39
|
export function timeAgo(date: Date | string | number, locale?: string) {
|
|
40
40
|
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
|
|
41
41
|
const diff = (new Date(date).getTime() - Date.now()) / 1000;
|
|
@@ -47,23 +47,23 @@ var i = e`
|
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
`;
|
|
50
|
-
function
|
|
50
|
+
function c(e) {
|
|
51
51
|
if (!t.existsSync(e)) return {
|
|
52
52
|
status: "not-found",
|
|
53
|
-
message:
|
|
53
|
+
message: a
|
|
54
54
|
};
|
|
55
|
-
let
|
|
55
|
+
let i = t.readFileSync(e, "utf8"), c = new n({ manipulationSettings: { quoteKind: r.Single } }).addSourceFileAtPath(e), l = c.getFunction("timeAgo") !== void 0 || c.getVariableDeclaration("timeAgo") !== void 0, u = c.getVariableDeclaration("TIME_AGO_UNITS") !== void 0;
|
|
56
56
|
if (l && u) return {
|
|
57
57
|
status: "success",
|
|
58
58
|
changed: !1
|
|
59
59
|
};
|
|
60
60
|
let d = [];
|
|
61
|
-
return u || d.push(
|
|
61
|
+
return u || d.push(o), l || d.push(s), c.addStatements("\n" + d.join("\n\n") + "\n"), c.saveSync(), {
|
|
62
62
|
status: "success",
|
|
63
|
-
changed: c.getFullText() !==
|
|
63
|
+
changed: c.getFullText() !== i
|
|
64
64
|
};
|
|
65
65
|
}
|
|
66
66
|
//#endregion
|
|
67
|
-
export {
|
|
67
|
+
export { c as t };
|
|
68
68
|
|
|
69
|
-
//# sourceMappingURL=modify-utils-
|
|
69
|
+
//# sourceMappingURL=modify-utils-Cw-on_cL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modify-utils-
|
|
1
|
+
{"version":3,"file":"modify-utils-Cw-on_cL.js","names":[],"sources":["../../src/runtime/modify-utils.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nconst TIME_AGO_SNIPPET = dedent`\n const TIME_AGO_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1]\n ];\n\n export function timeAgo(date: Date | string | number, locale?: string) {\n const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });\n const diff = (new Date(date).getTime() - Date.now()) / 1000;\n\n for (const [unit, secs] of TIME_AGO_UNITS) {\n if (Math.abs(diff) >= secs || unit === 'second') {\n return rtf.format(Math.round(diff / secs), unit);\n }\n }\n }\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/lib/utils.ts with a timeAgo helper:\n\n ${TIME_AGO_SNIPPET}\n`;\n\nconst UNITS_SNIPPET = dedent`\n const TIME_AGO_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1]\n ];\n`;\n\nconst FUNCTION_SNIPPET = dedent`\n export function timeAgo(date: Date | string | number, locale?: string) {\n const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });\n const diff = (new Date(date).getTime() - Date.now()) / 1000;\n\n for (const [unit, secs] of TIME_AGO_UNITS) {\n if (Math.abs(diff) >= secs || unit === 'second') {\n return rtf.format(Math.round(diff / secs), unit);\n }\n }\n }\n`;\n\nexport function modifyUtils(utilsPath: string): ModifyOutcome {\n if (!fs.existsSync(utilsPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(utilsPath, \"utf8\");\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(utilsPath);\n\n const hasTimeAgo =\n sourceFile.getFunction(\"timeAgo\") !== undefined ||\n sourceFile.getVariableDeclaration(\"timeAgo\") !== undefined;\n const hasUnits =\n sourceFile.getVariableDeclaration(\"TIME_AGO_UNITS\") !== undefined;\n\n if (hasTimeAgo && hasUnits) {\n return { status: \"success\", changed: false };\n }\n\n const toAppend: string[] = [];\n if (!hasUnits) toAppend.push(UNITS_SNIPPET);\n if (!hasTimeAgo) toAppend.push(FUNCTION_SNIPPET);\n\n sourceFile.addStatements(\"\\n\" + toAppend.join(\"\\n\\n\") + \"\\n\");\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n"],"mappings":";;;;AAKA,IAAM,IAAmB,CAAM;;;;;;;;;;;;;;;;;;;;GAsBzB,IAAiB,CAAM;;;IAGzB,EAAiB;GAGf,IAAgB,CAAM;;;;;;;;;GAWtB,IAAmB,CAAM;;;;;;;;;;;;AAa/B,SAAgB,EAAY,GAAkC;CAC5D,IAAI,CAAC,EAAG,WAAW,CAAS,GAC1B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAiB,EAAG,aAAa,GAAW,MAAM,GAIlD,IAAa,IAHC,EAAQ,EAC1B,sBAAsB,EAAE,WAAW,EAAU,OAAO,EACtD,CACmB,CAAA,CAAQ,oBAAoB,CAAS,GAElD,IACJ,EAAW,YAAY,SAAS,MAAM,KAAA,KACtC,EAAW,uBAAuB,SAAS,MAAM,KAAA,GAC7C,IACJ,EAAW,uBAAuB,gBAAgB,MAAM,KAAA;CAE1D,IAAI,KAAc,GAChB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAqB,CAAC;CAO5B,OANK,KAAU,EAAS,KAAK,CAAa,GACrC,KAAY,EAAS,KAAK,CAAgB,GAE/C,EAAW,cAAc,OAAO,EAAS,KAAK,MAAM,IAAI,IAAI,GAC5D,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAAS,EAAW,YAAY,MAAM;CACxC;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nav-user-CndUO69x.js","names":[],"sources":[],"mappings":""}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as e, r as t } from "./constants-
|
|
1
|
+
import { n as e, r as t } from "./constants-qmioN-7W.js";
|
|
2
2
|
import { existsSync as n, readFileSync as r, readdirSync as i } from "node:fs";
|
|
3
3
|
import a from "node:path";
|
|
4
4
|
import o from "pocketbase";
|
|
@@ -103,4 +103,4 @@ async function y(r, i) {
|
|
|
103
103
|
//#endregion
|
|
104
104
|
export { g as getMigrationFile, h as migrationDelay, y as withPocketbase };
|
|
105
105
|
|
|
106
|
-
//# sourceMappingURL=pocketbase
|
|
106
|
+
//# sourceMappingURL=pocketbase-BbFvZ4HI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pocketbase
|
|
1
|
+
{"version":3,"file":"pocketbase-BbFvZ4HI.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n// Generate a random port\nexport function randomPort() {\n return Math.floor(Math.random() * 10000) + 10000;\n}\n\n// Wait for the port to be available\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 10,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 10): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n } catch {\n // Ignore fetch errors and continue retrying\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for health check at ${url}/api/health`),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { randomPort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = randomPort();\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process\n const serverProcess = spawn(command, args, {\n stdio: \"ignore\",\n });\n\n try {\n // Wait for the server to be ready\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process\n serverProcess.kill();\n }\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,IAAa;CAC3B,OAAO,KAAK,MAAM,KAAK,OAAO,IAAI,GAAK,IAAI;AAC7C;AAGA,SAAgB,EACd,GACA,GACA,IAAc,IACC;CACf,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAI,IAAW,GAET,UAAmB;GACvB;GAEA,IAAM,IAAS,IAAI,EAAI,OAAO;GAiB9B,AAFA,EAAO,KAAK,eAbU;IAGpB,IAFA,EAAO,QAAQ,GAEX,MAAa,GAAa;KAC5B,EACE,gBAAI,MAAM,8BAA8B,EAAK,iBAAiB,CAChE;KACA;IACF;IAEA,WAAW,GAAY,GAAG;GAC5B,CAE4B,GAE5B,EAAO,QAAQ,GAAM,SAAY;IAE/B,AADA,EAAO,QAAQ,GACf,EAAQ;GACV,CAAC;EACH;EAEA,EAAW;CACb,CAAC;AACH;AAGA,SAAgB,EAAc,GAAa,IAAc,IAAmB;CAC1E,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAI,IAAW,GAET,IAAY,YAAY;GAC5B;GAEA,IAAI;IAEF,KAAI,MADmB,MAAM,GAAG,EAAI,YAAY,EAAA,CACnC,WAAW,KAAK;KAC3B,EAAQ;KACR;IACF;GACF,QAAQ,CAER;GAEA,IAAI,MAAa,GAAa;IAC5B,EACE,gBAAI,MAAM,yCAAyC,EAAI,YAAY,CACrE;IACA;GACF;GAEA,WAAW,GAAW,GAAG;EAC3B;EAEA,EAAU;CACZ,CAAC;AACH;;;AC1DA,IAAM,IAAqB;AAE3B,SAAgB,IAAgC;CAC9C,OAAO,IAAI,SAAS,MAAY,WAAW,GAAS,CAAkB,CAAC;AACzE;AAEA,SAAgB,EACd,GACA,GACA,GACoB;CACpB,IAAM,IAAS,GAAG,EAAO,GAAG,EAAe,MAOrC,IAJ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AClD,EAAE,YAAS,YAAS,EACxB,GACA,WACA,CACF;CAGA,AAAI,MAAmB,SAAO,EAAK,QAAQ,OAAO;CAGlD,IAAM,IAAgB,EAAM,GAAS,GAAM,EACzC,OAAO,SACT,CAAC;CAED,IAAI;EAGF,AADA,MAAM,EAAY,GAAM,CAAI,GAC5B,MAAM,EAAc,UAAU,EAAK,GAAG,GAAM;EAE5C,IAAM,IAAK,IAAI,EAAW,UAAU,EAAK,GAAG,GAAM;EAMlD,AALA,MAAM,EACJ,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAM,EAAG,CAAE;CACb,UAAU;EAER,EAAc,KAAK;CACrB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pocketbase-
|
|
1
|
+
{"version":3,"file":"pocketbase-C5GS-Dh5.js","names":[],"sources":["../../src/patterns/enable/teams/runtime/pocketbase.ts"],"sourcesContent":["import type { CollectionRulesPatch } from \"../../../../core/types\";\n\n/** Applied after all team collections are created (create-time rules are omitted). */\nexport const TEAM_RULE_PATCHES: CollectionRulesPatch[] = [\n {\n collectionName: \"teams\",\n listRule:\n \"team_memberships_via_team.user ?= @request.auth.id || owner = @request.auth.id\",\n viewRule: '@request.auth.id != \"\"',\n createRule: \"owner = @request.auth.id\",\n updateRule: \"owner = @request.auth.id\",\n deleteRule: \"owner = @request.auth.id\",\n },\n {\n collectionName: \"team_memberships\",\n listRule:\n \"user = @request.auth.id || team.team_memberships_via_team.user ?= @request.auth.id\",\n viewRule:\n \"user = @request.auth.id || team.team_memberships_via_team.user ?= @request.auth.id\",\n createRule: null,\n updateRule:\n \"((team.team_memberships_via_team.role ?= 'owner' || team.team_memberships_via_team.role ?= 'admin') && team.team_memberships_via_team.user ?= @request.auth.id)\",\n deleteRule:\n \"user = @request.auth.id || ((team.team_memberships_via_team.role ?= 'owner' || team.team_memberships_via_team.role ?= 'admin') && team.team_memberships_via_team.user ?= @request.auth.id)\",\n },\n {\n collectionName: \"team_users\",\n listRule:\n \"id = @request.auth.id || team.team_memberships_via_team.user ?= @request.auth.id\",\n viewRule:\n \"id = @request.auth.id || team.team_memberships_via_team.user ?= @request.auth.id\",\n createRule: null,\n updateRule: null,\n deleteRule: null,\n },\n {\n collectionName: \"team_invites\",\n listRule:\n \"email = @request.auth.email || ((team.team_memberships_via_team.role ?= 'owner' || team.team_memberships_via_team.role ?= 'admin') && team.team_memberships_via_team.user ?= @request.auth.id)\",\n viewRule:\n \"email = @request.auth.email || ((team.team_memberships_via_team.role ?= 'owner' || team.team_memberships_via_team.role ?= 'admin') && team.team_memberships_via_team.user ?= @request.auth.id)\",\n createRule:\n \"((team.team_memberships_via_team.role ?= 'owner' || team.team_memberships_via_team.role ?= 'admin') && team.team_memberships_via_team.user ?= @request.auth.id)\",\n updateRule: null,\n deleteRule:\n \"((team.team_memberships_via_team.role ?= 'owner' || team.team_memberships_via_team.role ?= 'admin') && team.team_memberships_via_team.user ?= @request.auth.id)\",\n },\n {\n collectionName: \"team_invite_links\",\n listRule: null,\n viewRule: '@request.auth.id != \"\"',\n createRule: null,\n updateRule: null,\n deleteRule: null,\n },\n];\n"],"mappings":";AAGA,IAAa,IAA4C;CACvD;EACE,gBAAgB;EAChB,UACE;EACF,UAAU;EACV,YAAY;EACZ,YAAY;EACZ,YAAY;CACd;CACA;EACE,gBAAgB;EAChB,UACE;EACF,UACE;EACF,YAAY;EACZ,YACE;EACF,YACE;CACJ;CACA;EACE,gBAAgB;EAChB,UACE;EACF,UACE;EACF,YAAY;EACZ,YAAY;EACZ,YAAY;CACd;CACA;EACE,gBAAgB;EAChB,UACE;EACF,UACE;EACF,YACE;EACF,YAAY;EACZ,YACE;CACJ;CACA;EACE,gBAAgB;EAChB,UAAU;EACV,UAAU;EACV,YAAY;EACZ,YAAY;EACZ,YAAY;CACd;AACF"}
|