@velastack/patterns 0.9.0 → 0.10.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.
@@ -0,0 +1,6 @@
1
+ //#region src/patterns/enable/orders/preview-modifies/src/routes/(public)/checkout/success/+page.server.ts?raw
2
+ var e = "import { error } from '@sveltejs/kit';\nimport stripe from '#lib/stripe.js';\n\ninterface OrderRecord {\n status: string;\n amount_total: number;\n currency: string;\n}\n\ninterface OrderLineRecord {\n id: string;\n name: string;\n quantity: number;\n amount_total: number;\n currency: string;\n}\n\n/**\n * The order as the webhook recorded it, with its lines; until that event has\n * arrived (it usually has), Stripe's own summary of the session.\n */\nexport const load = async ({ url, locals }) => {\n const id = url.searchParams.get('session_id');\n if (!id) error(404, 'Not found');\n\n const order = await locals.admin\n .collection('orders')\n .getOne<OrderRecord>(id)\n .catch(() => null);\n if (order) {\n const lines = await locals.admin.collection('order_lines').getFullList<OrderLineRecord>({\n filter: locals.admin.filter('order = {:order}', { order: id }),\n sort: 'created'\n });\n return {\n amountTotal: order.amount_total,\n currency: order.currency,\n paid: order.status === 'paid',\n lines: lines.map((line) => ({\n id: line.id,\n name: line.name,\n quantity: line.quantity,\n amountTotal: line.amount_total,\n currency: line.currency\n }))\n };\n }\n\n try {\n const session = await stripe.checkout.sessions.retrieve(id);\n return {\n amountTotal: session.amount_total,\n currency: session.currency,\n paid: session.payment_status === 'paid',\n lines: []\n };\n } catch {\n error(404, 'Not found');\n }\n};\n", t = "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { cart, formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n onMount(() => {\n cart.load();\n if (data.paid) cart.clear();\n });\n<\/script>\n\n<section data-role=\"content\" class=\"max-w-xl\">\n {#if data.paid}\n <h1 class=\"mb-2 text-2xl font-semibold\">Thank you</h1>\n <p class=\"text-muted-foreground\">\n {#if data.amountTotal !== null && data.currency}\n Your payment of {formatAmount(data.amountTotal, data.currency)} went through.\n {:else}\n Your payment went through.\n {/if}\n </p>\n {:else}\n <h1 class=\"mb-2 text-2xl font-semibold\">Payment pending</h1>\n <p class=\"text-muted-foreground\">Your order is placed; the payment has not cleared yet.</p>\n {/if}\n\n {#if data.lines.length > 0}\n <ul class=\"mt-6 divide-y border-y\">\n {#each data.lines as line (line.id)}\n <li class=\"flex items-center justify-between gap-4 py-3 text-sm\">\n <span>{line.quantity} × {line.name}</span>\n <span>{formatAmount(line.amountTotal, line.currency)}</span>\n </li>\n {/each}\n </ul>\n {/if}\n</section>\n";
3
+ //#endregion
4
+ export { e as n, t };
5
+
6
+ //# sourceMappingURL=_page-B6yd6_Vl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_page-B6yd6_Vl.js","names":["_page_server_default","_page_default"],"sources":[],"mappings":""}
@@ -0,0 +1,175 @@
1
+ import { r as e } from "./util-BLYliuUK.js";
2
+ //#region src/patterns/enable/ecommerce/providers/stripe/src/routes/(public)/checkout/success/+page.server.ts?raw
3
+ var t = "import { error } from '@sveltejs/kit';\nimport stripe from '#lib/stripe.js';\n\nexport const load = async ({ url }) => {\n const id = url.searchParams.get('session_id');\n if (!id) error(404, 'Not found');\n\n try {\n const session = await stripe.checkout.sessions.retrieve(id);\n return {\n amountTotal: session.amount_total,\n currency: session.currency,\n paid: session.payment_status === 'paid'\n };\n } catch {\n error(404, 'Not found');\n }\n};\n", n = "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { cart, formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n onMount(() => {\n cart.load();\n if (data.paid) cart.clear();\n });\n<\/script>\n\n<section data-role=\"content\" class=\"max-w-xl\">\n {#if data.paid}\n <h1 class=\"mb-2 text-2xl font-semibold\">Thank you</h1>\n <p class=\"text-muted-foreground\">\n {#if data.amountTotal !== null && data.currency}\n Your payment of {formatAmount(data.amountTotal, data.currency)} went through.\n {:else}\n Your payment went through.\n {/if}\n </p>\n {:else}\n <h1 class=\"mb-2 text-2xl font-semibold\">Payment pending</h1>\n <p class=\"text-muted-foreground\">Your order is placed; the payment has not cleared yet.</p>\n {/if}\n</section>\n", r = "import type Stripe from 'stripe';\nimport { syncOrder } from './shared';\n\n/**\n * `checkout.session.async_payment_succeeded` and `_failed`: a payment that\n * settles after Checkout (a bank debit, a voucher) is now final either way,\n * and the order's status follows the session's.\n */\nexport async function handleCheckoutAsyncPayment(\n session: Stripe.Checkout.Session,\n locals: App.Locals\n) {\n await syncOrder(session, locals);\n}\n", i = "import type Stripe from 'stripe';\nimport { syncOrder } from './shared';\n\n/** `checkout.session.completed`: the buyer finished Checkout; the payment may still be settling. */\nexport async function handleCheckoutSessionCompleted(\n session: Stripe.Checkout.Session,\n locals: App.Locals\n) {\n await syncOrder(session, locals);\n}\n", a = "import { beforeAll, describe, expect, it } from 'vitest';\nimport type Stripe from 'stripe';\nimport stripe from '#lib/stripe.js';\nimport { handleCheckoutSessionCompleted } from './completed';\n\n/**\n * A real test-mode Checkout Session stands in for the webhook's payload: its\n * line items come from Stripe either way, and an unpaid session lists them\n * just as a paid one does.\n */\ndescribe('checkout.session.completed', () => {\n let session: Stripe.Checkout.Session;\n\n beforeAll(async () => {\n const name = 'Test Product - Orders';\n const found = await stripe.products.search({\n query: `name:\"${name}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1\n });\n const product =\n found.data[0] ?? (await stripe.products.create({ name, metadata: { test: 'true' } }));\n const price =\n (await stripe.prices.list({ product: product.id, active: true, limit: 1 })).data[0] ??\n (await stripe.prices.create({ product: product.id, unit_amount: 1500, currency: 'usd' }));\n session = await stripe.checkout.sessions.create({\n mode: 'payment',\n line_items: [{ price: price.id, quantity: 2 }],\n success_url: 'https://example.com/checkout/success',\n cancel_url: 'https://example.com/cart'\n });\n });\n\n it('records the order and its lines, and a redelivery updates them', async (context) => {\n await handleCheckoutSessionCompleted(session, { admin: context.admin } as App.Locals);\n\n const order = await context.admin.collection('orders').getOne(session.id);\n expect(order.status).toBe('unpaid');\n expect(order.amount_total).toBe(3000);\n expect(order.currency).toBe('USD');\n\n const lines = await context.admin.collection('order_lines').getFullList({\n filter: context.admin.filter('order = {:order}', { order: session.id })\n });\n expect(lines).toHaveLength(1);\n expect(lines[0].quantity).toBe(2);\n expect(lines[0].unit_amount).toBe(1500);\n expect(lines[0].name).toBe('Test Product - Orders');\n\n await handleCheckoutSessionCompleted(session, { admin: context.admin } as App.Locals);\n expect(\n await context.admin.collection('order_lines').getFullList({\n filter: context.admin.filter('order = {:order}', { order: session.id })\n })\n ).toHaveLength(1);\n\n // The lines go with the order.\n await context.admin.collection('orders').delete(session.id);\n });\n});\n", o = "import type Stripe from 'stripe';\nimport type { RecordModel } from 'pocketbase';\nimport stripe from '#lib/stripe.js';\n\n/**\n * What a Checkout Session becomes in `orders`: keyed by the session id, so a\n * redelivered or replayed event updates the row it already made. `status` is\n * Stripe's `payment_status` (`paid`, `unpaid`, `no_payment_required`); an\n * order whose payment clears later (a bank debit) is created `unpaid` and\n * updated by the async payment event.\n */\nexport function orderRecordFields(session: Stripe.Checkout.Session) {\n const paymentIntent =\n typeof session.payment_intent === 'string'\n ? session.payment_intent\n : (session.payment_intent?.id ?? null);\n return {\n status: session.payment_status,\n amount_total: session.amount_total ?? 0,\n currency: (session.currency ?? '').toUpperCase(),\n email: session.customer_details?.email ?? null,\n payment_intent: paymentIntent\n };\n}\n\n/**\n * Records the session as an order with its lines, from Stripe's own line\n * items (the webhook payload carries none). Returns the stored order.\n */\nexport async function syncOrder(\n session: Stripe.Checkout.Session,\n locals: App.Locals\n): Promise<RecordModel> {\n const orders = locals.admin.collection('orders');\n const fields = orderRecordFields(session);\n let order: RecordModel;\n try {\n order = await orders.update(session.id, fields);\n } catch {\n order = await orders.create({ id: session.id, ...fields });\n }\n\n const lines = locals.admin.collection('order_lines');\n for await (const line of stripe.checkout.sessions.listLineItems(session.id, {\n limit: 100,\n expand: ['data.price.product']\n })) {\n const product = line.price?.product;\n const lineFields = {\n order: session.id,\n price: line.price?.id ?? null,\n product: typeof product === 'string' ? product : (product?.id ?? null),\n name: line.description,\n unit_amount: line.price?.unit_amount ?? null,\n quantity: line.quantity ?? 1,\n amount_total: line.amount_total,\n currency: line.currency.toUpperCase()\n };\n try {\n await lines.update(line.id, lineFields);\n } catch {\n await lines.create({ id: line.id, ...lineFields });\n }\n }\n return order;\n}\n", s = "import { redirect } from '@sveltejs/kit';\n\n/** The fields of an order this page reads. */\ninterface OrderRecord {\n id: string;\n status: string;\n amount_total: number;\n currency: string;\n created: string;\n}\n\n/** The signed-in user's orders, newest first. */\nexport const load = async ({ locals, parent }) => {\n const { user } = await parent();\n if (!user) redirect(303, '/login');\n\n const orders = await locals.admin.collection('orders').getFullList<OrderRecord>({\n filter: locals.admin.filter('user = {:user}', { user: user.id }),\n sort: '-created'\n });\n\n return {\n orders: orders.map((order) => ({\n id: order.id,\n status: order.status,\n amountTotal: order.amount_total,\n currency: order.currency,\n created: order.created\n }))\n };\n};\n", c = "<script lang=\"ts\">\n import * as Card from '#lib/components/ui/card/index.js';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import { formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n const when = (iso: string) =>\n new Date(iso).toLocaleDateString(undefined, { dateStyle: 'medium' });\n<\/script>\n\n<div class=\"flex flex-col gap-6\">\n <div>\n <h1 class=\"text-2xl font-semibold\">Orders</h1>\n <p class=\"text-muted-foreground text-sm\">What you have bought here.</p>\n </div>\n\n {#if data.orders.length === 0}\n <p class=\"text-muted-foreground text-sm\">No orders yet.</p>\n {:else}\n <Card.Root>\n <Card.Content class=\"p-0\">\n <ul class=\"divide-y\">\n {#each data.orders as order (order.id)}\n <li>\n <a\n href=\"/orders/{order.id}\"\n class=\"hover:bg-muted/50 flex items-center justify-between gap-4 px-6 py-4\"\n >\n <div class=\"flex flex-col\">\n <span class=\"font-medium\">{when(order.created)}</span>\n <span class=\"text-muted-foreground text-xs\">{order.id}</span>\n </div>\n <div class=\"flex items-center gap-3\">\n <Badge variant={order.status === 'paid' ? 'default' : 'secondary'}>\n {order.status === 'paid' ? 'Paid' : 'Pending'}\n </Badge>\n <span class=\"font-medium\">{formatAmount(order.amountTotal, order.currency)}</span>\n </div>\n </a>\n </li>\n {/each}\n </ul>\n </Card.Content>\n </Card.Root>\n {/if}\n</div>\n", l = "import { error, redirect } from '@sveltejs/kit';\n\ninterface OrderRecord {\n id: string;\n status: string;\n amount_total: number;\n currency: string;\n email: string | null;\n user: string;\n created: string;\n}\n\ninterface OrderLineRecord {\n id: string;\n name: string;\n quantity: number;\n unit_amount: number | null;\n amount_total: number;\n currency: string;\n}\n\n/** One of the signed-in user's orders, with its lines. Anyone else's is not found. */\nexport const load = async ({ locals, params, parent }) => {\n const { user } = await parent();\n if (!user) redirect(303, '/login');\n\n const order = await locals.admin\n .collection('orders')\n .getOne<OrderRecord>(params.id)\n .catch(() => null);\n if (!order || order.user !== user.id) error(404, 'Not found');\n\n const lines = await locals.admin.collection('order_lines').getFullList<OrderLineRecord>({\n filter: locals.admin.filter('order = {:order}', { order: order.id }),\n sort: 'created'\n });\n\n return {\n order: {\n id: order.id,\n status: order.status,\n amountTotal: order.amount_total,\n currency: order.currency,\n email: order.email,\n created: order.created\n },\n lines: lines.map((line) => ({\n id: line.id,\n name: line.name,\n quantity: line.quantity,\n unitAmount: line.unit_amount,\n amountTotal: line.amount_total,\n currency: line.currency\n }))\n };\n};\n", u = "<script lang=\"ts\">\n import * as Card from '#lib/components/ui/card/index.js';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import { Separator } from '#lib/components/ui/separator/index.js';\n import { formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n const when = new Date(data.order.created).toLocaleDateString(undefined, { dateStyle: 'long' });\n<\/script>\n\n<div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/orders\">Orders</a></p>\n <h1 class=\"text-2xl font-semibold\">Order of {when}</h1>\n <p class=\"text-muted-foreground text-xs\">{data.order.id}</p>\n </div>\n\n <Card.Root>\n <Card.Header class=\"flex flex-row items-center justify-between\">\n <Card.Title>Items</Card.Title>\n <Badge variant={data.order.status === 'paid' ? 'default' : 'secondary'}>\n {data.order.status === 'paid' ? 'Paid' : 'Pending'}\n </Badge>\n </Card.Header>\n <Card.Content class=\"flex flex-col gap-4\">\n <ul class=\"divide-y\">\n {#each data.lines as line (line.id)}\n <li class=\"flex items-center justify-between gap-4 py-3\">\n <div class=\"flex flex-col\">\n <span class=\"font-medium\">{line.name}</span>\n {#if line.unitAmount !== null}\n <span class=\"text-muted-foreground text-sm\">\n {line.quantity} × {formatAmount(line.unitAmount, line.currency)}\n </span>\n {/if}\n </div>\n <span>{formatAmount(line.amountTotal, line.currency)}</span>\n </li>\n {/each}\n </ul>\n <Separator />\n <div class=\"flex justify-between font-medium\">\n <span>Total</span>\n <span>{formatAmount(data.order.amountTotal, data.order.currency)}</span>\n </div>\n </Card.Content>\n </Card.Root>\n</div>\n", d = "import type Stripe from 'stripe';\nimport type { RecordModel } from 'pocketbase';\nimport stripe from '#lib/stripe.js';\n\n/**\n * What a Checkout Session becomes in `orders`: keyed by the session id, so a\n * redelivered or replayed event updates the row it already made. `status` is\n * Stripe's `payment_status` (`paid`, `unpaid`, `no_payment_required`); an\n * order whose payment clears later (a bank debit) is created `unpaid` and\n * updated by the async payment event.\n *\n * A signed-in buyer checked out as their Stripe customer, which\n * `stripe_customers` maps back to the user; a guest has only an email.\n */\nexport async function orderRecordFields(session: Stripe.Checkout.Session, locals: App.Locals) {\n const paymentIntent =\n typeof session.payment_intent === 'string'\n ? session.payment_intent\n : (session.payment_intent?.id ?? null);\n const customerId =\n typeof session.customer === 'string' ? session.customer : (session.customer?.id ?? null);\n const customer = customerId\n ? await locals.admin\n .collection('stripe_customers')\n .getOne<{ id: string; user: string }>(customerId)\n .catch(() => null)\n : null;\n return {\n status: session.payment_status,\n amount_total: session.amount_total ?? 0,\n currency: (session.currency ?? '').toUpperCase(),\n email: session.customer_details?.email ?? null,\n payment_intent: paymentIntent,\n customer: customer?.id ?? null,\n user: customer?.user ?? null\n };\n}\n\n/**\n * Records the session as an order with its lines, from Stripe's own line\n * items (the webhook payload carries none). Returns the stored order.\n */\nexport async function syncOrder(\n session: Stripe.Checkout.Session,\n locals: App.Locals\n): Promise<RecordModel> {\n const orders = locals.admin.collection('orders');\n const fields = await orderRecordFields(session, locals);\n let order: RecordModel;\n try {\n order = await orders.update(session.id, fields);\n } catch {\n order = await orders.create({ id: session.id, ...fields });\n }\n\n const lines = locals.admin.collection('order_lines');\n for await (const line of stripe.checkout.sessions.listLineItems(session.id, {\n limit: 100,\n expand: ['data.price.product']\n })) {\n const product = line.price?.product;\n const lineFields = {\n order: session.id,\n price: line.price?.id ?? null,\n product: typeof product === 'string' ? product : (product?.id ?? null),\n name: line.description,\n unit_amount: line.price?.unit_amount ?? null,\n quantity: line.quantity ?? 1,\n amount_total: line.amount_total,\n currency: line.currency.toUpperCase()\n };\n try {\n await lines.update(line.id, lineFields);\n } catch {\n await lines.create({ id: line.id, ...lineFields });\n }\n }\n return order;\n}\n", f = "import type Stripe from 'stripe';\nimport { notify } from '#lib/server/notifications.js';\nimport { formatAmount } from '#lib/cart.svelte.js';\nimport { syncOrder } from './shared';\n\n/**\n * `checkout.session.completed`: the buyer finished Checkout; the payment may\n * still be settling. A signed-in buyer gets a notification once it is paid.\n */\nexport async function handleCheckoutSessionCompleted(\n session: Stripe.Checkout.Session,\n locals: App.Locals\n) {\n const order = await syncOrder(session, locals);\n if (order.user && order.status === 'paid') {\n await notify(locals.admin, order.user, {\n title: 'Order received',\n body: `Your order of ${formatAmount(order.amount_total, order.currency)} is confirmed.`\n });\n }\n}\n", p = /* #__PURE__ */ Object.assign({
4
+ "./creates/src/routes/webhooks/stripe/handlers/checkout/async-payment.ts": r,
5
+ "./creates/src/routes/webhooks/stripe/handlers/checkout/completed.ts": i,
6
+ "./creates/src/routes/webhooks/stripe/handlers/checkout/server.test.ts": a,
7
+ "./creates/src/routes/webhooks/stripe/handlers/checkout/shared.ts": o
8
+ }), m = /* #__PURE__ */ Object.assign({
9
+ "./creates-app-mode/src/routes/(app)/orders/+page.server.ts": s,
10
+ "./creates-app-mode/src/routes/(app)/orders/+page.svelte": c,
11
+ "./creates-app-mode/src/routes/(app)/orders/[id]/+page.server.ts": l,
12
+ "./creates-app-mode/src/routes/(app)/orders/[id]/+page.svelte": u,
13
+ "./creates-app-mode/src/routes/webhooks/stripe/handlers/checkout/shared.ts": d
14
+ }), h = /* #__PURE__ */ Object.assign({ "./creates-notifications/src/routes/webhooks/stripe/handlers/checkout/completed.ts": f }), g = ["orders", "order_lines"];
15
+ function _(e) {
16
+ return {
17
+ name: "orders",
18
+ type: "base",
19
+ fields: [
20
+ {
21
+ name: "id",
22
+ pattern: "^[a-zA-Z0-9_]+$",
23
+ primaryKey: !0,
24
+ required: !0,
25
+ system: !0,
26
+ type: "text"
27
+ },
28
+ {
29
+ name: "status",
30
+ required: !0,
31
+ type: "text"
32
+ },
33
+ {
34
+ name: "amount_total",
35
+ required: !1,
36
+ type: "number"
37
+ },
38
+ {
39
+ name: "currency",
40
+ required: !1,
41
+ type: "text"
42
+ },
43
+ {
44
+ name: "email",
45
+ required: !1,
46
+ type: "text"
47
+ },
48
+ {
49
+ name: "payment_intent",
50
+ required: !1,
51
+ type: "text"
52
+ },
53
+ {
54
+ name: "customer",
55
+ required: !1,
56
+ type: "text"
57
+ },
58
+ ...e ? [{
59
+ collectionId: "_pb_users_auth_",
60
+ maxSelect: 1,
61
+ minSelect: 0,
62
+ name: "user",
63
+ required: !1,
64
+ type: "relation"
65
+ }] : [],
66
+ {
67
+ name: "created",
68
+ onCreate: !0,
69
+ onUpdate: !1,
70
+ type: "autodate"
71
+ },
72
+ {
73
+ name: "updated",
74
+ onCreate: !0,
75
+ onUpdate: !0,
76
+ type: "autodate"
77
+ }
78
+ ]
79
+ };
80
+ }
81
+ var v = {
82
+ name: "order_lines",
83
+ type: "base",
84
+ fields: [
85
+ {
86
+ name: "id",
87
+ pattern: "^[a-zA-Z0-9_]+$",
88
+ primaryKey: !0,
89
+ required: !0,
90
+ system: !0,
91
+ type: "text"
92
+ },
93
+ {
94
+ collectionId: "orders",
95
+ maxSelect: 1,
96
+ minSelect: 0,
97
+ name: "order",
98
+ required: !0,
99
+ type: "relation",
100
+ cascadeDelete: !0
101
+ },
102
+ {
103
+ name: "price",
104
+ required: !1,
105
+ type: "text"
106
+ },
107
+ {
108
+ name: "product",
109
+ required: !1,
110
+ type: "text"
111
+ },
112
+ {
113
+ name: "name",
114
+ required: !1,
115
+ type: "text"
116
+ },
117
+ {
118
+ name: "unit_amount",
119
+ required: !1,
120
+ type: "number"
121
+ },
122
+ {
123
+ name: "quantity",
124
+ required: !1,
125
+ type: "number"
126
+ },
127
+ {
128
+ name: "amount_total",
129
+ required: !1,
130
+ type: "number"
131
+ },
132
+ {
133
+ name: "currency",
134
+ required: !1,
135
+ type: "text"
136
+ },
137
+ {
138
+ name: "created",
139
+ onCreate: !0,
140
+ onUpdate: !1,
141
+ type: "autodate"
142
+ },
143
+ {
144
+ name: "updated",
145
+ onCreate: !0,
146
+ onUpdate: !0,
147
+ type: "autodate"
148
+ }
149
+ ]
150
+ };
151
+ async function y(t) {
152
+ let n = t.features.auth, r = new Map(Object.values(e(p, "./creates/")).map((e) => [e.path, e]));
153
+ if (n) {
154
+ for (let t of Object.values(e(m, "./creates-app-mode/"))) r.set(t.path, t);
155
+ if (t.features.notifications) for (let t of Object.values(e(h, "./creates-notifications/"))) r.set(t.path, t);
156
+ }
157
+ return {
158
+ creates: [...r.values()].sort((e, t) => e.path.localeCompare(t.path)),
159
+ modifies: [],
160
+ deletes: [],
161
+ components: n ? [
162
+ "card",
163
+ "badge",
164
+ "separator"
165
+ ] : [],
166
+ packages: [],
167
+ collections: [_(n), v],
168
+ collectionPatches: [],
169
+ collectionDrops: []
170
+ };
171
+ }
172
+ //#endregion
173
+ export { u as a, s as c, i as d, r as f, d as i, o as l, t as m, y as n, l as o, n as p, f as r, c as s, g as t, a as u };
174
+
175
+ //# sourceMappingURL=generate-BrOPb9tW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-BrOPb9tW.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__1_2_","__import_glob__1_3_","__import_glob__1_4_","__import_glob__2_0_","filesFromGlob","_page_server_default$2","_page_default$2","async_payment_default","completed_default$1","server_test_default","shared_default$1","_page_server_default$1","_page_default$1","_page_server_default","_page_default","shared_default","completed_default","createsRaw","createsAppModeRaw","createsNotificationsRaw","ORDER_COLLECTIONS","orders","appMode","orderLines","generate","options","creates","file","a","b"],"sources":["../../src/patterns/enable/orders/generate.ts"],"sourcesContent":["import type { CollectionSpec, Options, Result } from \"../../../core/types\";\nimport { filesFromGlob } from \"../../../core/util\";\n\nconst createsRaw = import.meta.glob<string>(\"./creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n// A signed-in buyer's orders: the user link on the record, and the pages\n// that list them.\nconst createsAppModeRaw = import.meta.glob<string>(\"./creates-app-mode/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n// With enable-notifications: a paid order drops a notification on its user.\nconst createsNotificationsRaw = import.meta.glob<string>(\n \"./creates-notifications/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n/** The collections in the order they are created, and dropped in reverse. */\nexport const ORDER_COLLECTIONS = [\"orders\", \"order_lines\"];\n\n/**\n * One row per Checkout Session, keyed by its id so Stripe's redeliveries and\n * replays update rather than duplicate. With auth, the buyer's user.\n */\nfunction orders(appMode: boolean): CollectionSpec {\n return {\n name: \"orders\",\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 // Stripe's payment_status: paid, unpaid, no_payment_required.\n { name: \"status\", required: true, type: \"text\" },\n { name: \"amount_total\", required: false, type: \"number\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"email\", required: false, type: \"text\" },\n { name: \"payment_intent\", required: false, type: \"text\" },\n // The Stripe customer id as text, not a relation: `stripe_customers`\n // exists only when payments came after auth, and a guest has none.\n { name: \"customer\", required: false, type: \"text\" },\n ...(appMode\n ? [\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: false,\n type: \"relation\",\n },\n ]\n : []),\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n };\n}\n\n/** A snapshot of each line as Stripe priced it, keyed by Stripe's line item id. */\nconst orderLines: CollectionSpec = {\n name: \"order_lines\",\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: \"orders\",\n maxSelect: 1,\n minSelect: 0,\n name: \"order\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n { name: \"price\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"quantity\", required: false, type: \"number\" },\n { name: \"amount_total\", required: false, type: \"number\" },\n { name: \"currency\", 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\nexport async function generate(options: Options) {\n const appMode = options.features.auth;\n const creates = new Map(\n Object.values(filesFromGlob(createsRaw, \"./creates/\")).map((file) => [\n file.path,\n file,\n ]),\n );\n if (appMode) {\n for (const file of Object.values(\n filesFromGlob(createsAppModeRaw, \"./creates-app-mode/\"),\n )) {\n creates.set(file.path, file);\n }\n if (options.features.notifications) {\n for (const file of Object.values(\n filesFromGlob(createsNotificationsRaw, \"./creates-notifications/\"),\n )) {\n creates.set(file.path, file);\n }\n }\n }\n\n return {\n creates: [...creates.values()].sort((a, b) => a.path.localeCompare(b.path)),\n modifies: [],\n deletes: [],\n components: appMode ? [\"card\", \"badge\", \"separator\"] : [],\n packages: [],\n collections: [orders(appMode), orderLines],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;A,6yeAGMuB,IAAa,uBAAA,OAAA;CAAA,2EAAAvB;CAAA,uEAAAC;CAAA,yEAAAC;CAAA,oEAAAC;AAIlB,CAAA,GAGKqB,IAAoB,uBAAA,OAAA;CAAA,8DAAApB;CAAA,2DAAAC;CAAA,mEAAAC;CAAA,gEAAAC;CAAA,6EAAAC;AAIzB,CAAA,GAEKiB,IAA0B,uBAAA,OAAA,EAAA,qFAAAhB,EAGhC,CAAA,GAGaiB,IAAoB,CAAC,UAAU,aAAa;AAMzD,SAASC,EAAO,GAAkC;CAChD,OAAO;EACL,MAAM;EACN,MAAM;EACN,QAAQ;GACN;IACE,MAAM;IACN,SAAS;IACT,YAAY;IACZ,UAAU;IACV,QAAQ;IACR,MAAM;GACR;GAEA;IAAE,MAAM;IAAU,UAAU;IAAM,MAAM;GAAO;GAC/C;IAAE,MAAM;IAAgB,UAAU;IAAO,MAAM;GAAS;GACxD;IAAE,MAAM;IAAY,UAAU;IAAO,MAAM;GAAO;GAClD;IAAE,MAAM;IAAS,UAAU;IAAO,MAAM;GAAO;GAC/C;IAAE,MAAM;IAAkB,UAAU;IAAO,MAAM;GAAO;GAGxD;IAAE,MAAM;IAAY,UAAU;IAAO,MAAM;GAAO;GAClD,GAAIC,IACA,CACE;IACE,cAAc;IACd,WAAW;IACX,WAAW;IACX,MAAM;IACN,UAAU;IACV,MAAM;GACR,CACF,IACA,CAAC;GACL;IAAE,MAAM;IAAW,UAAU;IAAM,UAAU;IAAO,MAAM;GAAW;GACrE;IAAE,MAAM;IAAW,UAAU;IAAM,UAAU;IAAM,MAAM;GAAW;EACtE;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,MAAME,EAAE,KAAK,cAAcC,EAAE,IAAI,CAAC;EAC1E,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAYP,IAAU;GAAC;GAAQ;GAAS;EAAW,IAAI,CAAC;EACxD,UAAU,CAAC;EACX,aAAa,CAACD,EAAOC,CAAO,GAAGC,CAAU;EACzC,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -0,0 +1,162 @@
1
+ import { a as e } from "./util-BLYliuUK.js";
2
+ import { t } from "./dedent-Gq6Krl4n.js";
3
+ import { n } from "./logger-CQONztPm.js";
4
+ import { n as r, t as i } from "./_page-B6yd6_Vl.js";
5
+ import { _ as a, o, r as s, u as c } from "./ts-morph-helpers-CHI9wAil.js";
6
+ import { r as l } from "./modify-file-B4uJzOEj.js";
7
+ import { t as u } from "./modify-nav-user-iUpv2lm-.js";
8
+ import d from "node:fs";
9
+ import f from "node:path";
10
+ import { Node as p, SyntaxKind as m } from "ts-morph";
11
+ //#region src/patterns/enable/orders/modifies/modify-webhook-server.ts
12
+ var h = "./checkout/completed", g = "./checkout/async-payment", _ = [
13
+ "checkout.session.completed",
14
+ "checkout.session.async_payment_succeeded",
15
+ "checkout.session.async_payment_failed"
16
+ ], v = t`
17
+ case 'checkout.session.completed':
18
+ await handleCheckoutSessionCompleted(event.data.object, locals);
19
+ break;
20
+
21
+ case 'checkout.session.async_payment_succeeded':
22
+ case 'checkout.session.async_payment_failed':
23
+ await handleCheckoutAsyncPayment(event.data.object, locals);
24
+ break;
25
+ `, y = t`
26
+ Route the Checkout Session events to the order handlers in src/routes/webhooks/stripe/handlers/dispatch.ts:
27
+
28
+ import { handleCheckoutSessionCompleted } from '${h}';
29
+ import { handleCheckoutAsyncPayment } from '${g}';
30
+
31
+ and, inside the \`switch (event.type)\`:
32
+
33
+ ${v.split("\n").join("\n ")}
34
+ `, b = "Enable payments first: src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.";
35
+ function x(e) {
36
+ return e.getDescendantsOfKind(m.SwitchStatement).find((e) => e.getExpression().getText().includes("event.type"));
37
+ }
38
+ function S(e) {
39
+ if (!d.existsSync(e)) return {
40
+ status: "not-found",
41
+ message: b
42
+ };
43
+ let t = d.readFileSync(e, "utf8");
44
+ if (t.includes("handleCheckoutSessionCompleted")) return {
45
+ status: "success",
46
+ changed: !1
47
+ };
48
+ let n = !1, { source: r } = a(t, (e) => {
49
+ let t = x(e);
50
+ if (!t) return;
51
+ let r = t.getCaseBlock().getClauses(), i = r.find(p.isDefaultClause);
52
+ if (i) i.replaceWithText(`${v}\n\n${i.getText()}`);
53
+ else if (r.length > 0) {
54
+ let e = r[r.length - 1];
55
+ e.replaceWithText(`${e.getText()}\n\n${v}`);
56
+ } else return;
57
+ s(e, [{
58
+ namedImports: ["handleCheckoutSessionCompleted"],
59
+ moduleSpecifier: h
60
+ }, {
61
+ namedImports: ["handleCheckoutAsyncPayment"],
62
+ moduleSpecifier: g
63
+ }]), o(e), n = !0;
64
+ });
65
+ return n ? (d.writeFileSync(e, r, "utf8"), {
66
+ status: "success",
67
+ changed: !0
68
+ }) : {
69
+ status: "failed",
70
+ message: y
71
+ };
72
+ }
73
+ function C(e) {
74
+ if (!d.existsSync(e)) return {
75
+ status: "success",
76
+ changed: !1
77
+ };
78
+ let t = d.readFileSync(e, "utf8");
79
+ if (!t.includes("handleCheckoutSessionCompleted")) return {
80
+ status: "success",
81
+ changed: !1
82
+ };
83
+ let { source: n } = a(t, (e) => {
84
+ let t = x(e);
85
+ if (t) {
86
+ let n = t.getCaseBlock().getClauses(), r = (e) => {
87
+ if (!p.isCaseClause(e)) return !1;
88
+ let t = e.getExpression();
89
+ return p.isStringLiteral(t) && _.includes(t.getLiteralText());
90
+ }, i = [];
91
+ for (let e = n.length - 1; e >= 0; e--) {
92
+ if (!r(n[e])) continue;
93
+ let t = e;
94
+ for (; t > 0 && r(n[t - 1]);) t--;
95
+ let a = t > 0 ? n[t - 1].getEnd() : n[t].getStart();
96
+ i.push([a, n[e].getEnd()]), e = t;
97
+ }
98
+ for (let [t, n] of i) e.removeText(t, n);
99
+ }
100
+ c(e, h), c(e, g), o(e);
101
+ });
102
+ return d.writeFileSync(e, n, "utf8"), {
103
+ status: "success",
104
+ changed: n !== t
105
+ };
106
+ }
107
+ //#endregion
108
+ //#region src/patterns/enable/orders/generate.runtime.ts
109
+ var w = "src/routes/(public)/checkout/success", T = f.join("src", "lib", "components", "nav-user.svelte");
110
+ async function E(t) {
111
+ let a = n(t), o = [], s = (e) => {
112
+ e && o.push(e);
113
+ };
114
+ a.info("Routing the Checkout Session events in webhooks/stripe/handlers/dispatch.ts");
115
+ let c = f.join(t.root, "src", "routes", "webhooks", "stripe", "handlers", "dispatch.ts");
116
+ s(l(c, S(c))), a.info("Showing the order on /checkout/success");
117
+ for (let [n, a] of [["+page.server.ts", r], ["+page.svelte", i]]) {
118
+ let r = f.join(t.root, w, n);
119
+ d.existsSync(r) && d.readFileSync(r, "utf8") === a || o.push({
120
+ path: r,
121
+ language: e(r),
122
+ content: a,
123
+ status: "success"
124
+ });
125
+ }
126
+ if (t.features.auth) {
127
+ a.info("Adding Orders to the user menu");
128
+ let n = f.join(t.root, T);
129
+ if (d.existsSync(n)) {
130
+ let t = d.readFileSync(n, "utf8");
131
+ if (!t.includes("'/orders'")) {
132
+ let { newNavUserSnippet: r, wasAdded: i } = u(t, "Orders", "/orders", "PackageIcon", "@lucide/svelte/icons/package");
133
+ i ? (d.writeFileSync(n, r, "utf8"), o.push({
134
+ path: n,
135
+ language: e(n),
136
+ content: r,
137
+ status: "success"
138
+ })) : o.push({
139
+ path: n,
140
+ language: e(n),
141
+ content: t,
142
+ status: "failed",
143
+ message: "Add an Orders item to the navUser array in nav-user.svelte:\n\nimport PackageIcon from '@lucide/svelte/icons/package';\n{ title: 'Orders', url: '/orders', icon: PackageIcon }"
144
+ });
145
+ }
146
+ }
147
+ }
148
+ return {
149
+ creates: [],
150
+ modifies: o,
151
+ deletes: [],
152
+ components: [],
153
+ packages: [],
154
+ collections: [],
155
+ collectionPatches: [],
156
+ collectionDrops: []
157
+ };
158
+ }
159
+ //#endregion
160
+ export { w as SUCCESS_PAGE, E as generate, C as t };
161
+
162
+ //# sourceMappingURL=generate.runtime-DuDcKDUl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate.runtime-DuDcKDUl.js","names":["successServer","successSvelte","languageFromPath","_page_server_default","_page_default","withInMemoryScript","ensureImports","removeImportByModuleSpecifier","modifyOutcomeToFile","addItemToNavUser","fs","path","COMPLETED","ASYNC_PAYMENT","EVENTS","CASES_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","eventSwitch","sf","SyntaxKind","statement","modifyWebhookServer","filePath","original","added","clauses","defaultClause","Node","last","formatLikeSource","source","unmodifyWebhookServer","isOrders","clause","expression","ranges","i","first","start","end","SUCCESS_PAGE","NAV_USER","generate","logger","getLogger","options","modifies","pushResult","file","dispatchPath","name","content","navUserPath","wasAdded","newNavUserSnippet"],"sources":["../../src/patterns/enable/orders/modifies/modify-webhook-server.ts","../../src/patterns/enable/orders/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n formatLikeSource,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst COMPLETED = \"./checkout/completed\";\nconst ASYNC_PAYMENT = \"./checkout/async-payment\";\n\n/** The Checkout Session events the order handlers take. */\nconst EVENTS = [\n \"checkout.session.completed\",\n \"checkout.session.async_payment_succeeded\",\n \"checkout.session.async_payment_failed\",\n];\n\nconst CASES_SNIPPET = dedent`\n case 'checkout.session.completed':\n await handleCheckoutSessionCompleted(event.data.object, locals);\n break;\n\n case 'checkout.session.async_payment_succeeded':\n case 'checkout.session.async_payment_failed':\n await handleCheckoutAsyncPayment(event.data.object, locals);\n break;\n`;\n\nconst FAILURE_HINT = dedent`\n Route the Checkout Session events to the order handlers in src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n import { handleCheckoutSessionCompleted } from '${COMPLETED}';\n import { handleCheckoutAsyncPayment } from '${ASYNC_PAYMENT}';\n\n and, inside the \\`switch (event.type)\\`:\n\n ${CASES_SNIPPET.split(\"\\n\").join(\"\\n \")}\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first: src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\n/** The `switch (event.type)` the dispatcher routes on. */\nfunction eventSwitch(sf: import(\"ts-morph\").SourceFile) {\n return sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((statement) =>\n statement.getExpression().getText().includes(\"event.type\"),\n );\n}\n\n/** The order handlers join the dispatcher's switch, ahead of its default. */\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n let added = false;\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (!statement) return;\n const clauses = statement.getCaseBlock().getClauses();\n const defaultClause = clauses.find(Node.isDefaultClause);\n if (defaultClause) {\n defaultClause.replaceWithText(\n `${CASES_SNIPPET}\\n\\n${defaultClause.getText()}`,\n );\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(`${last.getText()}\\n\\n${CASES_SNIPPET}`);\n } else {\n return;\n }\n ensureImports(sf, [\n {\n namedImports: [\"handleCheckoutSessionCompleted\"],\n moduleSpecifier: COMPLETED,\n },\n {\n namedImports: [\"handleCheckoutAsyncPayment\"],\n moduleSpecifier: ASYNC_PAYMENT,\n },\n ]);\n formatLikeSource(sf);\n added = true;\n });\n if (!added) return { status: \"failed\", message: FAILURE_HINT };\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/** Take the order cases and their imports back out of the dispatcher. */\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(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (statement) {\n // Each run of order clauses goes with the whitespace before it, so the\n // blank line that separated its neighbours is the one that stays.\n const clauses = statement.getCaseBlock().getClauses();\n const isOrders = (clause: (typeof clauses)[number]) => {\n if (!Node.isCaseClause(clause)) return false;\n const expression = clause.getExpression();\n return (\n Node.isStringLiteral(expression) &&\n EVENTS.includes(expression.getLiteralText())\n );\n };\n // Positions first, bottom-up: removing text forgets the nodes after it.\n const ranges: [number, number][] = [];\n for (let i = clauses.length - 1; i >= 0; i--) {\n if (!isOrders(clauses[i])) continue;\n let first = i;\n while (first > 0 && isOrders(clauses[first - 1])) first--;\n const start =\n first > 0 ? clauses[first - 1].getEnd() : clauses[first].getStart();\n ranges.push([start, clauses[i].getEnd()]);\n i = first;\n }\n for (const [start, end] of ranges) sf.removeText(start, end);\n }\n removeImportByModuleSpecifier(sf, COMPLETED);\n removeImportByModuleSpecifier(sf, ASYNC_PAYMENT);\n formatLikeSource(sf);\n });\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: source !== original };\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 { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { addItemToNavUser } from \"../payments/modifies/modify-nav-user\";\nimport successServer from \"./preview-modifies/src/routes/(public)/checkout/success/+page.server.ts?raw\";\nimport successSvelte from \"./preview-modifies/src/routes/(public)/checkout/success/+page.svelte?raw\";\n\n/** The success page, which enable-ecommerce wrote and this pattern rewrites to show the order. */\nexport const SUCCESS_PAGE = \"src/routes/(public)/checkout/success\";\n\nconst NAV_USER = path.join(\"src\", \"lib\", \"components\", \"nav-user.svelte\");\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(\n \"Routing the Checkout Session events in webhooks/stripe/handlers/dispatch.ts\",\n );\n const dispatchPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(dispatchPath, modifyWebhookServer(dispatchPath)),\n );\n\n // A rewrite rather than an edit: the page's load changes shape (the order\n // and its lines, then Stripe's summary as the fallback).\n logger.info(\"Showing the order on /checkout/success\");\n for (const [name, content] of [\n [\"+page.server.ts\", successServer],\n [\"+page.svelte\", successSvelte],\n ] as const) {\n const file = path.join(options.root, SUCCESS_PAGE, name);\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === content)\n continue;\n modifies.push({\n path: file,\n language: languageFromPath(file),\n content,\n status: \"success\",\n });\n }\n\n if (options.features.auth) {\n logger.info(\"Adding Orders to the user menu\");\n const navUserPath = path.join(options.root, NAV_USER);\n if (fs.existsSync(navUserPath)) {\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"'/orders'\")) {\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n source,\n \"Orders\",\n \"/orders\",\n \"PackageIcon\",\n \"@lucide/svelte/icons/package\",\n );\n if (wasAdded) {\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: newNavUserSnippet,\n status: \"success\",\n });\n } else {\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: source,\n status: \"failed\",\n message:\n \"Add an Orders item to the navUser array in nav-user.svelte:\\n\\n\" +\n \"import PackageIcon from '@lucide/svelte/icons/package';\\n\" +\n \"{ title: 'Orders', url: '/orders', icon: PackageIcon }\",\n });\n }\n }\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":";;;;;;;;;;;AAWA,IAAMY,IAAY,wBACZC,IAAgB,4BAGhBC,IAAS;CACb;CACA;CACA;AACF,GAEMC,IAAgB,CAAM;;;;;;;;;GAWtBC,IAAe,CAAM;;;oDAGyBJ,EAAU;gDACdC,EAAc;;;;IAI1DE,EAAc,MAAM,IAAI,CAAC,CAAC,KAAK,MAAM,EAAE;GAGrCE,IACJ;AAGF,SAASC,EAAY,GAAmC;CACtD,OAAOC,EACJ,qBAAqBC,EAAW,eAAe,CAAC,CAChD,MAAM,MACLC,EAAU,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAC3D;AACJ;AAGA,SAAgBC,EAAoB,GAAiC;CACnE,IAAI,CAACZ,EAAG,WAAWa,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAASN;CAAe;CAExD,IAAMO,IAAWd,EAAG,aAAaa,GAAU,MAAM;CACjD,IAAIC,EAAS,SAAS,gCAAgC,GACpD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAIC,IAAQ,IACN,EAAE,cAAWpB,EAAmBmB,IAAW,MAAO;EACtD,IAAMH,IAAYH,EAAYC,CAAE;EAChC,IAAI,CAACE,GAAW;EAChB,IAAMK,IAAUL,EAAU,aAAa,CAAC,CAAC,WAAW,GAC9CM,IAAgBD,EAAQ,KAAKE,EAAK,eAAe;EACvD,IAAID,GACF,EAAc,gBACZ,GAAGZ,EAAc,MAAMY,EAAc,QAAQ,GAC/C;OACK,IAAID,EAAQ,SAAS,GAAG;GAC7B,IAAMG,IAAOH,EAAQA,EA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