@velastack/patterns 0.0.32 → 0.0.34
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/dist/chunks/collections-Czm1C8ow.js +108 -0
- package/dist/chunks/collections-Czm1C8ow.js.map +1 -0
- package/dist/chunks/{env.preview-NYMljYNr.js → env.preview-BZwjhgoi.js} +1 -1
- package/dist/chunks/{env.preview-NYMljYNr.js.map → env.preview-BZwjhgoi.js.map} +1 -1
- package/dist/chunks/{env.runtime-ZUZgxjxf.js → env.runtime-BEdollKV.js} +1 -1
- package/dist/chunks/{env.runtime-ZUZgxjxf.js.map → env.runtime-BEdollKV.js.map} +1 -1
- package/dist/chunks/{generate.runtime-uk9-KOP-.js → generate.runtime-BCz-NNqq.js} +123 -117
- package/dist/chunks/generate.runtime-BCz-NNqq.js.map +1 -0
- package/dist/chunks/{generate.runtime-4zd9-8H_.js → generate.runtime-BZ-KaCUr.js} +118 -102
- package/dist/chunks/generate.runtime-BZ-KaCUr.js.map +1 -0
- package/dist/chunks/generate.runtime-Caqa5ndO.js +85 -0
- package/dist/chunks/{generate.runtime-CbiQhqdL.js.map → generate.runtime-Caqa5ndO.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DpeB3h-P.js → generate.runtime-Cbq2649r.js} +94 -91
- package/dist/chunks/{generate.runtime-DpeB3h-P.js.map → generate.runtime-Cbq2649r.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CXqD8em8.js → generate.runtime-D7ksYerH.js} +133 -130
- package/dist/chunks/{generate.runtime-CXqD8em8.js.map → generate.runtime-D7ksYerH.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BKrtBCRk.js → generate.runtime-DTZ1PeDS.js} +94 -91
- package/dist/chunks/{generate.runtime-BKrtBCRk.js.map → generate.runtime-DTZ1PeDS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BkjQiaP_.js → generate.runtime-y1Ga_5QI.js} +70 -64
- package/dist/chunks/{generate.runtime-BkjQiaP_.js.map → generate.runtime-y1Ga_5QI.js.map} +1 -1
- package/dist/chunks/logger-BpgCb-ZG.js +9 -0
- package/dist/chunks/logger-BpgCb-ZG.js.map +1 -0
- package/dist/chunks/{modify-file-D3OuKUEp.js → modify-file-DT_1_kvI.js} +1 -1
- package/dist/chunks/{modify-file-D3OuKUEp.js.map → modify-file-DT_1_kvI.js.map} +1 -1
- package/dist/chunks/{modify-svelte-config-remote-Dzgk1OIN.js → modify-svelte-config-remote-CFsA9Mom.js} +1 -1
- package/dist/chunks/{modify-svelte-config-remote-Dzgk1OIN.js.map → modify-svelte-config-remote-CFsA9Mom.js.map} +1 -1
- package/dist/chunks/{pocketbase--dNkFDJ5.js → pocketbase-BiRWz-OQ.js} +1 -1
- package/dist/chunks/{pocketbase--dNkFDJ5.js.map → pocketbase-BiRWz-OQ.js.map} +1 -1
- package/dist/chunks/{pocketbase-W_FJaYZ3.js → pocketbase-iFJBbNJu.js} +1 -1
- package/dist/chunks/{pocketbase-W_FJaYZ3.js.map → pocketbase-iFJBbNJu.js.map} +1 -1
- package/dist/chunks/{ts-morph-helpers-digNcfBD.js → ts-morph-helpers-C0HeJDjR.js} +1 -1
- package/dist/chunks/{ts-morph-helpers-digNcfBD.js.map → ts-morph-helpers-C0HeJDjR.js.map} +1 -1
- package/dist/chunks/write-result-B0-q-egx.js +219 -0
- package/dist/chunks/{write-result-C80dpjr-.js.map → write-result-B0-q-egx.js.map} +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +664 -659
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunks/collections-BRIAYJ-Q.js +0 -94
- package/dist/chunks/collections-BRIAYJ-Q.js.map +0 -1
- package/dist/chunks/generate.runtime-4zd9-8H_.js.map +0 -1
- package/dist/chunks/generate.runtime-CbiQhqdL.js +0 -82
- package/dist/chunks/generate.runtime-uk9-KOP-.js.map +0 -1
- package/dist/chunks/write-result-C80dpjr-.js +0 -216
package/dist/index.js
CHANGED
|
@@ -3,25 +3,26 @@ import { t } from "./chunks/dedent-C4qKBQXh.js";
|
|
|
3
3
|
import { n, r, t as i } from "./chunks/util-C064WO8o.js";
|
|
4
4
|
import { i as a, t as o } from "./chunks/constants-BMZmCRiI.js";
|
|
5
5
|
import { t as s } from "./chunks/taggedTemplateLiteral-Bfbldyfk.js";
|
|
6
|
-
import {
|
|
7
|
-
import l from "
|
|
8
|
-
import u from "prettier
|
|
6
|
+
import { n as c } from "./chunks/logger-BpgCb-ZG.js";
|
|
7
|
+
import { t as l } from "./chunks/pocketbase-BiRWz-OQ.js";
|
|
8
|
+
import u from "prettier";
|
|
9
|
+
import d from "prettier-plugin-svelte";
|
|
9
10
|
//#region \0rolldown/runtime.js
|
|
10
|
-
var
|
|
11
|
-
if (t && typeof t == "object" || typeof t == "function") for (var i =
|
|
11
|
+
var f = Object.create, p = Object.defineProperty, m = Object.getOwnPropertyDescriptor, h = Object.getOwnPropertyNames, ee = Object.getPrototypeOf, g = Object.prototype.hasOwnProperty, te = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), ne = (e, t, n, r) => {
|
|
12
|
+
if (t && typeof t == "object" || typeof t == "function") for (var i = h(t), a = 0, o = i.length, s; a < o; a++) s = i[a], !g.call(e, s) && s !== n && p(e, s, {
|
|
12
13
|
get: ((e) => t[e]).bind(null, s),
|
|
13
|
-
enumerable: !(r =
|
|
14
|
+
enumerable: !(r = m(t, s)) || r.enumerable
|
|
14
15
|
});
|
|
15
16
|
return e;
|
|
16
|
-
},
|
|
17
|
+
}, re = (e, t, n) => (n = e == null ? {} : f(ee(e)), ne(t || !e || !e.__esModule ? p(n, "default", {
|
|
17
18
|
value: e,
|
|
18
19
|
enumerable: !0
|
|
19
|
-
}) : n, e)),
|
|
20
|
+
}) : n, e)), ie = /* @__PURE__ */ ((e) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(e, { get: (e, t) => (typeof require < "u" ? require : e)[t] }) : e)(function(e) {
|
|
20
21
|
if (typeof require < "u") return require.apply(this, arguments);
|
|
21
22
|
throw Error("Calling `require` for \"" + e + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
|
|
22
|
-
}),
|
|
23
|
+
}), ae = {
|
|
23
24
|
name: "@velastack/patterns",
|
|
24
|
-
version: "0.0.
|
|
25
|
+
version: "0.0.34",
|
|
25
26
|
type: "module",
|
|
26
27
|
private: !1,
|
|
27
28
|
main: "./dist/index.js",
|
|
@@ -45,7 +46,7 @@ var d = Object.create, f = Object.defineProperty, p = Object.getOwnPropertyDescr
|
|
|
45
46
|
"prettier-plugin-svelte": "^3.5.1"
|
|
46
47
|
},
|
|
47
48
|
peerDependencies: {
|
|
48
|
-
"@velastack/pocketbase": "^0.0.
|
|
49
|
+
"@velastack/pocketbase": "^0.0.46",
|
|
49
50
|
"cross-spawn": "^7.0.6",
|
|
50
51
|
"magic-string": "^0.30.21",
|
|
51
52
|
"package-manager-detector": "^1.6.0",
|
|
@@ -68,7 +69,7 @@ var d = Object.create, f = Object.defineProperty, p = Object.getOwnPropertyDescr
|
|
|
68
69
|
"@types/cross-spawn": "^6.0.6",
|
|
69
70
|
"@types/node": "^22.0.0",
|
|
70
71
|
"@types/pluralize": "^0.0.33",
|
|
71
|
-
"@velastack/pocketbase": "^0.0.
|
|
72
|
+
"@velastack/pocketbase": "^0.0.46",
|
|
72
73
|
"change-case": "^5.4.4",
|
|
73
74
|
"cross-spawn": "^7.0.6",
|
|
74
75
|
dedent: "^1.7.2",
|
|
@@ -88,15 +89,15 @@ var d = Object.create, f = Object.defineProperty, p = Object.getOwnPropertyDescr
|
|
|
88
89
|
};
|
|
89
90
|
//#endregion
|
|
90
91
|
//#region src/core/format-result.ts
|
|
91
|
-
function
|
|
92
|
+
function oe(e) {
|
|
92
93
|
return e.language === "ts" || e.language === "svelte" || e.path.endsWith(".json");
|
|
93
94
|
}
|
|
94
|
-
async function
|
|
95
|
-
if (e.status !== "success" || !
|
|
95
|
+
async function se(e) {
|
|
96
|
+
if (e.status !== "success" || !oe(e)) return e;
|
|
96
97
|
try {
|
|
97
|
-
let t = await
|
|
98
|
+
let t = await u.format(e.content, {
|
|
98
99
|
filepath: e.path,
|
|
99
|
-
plugins: [
|
|
100
|
+
plugins: [d]
|
|
100
101
|
});
|
|
101
102
|
return {
|
|
102
103
|
...e,
|
|
@@ -106,11 +107,11 @@ async function oe(e) {
|
|
|
106
107
|
return e;
|
|
107
108
|
}
|
|
108
109
|
}
|
|
109
|
-
async function
|
|
110
|
-
return Promise.all(e.map((e) =>
|
|
110
|
+
async function ce(e) {
|
|
111
|
+
return Promise.all(e.map((e) => se(e)));
|
|
111
112
|
}
|
|
112
113
|
async function _(e) {
|
|
113
|
-
let [t, n] = await Promise.all([
|
|
114
|
+
let [t, n] = await Promise.all([ce(e.creates), ce(e.modifies)]);
|
|
114
115
|
return {
|
|
115
116
|
...e,
|
|
116
117
|
creates: t,
|
|
@@ -119,7 +120,7 @@ async function _(e) {
|
|
|
119
120
|
}
|
|
120
121
|
//#endregion
|
|
121
122
|
//#region src/core/field/index.ts
|
|
122
|
-
var
|
|
123
|
+
var le = {
|
|
123
124
|
text: ["form", "input"],
|
|
124
125
|
number: ["form", "input"],
|
|
125
126
|
email: ["form", "input"],
|
|
@@ -139,7 +140,7 @@ var ce = {
|
|
|
139
140
|
url: ["form", "input"],
|
|
140
141
|
editor: ["form", "textarea"],
|
|
141
142
|
autodate: ["form", "input"]
|
|
142
|
-
},
|
|
143
|
+
}, ue = {
|
|
143
144
|
form: ["import * as Form from \"$lib/components/ui/form\";"],
|
|
144
145
|
"file-form": ["import * as FileForm from \"$lib/components/ui/file-form\";"],
|
|
145
146
|
multiselect: ["import * as MultiSelect from \"$lib/components/ui/multiselect\";", "import * as Command from \"$lib/components/ui/command\";"],
|
|
@@ -178,7 +179,7 @@ function x(e, n) {
|
|
|
178
179
|
</Form.Field>
|
|
179
180
|
`;
|
|
180
181
|
}
|
|
181
|
-
function
|
|
182
|
+
function de(e) {
|
|
182
183
|
let n = e.required ? " required" : "";
|
|
183
184
|
return t`
|
|
184
185
|
<Form.Field {form} name="${e.name}" class="col-span-2">
|
|
@@ -192,7 +193,7 @@ function ue(e) {
|
|
|
192
193
|
</Form.Field>
|
|
193
194
|
`;
|
|
194
195
|
}
|
|
195
|
-
function
|
|
196
|
+
function fe(e) {
|
|
196
197
|
let n = e.required ? " required" : "";
|
|
197
198
|
return t`
|
|
198
199
|
<Form.Field {form} name="${e.name}" class="col-span-1 flex items-start space-x-2">
|
|
@@ -206,7 +207,7 @@ function de(e) {
|
|
|
206
207
|
</Form.Field>
|
|
207
208
|
`;
|
|
208
209
|
}
|
|
209
|
-
function
|
|
210
|
+
function pe(e) {
|
|
210
211
|
return t`
|
|
211
212
|
<Form.Field {form} name="${e.name}" class="col-span-1">
|
|
212
213
|
<Form.Control>
|
|
@@ -219,7 +220,7 @@ function fe(e) {
|
|
|
219
220
|
</Form.Field>
|
|
220
221
|
`;
|
|
221
222
|
}
|
|
222
|
-
function
|
|
223
|
+
function me(e) {
|
|
223
224
|
let n = e.required ? " required" : "", r = e.maxSelect > 1 ? "Multiple" : "Single";
|
|
224
225
|
return t`
|
|
225
226
|
<FileForm.Field {form} name="${e.name}" class="col-span-1">
|
|
@@ -246,7 +247,7 @@ function pe(e) {
|
|
|
246
247
|
</FileForm.Field>
|
|
247
248
|
`;
|
|
248
249
|
}
|
|
249
|
-
function
|
|
250
|
+
function he(e) {
|
|
250
251
|
let n = e.maxSelect > 1 ? "multiple" : "single", r = e.required ? " required" : "", i = e.maxSelect > 1 ? "Select options" : "Select an option", a = e.options.map((t) => `<MultiSelect.Item value=${JSON.stringify(t.value)} label={${e.name}Labels[${JSON.stringify(t.value)}].label} />`).join("\n ");
|
|
251
252
|
return t`
|
|
252
253
|
<MultiSelect.Field {form} type="${n}" name="${e.name}"${r} class="col-span-1">
|
|
@@ -281,7 +282,7 @@ function me(e) {
|
|
|
281
282
|
</MultiSelect.Field>
|
|
282
283
|
`;
|
|
283
284
|
}
|
|
284
|
-
function
|
|
285
|
+
function ge(e) {
|
|
285
286
|
let n = e.maxSelect > 1 ? "multiple" : "single", r = e.maxSelect > 1 ? `Select ${e.relatedModel.pluralDisplayName.toLowerCase()}` : `Select ${e.relatedModel.displayName.toLowerCase()}`, i = `Search ${e.relatedModel.pluralDisplayName.toLowerCase()}...`, a = `No ${e.relatedModel.pluralDisplayName.toLowerCase()} found`, o = e.relatedModel.name, s = e.relatedModel.pluralName;
|
|
286
287
|
return t`
|
|
287
288
|
<MultiSelect.Field {form} type="${n}" name="${e.name}" class="col-span-1">
|
|
@@ -319,7 +320,7 @@ function he(e) {
|
|
|
319
320
|
</MultiSelect.Field>
|
|
320
321
|
`;
|
|
321
322
|
}
|
|
322
|
-
function
|
|
323
|
+
function _e(e) {
|
|
323
324
|
return t`
|
|
324
325
|
<Form.Field {form} name="${e.name}" class="col-span-1">
|
|
325
326
|
<Form.Control>
|
|
@@ -332,7 +333,7 @@ function ge(e) {
|
|
|
332
333
|
</Form.Field>
|
|
333
334
|
`;
|
|
334
335
|
}
|
|
335
|
-
function
|
|
336
|
+
function ve(e) {
|
|
336
337
|
switch (e.type) {
|
|
337
338
|
case "text": return x(e, "text");
|
|
338
339
|
case "number": return x(e, "number");
|
|
@@ -340,14 +341,14 @@ function _e(e) {
|
|
|
340
341
|
case "email": return x(e, "email");
|
|
341
342
|
case "password": return x(e, "password");
|
|
342
343
|
case "url": return x(e, "url");
|
|
343
|
-
case "autodate": return
|
|
344
|
+
case "autodate": return _e(e);
|
|
344
345
|
case "editor":
|
|
345
|
-
case "json": return
|
|
346
|
-
case "bool": return
|
|
347
|
-
case "geoPoint": return
|
|
348
|
-
case "file": return
|
|
349
|
-
case "select": return
|
|
350
|
-
case "relation": return
|
|
346
|
+
case "json": return de(e);
|
|
347
|
+
case "bool": return fe(e);
|
|
348
|
+
case "geoPoint": return pe(e);
|
|
349
|
+
case "file": return me(e);
|
|
350
|
+
case "select": return he(e);
|
|
351
|
+
case "relation": return ge(e);
|
|
351
352
|
default: return e;
|
|
352
353
|
}
|
|
353
354
|
}
|
|
@@ -365,16 +366,16 @@ function S(e) {
|
|
|
365
366
|
`;
|
|
366
367
|
}
|
|
367
368
|
function C(e) {
|
|
368
|
-
let t = e.flatMap((e) =>
|
|
369
|
+
let t = e.flatMap((e) => le[e.type]);
|
|
369
370
|
return [...new Set(t)];
|
|
370
371
|
}
|
|
371
372
|
function w(e) {
|
|
372
|
-
return [...new Set(e.flatMap((e) =>
|
|
373
|
+
return [...new Set(e.flatMap((e) => ue[e]))];
|
|
373
374
|
}
|
|
374
375
|
function T(e, t) {
|
|
375
376
|
return `data.${e.name}.${t.name}`;
|
|
376
377
|
}
|
|
377
|
-
function
|
|
378
|
+
function ye(e, n, r) {
|
|
378
379
|
return t`
|
|
379
380
|
<div class="space-y-2">
|
|
380
381
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -382,7 +383,7 @@ function ve(e, n, r) {
|
|
|
382
383
|
</div>
|
|
383
384
|
`;
|
|
384
385
|
}
|
|
385
|
-
function
|
|
386
|
+
function be(e, n) {
|
|
386
387
|
let r = T(e, n), i = `<p class="text-muted-foreground">{new Date(${r}).toLocaleDateString()}</p>`, a = n.required ? i : t`
|
|
387
388
|
{#if ${r}}
|
|
388
389
|
${i}
|
|
@@ -395,7 +396,7 @@ function ye(e, n) {
|
|
|
395
396
|
</div>
|
|
396
397
|
`;
|
|
397
398
|
}
|
|
398
|
-
function
|
|
399
|
+
function xe(e, n) {
|
|
399
400
|
let r = T(e, n), i = t`
|
|
400
401
|
<a href={${r}} target="_blank" rel="noopener noreferrer">
|
|
401
402
|
{${r}}
|
|
@@ -414,7 +415,7 @@ function be(e, n) {
|
|
|
414
415
|
</div>
|
|
415
416
|
`;
|
|
416
417
|
}
|
|
417
|
-
function
|
|
418
|
+
function Se(e, n) {
|
|
418
419
|
let r = T(e, n);
|
|
419
420
|
if (n.maxSelect > 1) return t`
|
|
420
421
|
<div class="space-y-2">
|
|
@@ -436,7 +437,7 @@ function xe(e, n) {
|
|
|
436
437
|
</div>
|
|
437
438
|
`;
|
|
438
439
|
}
|
|
439
|
-
function
|
|
440
|
+
function Ce(e, n) {
|
|
440
441
|
let r = T(e, n);
|
|
441
442
|
return n.maxSelect > 1 ? t`
|
|
442
443
|
<div class="space-y-2">
|
|
@@ -482,11 +483,11 @@ function Se(e, n) {
|
|
|
482
483
|
</div>
|
|
483
484
|
`;
|
|
484
485
|
}
|
|
485
|
-
function
|
|
486
|
+
function we(e) {
|
|
486
487
|
return `/${e.relatedModel.routeSegment}`;
|
|
487
488
|
}
|
|
488
|
-
function
|
|
489
|
-
let r = `data.${e.name}.expand?.${n.name}`, i =
|
|
489
|
+
function Te(e, n) {
|
|
490
|
+
let r = `data.${e.name}.expand?.${n.name}`, i = we(n);
|
|
490
491
|
return n.maxSelect > 1 ? t`
|
|
491
492
|
<div class="space-y-2">
|
|
492
493
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -513,7 +514,7 @@ function we(e, n) {
|
|
|
513
514
|
</div>
|
|
514
515
|
`;
|
|
515
516
|
}
|
|
516
|
-
function
|
|
517
|
+
function Ee(e, n) {
|
|
517
518
|
let r = T(e, n), i = t`
|
|
518
519
|
{#await import("$lib/components/ui/leaflet/leaflet.svelte")}
|
|
519
520
|
<div class="h-56.25 w-full bg-input rounded-md"></div>
|
|
@@ -535,12 +536,12 @@ function Te(e, n) {
|
|
|
535
536
|
</div>
|
|
536
537
|
`;
|
|
537
538
|
}
|
|
538
|
-
function
|
|
539
|
+
function De(e, n) {
|
|
539
540
|
switch (n.type) {
|
|
540
541
|
case "text":
|
|
541
542
|
case "number":
|
|
542
543
|
case "email":
|
|
543
|
-
case "editor": return
|
|
544
|
+
case "editor": return ye(e, n, `{${T(e, n)}}`);
|
|
544
545
|
case "password": return t`
|
|
545
546
|
<div class="space-y-2">
|
|
546
547
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -549,34 +550,34 @@ function Ee(e, n) {
|
|
|
549
550
|
</p>
|
|
550
551
|
</div>
|
|
551
552
|
`;
|
|
552
|
-
case "bool": return
|
|
553
|
+
case "bool": return ye(e, n, `{${T(e, n)} ? "Yes" : "No"}`);
|
|
553
554
|
case "date":
|
|
554
|
-
case "autodate": return
|
|
555
|
-
case "url": return
|
|
556
|
-
case "select": return
|
|
557
|
-
case "file": return
|
|
558
|
-
case "json": return
|
|
559
|
-
case "geoPoint": return
|
|
560
|
-
case "relation": return
|
|
555
|
+
case "autodate": return be(e, n);
|
|
556
|
+
case "url": return xe(e, n);
|
|
557
|
+
case "select": return Se(e, n);
|
|
558
|
+
case "file": return Ce(e, n);
|
|
559
|
+
case "json": return ye(e, n, `{JSON.stringify(${T(e, n)})}`);
|
|
560
|
+
case "geoPoint": return Ee(e, n);
|
|
561
|
+
case "relation": return Te(e, n);
|
|
561
562
|
default: return n;
|
|
562
563
|
}
|
|
563
564
|
}
|
|
564
565
|
//#endregion
|
|
565
566
|
//#region node_modules/change-case/dist/index.js
|
|
566
|
-
var
|
|
567
|
-
function
|
|
567
|
+
var Oe = /([\p{Ll}\d])(\p{Lu})/gu, ke = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu, Ae = /(\d)\p{Ll}|(\p{L})\d/u, je = /[^\p{L}\d]+/giu, Me = "$1\0$2", Ne = "";
|
|
568
|
+
function Pe(e) {
|
|
568
569
|
let t = e.trim();
|
|
569
|
-
t = t.replace(
|
|
570
|
+
t = t.replace(Oe, Me).replace(ke, Me), t = t.replace(je, "\0");
|
|
570
571
|
let n = 0, r = t.length;
|
|
571
572
|
for (; t.charAt(n) === "\0";) n++;
|
|
572
573
|
if (n === r) return [];
|
|
573
574
|
for (; t.charAt(r - 1) === "\0";) r--;
|
|
574
575
|
return t.slice(n, r).split(/\0/g);
|
|
575
576
|
}
|
|
576
|
-
function
|
|
577
|
-
let t =
|
|
577
|
+
function Fe(e) {
|
|
578
|
+
let t = Pe(e);
|
|
578
579
|
for (let e = 0; e < t.length; e++) {
|
|
579
|
-
let n = t[e], r =
|
|
580
|
+
let n = t[e], r = Ae.exec(n);
|
|
580
581
|
if (r) {
|
|
581
582
|
let i = r.index + (r[1] ?? r[2]).length;
|
|
582
583
|
t.splice(e, 1, n.slice(0, i), n.slice(i));
|
|
@@ -584,30 +585,30 @@ function Pe(e) {
|
|
|
584
585
|
}
|
|
585
586
|
return t;
|
|
586
587
|
}
|
|
587
|
-
function
|
|
588
|
+
function Ie(e, t) {
|
|
588
589
|
let [n, r, i] = O(e, t);
|
|
589
590
|
return n + r.map(D(t?.locale)).join(t?.delimiter ?? " ") + i;
|
|
590
591
|
}
|
|
591
592
|
function E(e, t) {
|
|
592
|
-
let [n, r, i] = O(e, t), a = D(t?.locale), o =
|
|
593
|
+
let [n, r, i] = O(e, t), a = D(t?.locale), o = Ve(t?.locale), s = t?.mergeAmbiguousCharacters ? He(a, o) : Ue(a, o);
|
|
593
594
|
return n + r.map((e, t) => t === 0 ? a(e) : s(e, t)).join(t?.delimiter ?? "") + i;
|
|
594
595
|
}
|
|
595
|
-
function Ie(e, t) {
|
|
596
|
-
let [n, r, i] = O(e, t), a = D(t?.locale), o = Be(t?.locale), s = t?.mergeAmbiguousCharacters ? Ve(a, o) : He(a, o);
|
|
597
|
-
return n + r.map(s).join(t?.delimiter ?? "") + i;
|
|
598
|
-
}
|
|
599
596
|
function Le(e, t) {
|
|
600
|
-
let [n, r, i] = O(e, t), a = D(t?.locale), o =
|
|
601
|
-
return n + r.map(
|
|
597
|
+
let [n, r, i] = O(e, t), a = D(t?.locale), o = Ve(t?.locale), s = t?.mergeAmbiguousCharacters ? He(a, o) : Ue(a, o);
|
|
598
|
+
return n + r.map(s).join(t?.delimiter ?? "") + i;
|
|
602
599
|
}
|
|
603
600
|
function Re(e, t) {
|
|
604
|
-
|
|
601
|
+
let [n, r, i] = O(e, t), a = D(t?.locale), o = Ve(t?.locale);
|
|
602
|
+
return n + r.map(He(a, o)).join(t?.delimiter ?? " ") + i;
|
|
603
|
+
}
|
|
604
|
+
function ze(e, t) {
|
|
605
|
+
return Ie(e, {
|
|
605
606
|
delimiter: "-",
|
|
606
607
|
...t
|
|
607
608
|
});
|
|
608
609
|
}
|
|
609
|
-
function
|
|
610
|
-
return
|
|
610
|
+
function Be(e, t) {
|
|
611
|
+
return Ie(e, {
|
|
611
612
|
delimiter: "_",
|
|
612
613
|
...t
|
|
613
614
|
});
|
|
@@ -615,20 +616,20 @@ function ze(e, t) {
|
|
|
615
616
|
function D(e) {
|
|
616
617
|
return e === !1 ? (e) => e.toLowerCase() : (t) => t.toLocaleLowerCase(e);
|
|
617
618
|
}
|
|
618
|
-
function
|
|
619
|
+
function Ve(e) {
|
|
619
620
|
return e === !1 ? (e) => e.toUpperCase() : (t) => t.toLocaleUpperCase(e);
|
|
620
621
|
}
|
|
621
|
-
function
|
|
622
|
+
function He(e, t) {
|
|
622
623
|
return (n) => `${t(n[0])}${e(n.slice(1))}`;
|
|
623
624
|
}
|
|
624
|
-
function
|
|
625
|
+
function Ue(e, t) {
|
|
625
626
|
return (n, r) => {
|
|
626
627
|
let i = n[0];
|
|
627
628
|
return (r > 0 && i >= "0" && i <= "9" ? "_" + i : t(i)) + e(n.slice(1));
|
|
628
629
|
};
|
|
629
630
|
}
|
|
630
631
|
function O(e, t = {}) {
|
|
631
|
-
let n = t.split ?? (t.separateNumbers ?
|
|
632
|
+
let n = t.split ?? (t.separateNumbers ? Fe : Pe), r = t.prefixCharacters ?? Ne, i = t.suffixCharacters ?? Ne, a = 0, o = e.length;
|
|
632
633
|
for (; a < e.length;) {
|
|
633
634
|
let t = e.charAt(a);
|
|
634
635
|
if (!r.includes(t)) break;
|
|
@@ -647,10 +648,10 @@ function O(e, t = {}) {
|
|
|
647
648
|
}
|
|
648
649
|
//#endregion
|
|
649
650
|
//#region src/parse/model.ts
|
|
650
|
-
var k = /* @__PURE__ */
|
|
651
|
+
var k = /* @__PURE__ */ re((/* @__PURE__ */ te(((e, t) => {
|
|
651
652
|
(function(n, r) {
|
|
652
653
|
/* istanbul ignore else */
|
|
653
|
-
typeof
|
|
654
|
+
typeof ie == "function" && typeof e == "object" && typeof t == "object" ? t.exports = r() : typeof define == "function" && define.amd ? define(function() {
|
|
654
655
|
return r();
|
|
655
656
|
}) : n.pluralize = r();
|
|
656
657
|
})(e, function() {
|
|
@@ -917,7 +918,7 @@ var k = /* @__PURE__ */ ne((/* @__PURE__ */ g(((e, t) => {
|
|
|
917
918
|
/sheep$/i
|
|
918
919
|
].forEach(f.addUncountableRule), f;
|
|
919
920
|
});
|
|
920
|
-
})))(), 1),
|
|
921
|
+
})))(), 1), We = new Set(/* @__PURE__ */ "break.case.catch.class.const.continue.debugger.default.delete.do.else.export.extends.finally.for.function.if.import.in.instanceof.new.return.super.switch.this.throw.try.typeof.var.void.while.with.yield.let.static.package.protected.private.public.interface.enum.implements.type.namespace.null.true.false.await.async.arguments.constructor".split(".")), Ge = {
|
|
921
922
|
function: "fn",
|
|
922
923
|
interface: "iface",
|
|
923
924
|
type: "type_",
|
|
@@ -966,30 +967,30 @@ var k = /* @__PURE__ */ ne((/* @__PURE__ */ g(((e, t) => {
|
|
|
966
967
|
arguments: "args",
|
|
967
968
|
constructor: "ctor"
|
|
968
969
|
};
|
|
969
|
-
function
|
|
970
|
-
return
|
|
970
|
+
function Ke(e) {
|
|
971
|
+
return We.has(e) ? Ge[e] ?? `${e}_` : e;
|
|
971
972
|
}
|
|
972
|
-
function
|
|
973
|
+
function qe(t) {
|
|
973
974
|
if (!/^[a-zA-Z][a-zA-Z0-9-_/]*$/.test(t)) throw new e("Model path must start with a letter and contain only alphanumeric characters, dash, slash, or underscore");
|
|
974
975
|
}
|
|
975
|
-
function
|
|
976
|
+
function Je(e) {
|
|
976
977
|
return e.features.auth ? `src/routes/${o}` : `src/routes/${a}`;
|
|
977
978
|
}
|
|
978
979
|
function A(e, t) {
|
|
979
|
-
let n = e.split("/"), r = n[n.length - 1], i = n.slice(0, -1), a = k.default.singular(
|
|
980
|
+
let n = e.split("/"), r = n[n.length - 1], i = n.slice(0, -1), a = k.default.singular(Re(r)), o = k.default.plural(a), s = E(a), c = ze(o), l = [...i, c].join("/");
|
|
980
981
|
return {
|
|
981
|
-
name:
|
|
982
|
-
pluralName:
|
|
983
|
-
typeName:
|
|
984
|
-
tableName:
|
|
982
|
+
name: Ke(s),
|
|
983
|
+
pluralName: Ke(E(o)),
|
|
984
|
+
typeName: Le(a),
|
|
985
|
+
tableName: Be(o),
|
|
985
986
|
displayName: a,
|
|
986
987
|
pluralDisplayName: o,
|
|
987
|
-
schemaName: `${
|
|
988
|
+
schemaName: `${Ke(s)}Schema`,
|
|
988
989
|
routeSegment: l,
|
|
989
|
-
routesDir:
|
|
990
|
+
routesDir: Je(t)
|
|
990
991
|
};
|
|
991
992
|
}
|
|
992
|
-
function
|
|
993
|
+
function Ye(e) {
|
|
993
994
|
let t = `${e.routesDir}/${e.routeSegment}`;
|
|
994
995
|
return {
|
|
995
996
|
list: t,
|
|
@@ -998,7 +999,7 @@ function Je(e) {
|
|
|
998
999
|
edit: `${t}/[id]/edit`
|
|
999
1000
|
};
|
|
1000
1001
|
}
|
|
1001
|
-
function
|
|
1002
|
+
function Xe(e) {
|
|
1002
1003
|
let t = `/${e.routeSegment}`;
|
|
1003
1004
|
return {
|
|
1004
1005
|
list: t,
|
|
@@ -1009,23 +1010,23 @@ function Ye(e) {
|
|
|
1009
1010
|
}
|
|
1010
1011
|
//#endregion
|
|
1011
1012
|
//#region src/parse/collections.ts
|
|
1012
|
-
var
|
|
1013
|
-
function
|
|
1014
|
-
for (let t of
|
|
1013
|
+
var Ze = /* @__PURE__ */ "title.name.label.display.display_name.full_name.first_name.last_name.given_name.surname.family_name.username.handle.nickname.email.phone.phone_number.headline.subject.caption.summary.description.sku.code.key.identifier.ref.reference.slug.path.url.id".split(".");
|
|
1014
|
+
function Qe(e) {
|
|
1015
|
+
for (let t of Ze) if (e.some((e) => e.name === t)) return t;
|
|
1015
1016
|
return "id";
|
|
1016
1017
|
}
|
|
1017
|
-
function
|
|
1018
|
+
function $e(e) {
|
|
1018
1019
|
return e.map((e) => e.name).filter((e) => !e.startsWith("_"));
|
|
1019
1020
|
}
|
|
1020
|
-
function
|
|
1021
|
+
function et(e) {
|
|
1021
1022
|
return Object.fromEntries(e.map((e) => [e.name, e.id]));
|
|
1022
1023
|
}
|
|
1023
|
-
function
|
|
1024
|
-
return Object.fromEntries(e.map((e) => [e.name,
|
|
1024
|
+
function tt(e) {
|
|
1025
|
+
return Object.fromEntries(e.map((e) => [e.name, Qe(e.fields)]));
|
|
1025
1026
|
}
|
|
1026
1027
|
//#endregion
|
|
1027
1028
|
//#region src/parse/permissions.ts
|
|
1028
|
-
var
|
|
1029
|
+
var nt = [
|
|
1029
1030
|
"user",
|
|
1030
1031
|
"owner",
|
|
1031
1032
|
"created_by",
|
|
@@ -1037,7 +1038,7 @@ var tt = [
|
|
|
1037
1038
|
function j(e) {
|
|
1038
1039
|
return e.toLowerCase();
|
|
1039
1040
|
}
|
|
1040
|
-
function
|
|
1041
|
+
function rt(e) {
|
|
1041
1042
|
return {
|
|
1042
1043
|
rule: "@request.auth.id != \"\"",
|
|
1043
1044
|
ownershipChainCollections: [e],
|
|
@@ -1045,10 +1046,10 @@ function nt(e) {
|
|
|
1045
1046
|
operator: "="
|
|
1046
1047
|
};
|
|
1047
1048
|
}
|
|
1048
|
-
function
|
|
1049
|
-
let r = new Set((n.authCollections ?? ["users"]).map(j)), i = new Set((n.userFieldHints ??
|
|
1049
|
+
function it(e, t, n = {}) {
|
|
1050
|
+
let r = new Set((n.authCollections ?? ["users"]).map(j)), i = new Set((n.userFieldHints ?? nt).map(j)), a = n.maxDepth ?? 8, o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
|
|
1050
1051
|
for (let t of e) o.set(t.name, t), s.set(t.id, t);
|
|
1051
|
-
if (!o.has(t)) return
|
|
1052
|
+
if (!o.has(t)) return rt(t);
|
|
1052
1053
|
if (r.has(j(t))) return {
|
|
1053
1054
|
rule: "@request.auth.id = id",
|
|
1054
1055
|
ownershipChainCollections: [t],
|
|
@@ -1101,7 +1102,7 @@ function rt(e, t, n = {}) {
|
|
|
1101
1102
|
for (let r of l(e)) h.has(r.to) || r.isMulti && !u(r.to) || (h.add(r.to), t.push(r), ee(r.to, t, n + 1), t.pop(), h.delete(r.to));
|
|
1102
1103
|
}
|
|
1103
1104
|
}
|
|
1104
|
-
if (ee(t, [], 0), m.length === 0) return
|
|
1105
|
+
if (ee(t, [], 0), m.length === 0) return rt(t);
|
|
1105
1106
|
m.sort((e, t) => {
|
|
1106
1107
|
let n = f(e) - f(t);
|
|
1107
1108
|
return n === 0 ? p(e).localeCompare(p(t)) : n;
|
|
@@ -1116,7 +1117,7 @@ function rt(e, t, n = {}) {
|
|
|
1116
1117
|
}
|
|
1117
1118
|
//#endregion
|
|
1118
1119
|
//#region src/parse/fields.ts
|
|
1119
|
-
function
|
|
1120
|
+
function at(e) {
|
|
1120
1121
|
let t = null, n = !1, r = 0;
|
|
1121
1122
|
for (let i = 0; i < e.length; i++) {
|
|
1122
1123
|
let a = e[i];
|
|
@@ -1148,11 +1149,11 @@ function it(e) {
|
|
|
1148
1149
|
}
|
|
1149
1150
|
return [e, ""];
|
|
1150
1151
|
}
|
|
1151
|
-
function
|
|
1152
|
+
function ot(e) {
|
|
1152
1153
|
let t = e.trim();
|
|
1153
1154
|
return t.startsWith("\"") && t.endsWith("\"") || t.startsWith("'") && t.endsWith("'") ? t.slice(1, -1).replace(/\\(["'])/g, "$1") : t;
|
|
1154
1155
|
}
|
|
1155
|
-
function
|
|
1156
|
+
function st(e) {
|
|
1156
1157
|
let t = -1, n = null, r = !1;
|
|
1157
1158
|
for (let i = 0; i < e.length; i++) {
|
|
1158
1159
|
let a = e[i];
|
|
@@ -1179,11 +1180,11 @@ function ot(e) {
|
|
|
1179
1180
|
}
|
|
1180
1181
|
let i, a;
|
|
1181
1182
|
return t >= 0 ? (i = e.slice(0, t).trim(), a = e.slice(t + 1).trim()) : (i = e.trim(), a = i), {
|
|
1182
|
-
label:
|
|
1183
|
-
value:
|
|
1183
|
+
label: ot(a),
|
|
1184
|
+
value: ot(i)
|
|
1184
1185
|
};
|
|
1185
1186
|
}
|
|
1186
|
-
function
|
|
1187
|
+
function ct(e) {
|
|
1187
1188
|
let t = [], n = "", r = null, i = !1;
|
|
1188
1189
|
for (let a = 0; a < e.length; a++) {
|
|
1189
1190
|
let o = e[a];
|
|
@@ -1209,15 +1210,15 @@ function st(e) {
|
|
|
1209
1210
|
}
|
|
1210
1211
|
if (o === ",") {
|
|
1211
1212
|
let e = n.trim();
|
|
1212
|
-
e.length > 0 && t.push(
|
|
1213
|
+
e.length > 0 && t.push(st(e)), n = "";
|
|
1213
1214
|
continue;
|
|
1214
1215
|
}
|
|
1215
1216
|
n += o;
|
|
1216
1217
|
}
|
|
1217
1218
|
let a = n.trim();
|
|
1218
|
-
return a.length > 0 && t.push(
|
|
1219
|
+
return a.length > 0 && t.push(st(a)), t;
|
|
1219
1220
|
}
|
|
1220
|
-
var
|
|
1221
|
+
var lt = {
|
|
1221
1222
|
string: "text",
|
|
1222
1223
|
boolean: "bool",
|
|
1223
1224
|
geopoint: "geoPoint",
|
|
@@ -1230,19 +1231,19 @@ var ct = {
|
|
|
1230
1231
|
datetime: "date",
|
|
1231
1232
|
timestamp: "date"
|
|
1232
1233
|
};
|
|
1233
|
-
function
|
|
1234
|
+
function ut(e) {
|
|
1234
1235
|
let t = e.endsWith("!"), n = t ? e.slice(0, -1) : e, r = [];
|
|
1235
|
-
return n.startsWith("select(") && n.endsWith(")") && (r =
|
|
1236
|
+
return n.startsWith("select(") && n.endsWith(")") && (r = ct(n.slice(7, -1)), n = "select"), n === "files" ? {
|
|
1236
1237
|
type: "file",
|
|
1237
1238
|
required: t,
|
|
1238
1239
|
selectOptions: r
|
|
1239
|
-
} : (n in
|
|
1240
|
+
} : (n in lt && (n = lt[n]), {
|
|
1240
1241
|
type: n,
|
|
1241
1242
|
required: t,
|
|
1242
1243
|
selectOptions: r
|
|
1243
1244
|
});
|
|
1244
1245
|
}
|
|
1245
|
-
function
|
|
1246
|
+
function dt(e) {
|
|
1246
1247
|
let t = k.default.singular(e);
|
|
1247
1248
|
return e === k.default.plural(t) ? 99 : 1;
|
|
1248
1249
|
}
|
|
@@ -1257,8 +1258,8 @@ function M(e, t, n, r, i, a) {
|
|
|
1257
1258
|
maxSelect: e === c ? 999 : 1
|
|
1258
1259
|
};
|
|
1259
1260
|
}
|
|
1260
|
-
function
|
|
1261
|
-
let o =
|
|
1261
|
+
function ft(t, n, r, i, a) {
|
|
1262
|
+
let o = Re(t), { type: s, required: c, selectOptions: l } = n, u = $e(i), d = et(i), f = tt(i), p = u.map((e) => k.default.singular(e));
|
|
1262
1263
|
if (a.features.auth && s === "current_user" && d.users) {
|
|
1263
1264
|
let e = M(t, "users", r, d, f, a);
|
|
1264
1265
|
return {
|
|
@@ -1292,7 +1293,7 @@ function dt(t, n, r, i, a) {
|
|
|
1292
1293
|
name: t,
|
|
1293
1294
|
title: o,
|
|
1294
1295
|
required: c,
|
|
1295
|
-
maxSelect:
|
|
1296
|
+
maxSelect: dt(t),
|
|
1296
1297
|
options: l
|
|
1297
1298
|
};
|
|
1298
1299
|
if (s === "file") return {
|
|
@@ -1300,7 +1301,7 @@ function dt(t, n, r, i, a) {
|
|
|
1300
1301
|
name: t,
|
|
1301
1302
|
title: o,
|
|
1302
1303
|
required: c,
|
|
1303
|
-
maxSelect:
|
|
1304
|
+
maxSelect: dt(t)
|
|
1304
1305
|
};
|
|
1305
1306
|
if (s === "relation") {
|
|
1306
1307
|
let n = k.default.singular(t), i = k.default.plural(n);
|
|
@@ -1378,18 +1379,18 @@ function dt(t, n, r, i, a) {
|
|
|
1378
1379
|
required: c
|
|
1379
1380
|
};
|
|
1380
1381
|
}
|
|
1381
|
-
function
|
|
1382
|
+
function pt(t, n, r, i) {
|
|
1382
1383
|
let a = [];
|
|
1383
1384
|
for (let o of t) {
|
|
1384
|
-
let [t, s] =
|
|
1385
|
+
let [t, s] = at(o);
|
|
1385
1386
|
if (!t || !s) throw new e(`Invalid field format: ${o}. Expected format: name:type or name:type!`);
|
|
1386
1387
|
if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)) throw new e(`Invalid field name: ${t}. Must start with a letter and contain only alphanumeric characters`);
|
|
1387
|
-
let c =
|
|
1388
|
-
a.push(
|
|
1388
|
+
let c = ut(s);
|
|
1389
|
+
a.push(ft(t, c, n, r, i));
|
|
1389
1390
|
}
|
|
1390
1391
|
return {
|
|
1391
1392
|
fields: a,
|
|
1392
|
-
auth: i.features.auth ?
|
|
1393
|
+
auth: i.features.auth ? it([...r, {
|
|
1393
1394
|
id: "new",
|
|
1394
1395
|
name: n.tableName,
|
|
1395
1396
|
type: "base",
|
|
@@ -1404,7 +1405,7 @@ function ft(t, n, r, i) {
|
|
|
1404
1405
|
}
|
|
1405
1406
|
//#endregion
|
|
1406
1407
|
//#region src/core/tests.ts
|
|
1407
|
-
var
|
|
1408
|
+
var mt = "2024-01-01T00:00:00.000Z", N = class {
|
|
1408
1409
|
constructor(e) {
|
|
1409
1410
|
this.expression = e;
|
|
1410
1411
|
}
|
|
@@ -1415,7 +1416,7 @@ function P(e) {
|
|
|
1415
1416
|
function F(e) {
|
|
1416
1417
|
return `{ ${Object.entries(e).map(([e, t]) => `${JSON.stringify(e)}: ${P(t)}`).join(", ")} }`;
|
|
1417
1418
|
}
|
|
1418
|
-
function
|
|
1419
|
+
function ht(e) {
|
|
1419
1420
|
switch (e) {
|
|
1420
1421
|
case "text":
|
|
1421
1422
|
case "number":
|
|
@@ -1447,13 +1448,13 @@ function mt(e) {
|
|
|
1447
1448
|
function I(e, t) {
|
|
1448
1449
|
return e.replace("[id]", `\${${t}}`);
|
|
1449
1450
|
}
|
|
1450
|
-
function
|
|
1451
|
+
function gt(e, t, n) {
|
|
1451
1452
|
switch (e.type) {
|
|
1452
1453
|
case "text":
|
|
1453
1454
|
case "editor": return `${e.name} value`;
|
|
1454
1455
|
case "number": return 42;
|
|
1455
1456
|
case "bool": return !0;
|
|
1456
|
-
case "date": return
|
|
1457
|
+
case "date": return mt;
|
|
1457
1458
|
case "email": return `test-${e.name}@example.com`;
|
|
1458
1459
|
case "password": return "password";
|
|
1459
1460
|
case "url": return "https://example.com";
|
|
@@ -1479,7 +1480,7 @@ function ht(e, t, n) {
|
|
|
1479
1480
|
default: return;
|
|
1480
1481
|
}
|
|
1481
1482
|
}
|
|
1482
|
-
function
|
|
1483
|
+
function _t(e, t, n) {
|
|
1483
1484
|
let r = {};
|
|
1484
1485
|
for (let i of e) {
|
|
1485
1486
|
if (i.type === "file" || i.type === "autodate") continue;
|
|
@@ -1487,23 +1488,23 @@ function gt(e, t, n) {
|
|
|
1487
1488
|
n.forForm || (r[i.name] = new N("context.user.id"));
|
|
1488
1489
|
continue;
|
|
1489
1490
|
}
|
|
1490
|
-
let e =
|
|
1491
|
+
let e = gt(i, t, n);
|
|
1491
1492
|
e !== void 0 && (r[i.name] = e);
|
|
1492
1493
|
}
|
|
1493
1494
|
return r;
|
|
1494
1495
|
}
|
|
1495
|
-
function
|
|
1496
|
+
function vt(e, t, n) {
|
|
1496
1497
|
let r = {};
|
|
1497
1498
|
for (let i of e) {
|
|
1498
1499
|
if (i.system || i.name === "id") continue;
|
|
1499
|
-
let e =
|
|
1500
|
+
let e = ht(i.type);
|
|
1500
1501
|
if (!e || e === "file" || e === "autodate" || e === "relation" && !i.collectionId) continue;
|
|
1501
1502
|
let a;
|
|
1502
1503
|
if (e === "relation") a = i.collectionId ? new N(t[i.collectionId] ?? "\"missing-relation-id\"") : void 0;
|
|
1503
1504
|
else if (e === "select") {
|
|
1504
1505
|
let e = i.values?.[0] ?? "default";
|
|
1505
1506
|
a = (i.maxSelect ?? 1) > 1 ? [e] : e;
|
|
1506
|
-
} else a =
|
|
1507
|
+
} else a = gt({
|
|
1507
1508
|
name: i.name,
|
|
1508
1509
|
type: e
|
|
1509
1510
|
}, t, {
|
|
@@ -1514,10 +1515,10 @@ function _t(e, t, n) {
|
|
|
1514
1515
|
}
|
|
1515
1516
|
return r;
|
|
1516
1517
|
}
|
|
1517
|
-
function
|
|
1518
|
+
function yt(e) {
|
|
1518
1519
|
e.email = new N("`test-${Math.random().toString(36).slice(2)}@example.com`"), e.password = "password", e.passwordConfirm = "password";
|
|
1519
1520
|
}
|
|
1520
|
-
function
|
|
1521
|
+
function bt(e, t) {
|
|
1521
1522
|
if (!e) return [];
|
|
1522
1523
|
let n = new Map(t.map((e) => [e.id, e])), r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Set(), a = [], o = (e) => {
|
|
1523
1524
|
if (r.has(e) || i.has(e)) return;
|
|
@@ -1531,14 +1532,14 @@ function yt(e, t) {
|
|
|
1531
1532
|
for (let t of e.fields) t.type !== "relation" || !t.collectionId || o(t.collectionId);
|
|
1532
1533
|
return a;
|
|
1533
1534
|
}
|
|
1534
|
-
function
|
|
1535
|
+
function xt(e, t) {
|
|
1535
1536
|
if (!t.has(e)) return t.add(e), e;
|
|
1536
1537
|
let n = 2;
|
|
1537
1538
|
for (; t.has(`${e}${n}`);) n += 1;
|
|
1538
1539
|
let r = `${e}${n}`;
|
|
1539
1540
|
return t.add(r), r;
|
|
1540
1541
|
}
|
|
1541
|
-
function
|
|
1542
|
+
function St(e, t) {
|
|
1542
1543
|
return {
|
|
1543
1544
|
id: `generated-${e.tableName}`,
|
|
1544
1545
|
name: e.tableName,
|
|
@@ -1564,17 +1565,17 @@ function xt(e, t) {
|
|
|
1564
1565
|
};
|
|
1565
1566
|
}
|
|
1566
1567
|
function L(e, n, r, i) {
|
|
1567
|
-
let a =
|
|
1568
|
+
let a = bt(i.find((t) => t.name === e.tableName) ?? St(e, n), i).filter((e) => !(r.features.auth && e.name === "users")), o = {}, s = [], c = /* @__PURE__ */ new Set();
|
|
1568
1569
|
for (let e of a) {
|
|
1569
|
-
let t =
|
|
1570
|
+
let t = xt(A(e.name, r).name, c);
|
|
1570
1571
|
s.push({
|
|
1571
1572
|
varName: t,
|
|
1572
1573
|
collection: e
|
|
1573
1574
|
}), o[e.id] = `${t}.id`;
|
|
1574
1575
|
}
|
|
1575
1576
|
let l = s.length ? `${s.map((e) => `let ${e.varName}: { id: string };`).join("\n")}\n\n` : "", u = s.map(({ varName: e, collection: t }) => {
|
|
1576
|
-
let n =
|
|
1577
|
-
return t.type === "auth" &&
|
|
1577
|
+
let n = vt(t.fields, o, r);
|
|
1578
|
+
return t.type === "auth" && yt(n), `${e} = await context.admin.collection("${t.name}").create(${F(n)});`;
|
|
1578
1579
|
}), d = s.slice().reverse().map(({ varName: e, collection: t }) => `await context.admin.collection("${t.name}").delete(${e}.id);`), f = r.features.auth ? "context.agent" : "context.request", p = r.features.auth ? "await context.agent.authenticateUser();\n " : "", m = "";
|
|
1579
1580
|
return (u.length > 0 || r.features.auth) && (m += t`
|
|
1580
1581
|
beforeEach(async (context) => {
|
|
@@ -1588,17 +1589,17 @@ function L(e, n, r, i) {
|
|
|
1588
1589
|
declarations: l,
|
|
1589
1590
|
setupSection: m,
|
|
1590
1591
|
requestAgent: f,
|
|
1591
|
-
modelDbData: F(
|
|
1592
|
+
modelDbData: F(_t(n, o, {
|
|
1592
1593
|
forForm: !1,
|
|
1593
1594
|
authEnabled: r.features.auth
|
|
1594
1595
|
})),
|
|
1595
|
-
modelFormData: F(
|
|
1596
|
+
modelFormData: F(_t(n, o, {
|
|
1596
1597
|
forForm: !0,
|
|
1597
1598
|
authEnabled: r.features.auth
|
|
1598
1599
|
}))
|
|
1599
1600
|
};
|
|
1600
1601
|
}
|
|
1601
|
-
function
|
|
1602
|
+
function Ct(e, n, r, i, a) {
|
|
1602
1603
|
let { declarations: o, setupSection: s, requestAgent: c, modelDbData: l, modelFormData: u } = L(e, r, i, a);
|
|
1603
1604
|
return t`
|
|
1604
1605
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
@@ -1676,7 +1677,7 @@ function St(e, n, r, i, a) {
|
|
|
1676
1677
|
});
|
|
1677
1678
|
`;
|
|
1678
1679
|
}
|
|
1679
|
-
function
|
|
1680
|
+
function wt(e, n, r, i, a) {
|
|
1680
1681
|
let { declarations: o, setupSection: s, requestAgent: c, modelDbData: l } = L(e, r, i, a);
|
|
1681
1682
|
return t`
|
|
1682
1683
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
@@ -1732,7 +1733,7 @@ function Ct(e, n, r, i, a) {
|
|
|
1732
1733
|
});
|
|
1733
1734
|
`;
|
|
1734
1735
|
}
|
|
1735
|
-
function
|
|
1736
|
+
function Tt(e, n, r, i, a) {
|
|
1736
1737
|
let { declarations: o, setupSection: s, requestAgent: c, modelFormData: l } = L(e, r, i, a);
|
|
1737
1738
|
return t`
|
|
1738
1739
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
@@ -1756,7 +1757,7 @@ function wt(e, n, r, i, a) {
|
|
|
1756
1757
|
});
|
|
1757
1758
|
`;
|
|
1758
1759
|
}
|
|
1759
|
-
function
|
|
1760
|
+
function Et(e, n, r, i, a) {
|
|
1760
1761
|
let { declarations: o, setupSection: s, requestAgent: c } = L(e, r, i, a);
|
|
1761
1762
|
return t`
|
|
1762
1763
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
@@ -1775,7 +1776,7 @@ function Tt(e, n, r, i, a) {
|
|
|
1775
1776
|
}
|
|
1776
1777
|
//#endregion
|
|
1777
1778
|
//#region src/core/shared.ts
|
|
1778
|
-
var
|
|
1779
|
+
var Dt = ["text"], Ot = {
|
|
1779
1780
|
string: "text",
|
|
1780
1781
|
boolean: "bool",
|
|
1781
1782
|
geopoint: "geoPoint",
|
|
@@ -1802,7 +1803,7 @@ var Et = ["text"], Dt = {
|
|
|
1802
1803
|
geoPoint: "geoPoint",
|
|
1803
1804
|
relation: "relation"
|
|
1804
1805
|
};
|
|
1805
|
-
function
|
|
1806
|
+
function kt(e) {
|
|
1806
1807
|
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e) ? e : `'${e}'`;
|
|
1807
1808
|
}
|
|
1808
1809
|
function R(e, n) {
|
|
@@ -1862,21 +1863,21 @@ function R(e, n) {
|
|
|
1862
1863
|
break;
|
|
1863
1864
|
default: return e.type;
|
|
1864
1865
|
}
|
|
1865
|
-
return
|
|
1866
|
+
return Dt.includes(e.type) ? e.required ? `${i}.nonempty()` : `${i}.optional()` : e.required || e.type === "geoPoint" ? i : e.type === "file" && (e.maxSelect ?? 1) <= 1 ? `${i}.optional().default("")` : `${i}.optional()`;
|
|
1866
1867
|
}
|
|
1867
|
-
async function
|
|
1868
|
+
async function At(e) {
|
|
1868
1869
|
if (e.env === "runtime") {
|
|
1869
|
-
let { getCollections: e } = await import("./chunks/env.runtime-
|
|
1870
|
+
let { getCollections: e } = await import("./chunks/env.runtime-BEdollKV.js");
|
|
1870
1871
|
return await e();
|
|
1871
1872
|
}
|
|
1872
|
-
let { getPreviewCollections: t } = await import("./chunks/env.preview-
|
|
1873
|
+
let { getPreviewCollections: t } = await import("./chunks/env.preview-BZwjhgoi.js");
|
|
1873
1874
|
return t(e);
|
|
1874
1875
|
}
|
|
1875
1876
|
async function z(e, t, n) {
|
|
1876
|
-
|
|
1877
|
-
let r = A(t, e), i = await
|
|
1877
|
+
qe(t);
|
|
1878
|
+
let r = A(t, e), i = await At(e);
|
|
1878
1879
|
if (n.length > 0) {
|
|
1879
|
-
let { fields: t, auth: a } =
|
|
1880
|
+
let { fields: t, auth: a } = pt(n, r, i, e);
|
|
1880
1881
|
return {
|
|
1881
1882
|
model: r,
|
|
1882
1883
|
fields: t,
|
|
@@ -1887,7 +1888,7 @@ async function z(e, t, n) {
|
|
|
1887
1888
|
}
|
|
1888
1889
|
return {
|
|
1889
1890
|
model: r,
|
|
1890
|
-
fields:
|
|
1891
|
+
fields: Mt(r, i, e),
|
|
1891
1892
|
auth: void 0,
|
|
1892
1893
|
shouldCreateCollection: !1,
|
|
1893
1894
|
collections: i
|
|
@@ -1932,7 +1933,7 @@ function B(e, n, r) {
|
|
|
1932
1933
|
schema: R(e, r)
|
|
1933
1934
|
});
|
|
1934
1935
|
}
|
|
1935
|
-
let a = i.map((e) => `${
|
|
1936
|
+
let a = i.map((e) => `${kt(e.name)}: ${e.schema}`).join(",\n "), o = r.includeModelFields ? "\nimport type { Schemas } from \"@velastack/pocketbase\";" : "", s = r.includeModelFields ? ` satisfies Schemas["${e.tableName}"]` : "";
|
|
1936
1937
|
return t`
|
|
1937
1938
|
import { z } from "zod";${o}
|
|
1938
1939
|
|
|
@@ -1941,18 +1942,18 @@ function B(e, n, r) {
|
|
|
1941
1942
|
})${s};
|
|
1942
1943
|
`;
|
|
1943
1944
|
}
|
|
1944
|
-
function
|
|
1945
|
-
let t =
|
|
1945
|
+
function jt(e) {
|
|
1946
|
+
let t = Ot[e];
|
|
1946
1947
|
if (!t) throw Error(`Unsupported collection field type "${e}" when generating from collection`);
|
|
1947
1948
|
return t;
|
|
1948
1949
|
}
|
|
1949
|
-
function
|
|
1950
|
+
function Mt(e, t, n) {
|
|
1950
1951
|
let r = t.find((t) => t.name === e.tableName);
|
|
1951
1952
|
if (!r) throw Error(`Collection "${e.tableName}" not found`);
|
|
1952
|
-
let i =
|
|
1953
|
+
let i = tt(t), a = new Map(t.map((e) => [e.id, e])), o = [];
|
|
1953
1954
|
for (let t of r.fields) {
|
|
1954
1955
|
if (t.name === "id" || t.system) continue;
|
|
1955
|
-
let r =
|
|
1956
|
+
let r = jt(t.type), s = !!t.required, c = Re(t.name);
|
|
1956
1957
|
if (r === "relation") {
|
|
1957
1958
|
let r = t.collectionId ? a.get(t.collectionId) : void 0;
|
|
1958
1959
|
if (!r) continue;
|
|
@@ -2025,7 +2026,7 @@ function H(e) {
|
|
|
2025
2026
|
for (let r of e) r.type === "relation" && (t.has(r.relatedModel.tableName) || (t.add(r.relatedModel.tableName), n.push(r.relatedModel)));
|
|
2026
2027
|
return n;
|
|
2027
2028
|
}
|
|
2028
|
-
function
|
|
2029
|
+
function Nt(e) {
|
|
2029
2030
|
let t = {
|
|
2030
2031
|
name: e.name,
|
|
2031
2032
|
type: e.type,
|
|
@@ -2048,7 +2049,7 @@ function Mt(e) {
|
|
|
2048
2049
|
onUpdate: e.onUpdate
|
|
2049
2050
|
} : t;
|
|
2050
2051
|
}
|
|
2051
|
-
function
|
|
2052
|
+
function Pt(e, t, n) {
|
|
2052
2053
|
let r = n ? {
|
|
2053
2054
|
listRule: n.rule,
|
|
2054
2055
|
viewRule: n.rule,
|
|
@@ -2060,20 +2061,20 @@ function Nt(e, t, n) {
|
|
|
2060
2061
|
name: e.tableName,
|
|
2061
2062
|
type: "base",
|
|
2062
2063
|
...r,
|
|
2063
|
-
fields: t.map(
|
|
2064
|
+
fields: t.map(Nt)
|
|
2064
2065
|
};
|
|
2065
2066
|
}
|
|
2066
2067
|
//#endregion
|
|
2067
2068
|
//#region src/patterns/generate/form/generate.ts
|
|
2068
|
-
var
|
|
2069
|
-
function
|
|
2069
|
+
var Ft;
|
|
2070
|
+
function It(e, t) {
|
|
2070
2071
|
let n = e.replace(/^\/+|\/+$/g, "");
|
|
2071
2072
|
return {
|
|
2072
2073
|
pagePath: `${t}/${n}`,
|
|
2073
2074
|
pageUrl: `/${n}`
|
|
2074
2075
|
};
|
|
2075
2076
|
}
|
|
2076
|
-
function
|
|
2077
|
+
function Lt(t) {
|
|
2077
2078
|
let [n, ...r] = t;
|
|
2078
2079
|
if (!n) throw new e("Invalid command arguments. Expected: <model> <fields...>");
|
|
2079
2080
|
if (r.length === 0) throw new e("At least one field definition is required.");
|
|
@@ -2082,10 +2083,10 @@ function It(t) {
|
|
|
2082
2083
|
fieldDefs: r
|
|
2083
2084
|
};
|
|
2084
2085
|
}
|
|
2085
|
-
function
|
|
2086
|
+
function Rt(e) {
|
|
2086
2087
|
return e.some((e) => e.type === "file");
|
|
2087
2088
|
}
|
|
2088
|
-
function
|
|
2089
|
+
function zt(e, t) {
|
|
2089
2090
|
let n = C(t), r = [
|
|
2090
2091
|
"import { untrack } from \"svelte\";",
|
|
2091
2092
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
@@ -2095,7 +2096,7 @@ function Rt(e, t) {
|
|
|
2095
2096
|
];
|
|
2096
2097
|
return [...new Set(r)];
|
|
2097
2098
|
}
|
|
2098
|
-
function
|
|
2099
|
+
function Bt(e, n) {
|
|
2099
2100
|
return t`
|
|
2100
2101
|
${n.filter((e) => e.type === "select").map((e) => S(e)).join("\n\n")}
|
|
2101
2102
|
|
|
@@ -2106,9 +2107,9 @@ function zt(e, n) {
|
|
|
2106
2107
|
const { form: formData } = form;
|
|
2107
2108
|
`;
|
|
2108
2109
|
}
|
|
2109
|
-
function
|
|
2110
|
-
let r =
|
|
2111
|
-
return t(
|
|
2110
|
+
function Vt(e, n) {
|
|
2111
|
+
let r = zt(e, n).join("\n"), i = Bt(e, n), a = n.map((e) => ve(e)).join("\n"), o = Rt(n) ? " enctype=\"multipart/form-data\"" : "";
|
|
2112
|
+
return t(Ft ||= s([
|
|
2112
2113
|
"\n <script lang=\"ts\">\n ",
|
|
2113
2114
|
"\n\n let { data } = $props();\n ",
|
|
2114
2115
|
"\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">",
|
|
@@ -2117,8 +2118,8 @@ function Bt(e, n) {
|
|
|
2117
2118
|
"\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Form.Button>Submit</Form.Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
2118
2119
|
]), r, i, e.displayName, o, a);
|
|
2119
2120
|
}
|
|
2120
|
-
function
|
|
2121
|
-
let r =
|
|
2121
|
+
function Ht(e, n) {
|
|
2122
|
+
let r = Rt(n);
|
|
2122
2123
|
return t`
|
|
2123
2124
|
${t`
|
|
2124
2125
|
import { fail, superValidate${r ? ", withFiles" : ""} } from "sveltekit-superforms";
|
|
@@ -2155,13 +2156,13 @@ function U(e, t) {
|
|
|
2155
2156
|
status: "success"
|
|
2156
2157
|
};
|
|
2157
2158
|
}
|
|
2158
|
-
async function
|
|
2159
|
-
let { modelPath: t, fieldDefs: n } =
|
|
2159
|
+
async function Ut(e) {
|
|
2160
|
+
let { modelPath: t, fieldDefs: n } = Lt(e.argv), { model: r, fields: i, collections: a } = await z(e, t, n), { pagePath: o, pageUrl: s } = It(t, r.routesDir);
|
|
2160
2161
|
return {
|
|
2161
2162
|
creates: [
|
|
2162
|
-
U(`${o}/+page.svelte`,
|
|
2163
|
-
U(`${o}/+page.server.ts`,
|
|
2164
|
-
U(`${o}/server.test.ts`,
|
|
2163
|
+
U(`${o}/+page.svelte`, Vt(r, i)),
|
|
2164
|
+
U(`${o}/+page.server.ts`, Ht(r, i)),
|
|
2165
|
+
U(`${o}/server.test.ts`, Tt(r, s, i, e, a)),
|
|
2165
2166
|
U(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2166
2167
|
includeModelFields: !1,
|
|
2167
2168
|
forForm: !0
|
|
@@ -2177,18 +2178,18 @@ async function Ht(e) {
|
|
|
2177
2178
|
}
|
|
2178
2179
|
//#endregion
|
|
2179
2180
|
//#region src/patterns/generate/form/index.ts
|
|
2180
|
-
var
|
|
2181
|
-
async function
|
|
2182
|
-
let t = await
|
|
2181
|
+
var Wt = "generate-form", Gt = "1.0.7", Kt = "src/patterns/generate/form", qt = "/generate/form";
|
|
2182
|
+
async function Jt(e) {
|
|
2183
|
+
let t = await Ut(e);
|
|
2183
2184
|
if (e.env !== "runtime") return _(t);
|
|
2184
|
-
let { writeResult: n } = await import("./chunks/write-result-
|
|
2185
|
+
let { writeResult: n } = await import("./chunks/write-result-B0-q-egx.js");
|
|
2185
2186
|
return n(await _(t), e);
|
|
2186
2187
|
}
|
|
2187
|
-
var
|
|
2188
|
-
version:
|
|
2189
|
-
slug:
|
|
2190
|
-
source:
|
|
2191
|
-
docs:
|
|
2188
|
+
var Yt = {
|
|
2189
|
+
version: Gt,
|
|
2190
|
+
slug: Wt,
|
|
2191
|
+
source: Kt,
|
|
2192
|
+
docs: qt,
|
|
2192
2193
|
plan: "open",
|
|
2193
2194
|
title: "Generate a form",
|
|
2194
2195
|
summary: "Generates a form.",
|
|
@@ -2233,8 +2234,8 @@ var Jt = {
|
|
|
2233
2234
|
],
|
|
2234
2235
|
tests: 2,
|
|
2235
2236
|
baseline: "velastack",
|
|
2236
|
-
generate:
|
|
2237
|
-
},
|
|
2237
|
+
generate: Jt
|
|
2238
|
+
}, Xt = {
|
|
2238
2239
|
text: ["input"],
|
|
2239
2240
|
number: ["input"],
|
|
2240
2241
|
email: ["input"],
|
|
@@ -2249,17 +2250,17 @@ var Jt = {
|
|
|
2249
2250
|
autodate: ["input"],
|
|
2250
2251
|
geoPoint: [],
|
|
2251
2252
|
relation: []
|
|
2252
|
-
},
|
|
2253
|
+
}, Zt = {
|
|
2253
2254
|
input: "import { Input } from \"$lib/components/ui/input\";",
|
|
2254
2255
|
textarea: "import { Textarea } from \"$lib/components/ui/textarea\";",
|
|
2255
2256
|
button: "import { Button } from \"$lib/components/ui/button\";"
|
|
2256
2257
|
};
|
|
2257
2258
|
function W(e) {
|
|
2258
|
-
let t = e.flatMap((e) =>
|
|
2259
|
+
let t = e.flatMap((e) => Xt[e.type]);
|
|
2259
2260
|
return [...new Set(t)];
|
|
2260
2261
|
}
|
|
2261
|
-
function
|
|
2262
|
-
return e.map((e) =>
|
|
2262
|
+
function Qt(e) {
|
|
2263
|
+
return e.map((e) => Zt[e]);
|
|
2263
2264
|
}
|
|
2264
2265
|
function G(e, t, n) {
|
|
2265
2266
|
return `{...${e}.fields.${t.name}.as(${JSON.stringify(n)})}`;
|
|
@@ -2281,7 +2282,7 @@ function q(e, n, r, i) {
|
|
|
2281
2282
|
</div>
|
|
2282
2283
|
`;
|
|
2283
2284
|
}
|
|
2284
|
-
function
|
|
2285
|
+
function $t(e, n) {
|
|
2285
2286
|
let r = e.required ? " required" : "";
|
|
2286
2287
|
return t`
|
|
2287
2288
|
<div class="space-y-2 col-span-2">
|
|
@@ -2291,7 +2292,7 @@ function Qt(e, n) {
|
|
|
2291
2292
|
</div>
|
|
2292
2293
|
`;
|
|
2293
2294
|
}
|
|
2294
|
-
function
|
|
2295
|
+
function en(e, n) {
|
|
2295
2296
|
let r = e.required ? " required" : "";
|
|
2296
2297
|
return t`
|
|
2297
2298
|
<div class="col-span-1 flex items-start space-x-2">
|
|
@@ -2301,7 +2302,7 @@ function $t(e, n) {
|
|
|
2301
2302
|
</div>
|
|
2302
2303
|
`;
|
|
2303
2304
|
}
|
|
2304
|
-
function
|
|
2305
|
+
function tn(e, n) {
|
|
2305
2306
|
let r = e.maxSelect > 1 ? " multiple" : "", i = e.required ? " required" : "", a = e.options.map((e) => `<option value=${JSON.stringify(e.value)}>${e.label}</option>`).join("\n ");
|
|
2306
2307
|
return t`
|
|
2307
2308
|
<div class="space-y-2 col-span-1">
|
|
@@ -2313,7 +2314,7 @@ function en(e, n) {
|
|
|
2313
2314
|
</div>
|
|
2314
2315
|
`;
|
|
2315
2316
|
}
|
|
2316
|
-
function
|
|
2317
|
+
function nn(e, n) {
|
|
2317
2318
|
let r = e.maxSelect > 1 ? " multiple" : "", i = e.required ? " required" : "";
|
|
2318
2319
|
return t`
|
|
2319
2320
|
<div class="space-y-2 col-span-1">
|
|
@@ -2323,7 +2324,7 @@ function tn(e, n) {
|
|
|
2323
2324
|
</div>
|
|
2324
2325
|
`;
|
|
2325
2326
|
}
|
|
2326
|
-
function
|
|
2327
|
+
function rn(e, n) {
|
|
2327
2328
|
return t`
|
|
2328
2329
|
<div class="space-y-2 col-span-1">
|
|
2329
2330
|
<label for="${e.name}" class="text-sm font-medium">${e.title}</label>
|
|
@@ -2331,10 +2332,10 @@ function nn(e, n) {
|
|
|
2331
2332
|
</div>
|
|
2332
2333
|
`;
|
|
2333
2334
|
}
|
|
2334
|
-
function
|
|
2335
|
+
function an(e) {
|
|
2335
2336
|
return `<!-- TODO: ${e.type} field "${e.name}" is not yet supported by the remote form variant -->`;
|
|
2336
2337
|
}
|
|
2337
|
-
function
|
|
2338
|
+
function on(e, t) {
|
|
2338
2339
|
let { formVar: n } = t;
|
|
2339
2340
|
switch (e.type) {
|
|
2340
2341
|
case "text": return q(e, n, "text");
|
|
@@ -2344,27 +2345,27 @@ function an(e, t) {
|
|
|
2344
2345
|
case "url": return q(e, n, "text", "url");
|
|
2345
2346
|
case "date": return q(e, n, "text", "date");
|
|
2346
2347
|
case "editor":
|
|
2347
|
-
case "json": return
|
|
2348
|
-
case "bool": return
|
|
2349
|
-
case "select": return
|
|
2350
|
-
case "file": return
|
|
2351
|
-
case "autodate": return
|
|
2348
|
+
case "json": return $t(e, n);
|
|
2349
|
+
case "bool": return en(e, n);
|
|
2350
|
+
case "select": return tn(e, n);
|
|
2351
|
+
case "file": return nn(e, n);
|
|
2352
|
+
case "autodate": return rn(e, n);
|
|
2352
2353
|
case "geoPoint":
|
|
2353
|
-
case "relation": return
|
|
2354
|
+
case "relation": return an(e);
|
|
2354
2355
|
default: return e;
|
|
2355
2356
|
}
|
|
2356
2357
|
}
|
|
2357
2358
|
//#endregion
|
|
2358
2359
|
//#region src/patterns/generate/form-remote/generate.ts
|
|
2359
|
-
var
|
|
2360
|
-
function
|
|
2360
|
+
var sn;
|
|
2361
|
+
function cn(e, t) {
|
|
2361
2362
|
let n = e.replace(/^\/+|\/+$/g, "");
|
|
2362
2363
|
return {
|
|
2363
2364
|
pagePath: `${t}/${n}`,
|
|
2364
2365
|
pageUrl: `/${n}`
|
|
2365
2366
|
};
|
|
2366
2367
|
}
|
|
2367
|
-
function
|
|
2368
|
+
function ln(t) {
|
|
2368
2369
|
let [n, ...r] = t;
|
|
2369
2370
|
if (!n) throw new e("Invalid command arguments. Expected: <model> <fields...>");
|
|
2370
2371
|
if (r.length === 0) throw new e("At least one field definition is required.");
|
|
@@ -2373,23 +2374,23 @@ function cn(t) {
|
|
|
2373
2374
|
fieldDefs: r
|
|
2374
2375
|
};
|
|
2375
2376
|
}
|
|
2376
|
-
function
|
|
2377
|
+
function un(e) {
|
|
2377
2378
|
return e.some((e) => e.type === "file");
|
|
2378
2379
|
}
|
|
2379
|
-
function
|
|
2380
|
+
function dn(e) {
|
|
2380
2381
|
return `submit${e.typeName}Form`;
|
|
2381
2382
|
}
|
|
2382
|
-
function
|
|
2383
|
+
function fn(e, t) {
|
|
2383
2384
|
let n = W(e), r = [
|
|
2384
2385
|
`import { ${t} } from "./form.remote";`,
|
|
2385
2386
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
2386
|
-
...
|
|
2387
|
+
...Qt(n)
|
|
2387
2388
|
];
|
|
2388
2389
|
return [...new Set(r)];
|
|
2389
2390
|
}
|
|
2390
|
-
function
|
|
2391
|
-
let i =
|
|
2392
|
-
return t(
|
|
2391
|
+
function pn(e, n, r) {
|
|
2392
|
+
let i = fn(n, r).join("\n"), a = n.map((e) => on(e, { formVar: r })).join("\n"), o = un(n) ? " enctype=\"multipart/form-data\"" : "";
|
|
2393
|
+
return t(sn ||= s([
|
|
2393
2394
|
"\n <script lang=\"ts\">\n ",
|
|
2394
2395
|
"\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">",
|
|
2395
2396
|
"</h1>\n </div>\n <div class=\"bg-card rounded-lg shadow-sm border p-4\">\n <form {...",
|
|
@@ -2398,7 +2399,7 @@ function fn(e, n, r) {
|
|
|
2398
2399
|
"\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Button type=\"submit\">Submit</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
2399
2400
|
]), i, e.displayName, r, o, a);
|
|
2400
2401
|
}
|
|
2401
|
-
function
|
|
2402
|
+
function mn(e, n) {
|
|
2402
2403
|
return t`
|
|
2403
2404
|
import { form, getRequestEvent } from "$app/server";
|
|
2404
2405
|
import { setFlash } from "sveltekit-flash-message/server";
|
|
@@ -2419,11 +2420,11 @@ function J(e, t) {
|
|
|
2419
2420
|
status: "success"
|
|
2420
2421
|
};
|
|
2421
2422
|
}
|
|
2422
|
-
async function
|
|
2423
|
-
let { modelPath: t, fieldDefs: n } =
|
|
2424
|
-
J(`${o}/+page.svelte`,
|
|
2425
|
-
J(`${o}/form.remote.ts`,
|
|
2426
|
-
J(`${o}/server.test.ts`,
|
|
2423
|
+
async function hn(e) {
|
|
2424
|
+
let { modelPath: t, fieldDefs: n } = ln(e.argv), { model: r, fields: i, collections: a } = await z(e, t, n), { pagePath: o, pageUrl: s } = cn(t, r.routesDir), c = dn(r), l = [
|
|
2425
|
+
J(`${o}/+page.svelte`, pn(r, i, c)),
|
|
2426
|
+
J(`${o}/form.remote.ts`, mn(r, c)),
|
|
2427
|
+
J(`${o}/server.test.ts`, Et(r, s, i, e, a)),
|
|
2427
2428
|
J(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2428
2429
|
includeModelFields: !1,
|
|
2429
2430
|
forForm: !0
|
|
@@ -2441,12 +2442,12 @@ async function mn(e) {
|
|
|
2441
2442
|
}
|
|
2442
2443
|
//#endregion
|
|
2443
2444
|
//#region src/patterns/generate/form-remote/generate.preview.ts
|
|
2444
|
-
var
|
|
2445
|
-
async function
|
|
2445
|
+
var gn = /* @__PURE__ */ Object.assign({ "./preview-modifies/svelte.config.js": "import adapter from \"@sveltejs/adapter-auto\";\nimport { vitePreprocess } from \"@sveltejs/vite-plugin-svelte\";\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n preprocess: vitePreprocess(),\n kit: {\n adapter,\n // [!code highlight:3]\n experimental: {\n remoteFunctions: true,\n },\n },\n // [!code highlight:5]\n compilerOptions: {\n experimental: {\n async: true,\n },\n },\n};\n\nexport default config;\n" }), _n = "./preview-modifies/";
|
|
2446
|
+
async function vn(e) {
|
|
2446
2447
|
return {
|
|
2447
2448
|
creates: [],
|
|
2448
|
-
modifies: Object.entries(
|
|
2449
|
-
let r = i(e,
|
|
2449
|
+
modifies: Object.entries(gn).map(([e, t]) => {
|
|
2450
|
+
let r = i(e, _n);
|
|
2450
2451
|
return {
|
|
2451
2452
|
path: r,
|
|
2452
2453
|
language: n(r),
|
|
@@ -2463,22 +2464,24 @@ async function _n(e) {
|
|
|
2463
2464
|
}
|
|
2464
2465
|
//#endregion
|
|
2465
2466
|
//#region src/patterns/generate/form-remote/index.ts
|
|
2466
|
-
var
|
|
2467
|
-
async function
|
|
2468
|
-
let t = await
|
|
2469
|
-
if (e.env === "preview") return _(r([t, await
|
|
2467
|
+
var yn = "generate-form-remote", bn = "1.0.0", xn = "src/patterns/generate/form-remote", Sn = "/generate/form-remote";
|
|
2468
|
+
async function Cn(e) {
|
|
2469
|
+
let t = await hn(e);
|
|
2470
|
+
if (e.env === "preview") return _(r([t, await vn(e)]));
|
|
2470
2471
|
if (e.env !== "runtime") return _(t);
|
|
2471
|
-
let { modifyOutcomeToFile: n } = await import("./chunks/modify-file-
|
|
2472
|
+
let { modifyOutcomeToFile: n } = await import("./chunks/modify-file-DT_1_kvI.js"), { findSvelteConfigPath: i, modifySvelteConfigRemote: a } = await import("./chunks/modify-svelte-config-remote-CFsA9Mom.js");
|
|
2473
|
+
c(e).info("Modifying svelte.config for remote");
|
|
2474
|
+
let o = i(e.root), s = n(o, a(o)), l = {
|
|
2472
2475
|
...t,
|
|
2473
2476
|
modifies: [...t.modifies, ...s ? [s] : []]
|
|
2474
|
-
}, { writeResult:
|
|
2475
|
-
return
|
|
2476
|
-
}
|
|
2477
|
-
var
|
|
2478
|
-
version:
|
|
2479
|
-
slug:
|
|
2480
|
-
source:
|
|
2481
|
-
docs:
|
|
2477
|
+
}, { writeResult: u } = await import("./chunks/write-result-B0-q-egx.js");
|
|
2478
|
+
return u(await _(l), e);
|
|
2479
|
+
}
|
|
2480
|
+
var wn = {
|
|
2481
|
+
version: bn,
|
|
2482
|
+
slug: yn,
|
|
2483
|
+
source: xn,
|
|
2484
|
+
docs: Sn,
|
|
2482
2485
|
plan: "open",
|
|
2483
2486
|
title: "Generate a form (remote functions)",
|
|
2484
2487
|
summary: "Generates a form using SvelteKit remote functions instead of sveltekit-superforms.",
|
|
@@ -2523,40 +2526,40 @@ var Cn = {
|
|
|
2523
2526
|
],
|
|
2524
2527
|
tests: 1,
|
|
2525
2528
|
baseline: "velastack",
|
|
2526
|
-
generate:
|
|
2527
|
-
},
|
|
2529
|
+
generate: Cn
|
|
2530
|
+
}, Tn = new Set([
|
|
2528
2531
|
"add",
|
|
2529
2532
|
"remove",
|
|
2530
2533
|
"rename",
|
|
2531
2534
|
"references"
|
|
2532
2535
|
]);
|
|
2533
|
-
function
|
|
2536
|
+
function En(t) {
|
|
2534
2537
|
let [n, r, ...i] = t;
|
|
2535
2538
|
if (!n || !r) throw new e("Invalid command arguments. Expected: <collection> <add|remove|rename|references> <args...>");
|
|
2536
|
-
if (!
|
|
2539
|
+
if (!Tn.has(r)) throw new e(`Invalid op: "${r}". Expected one of: add, remove, rename, references`);
|
|
2537
2540
|
return {
|
|
2538
2541
|
collectionName: n,
|
|
2539
2542
|
op: r,
|
|
2540
2543
|
rest: i
|
|
2541
2544
|
};
|
|
2542
2545
|
}
|
|
2543
|
-
async function
|
|
2544
|
-
let { collectionName: n, op: r, rest: i } =
|
|
2545
|
-
|
|
2546
|
-
let a = await
|
|
2546
|
+
async function Dn(t) {
|
|
2547
|
+
let { collectionName: n, op: r, rest: i } = En(t.argv);
|
|
2548
|
+
qe(n);
|
|
2549
|
+
let a = await At(t), o = a.find((e) => e.name === n);
|
|
2547
2550
|
if (!o) throw new e(`Collection "${n}" not found`);
|
|
2548
2551
|
let s = A(n, t), c = new Set(o.fields.map((e) => e.name)), l = [];
|
|
2549
2552
|
if (r === "add" || r === "references") {
|
|
2550
|
-
let { fields: o } =
|
|
2553
|
+
let { fields: o } = pt(r === "references" ? [On(i)] : kn(i, "Expected at least one field definition for add"), s, a, t);
|
|
2551
2554
|
for (let t of o) {
|
|
2552
2555
|
if (c.has(t.name)) throw new e(`Field "${t.name}" already exists on collection "${n}"`);
|
|
2553
2556
|
l.push({
|
|
2554
2557
|
op: "add",
|
|
2555
|
-
field:
|
|
2558
|
+
field: Nt(t)
|
|
2556
2559
|
});
|
|
2557
2560
|
}
|
|
2558
2561
|
} else if (r === "remove") {
|
|
2559
|
-
let t =
|
|
2562
|
+
let t = kn(i, "Expected at least one field name for remove");
|
|
2560
2563
|
for (let r of t) {
|
|
2561
2564
|
if (!c.has(r)) throw new e(`Field "${r}" does not exist on collection "${n}"`);
|
|
2562
2565
|
l.push({
|
|
@@ -2588,36 +2591,36 @@ async function En(t) {
|
|
|
2588
2591
|
}]
|
|
2589
2592
|
};
|
|
2590
2593
|
}
|
|
2591
|
-
function
|
|
2594
|
+
function On(t) {
|
|
2592
2595
|
if (t.length !== 1) throw new e(`Expected exactly one argument for references, got ${t.length}`);
|
|
2593
2596
|
let n = t[0];
|
|
2594
2597
|
return `${n}:${k.default.plural(k.default.singular(n))}`;
|
|
2595
2598
|
}
|
|
2596
|
-
function
|
|
2599
|
+
function kn(t, n) {
|
|
2597
2600
|
if (t.length === 0) throw new e(n);
|
|
2598
2601
|
return t;
|
|
2599
2602
|
}
|
|
2600
2603
|
//#endregion
|
|
2601
2604
|
//#region src/patterns/generate/migration/index.ts
|
|
2602
|
-
var
|
|
2603
|
-
async function
|
|
2604
|
-
let t = await
|
|
2605
|
+
var An = "generate-migration", jn = "1.0.0", Mn = "src/patterns/generate/migration", Nn = "/generate/migration";
|
|
2606
|
+
async function Pn(e) {
|
|
2607
|
+
let t = await Dn(e);
|
|
2605
2608
|
if (e.env !== "runtime") return _(t);
|
|
2606
|
-
let { applyCollectionFieldsPatches: n } = await import("./chunks/collections-
|
|
2609
|
+
let { applyCollectionFieldsPatches: n } = await import("./chunks/collections-Czm1C8ow.js"), { withPocketbase: r } = await import("./chunks/pocketbase-iFJBbNJu.js"), i = c(e), a = [];
|
|
2607
2610
|
await r(e.root, async (r) => {
|
|
2608
|
-
|
|
2611
|
+
a = await n(r, t.collectionPatches, e, i);
|
|
2609
2612
|
});
|
|
2610
|
-
let
|
|
2613
|
+
let o = {
|
|
2611
2614
|
...t,
|
|
2612
|
-
creates: [...t.creates, ...
|
|
2613
|
-
}, { writeResult:
|
|
2614
|
-
return
|
|
2615
|
-
}
|
|
2616
|
-
var
|
|
2617
|
-
version:
|
|
2618
|
-
slug:
|
|
2619
|
-
source:
|
|
2620
|
-
docs:
|
|
2615
|
+
creates: [...t.creates, ...a]
|
|
2616
|
+
}, { writeResult: s } = await import("./chunks/write-result-B0-q-egx.js");
|
|
2617
|
+
return s(await _(o), e);
|
|
2618
|
+
}
|
|
2619
|
+
var Fn = {
|
|
2620
|
+
version: jn,
|
|
2621
|
+
slug: An,
|
|
2622
|
+
source: Mn,
|
|
2623
|
+
docs: Nn,
|
|
2621
2624
|
plan: "open",
|
|
2622
2625
|
title: "Generate a migration",
|
|
2623
2626
|
summary: "Adds, removes, renames, or references fields on an existing collection.",
|
|
@@ -2668,11 +2671,11 @@ var Pn = {
|
|
|
2668
2671
|
],
|
|
2669
2672
|
tests: 0,
|
|
2670
2673
|
baseline: "velastack",
|
|
2671
|
-
generate:
|
|
2674
|
+
generate: Pn
|
|
2672
2675
|
};
|
|
2673
2676
|
//#endregion
|
|
2674
2677
|
//#region src/patterns/generate/resource/generate.ts
|
|
2675
|
-
function
|
|
2678
|
+
function In(t) {
|
|
2676
2679
|
let [n, ...r] = t;
|
|
2677
2680
|
if (!n) throw new e("Invalid command arguments. Expected: <model> [fields...]");
|
|
2678
2681
|
return {
|
|
@@ -2680,7 +2683,7 @@ function Fn(t) {
|
|
|
2680
2683
|
fields: r
|
|
2681
2684
|
};
|
|
2682
2685
|
}
|
|
2683
|
-
function
|
|
2686
|
+
function Ln(e, t) {
|
|
2684
2687
|
return {
|
|
2685
2688
|
path: e,
|
|
2686
2689
|
language: n(e),
|
|
@@ -2688,10 +2691,10 @@ function In(e, t) {
|
|
|
2688
2691
|
status: "success"
|
|
2689
2692
|
};
|
|
2690
2693
|
}
|
|
2691
|
-
async function
|
|
2692
|
-
let { modelPath: t, fields: n } =
|
|
2694
|
+
async function Rn(e) {
|
|
2695
|
+
let { modelPath: t, fields: n } = In(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o } = await z(e, t, n);
|
|
2693
2696
|
return {
|
|
2694
|
-
creates: [
|
|
2697
|
+
creates: [Ln(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2695
2698
|
includeModelFields: !0,
|
|
2696
2699
|
forForm: !0
|
|
2697
2700
|
}))],
|
|
@@ -2699,27 +2702,27 @@ async function Ln(e) {
|
|
|
2699
2702
|
deletes: [],
|
|
2700
2703
|
components: [],
|
|
2701
2704
|
packages: [],
|
|
2702
|
-
collections: o ? [
|
|
2705
|
+
collections: o ? [Pt(r, i, a)] : [],
|
|
2703
2706
|
collectionPatches: []
|
|
2704
2707
|
};
|
|
2705
2708
|
}
|
|
2706
2709
|
//#endregion
|
|
2707
2710
|
//#region src/patterns/generate/resource/index.ts
|
|
2708
|
-
var
|
|
2709
|
-
async function
|
|
2710
|
-
let t = await
|
|
2711
|
+
var zn = "generate-resource", Bn = "1.0.7", Vn = "src/patterns/generate/resource", Hn = "/generate/resource";
|
|
2712
|
+
async function Un(e) {
|
|
2713
|
+
let t = await Rn(e);
|
|
2711
2714
|
if (e.env !== "runtime") return _(t);
|
|
2712
|
-
let { createCollections: n } = await import("./chunks/collections-
|
|
2715
|
+
let { createCollections: n } = await import("./chunks/collections-Czm1C8ow.js"), r = await n(t.collections, e), i = {
|
|
2713
2716
|
...t,
|
|
2714
2717
|
creates: [...t.creates, ...r]
|
|
2715
|
-
}, { writeResult: a } = await import("./chunks/write-result-
|
|
2718
|
+
}, { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
2716
2719
|
return a(await _(i), e);
|
|
2717
2720
|
}
|
|
2718
|
-
var
|
|
2719
|
-
version:
|
|
2720
|
-
slug:
|
|
2721
|
-
source:
|
|
2722
|
-
docs:
|
|
2721
|
+
var Wn = {
|
|
2722
|
+
version: Bn,
|
|
2723
|
+
slug: zn,
|
|
2724
|
+
source: Vn,
|
|
2725
|
+
docs: Hn,
|
|
2723
2726
|
plan: "open",
|
|
2724
2727
|
title: "Generate a resource",
|
|
2725
2728
|
summary: "Generates model schema resources.",
|
|
@@ -2762,9 +2765,9 @@ var Un = {
|
|
|
2762
2765
|
],
|
|
2763
2766
|
tests: 0,
|
|
2764
2767
|
baseline: "velastack",
|
|
2765
|
-
generate:
|
|
2766
|
-
},
|
|
2767
|
-
function
|
|
2768
|
+
generate: Un
|
|
2769
|
+
}, Gn, Kn, qn, Jn;
|
|
2770
|
+
function Yn(t) {
|
|
2768
2771
|
let [n, ...r] = t;
|
|
2769
2772
|
if (!n) throw new e("Invalid command arguments. Expected: <model> [fields...]");
|
|
2770
2773
|
return {
|
|
@@ -2783,24 +2786,24 @@ function Y(e, t) {
|
|
|
2783
2786
|
function X(e) {
|
|
2784
2787
|
return e.some((e) => e.type === "file");
|
|
2785
2788
|
}
|
|
2786
|
-
function
|
|
2789
|
+
function Xn(e) {
|
|
2787
2790
|
return [...new Set(e.filter(Boolean))];
|
|
2788
2791
|
}
|
|
2789
|
-
function
|
|
2792
|
+
function Zn(e) {
|
|
2790
2793
|
return e.filter((e) => e.type === "select").map((e) => S(e)).join("\n\n");
|
|
2791
2794
|
}
|
|
2792
|
-
function
|
|
2795
|
+
function Qn(e, t) {
|
|
2793
2796
|
return H(e).map((e) => `const ${e.pluralName} = await ${t}.collection("${e.tableName}").getFullList();`).join("\n ");
|
|
2794
2797
|
}
|
|
2795
|
-
function
|
|
2798
|
+
function $n(e) {
|
|
2796
2799
|
return H(e).map((e) => e.pluralName).join(", ");
|
|
2797
2800
|
}
|
|
2798
|
-
function
|
|
2801
|
+
function er(e) {
|
|
2799
2802
|
return e.features.auth ? "locals.pb" : "locals.admin";
|
|
2800
2803
|
}
|
|
2801
|
-
function
|
|
2804
|
+
function tr(e, n, r = !1) {
|
|
2802
2805
|
return t`
|
|
2803
|
-
${
|
|
2806
|
+
${Zn(n)}
|
|
2804
2807
|
${r ? "let { data, params } = $props();" : "let { data } = $props();"}
|
|
2805
2808
|
|
|
2806
2809
|
const form = superForm(untrack(() => data.form), {
|
|
@@ -2810,8 +2813,8 @@ function er(e, n, r = !1) {
|
|
|
2810
2813
|
const { form: formData } = form;
|
|
2811
2814
|
`;
|
|
2812
2815
|
}
|
|
2813
|
-
function
|
|
2814
|
-
let i = r.some((e) => e.type === "select"), a =
|
|
2816
|
+
function nr(e, n, r) {
|
|
2817
|
+
let i = r.some((e) => e.type === "select"), a = Xn([
|
|
2815
2818
|
"import { untrack } from \"svelte\";",
|
|
2816
2819
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
2817
2820
|
"import { zod4Client } from \"sveltekit-superforms/adapters\";",
|
|
@@ -2821,8 +2824,8 @@ function tr(e, n, r) {
|
|
|
2821
2824
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2822
2825
|
"import * as Form from \"$lib/components/ui/form\";",
|
|
2823
2826
|
i ? "import type { Models } from \"@velastack/pocketbase\";" : ""
|
|
2824
|
-
]).join("\n"), o = r.map((e) =>
|
|
2825
|
-
return t(
|
|
2827
|
+
]).join("\n"), o = r.map((e) => ve(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
2828
|
+
return t(Gn ||= s([
|
|
2826
2829
|
"\n <script lang=\"ts\">\n ",
|
|
2827
2830
|
"\n ",
|
|
2828
2831
|
"\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">New ",
|
|
@@ -2831,10 +2834,10 @@ function tr(e, n, r) {
|
|
|
2831
2834
|
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
2832
2835
|
"\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Form.Button size=\"sm\">Save</Form.Button>\n <Button href=\"",
|
|
2833
2836
|
"\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
2834
|
-
]), a,
|
|
2837
|
+
]), a, tr(e, r), e.displayName.toLowerCase(), n.list, c, o, n.list);
|
|
2835
2838
|
}
|
|
2836
|
-
function
|
|
2837
|
-
let i = r.some((e) => e.type === "select"), a =
|
|
2839
|
+
function rr(e, n, r) {
|
|
2840
|
+
let i = r.some((e) => e.type === "select"), a = Xn([
|
|
2838
2841
|
"import { untrack } from \"svelte\";",
|
|
2839
2842
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
2840
2843
|
"import { zod4Client } from \"sveltekit-superforms/adapters\";",
|
|
@@ -2844,8 +2847,8 @@ function nr(e, n, r) {
|
|
|
2844
2847
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2845
2848
|
"import * as Form from \"$lib/components/ui/form\";",
|
|
2846
2849
|
i ? "import type { Models } from \"@velastack/pocketbase\";" : ""
|
|
2847
|
-
]).join("\n"), o = r.map((e) =>
|
|
2848
|
-
return t(
|
|
2850
|
+
]).join("\n"), o = r.map((e) => ve(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
2851
|
+
return t(Kn ||= s([
|
|
2849
2852
|
"\n <script lang=\"ts\">\n ",
|
|
2850
2853
|
"\n ",
|
|
2851
2854
|
"\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">Edit ",
|
|
@@ -2863,10 +2866,10 @@ function nr(e, n, r) {
|
|
|
2863
2866
|
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
2864
2867
|
"\n </div>\n <div class=\"mt-4 flex gap-2 border-t pt-4 -mx-4 px-4\">\n <Form.Button size=\"sm\">Save changes</Form.Button>\n <Button href=\"",
|
|
2865
2868
|
"/\\${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
2866
|
-
]), a,
|
|
2869
|
+
]), a, tr(e, r, !0), e.displayName.toLowerCase(), n.list, c, o, n.list);
|
|
2867
2870
|
}
|
|
2868
|
-
function
|
|
2869
|
-
let i = r.some((e) => e.type === "select"), a = i ? `${
|
|
2871
|
+
function ir(e, n, r) {
|
|
2872
|
+
let i = r.some((e) => e.type === "select"), a = i ? `${Zn(r)}` : "", o = r.map((e) => {
|
|
2870
2873
|
let n = "{ getValue }", r = "{ value: getValue() }";
|
|
2871
2874
|
return e.type === "relation" && (n = "{ getValue, row }", r = `{ value: getValue(), expanded: row.original.expand?.${e.name}, displayField: "${e.displayField}" }`), e.type === "select" && (r = `{ value: getValue(), options: ${e.name}Labels }`), e.type === "file" && (n = "{ getValue, row }", r = "{ value: getValue(), collectionId: row.original.collectionId, id: row.original.id }"), t`
|
|
2872
2875
|
columnHelper.accessor("${e.name}", {
|
|
@@ -2875,7 +2878,7 @@ function rr(e, n, r) {
|
|
|
2875
2878
|
})
|
|
2876
2879
|
`;
|
|
2877
2880
|
}).join(",\n"), c = r.filter((e) => e.type === "select").map((e) => `<FacetedFilter column={table.getColumn("${e.name}")!} title="${e.title}" options={Object.values(${e.name}Labels)} />`).join("\n");
|
|
2878
|
-
return t(
|
|
2881
|
+
return t(qn ||= s([
|
|
2879
2882
|
"\n <script lang=\"ts\">\n import {\n type ColumnFiltersState,\n type PaginationState,\n type RowSelectionState,\n type SortingState,\n type VisibilityState,\n getCoreRowModel,\n getFacetedRowModel,\n getFacetedUniqueValues,\n getFilteredRowModel,\n getPaginationRowModel,\n getSortedRowModel,\n createColumnHelper\n } from \"@tanstack/table-core\";\n import { createSvelteTable, FlexRender, renderComponent } from \"$lib/components/ui/data-table\";\n import * as Table from \"$lib/components/ui/table\";\n import { Checkbox } from \"$lib/components/ui/checkbox\";\n import { ColumnHeader } from \"$lib/components/ui/column-header\";\n import { Pagination } from \"$lib/components/ui/pagination\";\n import { RowActions } from \"$lib/components/ui/row-actions\";\n import * as Cells from \"$lib/components/ui/cells\";\n import { Button } from \"$lib/components/ui/button\";\n import { Input } from \"$lib/components/ui/input\";\n ",
|
|
2880
2883
|
"\n import XIcon from \"@lucide/svelte/icons/x\";\n import PlusIcon from \"@lucide/svelte/icons/plus\";\n import type { Models } from \"@velastack/pocketbase\";\n\n let { data } = $props();\n let rowSelection = $state<RowSelectionState>({});\n let columnVisibility = $state<VisibilityState>({});\n let columnFilters = $state<ColumnFiltersState>([]);\n let sorting = $state<SortingState>([]);\n let pagination = $state<PaginationState>({ pageIndex: 0, pageSize: 10 });\n\n ",
|
|
2881
2884
|
"\n\n const columnHelper = createColumnHelper<Models[\"",
|
|
@@ -2909,7 +2912,7 @@ function rr(e, n, r) {
|
|
|
2909
2912
|
"\n </Button>\n </div>\n\n <div class=\"rounded-md border overflow-hidden\">\n <Table.Root>\n <Table.Header>\n {#each table.getHeaderGroups() as headerGroup (headerGroup.id)}\n <Table.Row>\n {#each headerGroup.headers as header (header.id)}\n <Table.Head colspan={header.colSpan} class={header.column.columnDef.meta?.class}>\n {#if !header.isPlaceholder}\n <FlexRender content={header.column.columnDef.header} context={header.getContext()} />\n {/if}\n </Table.Head>\n {/each}\n </Table.Row>\n {/each}\n </Table.Header>\n <Table.Body>\n {#each table.getRowModel().rows as row (row.id)}\n <Table.Row data-state={row.getIsSelected() && \"selected\"}>\n {#each row.getVisibleCells() as cell (cell.id)}\n <Table.Cell class={cell.column.columnDef.meta?.class}>\n <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />\n </Table.Cell>\n {/each}\n </Table.Row>\n {:else}\n <Table.Row>\n <Table.Cell colspan={columns.length} class=\"h-24 text-center\">No results.</Table.Cell>\n </Table.Row>\n {/each}\n </Table.Body>\n </Table.Root>\n </div>\n\n <Pagination {table} />\n </div>\n </section>\n "
|
|
2910
2913
|
]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, e.tableName, o, r.length > 0 ? "," : "", n.list, n.list, n.list, e.pluralName, e.pluralDisplayName, e.pluralDisplayName.toLowerCase(), c, n.new, e.displayName.toLowerCase());
|
|
2911
2914
|
}
|
|
2912
|
-
function
|
|
2915
|
+
function ar(e, n, r) {
|
|
2913
2916
|
let i = V(n), a = i ? `{ expand: "${i}" }` : "";
|
|
2914
2917
|
return t`
|
|
2915
2918
|
export const load = async ({ locals }) => {
|
|
@@ -2918,8 +2921,8 @@ function ir(e, n, r) {
|
|
|
2918
2921
|
};
|
|
2919
2922
|
`;
|
|
2920
2923
|
}
|
|
2921
|
-
function
|
|
2922
|
-
let o = X(r), s =
|
|
2924
|
+
function or(e, n, r, i, a) {
|
|
2925
|
+
let o = X(r), s = Qn(r, i), c = $n(r), l = c ? `, ${c}` : "", u = r.find((e) => e.type === "relation" && e.isCurrentUser), d = a && u ? t`
|
|
2923
2926
|
{
|
|
2924
2927
|
...form.data,
|
|
2925
2928
|
${u.name}: locals.pb.authStore.record?.id
|
|
@@ -2961,7 +2964,7 @@ function ar(e, n, r, i, a) {
|
|
|
2961
2964
|
};
|
|
2962
2965
|
`;
|
|
2963
2966
|
}
|
|
2964
|
-
function
|
|
2967
|
+
function sr(e, n, r, i) {
|
|
2965
2968
|
let a = V(r), o = a ? `, { expand: "${a}" }` : "";
|
|
2966
2969
|
return t`
|
|
2967
2970
|
import { error, redirect } from "@sveltejs/kit";
|
|
@@ -2983,15 +2986,15 @@ function or(e, n, r, i) {
|
|
|
2983
2986
|
};
|
|
2984
2987
|
`;
|
|
2985
2988
|
}
|
|
2986
|
-
function
|
|
2989
|
+
function cr(e, n, r) {
|
|
2987
2990
|
let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), o = r.some((e) => e.type === "file"), c = [
|
|
2988
2991
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
2989
2992
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2990
2993
|
i || a ? "import { Badge } from \"$lib/components/ui/badge\";" : "",
|
|
2991
2994
|
a ? "import CircleArrowRightIcon from \"@lucide/svelte/icons/circle-arrow-right\";" : "",
|
|
2992
2995
|
o ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
|
|
2993
|
-
].filter(Boolean).join("\n"), l =
|
|
2994
|
-
return t(
|
|
2996
|
+
].filter(Boolean).join("\n"), l = Zn(r), u = r.map((t) => De(e, t)).join("\n");
|
|
2997
|
+
return t(Jn ||= s([
|
|
2995
2998
|
"\n <script lang=\"ts\">\n ",
|
|
2996
2999
|
"\n ",
|
|
2997
3000
|
"\n\n let { data } = $props();\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">",
|
|
@@ -3002,8 +3005,8 @@ function sr(e, n, r) {
|
|
|
3002
3005
|
".id}/edit\" variant=\"outline\" size=\"sm\">\n Edit\n </Button>\n <form method=\"POST\">\n <Button type=\"submit\" variant=\"destructive\" size=\"sm\">Delete</Button>\n </form>\n </div>\n </div>\n </section>\n "
|
|
3003
3006
|
]), c, l, e.displayName, n.list, u, n.list, e.name);
|
|
3004
3007
|
}
|
|
3005
|
-
function
|
|
3006
|
-
let a = X(r), o =
|
|
3008
|
+
function lr(e, n, r, i) {
|
|
3009
|
+
let a = X(r), o = Qn(r, i), s = $n(r), c = s ? `, ${s}` : "";
|
|
3007
3010
|
return t`
|
|
3008
3011
|
import { error, fail, redirect } from "@sveltejs/kit";
|
|
3009
3012
|
import { setPocketbaseErrors, setDefaultData } from "@velastack/pocketbase";
|
|
@@ -3044,21 +3047,21 @@ function cr(e, n, r, i) {
|
|
|
3044
3047
|
};
|
|
3045
3048
|
`;
|
|
3046
3049
|
}
|
|
3047
|
-
async function
|
|
3048
|
-
let { modelPath: t, fields: n } =
|
|
3050
|
+
async function ur(e) {
|
|
3051
|
+
let { modelPath: t, fields: n } = Yn(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = Ye(r), l = Xe(r), u = er(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
|
|
3049
3052
|
Y(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
3050
3053
|
includeModelFields: !0,
|
|
3051
3054
|
forForm: !0
|
|
3052
3055
|
})),
|
|
3053
|
-
Y(`${c.list}/+page.server.ts`,
|
|
3054
|
-
Y(`${c.list}/+page.svelte`,
|
|
3055
|
-
Y(`${c.new}/+page.server.ts`,
|
|
3056
|
-
Y(`${c.new}/+page.svelte`,
|
|
3057
|
-
Y(`${c.show}/+page.server.ts`,
|
|
3058
|
-
Y(`${c.show}/+page.svelte`,
|
|
3059
|
-
Y(`${c.edit}/+page.server.ts`,
|
|
3060
|
-
Y(`${c.edit}/+page.svelte`,
|
|
3061
|
-
Y(`${c.list}/server.test.ts`,
|
|
3056
|
+
Y(`${c.list}/+page.server.ts`, ar(r, d, u)),
|
|
3057
|
+
Y(`${c.list}/+page.svelte`, ir(r, l, d)),
|
|
3058
|
+
Y(`${c.new}/+page.server.ts`, or(r, l, d, u, e.features.auth)),
|
|
3059
|
+
Y(`${c.new}/+page.svelte`, nr(r, l, d)),
|
|
3060
|
+
Y(`${c.show}/+page.server.ts`, sr(r, l, d, u)),
|
|
3061
|
+
Y(`${c.show}/+page.svelte`, cr(r, l, d)),
|
|
3062
|
+
Y(`${c.edit}/+page.server.ts`, lr(r, l, d, u)),
|
|
3063
|
+
Y(`${c.edit}/+page.svelte`, rr(r, l, d)),
|
|
3064
|
+
Y(`${c.list}/server.test.ts`, Ct(r, l, i, e, s))
|
|
3062
3065
|
], p = [
|
|
3063
3066
|
...C(d),
|
|
3064
3067
|
"button",
|
|
@@ -3083,27 +3086,27 @@ async function lr(e) {
|
|
|
3083
3086
|
deletes: [],
|
|
3084
3087
|
components: [...new Set(p)],
|
|
3085
3088
|
packages: ["@tanstack/table-core"],
|
|
3086
|
-
collections: o ? [
|
|
3089
|
+
collections: o ? [Pt(r, i, a)] : [],
|
|
3087
3090
|
collectionPatches: []
|
|
3088
3091
|
};
|
|
3089
3092
|
}
|
|
3090
3093
|
//#endregion
|
|
3091
3094
|
//#region src/patterns/generate/scaffold/index.ts
|
|
3092
|
-
var
|
|
3093
|
-
async function
|
|
3094
|
-
let t = await
|
|
3095
|
+
var dr = "generate-scaffold", fr = "1.0.7", pr = "src/patterns/generate/scaffold", mr = "/generate/scaffold";
|
|
3096
|
+
async function hr(e) {
|
|
3097
|
+
let t = await ur(e);
|
|
3095
3098
|
if (e.env !== "runtime") return _(t);
|
|
3096
|
-
let { createCollections: n } = await import("./chunks/collections-
|
|
3099
|
+
let { createCollections: n } = await import("./chunks/collections-Czm1C8ow.js"), r = await n(t.collections, e), i = {
|
|
3097
3100
|
...t,
|
|
3098
3101
|
creates: [...t.creates, ...r]
|
|
3099
|
-
}, { writeResult: a } = await import("./chunks/write-result-
|
|
3102
|
+
}, { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
3100
3103
|
return a(await _(i), e);
|
|
3101
3104
|
}
|
|
3102
|
-
var
|
|
3103
|
-
version:
|
|
3104
|
-
slug:
|
|
3105
|
-
source:
|
|
3106
|
-
docs:
|
|
3105
|
+
var gr = {
|
|
3106
|
+
version: fr,
|
|
3107
|
+
slug: dr,
|
|
3108
|
+
source: pr,
|
|
3109
|
+
docs: mr,
|
|
3107
3110
|
plan: "open",
|
|
3108
3111
|
title: "Generate a scaffold",
|
|
3109
3112
|
summary: "Generates CRUD routes and schema.",
|
|
@@ -3147,9 +3150,9 @@ var hr = {
|
|
|
3147
3150
|
],
|
|
3148
3151
|
tests: 8,
|
|
3149
3152
|
baseline: "velastack",
|
|
3150
|
-
generate:
|
|
3151
|
-
},
|
|
3152
|
-
function
|
|
3153
|
+
generate: hr
|
|
3154
|
+
}, _r, vr, yr, br;
|
|
3155
|
+
function xr(t) {
|
|
3153
3156
|
let [n, ...r] = t;
|
|
3154
3157
|
if (!n) throw new e("Invalid command arguments. Expected: <model> [fields...]");
|
|
3155
3158
|
return {
|
|
@@ -3165,38 +3168,38 @@ function Z(e, t) {
|
|
|
3165
3168
|
status: "success"
|
|
3166
3169
|
};
|
|
3167
3170
|
}
|
|
3168
|
-
function
|
|
3171
|
+
function Sr(e) {
|
|
3169
3172
|
return e.some((e) => e.type === "file");
|
|
3170
3173
|
}
|
|
3171
|
-
function
|
|
3174
|
+
function Cr(e) {
|
|
3172
3175
|
return e.filter((e) => e.type === "select").map((e) => S(e)).join("\n\n");
|
|
3173
3176
|
}
|
|
3174
|
-
function
|
|
3177
|
+
function wr(e, t) {
|
|
3175
3178
|
return H(e).map((e) => `const ${e.pluralName} = await ${t}.collection("${e.tableName}").getFullList();`).join("\n ");
|
|
3176
3179
|
}
|
|
3177
|
-
function
|
|
3180
|
+
function Tr(e) {
|
|
3178
3181
|
return H(e).map((e) => e.pluralName).join(", ");
|
|
3179
3182
|
}
|
|
3180
|
-
function
|
|
3183
|
+
function Er(e) {
|
|
3181
3184
|
return e.features.auth ? "locals.pb" : "locals.admin";
|
|
3182
3185
|
}
|
|
3183
|
-
function
|
|
3186
|
+
function Dr(e) {
|
|
3184
3187
|
return `create${e.typeName}Form`;
|
|
3185
3188
|
}
|
|
3186
|
-
function
|
|
3189
|
+
function Or(e) {
|
|
3187
3190
|
return `update${e.typeName}Form`;
|
|
3188
3191
|
}
|
|
3189
|
-
function
|
|
3192
|
+
function kr(e) {
|
|
3190
3193
|
return H(e).length > 0;
|
|
3191
3194
|
}
|
|
3192
|
-
function
|
|
3193
|
-
let i =
|
|
3195
|
+
function Ar(e, n, r) {
|
|
3196
|
+
let i = Dr(e), a = W(r), o = [
|
|
3194
3197
|
`import { ${i} } from "./form.remote";`,
|
|
3195
3198
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
3196
3199
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3197
|
-
...
|
|
3198
|
-
].join("\n"), c = r.map((e) =>
|
|
3199
|
-
return t(
|
|
3200
|
+
...Qt(a)
|
|
3201
|
+
].join("\n"), c = r.map((e) => on(e, { formVar: i })).join("\n"), l = Sr(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
3202
|
+
return t(_r ||= s([
|
|
3200
3203
|
"\n <script lang=\"ts\">\n ",
|
|
3201
3204
|
"\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">New ",
|
|
3202
3205
|
"</h1>\n <Button href=\"",
|
|
@@ -3207,14 +3210,14 @@ function kr(e, n, r) {
|
|
|
3207
3210
|
"\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
3208
3211
|
]), o, e.displayName.toLowerCase(), n.list, i, l, c, n.list);
|
|
3209
3212
|
}
|
|
3210
|
-
function
|
|
3211
|
-
let i =
|
|
3213
|
+
function jr(e, n, r) {
|
|
3214
|
+
let i = Or(e), a = W(r), o = [
|
|
3212
3215
|
`import { ${i} } from "./form.remote";`,
|
|
3213
3216
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
3214
3217
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3215
|
-
...
|
|
3216
|
-
].join("\n"), c = r.map((e) =>
|
|
3217
|
-
return t(
|
|
3218
|
+
...Qt(a)
|
|
3219
|
+
].join("\n"), c = r.map((e) => on(e, { formVar: i })).join("\n"), l = Sr(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
3220
|
+
return t(vr ||= s([
|
|
3218
3221
|
"\n <script lang=\"ts\">\n ",
|
|
3219
3222
|
"\n\n let { data, params } = $props();\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">Edit ",
|
|
3220
3223
|
"</h1>\n <Button href=\"",
|
|
@@ -3236,8 +3239,8 @@ function Ar(e, n, r) {
|
|
|
3236
3239
|
"/\\${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
3237
3240
|
]), o, e.displayName.toLowerCase(), n.list, i, l, e.name, c, n.list);
|
|
3238
3241
|
}
|
|
3239
|
-
function
|
|
3240
|
-
let i = r.some((e) => e.type === "select"), a = i ? `${
|
|
3242
|
+
function Mr(e, n, r) {
|
|
3243
|
+
let i = r.some((e) => e.type === "select"), a = i ? `${Cr(r)}` : "", o = r.map((e) => {
|
|
3241
3244
|
let n = "{ getValue }", r = "{ value: getValue() }";
|
|
3242
3245
|
return e.type === "relation" && (n = "{ getValue, row }", r = `{ value: getValue(), expanded: row.original.expand?.${e.name}, displayField: "${e.displayField}" }`), e.type === "select" && (r = `{ value: getValue(), options: ${e.name}Labels }`), e.type === "file" && (n = "{ getValue, row }", r = "{ value: getValue(), collectionId: row.original.collectionId, id: row.original.id }"), t`
|
|
3243
3246
|
columnHelper.accessor("${e.name}", {
|
|
@@ -3246,7 +3249,7 @@ function jr(e, n, r) {
|
|
|
3246
3249
|
})
|
|
3247
3250
|
`;
|
|
3248
3251
|
}).join(",\n"), c = r.filter((e) => e.type === "select").map((e) => `<FacetedFilter column={table.getColumn("${e.name}")!} title="${e.title}" options={Object.values(${e.name}Labels)} />`).join("\n");
|
|
3249
|
-
return t(
|
|
3252
|
+
return t(yr ||= s([
|
|
3250
3253
|
"\n <script lang=\"ts\">\n import {\n type ColumnFiltersState,\n type PaginationState,\n type RowSelectionState,\n type SortingState,\n type VisibilityState,\n getCoreRowModel,\n getFacetedRowModel,\n getFacetedUniqueValues,\n getFilteredRowModel,\n getPaginationRowModel,\n getSortedRowModel,\n createColumnHelper\n } from \"@tanstack/table-core\";\n import { createSvelteTable, FlexRender, renderComponent } from \"$lib/components/ui/data-table\";\n import * as Table from \"$lib/components/ui/table\";\n import { Checkbox } from \"$lib/components/ui/checkbox\";\n import { ColumnHeader } from \"$lib/components/ui/column-header\";\n import { Pagination } from \"$lib/components/ui/pagination\";\n import { RowActions } from \"$lib/components/ui/row-actions\";\n import * as Cells from \"$lib/components/ui/cells\";\n import { Button } from \"$lib/components/ui/button\";\n import { Input } from \"$lib/components/ui/input\";\n ",
|
|
3251
3254
|
"\n import XIcon from \"@lucide/svelte/icons/x\";\n import PlusIcon from \"@lucide/svelte/icons/plus\";\n import type { Models } from \"@velastack/pocketbase\";\n\n let { data } = $props();\n let rowSelection = $state<RowSelectionState>({});\n let columnVisibility = $state<VisibilityState>({});\n let columnFilters = $state<ColumnFiltersState>([]);\n let sorting = $state<SortingState>([]);\n let pagination = $state<PaginationState>({ pageIndex: 0, pageSize: 10 });\n\n ",
|
|
3252
3255
|
"\n\n const columnHelper = createColumnHelper<Models[\"",
|
|
@@ -3280,7 +3283,7 @@ function jr(e, n, r) {
|
|
|
3280
3283
|
"\n </Button>\n </div>\n\n <div class=\"rounded-md border overflow-hidden\">\n <Table.Root>\n <Table.Header>\n {#each table.getHeaderGroups() as headerGroup (headerGroup.id)}\n <Table.Row>\n {#each headerGroup.headers as header (header.id)}\n <Table.Head colspan={header.colSpan} class={header.column.columnDef.meta?.class}>\n {#if !header.isPlaceholder}\n <FlexRender content={header.column.columnDef.header} context={header.getContext()} />\n {/if}\n </Table.Head>\n {/each}\n </Table.Row>\n {/each}\n </Table.Header>\n <Table.Body>\n {#each table.getRowModel().rows as row (row.id)}\n <Table.Row data-state={row.getIsSelected() && \"selected\"}>\n {#each row.getVisibleCells() as cell (cell.id)}\n <Table.Cell class={cell.column.columnDef.meta?.class}>\n <FlexRender content={cell.column.columnDef.cell} context={cell.getContext()} />\n </Table.Cell>\n {/each}\n </Table.Row>\n {:else}\n <Table.Row>\n <Table.Cell colspan={columns.length} class=\"h-24 text-center\">No results.</Table.Cell>\n </Table.Row>\n {/each}\n </Table.Body>\n </Table.Root>\n </div>\n\n <Pagination {table} />\n </div>\n </section>\n "
|
|
3281
3284
|
]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, e.tableName, o, r.length > 0 ? "," : "", n.list, n.list, n.list, e.pluralName, e.pluralDisplayName, e.pluralDisplayName.toLowerCase(), c, n.new, e.displayName.toLowerCase());
|
|
3282
3285
|
}
|
|
3283
|
-
function
|
|
3286
|
+
function Nr(e, n, r) {
|
|
3284
3287
|
let i = V(n), a = i ? `{ expand: "${i}" }` : "";
|
|
3285
3288
|
return t`
|
|
3286
3289
|
export const load = async ({ locals }) => {
|
|
@@ -3289,16 +3292,16 @@ function Mr(e, n, r) {
|
|
|
3289
3292
|
};
|
|
3290
3293
|
`;
|
|
3291
3294
|
}
|
|
3292
|
-
function
|
|
3293
|
-
return
|
|
3295
|
+
function Pr(e, n, r) {
|
|
3296
|
+
return kr(n) ? t`
|
|
3294
3297
|
export const load = async ({ locals }) => {
|
|
3295
|
-
${
|
|
3296
|
-
return { ${
|
|
3298
|
+
${wr(n, r)}
|
|
3299
|
+
return { ${Tr(n)} };
|
|
3297
3300
|
};
|
|
3298
3301
|
` : "";
|
|
3299
3302
|
}
|
|
3300
|
-
function
|
|
3301
|
-
let o =
|
|
3303
|
+
function Fr(e, n, r, i, a) {
|
|
3304
|
+
let o = Dr(e), s = r.find((e) => e.type === "relation" && e.isCurrentUser), c = a && s ? t`
|
|
3302
3305
|
{
|
|
3303
3306
|
...data,
|
|
3304
3307
|
${s.name}: locals.pb.authStore.record?.id
|
|
@@ -3318,7 +3321,7 @@ function Pr(e, n, r, i, a) {
|
|
|
3318
3321
|
});
|
|
3319
3322
|
`;
|
|
3320
3323
|
}
|
|
3321
|
-
function
|
|
3324
|
+
function Ir(e, n, r, i) {
|
|
3322
3325
|
let a = V(r), o = a ? `, { expand: "${a}" }` : "";
|
|
3323
3326
|
return t`
|
|
3324
3327
|
import { error, redirect } from "@sveltejs/kit";
|
|
@@ -3340,15 +3343,15 @@ function Fr(e, n, r, i) {
|
|
|
3340
3343
|
};
|
|
3341
3344
|
`;
|
|
3342
3345
|
}
|
|
3343
|
-
function
|
|
3346
|
+
function Lr(e, n, r) {
|
|
3344
3347
|
let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), o = r.some((e) => e.type === "file"), c = [
|
|
3345
3348
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
3346
3349
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3347
3350
|
i || a ? "import { Badge } from \"$lib/components/ui/badge\";" : "",
|
|
3348
3351
|
a ? "import CircleArrowRightIcon from \"@lucide/svelte/icons/circle-arrow-right\";" : "",
|
|
3349
3352
|
o ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
|
|
3350
|
-
].filter(Boolean).join("\n"), l =
|
|
3351
|
-
return t(
|
|
3353
|
+
].filter(Boolean).join("\n"), l = Cr(r), u = r.map((t) => De(e, t)).join("\n");
|
|
3354
|
+
return t(br ||= s([
|
|
3352
3355
|
"\n <script lang=\"ts\">\n ",
|
|
3353
3356
|
"\n ",
|
|
3354
3357
|
"\n\n let { data } = $props();\n <\/script>\n\n <section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">",
|
|
@@ -3359,8 +3362,8 @@ function Ir(e, n, r) {
|
|
|
3359
3362
|
".id}/edit\" variant=\"outline\" size=\"sm\">\n Edit\n </Button>\n <form method=\"POST\">\n <Button type=\"submit\" variant=\"destructive\" size=\"sm\">Delete</Button>\n </form>\n </div>\n </div>\n </section>\n "
|
|
3360
3363
|
]), c, l, e.displayName, n.list, u, n.list, e.name);
|
|
3361
3364
|
}
|
|
3362
|
-
function
|
|
3363
|
-
let i =
|
|
3365
|
+
function Rr(e, n, r) {
|
|
3366
|
+
let i = wr(n, r), a = Tr(n), o = a ? `, ${a}` : "";
|
|
3364
3367
|
return t`
|
|
3365
3368
|
import { error } from "@sveltejs/kit";
|
|
3366
3369
|
|
|
@@ -3376,8 +3379,8 @@ function Lr(e, n, r) {
|
|
|
3376
3379
|
};
|
|
3377
3380
|
`;
|
|
3378
3381
|
}
|
|
3379
|
-
function
|
|
3380
|
-
let i =
|
|
3382
|
+
function zr(e, n, r) {
|
|
3383
|
+
let i = Or(e);
|
|
3381
3384
|
return t`
|
|
3382
3385
|
import { form, getRequestEvent, error } from "$app/server";
|
|
3383
3386
|
import { redirect } from "@sveltejs/kit";
|
|
@@ -3392,16 +3395,16 @@ function Rr(e, n, r) {
|
|
|
3392
3395
|
});
|
|
3393
3396
|
`;
|
|
3394
3397
|
}
|
|
3395
|
-
async function
|
|
3396
|
-
let { modelPath: t, fields: n } =
|
|
3398
|
+
async function Br(e) {
|
|
3399
|
+
let { modelPath: t, fields: n } = xr(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = Ye(r), l = Xe(r), u = Er(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
|
|
3397
3400
|
Z(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
3398
3401
|
includeModelFields: !0,
|
|
3399
3402
|
forForm: !0
|
|
3400
3403
|
})),
|
|
3401
|
-
Z(`${c.list}/+page.server.ts`,
|
|
3402
|
-
Z(`${c.list}/+page.svelte`,
|
|
3403
|
-
], p =
|
|
3404
|
-
p && f.push(Z(`${c.new}/+page.server.ts`, p)), f.push(Z(`${c.new}/form.remote.ts`,
|
|
3404
|
+
Z(`${c.list}/+page.server.ts`, Nr(r, d, u)),
|
|
3405
|
+
Z(`${c.list}/+page.svelte`, Mr(r, l, d))
|
|
3406
|
+
], p = Pr(r, d, u);
|
|
3407
|
+
p && f.push(Z(`${c.new}/+page.server.ts`, p)), f.push(Z(`${c.new}/form.remote.ts`, Fr(r, l, i, u, e.features.auth)), Z(`${c.new}/+page.svelte`, Ar(r, l, d)), Z(`${c.show}/+page.server.ts`, Ir(r, l, d, u)), Z(`${c.show}/+page.svelte`, Lr(r, l, d)), Z(`${c.edit}/+page.server.ts`, Rr(r, d, u)), Z(`${c.edit}/form.remote.ts`, zr(r, l, u)), Z(`${c.edit}/+page.svelte`, jr(r, l, d)), Z(`${c.list}/server.test.ts`, wt(r, l, i, e, s)));
|
|
3405
3408
|
let m = [
|
|
3406
3409
|
...W(d),
|
|
3407
3410
|
"button",
|
|
@@ -3425,18 +3428,18 @@ async function zr(e) {
|
|
|
3425
3428
|
deletes: [],
|
|
3426
3429
|
components: [...new Set(m)],
|
|
3427
3430
|
packages: ["@tanstack/table-core"],
|
|
3428
|
-
collections: o ? [
|
|
3431
|
+
collections: o ? [Pt(r, i, a)] : [],
|
|
3429
3432
|
collectionPatches: []
|
|
3430
3433
|
};
|
|
3431
3434
|
}
|
|
3432
3435
|
//#endregion
|
|
3433
3436
|
//#region src/patterns/generate/scaffold-remote/generate.preview.ts
|
|
3434
|
-
var
|
|
3435
|
-
async function
|
|
3437
|
+
var Vr = /* @__PURE__ */ Object.assign({ "./preview-modifies/svelte.config.js": "import adapter from \"@sveltejs/adapter-auto\";\nimport { vitePreprocess } from \"@sveltejs/vite-plugin-svelte\";\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n preprocess: vitePreprocess(),\n kit: {\n adapter,\n // [!code highlight:3]\n experimental: {\n remoteFunctions: true,\n },\n },\n // [!code highlight:5]\n compilerOptions: {\n experimental: {\n async: true,\n },\n },\n};\n\nexport default config;\n" }), Hr = "./preview-modifies/";
|
|
3438
|
+
async function Ur(e) {
|
|
3436
3439
|
return {
|
|
3437
3440
|
creates: [],
|
|
3438
|
-
modifies: Object.entries(
|
|
3439
|
-
let r = i(e,
|
|
3441
|
+
modifies: Object.entries(Vr).map(([e, t]) => {
|
|
3442
|
+
let r = i(e, Hr);
|
|
3440
3443
|
return {
|
|
3441
3444
|
path: r,
|
|
3442
3445
|
language: n(r),
|
|
@@ -3453,23 +3456,25 @@ async function Hr(e) {
|
|
|
3453
3456
|
}
|
|
3454
3457
|
//#endregion
|
|
3455
3458
|
//#region src/patterns/generate/scaffold-remote/index.ts
|
|
3456
|
-
var
|
|
3457
|
-
async function
|
|
3458
|
-
let t = await
|
|
3459
|
-
if (e.env === "preview") return _(r([t, await
|
|
3459
|
+
var Wr = "generate-scaffold-remote", Gr = "1.0.0", Kr = "src/patterns/generate/scaffold-remote", qr = "/generate/scaffold-remote";
|
|
3460
|
+
async function Jr(e) {
|
|
3461
|
+
let t = await Br(e);
|
|
3462
|
+
if (e.env === "preview") return _(r([t, await Ur(e)]));
|
|
3460
3463
|
if (e.env !== "runtime") return _(t);
|
|
3461
|
-
let { createCollections: n } = await import("./chunks/collections-
|
|
3464
|
+
let { createCollections: n } = await import("./chunks/collections-Czm1C8ow.js"), i = await n(t.collections, e), { modifyOutcomeToFile: a } = await import("./chunks/modify-file-DT_1_kvI.js"), { findSvelteConfigPath: o, modifySvelteConfigRemote: s } = await import("./chunks/modify-svelte-config-remote-CFsA9Mom.js");
|
|
3465
|
+
c(e).info("Modifying svelte.config for remote");
|
|
3466
|
+
let l = o(e.root), u = a(l, s(l)), d = {
|
|
3462
3467
|
...t,
|
|
3463
3468
|
creates: [...t.creates, ...i],
|
|
3464
|
-
modifies: [...t.modifies, ...
|
|
3465
|
-
}, { writeResult:
|
|
3466
|
-
return
|
|
3467
|
-
}
|
|
3468
|
-
var
|
|
3469
|
-
version:
|
|
3470
|
-
slug:
|
|
3471
|
-
source:
|
|
3472
|
-
docs:
|
|
3469
|
+
modifies: [...t.modifies, ...u ? [u] : []]
|
|
3470
|
+
}, { writeResult: f } = await import("./chunks/write-result-B0-q-egx.js");
|
|
3471
|
+
return f(await _(d), e);
|
|
3472
|
+
}
|
|
3473
|
+
var Yr = {
|
|
3474
|
+
version: Gr,
|
|
3475
|
+
slug: Wr,
|
|
3476
|
+
source: Kr,
|
|
3477
|
+
docs: qr,
|
|
3473
3478
|
plan: "open",
|
|
3474
3479
|
title: "Generate a scaffold (remote functions)",
|
|
3475
3480
|
summary: "Generates CRUD routes and schema using SvelteKit remote functions for create/update forms.",
|
|
@@ -3514,11 +3519,11 @@ var Jr = {
|
|
|
3514
3519
|
],
|
|
3515
3520
|
tests: 6,
|
|
3516
3521
|
baseline: "velastack",
|
|
3517
|
-
generate:
|
|
3522
|
+
generate: Jr
|
|
3518
3523
|
};
|
|
3519
3524
|
//#endregion
|
|
3520
3525
|
//#region src/patterns/generate/schema/generate.ts
|
|
3521
|
-
function
|
|
3526
|
+
function Xr(t) {
|
|
3522
3527
|
let [n, ...r] = t;
|
|
3523
3528
|
if (!n) throw new e("Invalid command arguments. Expected: <model> [fields...]");
|
|
3524
3529
|
return {
|
|
@@ -3526,7 +3531,7 @@ function Yr(t) {
|
|
|
3526
3531
|
fields: r
|
|
3527
3532
|
};
|
|
3528
3533
|
}
|
|
3529
|
-
function
|
|
3534
|
+
function Zr(e, t) {
|
|
3530
3535
|
return {
|
|
3531
3536
|
path: e,
|
|
3532
3537
|
language: n(e),
|
|
@@ -3534,10 +3539,10 @@ function Xr(e, t) {
|
|
|
3534
3539
|
status: "success"
|
|
3535
3540
|
};
|
|
3536
3541
|
}
|
|
3537
|
-
async function
|
|
3538
|
-
let { modelPath: t, fields: n } =
|
|
3542
|
+
async function Qr(e) {
|
|
3543
|
+
let { modelPath: t, fields: n } = Xr(e.argv), { model: r, fields: i, shouldCreateCollection: a } = await z(e, t, n);
|
|
3539
3544
|
return {
|
|
3540
|
-
creates: [
|
|
3545
|
+
creates: [Zr(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
3541
3546
|
includeModelFields: !a,
|
|
3542
3547
|
forForm: !0
|
|
3543
3548
|
}))],
|
|
@@ -3551,18 +3556,18 @@ async function Zr(e) {
|
|
|
3551
3556
|
}
|
|
3552
3557
|
//#endregion
|
|
3553
3558
|
//#region src/patterns/generate/schema/index.ts
|
|
3554
|
-
var
|
|
3555
|
-
async function
|
|
3556
|
-
let t = await
|
|
3559
|
+
var $r = "generate-schema", ei = "1.0.7", ti = "src/patterns/generate/schema", ni = "/generate/schema";
|
|
3560
|
+
async function ri(e) {
|
|
3561
|
+
let t = await Qr(e);
|
|
3557
3562
|
if (e.env !== "runtime") return _(t);
|
|
3558
|
-
let { writeResult: n } = await import("./chunks/write-result-
|
|
3563
|
+
let { writeResult: n } = await import("./chunks/write-result-B0-q-egx.js");
|
|
3559
3564
|
return n(await _(t), e);
|
|
3560
3565
|
}
|
|
3561
|
-
var
|
|
3562
|
-
version:
|
|
3563
|
-
slug:
|
|
3564
|
-
source:
|
|
3565
|
-
docs:
|
|
3566
|
+
var ii = {
|
|
3567
|
+
version: ei,
|
|
3568
|
+
slug: $r,
|
|
3569
|
+
source: ti,
|
|
3570
|
+
docs: ni,
|
|
3566
3571
|
plan: "open",
|
|
3567
3572
|
title: "Generate a schema",
|
|
3568
3573
|
summary: "Generates a zod schema.",
|
|
@@ -3605,8 +3610,8 @@ var ri = {
|
|
|
3605
3610
|
],
|
|
3606
3611
|
tests: 0,
|
|
3607
3612
|
baseline: "velastack",
|
|
3608
|
-
generate:
|
|
3609
|
-
},
|
|
3613
|
+
generate: ri
|
|
3614
|
+
}, ai = /* @__PURE__ */ Object.assign({
|
|
3610
3615
|
"./creates/src/lib/components/app-sidebar.svelte": "<script lang=\"ts\">\n import type { ComponentProps } from 'svelte';\n import HomeIcon from '@lucide/svelte/icons/home';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n\n let {\n user,\n meta,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & { user: any; meta: any } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src=\"/favicon.svg\" alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{meta.appName}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} />\n </Sidebar.Footer>\n</Sidebar.Root>\n",
|
|
3611
3616
|
"./creates/src/lib/components/nav-main.svelte": "<script lang=\"ts\">\n import type { Component } from 'svelte';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import { page } from '$app/state';\n\n const isActive = (url: string) => {\n return page.url.pathname.startsWith(url);\n };\n\n let {\n items\n }: {\n items: {\n title: string;\n url: string;\n icon: Component;\n items?: {\n title: string;\n url: string;\n }[];\n }[];\n } = $props();\n<\/script>\n\n<Sidebar.Group>\n <Sidebar.Menu>\n {#each items as item (item.title)}\n <Sidebar.MenuItem>\n <Sidebar.MenuButton isActive={isActive(item.url)}>\n {#snippet child({ props })}\n <a href={item.url} {...props}>\n <item.icon />\n <span>{item.title}</span>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n {/each}\n </Sidebar.Menu>\n</Sidebar.Group>\n",
|
|
3612
3617
|
"./creates/src/lib/components/nav-user.svelte": "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n \n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n",
|
|
@@ -3648,10 +3653,10 @@ var ri = {
|
|
|
3648
3653
|
"./creates/src/routes/(public)/signup/+page.server.ts": "import { redirect } from \"@sveltejs/kit\";\nimport { fail, superValidate } from \"sveltekit-superforms\";\nimport { zod4 } from \"sveltekit-superforms/adapters\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { setPocketbaseErrors } from \"@velastack/pocketbase\";\nimport { dev } from \"$app/environment\";\nimport { signupSchema } from \"$lib/schemas/signup\";\n\nexport const load = async ({ locals }) => {\n const authMethods = await locals.admin.collection(\"users\").listAuthMethods();\n\n if (locals.pb.authStore.isValid) {\n redirect(303, \"/dashboard\");\n }\n\n return { form: await superValidate(zod4(signupSchema)), authMethods };\n};\n\nexport const actions = {\n default: async ({ locals, request, cookies, url }) => {\n const form = await superValidate(request, zod4(signupSchema));\n\n if (!form.valid) {\n return fail(400, { form });\n }\n\n let user;\n\n try {\n user = await locals.admin.collection(\"users\").create({\n email: form.data.email,\n password: form.data.password,\n passwordConfirm: form.data.passwordConfirm,\n });\n } catch (error) {\n setPocketbaseErrors(form, error);\n return fail(400, { form });\n }\n\n await locals.pb.collection(\"users\").requestVerification(user.email);\n await locals.pb\n .collection(\"users\")\n .authWithPassword(form.data.email, form.data.password);\n\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n const cookie = locals.pb.authStore.getCookie();\n cookies.set(\"pb_auth\", cookie, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n setFlash(\n { type: \"toast\", message: \"We sent a confirmation link to your email.\" },\n cookies,\n );\n return redirect(303, redirectUrl);\n },\n};\n",
|
|
3649
3654
|
"./creates/src/routes/(public)/signup/+page.svelte": "<script lang=\"ts\">\n import { untrack } from \"svelte\";\n import { Button } from \"$lib/components/ui/button\";\n import * as Card from \"$lib/components/ui/card\";\n import { superForm } from \"sveltekit-superforms\";\n import { zod4Client } from \"sveltekit-superforms/adapters\";\n import { signupSchema } from \"$lib/schemas/signup\";\n import * as Form from \"$lib/components/ui/form\";\n import { Input } from \"$lib/components/ui/input\";\n import PocketBase from \"pocketbase-sveltekit\";\n import { goto } from \"$app/navigation\";\n import { page } from \"$app/state\";\n\n let { data } = $props();\n let authMethods = $derived(data.authMethods);\n\n const redirect = page.url.searchParams.get(\"redirect\");\n const hasOAuth2 = $derived(\n authMethods.oauth2.enabled && authMethods.oauth2.providers.length > 0,\n );\n const hasAuthMethods = $derived(\n authMethods.password.enabled || authMethods.otp.enabled || hasOAuth2,\n );\n\n const form = superForm(\n untrack(() => data.form),\n {\n validators: zod4Client(signupSchema),\n },\n );\n\n const handleOAuth2 = (provider: string) => {\n const pb = new PocketBase(\"/\");\n\n pb.collection(\"users\")\n .authWithOAuth2({ provider, createData: {} })\n .then(() => goto(\"/dashboard\"));\n };\n\n const { form: formData } = form;\n<\/script>\n\n<div class=\"h-full flex flex-col items-center justify-center gap-6 p-6 md:p-10\">\n <div class=\"flex w-full max-w-sm flex-col gap-6\">\n <a href=\"/\" class=\"flex items-center gap-2 self-center font-medium\">\n <div\n class=\"bg-primary text-primary-foreground flex size-6 items-center justify-center rounded-md\"\n >\n <img src=\"/favicon.svg\" alt=\"logo\" class=\"size-4\" />\n </div>\n {data.meta.appName}\n </a>\n\n <div class=\"flex flex-col gap-6\">\n <Card.Root>\n {#if hasAuthMethods}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Create an account</Card.Title>\n {#if hasOAuth2}\n <Card.Description>Choose a sign up method</Card.Description>\n {:else}\n <Card.Description>Use your email to sign up</Card.Description>\n {/if}\n </Card.Header>\n {:else}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Signups are disabled</Card.Title>\n <Card.Description\n >Check back later for signup options</Card.Description\n >\n </Card.Header>\n {/if}\n <Card.Content>\n <form method=\"POST\">\n <div class=\"grid gap-6\">\n {#if hasOAuth2}\n <div class=\"flex flex-col gap-4\">\n {#each authMethods.oauth2.providers as provider}\n <Button\n variant=\"outline\"\n class=\"w-full\"\n onclick={() => handleOAuth2(provider.name)}\n >\n <img\n src=\"/admin/_/images/oauth2/{provider.name}.svg\"\n class=\"size-5 bg-white p-0.5 rounded-sm\"\n alt=\"\"\n />\n Login with {provider.displayName}\n </Button>\n {/each}\n </div>\n {/if}\n\n {#if authMethods.password.enabled}\n {#if hasOAuth2}\n <div\n class=\"after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t\"\n >\n <span\n class=\"bg-card text-muted-foreground relative z-10 px-2\"\n >\n Or continue with\n </span>\n </div>\n {/if}\n\n <div class=\"grid gap-2\">\n <Form.Field {form} name=\"email\" class=\"col-span-1\">\n <Form.Control>\n {#snippet children({ props })}\n <Form.Label>Email</Form.Label>\n <Input\n {...props}\n type=\"email\"\n bind:value={$formData.email}\n required\n />\n {/snippet}\n </Form.Control>\n <Form.FieldErrors class=\"contents text-destructive\" />\n </Form.Field>\n\n <Form.Field {form} name=\"password\" class=\"col-span-1\">\n <Form.Control>\n {#snippet children({ props })}\n <Form.Label>Password</Form.Label>\n <Input\n {...props}\n type=\"password\"\n bind:value={$formData.password}\n required\n autocomplete=\"new-password\"\n />\n {/snippet}\n </Form.Control>\n <Form.FieldErrors class=\"contents text-destructive\" />\n </Form.Field>\n\n <Form.Field {form} name=\"passwordConfirm\" class=\"col-span-1\">\n <Form.Control>\n {#snippet children({ props })}\n <Form.Label>Confirm Password</Form.Label>\n <Input\n {...props}\n type=\"password\"\n bind:value={$formData.passwordConfirm}\n required\n autocomplete=\"new-password\"\n />\n {/snippet}\n </Form.Control>\n <Form.FieldErrors class=\"contents text-destructive\" />\n </Form.Field>\n <Button type=\"submit\" class=\"w-full\">Create account</Button>\n </div>\n {/if}\n\n <div class=\"text-center text-sm\">\n Already have an account?\n <a\n href=\"/login{redirect\n ? `?redirect=${encodeURIComponent(redirect)}`\n : ''}\"\n class=\"underline underline-offset-4\"\n >\n Log in\n </a>\n </div>\n </div>\n </form>\n </Card.Content>\n </Card.Root>\n <div\n class=\"text-muted-foreground *:[a]:hover:text-primary *:[a]:underline *:[a]:underline-offset-4 text-balance text-center text-xs\"\n >\n By clicking continue, you agree to our <a href=\"/terms\"\n >Terms of Service</a\n >\n and <a href=\"/privacy\">Privacy Policy</a>.\n </div>\n </div>\n </div>\n</div>\n",
|
|
3650
3655
|
"./creates/src/routes/(public)/signup/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport * as devalue from \"devalue\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /signup\", () => {\n it(\"should render the signup page\", async (context) => {\n const response = await context.request.get(\n \"/signup\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n\ndescribe(\"POST /signup\", () => {\n it(\"should signup with password\", async (context) => {\n const response = await context.agent\n .post(\"/signup\" satisfies Match<RouteId>)\n .type(\"form\")\n .send({\n email: `test-${Math.random().toString(36).slice(2)}@example.com`,\n password: \"password\",\n passwordConfirm: \"password\",\n });\n expect(response.body.status).toBe(303);\n expect(response.body.location).toBe(\"/dashboard\");\n });\n\n it(\"should error if the password does not match\", async (context) => {\n const response = await context.agent\n .post(\"/signup\" satisfies Match<RouteId>)\n .type(\"form\")\n .send({\n email: `test-${Math.random().toString(36).slice(2)}@example.com`,\n password: \"password\",\n passwordConfirm: \"password2\",\n });\n expect(response.body.status).toBe(400);\n const data = devalue.parse(response.body.data);\n expect(data.form.errors.passwordConfirm).toBeDefined();\n expect(data.form.errors.passwordConfirm[0]).toBe(\"Values don't match.\");\n });\n\n it(\"should error if the email is already taken\", async (context) => {\n const response = await context.agent\n .post(\"/signup\" satisfies Match<RouteId>)\n .type(\"form\")\n .send({\n email: context.user.email,\n password: \"password\",\n passwordConfirm: \"password\",\n });\n expect(response.body.status).toBe(400);\n const data = devalue.parse(response.body.data);\n expect(data.form.errors.email).toBeDefined();\n expect(data.form.errors.email[0]).toBe(\"Value must be unique.\");\n });\n});\n"
|
|
3651
|
-
}),
|
|
3652
|
-
async function
|
|
3653
|
-
let t = Object.entries(
|
|
3654
|
-
let r = i(e,
|
|
3656
|
+
}), oi = "./creates/";
|
|
3657
|
+
async function si(e) {
|
|
3658
|
+
let t = Object.entries(ai).map(([e, t]) => {
|
|
3659
|
+
let r = i(e, oi);
|
|
3655
3660
|
return {
|
|
3656
3661
|
path: r,
|
|
3657
3662
|
language: n(r),
|
|
@@ -3744,16 +3749,16 @@ async function oi(e) {
|
|
|
3744
3749
|
}
|
|
3745
3750
|
//#endregion
|
|
3746
3751
|
//#region src/patterns/enable/auth/generate.preview.ts
|
|
3747
|
-
var
|
|
3752
|
+
var ci = /* @__PURE__ */ Object.assign({
|
|
3748
3753
|
"./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n auth: { protectedRoutes: [\"/(app)\"] },\n});\n",
|
|
3749
3754
|
"./preview-modifies/src/routes/(public)/root-layout.svelte": "<script lang=\"ts\">\n import { toggleMode } from \"mode-watcher\";\n import * as Navbar from \"$lib/components/ui/navbar\";\n import { Button } from \"$lib/components/ui/button\";\n // [!code highlight:2]\n import * as AuthMenu from \"$lib/components/ui/auth-menu\";\n import * as Avatar from \"$lib/components/ui/avatar\";\n\n let { children, data } = $props();\n<\/script>\n\n<div class=\"min-h-dvh grid grid-rows-[max-content_1fr_max-content] root-layout\">\n <Navbar.Root>\n <Navbar.Brand href=\"/\">\n <Navbar.Logo src=\"/favicon.svg\" alt=\"Logo\" />\n </Navbar.Brand>\n\n <Navbar.MobileToggle />\n\n <Navbar.List>\n <Navbar.Item>\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n href=\"/\"\n variant=\"ghost\"\n >\n Home\n </Button>\n </Navbar.Item>\n\n <!-- [!code highlight:44] -->\n <Navbar.Item\n class=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n >\n <AuthMenu.Root>\n {#snippet user()}\n <AuthMenu.Trigger>\n <Avatar.Root>\n {#if data.user?.avatar}\n <Avatar.Image\n src=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n alt={data.user?.email}\n />\n {/if}\n <Avatar.Fallback>\n {data.user?.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n </AuthMenu.Trigger>\n <AuthMenu.Content align=\"end\">\n <AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n <AuthMenu.Group>\n <AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n <AuthMenu.Item>\n <form action=\"/logout\" method=\"post\">\n <button type=\"submit\" class=\"contents\">Logout</button>\n </form>\n </AuthMenu.Item>\n </AuthMenu.Group>\n </AuthMenu.Content>\n {/snippet}\n {#snippet guest()}\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"ghost\"\n href=\"/login\">Login</Button\n >\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"outline\"\n href=\"/signup\">Sign up</Button\n >\n {/snippet}\n </AuthMenu.Root>\n </Navbar.Item>\n </Navbar.List>\n </Navbar.Root>\n\n {@render children?.()}\n\n <footer class=\"border-t border-border py-4\">\n <div\n class=\"mx-auto flex max-w-7xl px-4 flex-col items-center justify-between gap-3 sm:flex-row\"\n >\n <p class=\"text-muted-foreground text-sm\">\n © {new Date().getFullYear()}\n {data.meta.appName}. All rights reserved.\n </p>\n <nav class=\"flex items-center gap-4 text-sm\">\n <Button onclick={toggleMode} variant=\"ghost\" size=\"icon\">\n <Navbar.Mode />\n </Button>\n <a href=\"/privacy\" class=\"underline-offset-4 hover:underline\">Privacy</a\n >\n <a href=\"/terms\" class=\"underline-offset-4 hover:underline\">Terms</a>\n </nav>\n </div>\n </footer>\n</div>\n\n<style lang=\"postcss\">\n @reference \"tailwindcss\";\n\n .root-layout :global(section[data-role=\"content\"]) {\n @apply container mx-auto max-w-7xl px-4 py-8 w-full;\n }\n</style>\n",
|
|
3750
3755
|
"./preview-modifies/src/routes/+layout.server.ts": "import { loadFlash } from \"sveltekit-flash-message/server\";\n\nexport const load = loadFlash(async ({ locals }) => {\n return {\n // [!code highlight:1]\n user: locals.pb.authStore.record,\n };\n});\n"
|
|
3751
|
-
}),
|
|
3752
|
-
async function
|
|
3756
|
+
}), li = "./preview-modifies/";
|
|
3757
|
+
async function ui(e) {
|
|
3753
3758
|
return {
|
|
3754
3759
|
creates: [],
|
|
3755
|
-
modifies: Object.entries(
|
|
3756
|
-
let r = i(e,
|
|
3760
|
+
modifies: Object.entries(ci).map(([e, t]) => {
|
|
3761
|
+
let r = i(e, li);
|
|
3757
3762
|
return {
|
|
3758
3763
|
path: r,
|
|
3759
3764
|
language: n(r),
|
|
@@ -3770,18 +3775,18 @@ async function li(e) {
|
|
|
3770
3775
|
}
|
|
3771
3776
|
//#endregion
|
|
3772
3777
|
//#region src/patterns/enable/auth/index.ts
|
|
3773
|
-
var
|
|
3774
|
-
async function
|
|
3775
|
-
let t = await
|
|
3776
|
-
if (e.env === "preview") return _(r([t, await
|
|
3777
|
-
let { generate: n } = await import("./chunks/generate.runtime-
|
|
3778
|
+
var di = "enable-auth", fi = "1.0.7", pi = "src/patterns/enable/auth", mi = "/enable/auth";
|
|
3779
|
+
async function hi(e) {
|
|
3780
|
+
let t = await si(e);
|
|
3781
|
+
if (e.env === "preview") return _(r([t, await ui(e)]));
|
|
3782
|
+
let { generate: n } = await import("./chunks/generate.runtime-DTZ1PeDS.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
3778
3783
|
return a(await _(r([t, i])), e);
|
|
3779
3784
|
}
|
|
3780
|
-
var
|
|
3781
|
-
version:
|
|
3782
|
-
slug:
|
|
3783
|
-
source:
|
|
3784
|
-
docs:
|
|
3785
|
+
var gi = {
|
|
3786
|
+
version: fi,
|
|
3787
|
+
slug: di,
|
|
3788
|
+
source: pi,
|
|
3789
|
+
docs: mi,
|
|
3785
3790
|
plan: "open",
|
|
3786
3791
|
title: "Enable authentication",
|
|
3787
3792
|
summary: "Enables authentication.",
|
|
@@ -3810,8 +3815,8 @@ var hi = {
|
|
|
3810
3815
|
examples: [],
|
|
3811
3816
|
tests: 18,
|
|
3812
3817
|
baseline: "velastack",
|
|
3813
|
-
generate:
|
|
3814
|
-
},
|
|
3818
|
+
generate: hi
|
|
3819
|
+
}, _i = /* @__PURE__ */ Object.assign({
|
|
3815
3820
|
"./creates/src/lib/components/app-sidebar.svelte": "<script lang=\"ts\">\n import type { ComponentProps } from 'svelte';\n import HomeIcon from '@lucide/svelte/icons/home';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n\n let {\n user,\n meta,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & { user: any; meta: any } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src=\"/favicon.svg\" alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{meta.appName}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} />\n </Sidebar.Footer>\n</Sidebar.Root>\n",
|
|
3816
3821
|
"./creates/src/lib/components/nav-main.svelte": "<script lang=\"ts\">\n import type { Component } from 'svelte';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import { page } from '$app/state';\n\n const isActive = (url: string) => {\n return page.url.pathname.startsWith(url);\n };\n\n let {\n items\n }: {\n items: {\n title: string;\n url: string;\n icon: Component;\n items?: {\n title: string;\n url: string;\n }[];\n }[];\n } = $props();\n<\/script>\n\n<Sidebar.Group>\n <Sidebar.Menu>\n {#each items as item (item.title)}\n <Sidebar.MenuItem>\n <Sidebar.MenuButton isActive={isActive(item.url)}>\n {#snippet child({ props })}\n <a href={item.url} {...props}>\n <item.icon />\n <span>{item.title}</span>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n {/each}\n </Sidebar.Menu>\n</Sidebar.Group>\n",
|
|
3817
3822
|
"./creates/src/lib/components/nav-user.svelte": "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n \n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n",
|
|
@@ -3860,10 +3865,10 @@ var hi = {
|
|
|
3860
3865
|
"./creates/src/routes/(public)/signup/+page.svelte": "<script lang=\"ts\">\n import { Button } from \"$lib/components/ui/button\";\n import * as Card from \"$lib/components/ui/card\";\n import { Input } from \"$lib/components/ui/input\";\n import PocketBase from \"pocketbase-sveltekit\";\n import { goto } from \"$app/navigation\";\n import { page } from \"$app/state\";\n import { signupForm } from \"./form.remote\";\n\n let { data } = $props();\n let authMethods = $derived(data.authMethods);\n\n const redirect = page.url.searchParams.get(\"redirect\");\n const hasOAuth2 = $derived(\n authMethods.oauth2.enabled && authMethods.oauth2.providers.length > 0,\n );\n const hasAuthMethods = $derived(\n authMethods.password.enabled || authMethods.otp.enabled || hasOAuth2,\n );\n\n const handleOAuth2 = (provider: string) => {\n const pb = new PocketBase(\"/\");\n\n pb.collection(\"users\")\n .authWithOAuth2({ provider, createData: {} })\n .then(() => goto(\"/dashboard\"));\n };\n<\/script>\n\n<div class=\"h-full flex flex-col items-center justify-center gap-6 p-6 md:p-10\">\n <div class=\"flex w-full max-w-sm flex-col gap-6\">\n <a href=\"/\" class=\"flex items-center gap-2 self-center font-medium\">\n <div\n class=\"bg-primary text-primary-foreground flex size-6 items-center justify-center rounded-md\"\n >\n <img src=\"/favicon.svg\" alt=\"logo\" class=\"size-4\" />\n </div>\n {data.meta.appName}\n </a>\n\n <div class=\"flex flex-col gap-6\">\n <Card.Root>\n {#if hasAuthMethods}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Create an account</Card.Title>\n {#if hasOAuth2}\n <Card.Description>Choose a sign up method</Card.Description>\n {:else}\n <Card.Description>Use your email to sign up</Card.Description>\n {/if}\n </Card.Header>\n {:else}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Signups are disabled</Card.Title>\n <Card.Description\n >Check back later for signup options</Card.Description\n >\n </Card.Header>\n {/if}\n <Card.Content>\n <form {...signupForm}>\n <div class=\"grid gap-6\">\n {#if hasOAuth2}\n <div class=\"flex flex-col gap-4\">\n {#each authMethods.oauth2.providers as provider}\n <Button\n variant=\"outline\"\n class=\"w-full\"\n onclick={() => handleOAuth2(provider.name)}\n >\n <img\n src=\"/admin/_/images/oauth2/{provider.name}.svg\"\n class=\"size-5 bg-white p-0.5 rounded-sm\"\n alt=\"\"\n />\n Login with {provider.displayName}\n </Button>\n {/each}\n </div>\n {/if}\n\n {#if authMethods.password.enabled}\n {#if hasOAuth2}\n <div\n class=\"after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t\"\n >\n <span\n class=\"bg-card text-muted-foreground relative z-10 px-2\"\n >\n Or continue with\n </span>\n </div>\n {/if}\n\n <div class=\"grid gap-2\">\n <div class=\"space-y-2 col-span-1\">\n <label for=\"email\" class=\"text-sm font-medium\">Email</label>\n <Input\n id=\"email\"\n {...signupForm.fields.email.as(\"text\")}\n type=\"email\"\n required\n />\n {#each signupForm.fields.email.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n <div class=\"space-y-2 col-span-1\">\n <label for=\"password\" class=\"text-sm font-medium\"\n >Password</label\n >\n <Input\n id=\"password\"\n {...signupForm.fields.password.as(\"text\")}\n type=\"password\"\n required\n autocomplete=\"new-password\"\n />\n {#each signupForm.fields.password.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n <div class=\"space-y-2 col-span-1\">\n <label for=\"passwordConfirm\" class=\"text-sm font-medium\"\n >Confirm Password</label\n >\n <Input\n id=\"passwordConfirm\"\n {...signupForm.fields.passwordConfirm.as(\"text\")}\n type=\"password\"\n required\n autocomplete=\"new-password\"\n />\n {#each signupForm.fields.passwordConfirm.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n {#if signupForm.result?.message}\n <div class=\"text-destructive text-sm font-medium -mt-2\">\n {signupForm.result.message}\n </div>\n {/if}\n\n <Button type=\"submit\" class=\"w-full\">Create account</Button>\n </div>\n {/if}\n\n <div class=\"text-center text-sm\">\n Already have an account?\n <a\n href=\"/login{redirect\n ? `?redirect=${encodeURIComponent(redirect)}`\n : ''}\"\n class=\"underline underline-offset-4\"\n >\n Log in\n </a>\n </div>\n </div>\n </form>\n </Card.Content>\n </Card.Root>\n <div\n class=\"text-muted-foreground *:[a]:hover:text-primary *:[a]:underline *:[a]:underline-offset-4 text-balance text-center text-xs\"\n >\n By clicking continue, you agree to our <a href=\"/terms\"\n >Terms of Service</a\n >\n and <a href=\"/privacy\">Privacy Policy</a>.\n </div>\n </div>\n </div>\n</div>\n",
|
|
3861
3866
|
"./creates/src/routes/(public)/signup/form.remote.ts": "import { form, getRequestEvent } from \"$app/server\";\nimport { error, redirect } from \"@sveltejs/kit\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { dev } from \"$app/environment\";\nimport { signupSchema } from \"$lib/schemas/signup\";\n\nexport const signupForm = form(signupSchema, async (data) => {\n const { locals, cookies, url } = getRequestEvent();\n\n let user;\n\n try {\n user = await locals.admin.collection(\"users\").create({\n email: data.email,\n password: data.password,\n passwordConfirm: data.passwordConfirm,\n });\n } catch (err: any) {\n const response = err?.response ?? {};\n const fieldError = response?.data\n ? Object.values(response.data)[0]\n : undefined;\n const message =\n (fieldError as any)?.message ??\n response?.message ??\n \"Failed to create account.\";\n error(400, message);\n }\n\n await locals.pb.collection(\"users\").requestVerification(user.email);\n await locals.pb\n .collection(\"users\")\n .authWithPassword(data.email, data.password);\n\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n const cookie = locals.pb.authStore.getCookie();\n cookies.set(\"pb_auth\", cookie, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n setFlash(\n { type: \"toast\", message: \"We sent a confirmation link to your email.\" },\n cookies,\n );\n redirect(303, redirectUrl);\n});\n",
|
|
3862
3867
|
"./creates/src/routes/(public)/signup/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /signup\", () => {\n it(\"should render the signup page\", async (context) => {\n const response = await context.request.get(\n \"/signup\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n"
|
|
3863
|
-
}),
|
|
3864
|
-
async function
|
|
3865
|
-
let t = Object.entries(
|
|
3866
|
-
let r = i(e,
|
|
3868
|
+
}), vi = "./creates/";
|
|
3869
|
+
async function yi(e) {
|
|
3870
|
+
let t = Object.entries(_i).map(([e, t]) => {
|
|
3871
|
+
let r = i(e, vi);
|
|
3867
3872
|
return {
|
|
3868
3873
|
path: r,
|
|
3869
3874
|
language: n(r),
|
|
@@ -3954,17 +3959,17 @@ async function vi(e) {
|
|
|
3954
3959
|
}
|
|
3955
3960
|
//#endregion
|
|
3956
3961
|
//#region src/patterns/enable/auth-remote/generate.preview.ts
|
|
3957
|
-
var
|
|
3962
|
+
var bi = /* @__PURE__ */ Object.assign({
|
|
3958
3963
|
"./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n auth: { protectedRoutes: [\"/(app)\"] },\n});\n",
|
|
3959
3964
|
"./preview-modifies/src/routes/(public)/root-layout.svelte": "<script lang=\"ts\">\n import { toggleMode } from \"mode-watcher\";\n import * as Navbar from \"$lib/components/ui/navbar\";\n import { Button } from \"$lib/components/ui/button\";\n // [!code highlight:2]\n import * as AuthMenu from \"$lib/components/ui/auth-menu\";\n import * as Avatar from \"$lib/components/ui/avatar\";\n\n let { children, data } = $props();\n<\/script>\n\n<div class=\"min-h-dvh grid grid-rows-[max-content_1fr_max-content] root-layout\">\n <Navbar.Root>\n <Navbar.Brand href=\"/\">\n <Navbar.Logo src=\"/favicon.svg\" alt=\"Logo\" />\n </Navbar.Brand>\n\n <Navbar.MobileToggle />\n\n <Navbar.List>\n <Navbar.Item>\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n href=\"/\"\n variant=\"ghost\"\n >\n Home\n </Button>\n </Navbar.Item>\n\n <!-- [!code highlight:44] -->\n <Navbar.Item\n class=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n >\n <AuthMenu.Root>\n {#snippet user()}\n <AuthMenu.Trigger>\n <Avatar.Root>\n {#if data.user?.avatar}\n <Avatar.Image\n src=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n alt={data.user?.email}\n />\n {/if}\n <Avatar.Fallback>\n {data.user?.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n </AuthMenu.Trigger>\n <AuthMenu.Content align=\"end\">\n <AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n <AuthMenu.Group>\n <AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n <AuthMenu.Item>\n <form action=\"/logout\" method=\"post\">\n <button type=\"submit\" class=\"contents\">Logout</button>\n </form>\n </AuthMenu.Item>\n </AuthMenu.Group>\n </AuthMenu.Content>\n {/snippet}\n {#snippet guest()}\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"ghost\"\n href=\"/login\">Login</Button\n >\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"outline\"\n href=\"/signup\">Sign up</Button\n >\n {/snippet}\n </AuthMenu.Root>\n </Navbar.Item>\n </Navbar.List>\n </Navbar.Root>\n\n {@render children?.()}\n\n <footer class=\"border-t border-border py-4\">\n <div\n class=\"mx-auto flex max-w-7xl px-4 flex-col items-center justify-between gap-3 sm:flex-row\"\n >\n <p class=\"text-muted-foreground text-sm\">\n © {new Date().getFullYear()}\n {data.meta.appName}. All rights reserved.\n </p>\n <nav class=\"flex items-center gap-4 text-sm\">\n <Button onclick={toggleMode} variant=\"ghost\" size=\"icon\">\n <Navbar.Mode />\n </Button>\n <a href=\"/privacy\" class=\"underline-offset-4 hover:underline\">Privacy</a\n >\n <a href=\"/terms\" class=\"underline-offset-4 hover:underline\">Terms</a>\n </nav>\n </div>\n </footer>\n</div>\n\n<style lang=\"postcss\">\n @reference \"tailwindcss\";\n\n .root-layout :global(section[data-role=\"content\"]) {\n @apply container mx-auto max-w-7xl px-4 py-8 w-full;\n }\n</style>\n",
|
|
3960
3965
|
"./preview-modifies/src/routes/+layout.server.ts": "import { loadFlash } from \"sveltekit-flash-message/server\";\n\nexport const load = loadFlash(async ({ locals }) => {\n return {\n // [!code highlight:1]\n user: locals.pb.authStore.record,\n };\n});\n",
|
|
3961
3966
|
"./preview-modifies/svelte.config.js": "import adapter from \"@sveltejs/adapter-auto\";\nimport { vitePreprocess } from \"@sveltejs/vite-plugin-svelte\";\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n preprocess: vitePreprocess(),\n kit: {\n adapter,\n // [!code highlight:3]\n experimental: {\n remoteFunctions: true,\n },\n },\n // [!code highlight:5]\n compilerOptions: {\n experimental: {\n async: true,\n },\n },\n};\n\nexport default config;\n"
|
|
3962
|
-
}),
|
|
3963
|
-
async function
|
|
3967
|
+
}), xi = "./preview-modifies/";
|
|
3968
|
+
async function Si(e) {
|
|
3964
3969
|
return {
|
|
3965
3970
|
creates: [],
|
|
3966
|
-
modifies: Object.entries(
|
|
3967
|
-
let r = i(e,
|
|
3971
|
+
modifies: Object.entries(bi).map(([e, t]) => {
|
|
3972
|
+
let r = i(e, xi);
|
|
3968
3973
|
return {
|
|
3969
3974
|
path: r,
|
|
3970
3975
|
language: n(r),
|
|
@@ -3981,18 +3986,18 @@ async function xi(e) {
|
|
|
3981
3986
|
}
|
|
3982
3987
|
//#endregion
|
|
3983
3988
|
//#region src/patterns/enable/auth-remote/index.ts
|
|
3984
|
-
var
|
|
3985
|
-
async function
|
|
3986
|
-
let t = await
|
|
3987
|
-
if (e.env === "preview") return _(r([t, await
|
|
3988
|
-
let { generate: n } = await import("./chunks/generate.runtime-
|
|
3989
|
+
var Ci = "enable-auth-remote", wi = "1.0.0", Ti = "src/patterns/enable/auth-remote", Ei = "/enable/auth-remote";
|
|
3990
|
+
async function Di(e) {
|
|
3991
|
+
let t = await yi(e);
|
|
3992
|
+
if (e.env === "preview") return _(r([t, await Si(e)]));
|
|
3993
|
+
let { generate: n } = await import("./chunks/generate.runtime-Cbq2649r.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
3989
3994
|
return a(await _(r([t, i])), e);
|
|
3990
3995
|
}
|
|
3991
|
-
var
|
|
3992
|
-
version:
|
|
3993
|
-
slug:
|
|
3994
|
-
source:
|
|
3995
|
-
docs:
|
|
3996
|
+
var Oi = {
|
|
3997
|
+
version: wi,
|
|
3998
|
+
slug: Ci,
|
|
3999
|
+
source: Ti,
|
|
4000
|
+
docs: Ei,
|
|
3996
4001
|
plan: "open",
|
|
3997
4002
|
title: "Enable authentication (remote functions)",
|
|
3998
4003
|
summary: "Enables authentication using SvelteKit remote functions for login, signup, reset, and settings forms.",
|
|
@@ -4022,12 +4027,12 @@ var Di = {
|
|
|
4022
4027
|
examples: [],
|
|
4023
4028
|
tests: 18,
|
|
4024
4029
|
baseline: "velastack",
|
|
4025
|
-
generate:
|
|
4026
|
-
},
|
|
4027
|
-
async function
|
|
4030
|
+
generate: Di
|
|
4031
|
+
}, ki = /* @__PURE__ */ Object.assign({ "./creates/src/routes/api/server.test.ts": "import { describe, expect, it } from \"vitest\";\n\ndescribe(\"GET /api/health\", () => {\n it(\"should return a 200 status code\", async (context) => {\n const response = await context.request.get(\"/api/health\");\n expect(response.status).toBe(200);\n });\n});\n" }), Ai = "./creates/";
|
|
4032
|
+
async function ji(e) {
|
|
4028
4033
|
return {
|
|
4029
|
-
creates: Object.entries(
|
|
4030
|
-
let r = i(e,
|
|
4034
|
+
creates: Object.entries(ki).map(([e, t]) => {
|
|
4035
|
+
let r = i(e, Ai);
|
|
4031
4036
|
return {
|
|
4032
4037
|
path: r,
|
|
4033
4038
|
language: n(r),
|
|
@@ -4045,12 +4050,12 @@ async function Ai(e) {
|
|
|
4045
4050
|
}
|
|
4046
4051
|
//#endregion
|
|
4047
4052
|
//#region src/patterns/enable/api/generate.preview.ts
|
|
4048
|
-
var
|
|
4049
|
-
async function
|
|
4053
|
+
var Mi = /* @__PURE__ */ Object.assign({ "./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n // [!code highlight:1]\n api: { enabled: true },\n});\n" }), Ni = "./preview-modifies/";
|
|
4054
|
+
async function Pi(e) {
|
|
4050
4055
|
return {
|
|
4051
4056
|
creates: [],
|
|
4052
|
-
modifies: Object.entries(
|
|
4053
|
-
let r = i(e,
|
|
4057
|
+
modifies: Object.entries(Mi).map(([e, t]) => {
|
|
4058
|
+
let r = i(e, Ni);
|
|
4054
4059
|
return {
|
|
4055
4060
|
path: r,
|
|
4056
4061
|
language: n(r),
|
|
@@ -4067,18 +4072,18 @@ async function Ni(e) {
|
|
|
4067
4072
|
}
|
|
4068
4073
|
//#endregion
|
|
4069
4074
|
//#region src/patterns/enable/api/index.ts
|
|
4070
|
-
var
|
|
4071
|
-
async function
|
|
4072
|
-
let t = await
|
|
4073
|
-
if (e.env === "preview") return _(r([t, await
|
|
4074
|
-
let { generate: n } = await import("./chunks/generate.runtime-
|
|
4075
|
+
var Fi = "enable-api", Ii = "1.0.7", Li = "src/patterns/enable/api", Ri = "/enable/api";
|
|
4076
|
+
async function zi(e) {
|
|
4077
|
+
let t = await ji(e);
|
|
4078
|
+
if (e.env === "preview") return _(r([t, await Pi(e)]));
|
|
4079
|
+
let { generate: n } = await import("./chunks/generate.runtime-Caqa5ndO.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
4075
4080
|
return a(await _(r([t, i])), e);
|
|
4076
4081
|
}
|
|
4077
|
-
var
|
|
4078
|
-
version:
|
|
4079
|
-
slug:
|
|
4080
|
-
source:
|
|
4081
|
-
docs:
|
|
4082
|
+
var Bi = {
|
|
4083
|
+
version: Ii,
|
|
4084
|
+
slug: Fi,
|
|
4085
|
+
source: Li,
|
|
4086
|
+
docs: Ri,
|
|
4082
4087
|
plan: "open",
|
|
4083
4088
|
title: "Enable API",
|
|
4084
4089
|
summary: "Enables the PocketBase API.",
|
|
@@ -4107,8 +4112,8 @@ var zi = {
|
|
|
4107
4112
|
examples: [],
|
|
4108
4113
|
tests: 1,
|
|
4109
4114
|
baseline: "velastack",
|
|
4110
|
-
generate:
|
|
4111
|
-
},
|
|
4115
|
+
generate: zi
|
|
4116
|
+
}, Vi = /* @__PURE__ */ Object.assign({
|
|
4112
4117
|
"./creates/src/lib/schemas/apiKey.ts": "import { z } from \"zod\";\nimport type { Schemas } from \"@velastack/pocketbase\";\n\nexport const apiKeySchema = z.object({\n label: z.string().optional(),\n}) satisfies Schemas[\"api_keys\"];\n",
|
|
4113
4118
|
"./creates/src/routes/(app)/api-keys/+page.server.ts": "export const load = async ({ locals }) => {\n const apiKeys = await locals.pb.collection(\"api_keys\").getFullList();\n return { apiKeys };\n};\n",
|
|
4114
4119
|
"./creates/src/routes/(app)/api-keys/+page.svelte": "<script lang=\"ts\">\n import { getFlash } from 'sveltekit-flash-message';\n import { page } from '$app/state';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import { Button } from '$lib/components/ui/button';\n import { Badge } from '$lib/components/ui/badge';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import SquareDashedMousePointerIcon from '@lucide/svelte/icons/square-dashed-mouse-pointer';\n\n const flash = getFlash(page);\n\n let open = $state(false);\n let message = $state('');\n let title = $state('');\n let apiKey = $state('');\n\n $effect(() => {\n if (!$flash) return;\n\n if ($flash.type === 'success') {\n message = $flash.message;\n title = $flash.title;\n apiKey = $flash.apiKey;\n open = true;\n }\n\n $flash = undefined;\n });\n\n async function handleAction() {\n open = false;\n await navigator.clipboard.writeText(apiKey);\n }\n\n let { data } = $props();\n<\/script>\n\n<section data-role=\"content\">\n <div class=\"flex justify-between items-center mb-4\">\n <h1 class=\"text-3xl font-bold tracking-tight\">API keys</h1>\n <Button href=\"/api-keys/new\" variant=\"outline\">\n <PlusIcon class=\"w-4 h-4\" />\n New API key\n </Button>\n </div>\n\n <AlertDialog.Root bind:open>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>{title}</AlertDialog.Title>\n <AlertDialog.Description>\n <p>{@html message}</p>\n <Badge variant=\"outline\" class=\"font-mono my-3 text-base\">{apiKey}</Badge>\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel>Close</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleAction}>Copy</AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n </AlertDialog.Root>\n\n <div class=\"rounded-lg border bg-card overflow-hidden\">\n <div class=\"relative w-full overflow-auto\">\n {#if data.apiKeys.length === 0}\n <div class=\"p-4 text-center text-muted-foreground space-y-4 py-12\">\n <SquareDashedMousePointerIcon strokeWidth={1.2} class=\"w-8 h-8 mx-auto mb-2\" />\n <p>Seems like there are no API keys yet, but you can create the first one</p>\n <p class=\"text-sm text-muted-foreground\">\n <Button href=\"/api-keys/new\" variant=\"outline\">\n <PlusIcon class=\"w-4 h-4\" />\n New API key\n </Button>\n </p>\n </div>\n {:else}\n <table class=\"w-full caption-bottom text-sm\">\n <thead>\n <tr class=\"border-b\">\n <th class=\"h-12 px-4 text-left align-middle font-medium text-muted-foreground\"\n >Label</th\n >\n <th class=\"h-12 px-4 text-left align-middle font-medium text-muted-foreground\"\n >API key</th\n >\n <th class=\"h-12 px-4 text-left align-middle font-medium text-muted-foreground\"\n >Created</th\n >\n <th class=\"h-12 px-4 text-left align-middle font-medium text-muted-foreground\"\n >Last used</th\n >\n <th class=\"h-12 px-4 text-right align-middle font-medium text-muted-foreground\"></th>\n </tr>\n </thead>\n <tbody>\n {#each data.apiKeys as apiKey}\n <tr\n class=\"border-t transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted\"\n >\n <td class=\"p-4 align-middle font-medium\">{apiKey.label}</td>\n\n <td class=\"p-4 align-middle font-medium\">\n <Badge variant=\"outline\" class=\"font-mono\">\n {apiKey.id}.***************\n </Badge>\n </td>\n\n <td class=\"p-4 align-middle font-medium\">\n {#if apiKey.created}\n {new Date(apiKey.created).toLocaleDateString()}\n {/if}\n </td>\n\n <td class=\"p-4 align-middle font-medium\">\n {#if apiKey.last_used}\n {new Date(apiKey.last_used).toLocaleDateString()}\n {:else}\n Never\n {/if}\n </td>\n\n <td class=\"p-4 align-middle text-right\">\n <form method=\"POST\" action=\"/api-keys/{apiKey.id}?/delete\" class=\"contents\">\n <Button\n variant=\"ghost\"\n class=\"h-8 px-2 text-destructive hover:text-destructive\"\n type=\"submit\">Delete</Button\n >\n </form>\n </td>\n </tr>\n {/each}\n </tbody>\n </table>\n {/if}\n </div>\n </div>\n</section>\n",
|
|
@@ -4118,11 +4123,11 @@ var zi = {
|
|
|
4118
4123
|
"./creates/src/routes/(app)/api-keys/new/create-api-key.ts": "import PocketBase from \"pocketbase-sveltekit\";\nimport argon2 from \"argon2\";\nimport { randomBytes } from \"node:crypto\";\n\nexport const createApiKey = async (\n pb: PocketBase,\n userId: string | undefined,\n label: string,\n) => {\n const keySecret = randomBytes(10).toString(\"hex\");\n const keyHash = await argon2.hash(keySecret, { type: argon2.argon2id });\n const apiKey = await pb\n .collection(\"api_keys\")\n .create({ key_hash: keyHash, user: userId, label });\n\n return `${apiKey.id}.${keySecret}`;\n};\n",
|
|
4119
4124
|
"./creates/src/routes/(app)/api-keys/new/server.test.ts": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport { createApiKey } from \"./create-api-key\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /api-keys/new\", () => {\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n });\n\n it(\"should return a 200 status code\", async (context) => {\n const response = await context.agent.get(\n \"/api-keys/new\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n\ndescribe(\"POST /api-keys/new\", () => {\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n });\n\n it(\"should create a new API key\", async (context) => {\n const response = await context.agent\n .post(\"/api-keys/new\")\n .type(\"form\")\n .send({ label: \"Test API Key\" });\n expect(response.body.status).toBe(303);\n expect(response.body.location).toBe(\"/api-keys\");\n });\n});\n\ndescribe(\"api keys authenticate as a user\", () => {\n it(\"should create a new api key\", async (context) => {\n const apiKey = await createApiKey(\n context.pb,\n context.user.id,\n \"Test API Key\",\n );\n expect(apiKey).toBeDefined();\n });\n\n it(\"should throw an error when creating for a non-existent user\", async (context) => {\n await expect(async () => {\n await createApiKey(context.pb, \"non-existent-user-id\", \"Test API Key\");\n }).rejects.toThrow();\n });\n\n it(\"should give access to the api\", async (context) => {\n const response = await context.request.get(\n `/api/collections/users/records/${context.user.id}`,\n );\n expect(response.status).toBe(404);\n\n const apiKey = await createApiKey(\n context.pb,\n context.user.id,\n \"Test API Key\",\n );\n const response2 = await context.request\n .get(`/api/collections/users/records/${context.user.id}`)\n .set(\"Authorization\", `Bearer ${apiKey}`);\n expect(response2.status).toBe(200);\n });\n});\n",
|
|
4120
4125
|
"./creates/src/routes/(app)/api-keys/server.test.ts": "import { describe, it, expect, beforeEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /api-keys\", () => {\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n });\n\n it(\"should return a 200 status code\", async (context) => {\n const response = await context.agent.get(\n \"/api-keys\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n"
|
|
4121
|
-
}),
|
|
4122
|
-
async function
|
|
4126
|
+
}), Hi = "./creates/";
|
|
4127
|
+
async function Ui(e) {
|
|
4123
4128
|
return {
|
|
4124
|
-
creates: Object.entries(
|
|
4125
|
-
let r = i(e,
|
|
4129
|
+
creates: Object.entries(Vi).map(([e, t]) => {
|
|
4130
|
+
let r = i(e, Hi);
|
|
4126
4131
|
return {
|
|
4127
4132
|
path: r,
|
|
4128
4133
|
language: n(r),
|
|
@@ -4144,12 +4149,12 @@ async function Hi(e) {
|
|
|
4144
4149
|
}
|
|
4145
4150
|
//#endregion
|
|
4146
4151
|
//#region src/patterns/enable/api-keys/generate.preview.ts
|
|
4147
|
-
var
|
|
4148
|
-
async function
|
|
4152
|
+
var Wi = /* @__PURE__ */ Object.assign({ "./preview-modifies/src/hooks.server.ts": "import {\n POCKETBASE_URL,\n POCKETBASE_SUPERUSER_EMAIL,\n POCKETBASE_SUPERUSER_PASSWORD,\n} from \"$env/static/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n\nexport const handle = handlePocketbase({\n pocketbaseUrl: POCKETBASE_URL,\n superuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: POCKETBASE_SUPERUSER_PASSWORD,\n api: {\n enabled: true,\n // [!code highlight:1]\n apiKeys: { enabled: true },\n },\n});\n" }), Gi = "./preview-modifies/";
|
|
4153
|
+
async function Ki(e) {
|
|
4149
4154
|
return {
|
|
4150
4155
|
creates: [],
|
|
4151
|
-
modifies: Object.entries(
|
|
4152
|
-
let r = i(e,
|
|
4156
|
+
modifies: Object.entries(Wi).map(([e, t]) => {
|
|
4157
|
+
let r = i(e, Gi);
|
|
4153
4158
|
return {
|
|
4154
4159
|
path: r,
|
|
4155
4160
|
language: n(r),
|
|
@@ -4166,18 +4171,18 @@ async function Gi(e) {
|
|
|
4166
4171
|
}
|
|
4167
4172
|
//#endregion
|
|
4168
4173
|
//#region src/patterns/enable/api-keys/index.ts
|
|
4169
|
-
var
|
|
4170
|
-
async function
|
|
4171
|
-
let t = await
|
|
4172
|
-
if (e.env === "preview") return _(r([t, await
|
|
4173
|
-
let { generate: n } = await import("./chunks/generate.runtime-
|
|
4174
|
+
var qi = "enable-api-keys", Ji = "1.0.0", Yi = "src/patterns/enable/api-keys", Xi = "/enable/api-keys";
|
|
4175
|
+
async function Zi(e) {
|
|
4176
|
+
let t = await Ui(e);
|
|
4177
|
+
if (e.env === "preview") return _(r([t, await Ki(e)]));
|
|
4178
|
+
let { generate: n } = await import("./chunks/generate.runtime-y1Ga_5QI.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
4174
4179
|
return a(await _(r([t, i])), e);
|
|
4175
4180
|
}
|
|
4176
|
-
var
|
|
4177
|
-
version:
|
|
4178
|
-
slug:
|
|
4179
|
-
source:
|
|
4180
|
-
docs:
|
|
4181
|
+
var Qi = {
|
|
4182
|
+
version: Ji,
|
|
4183
|
+
slug: qi,
|
|
4184
|
+
source: Yi,
|
|
4185
|
+
docs: Xi,
|
|
4181
4186
|
plan: "open",
|
|
4182
4187
|
title: "Enable API keys",
|
|
4183
4188
|
summary: "Adds API key management for authenticated users and PocketBase API access.",
|
|
@@ -4206,17 +4211,17 @@ var Zi = {
|
|
|
4206
4211
|
examples: [],
|
|
4207
4212
|
tests: 6,
|
|
4208
4213
|
baseline: "velastack",
|
|
4209
|
-
generate:
|
|
4210
|
-
},
|
|
4214
|
+
generate: Zi
|
|
4215
|
+
}, $i = /* @__PURE__ */ Object.assign({
|
|
4211
4216
|
"./creates/src/hooks.ts": "import { deLocalizeDefault } from \"wuchale/url\";\nimport { matchUrl } from \"$locales/main.url\";\nimport { locales } from \"$locales/data\";\n\nexport const reroute = ({ url }) => {\n const [upath, locale] = deLocalizeDefault(url.pathname, locales);\n const { path } = matchUrl(upath, locale);\n return path ?? url.pathname;\n};\n",
|
|
4212
4217
|
"./creates/src/lib/components/language-select.svelte": "<script lang=\"ts\">\n import * as Select from \"$lib/components/ui/select/index.js\";\n import { locales, type Locale } from \"$locales/data.js\";\n import { page } from \"$app/state\";\n import { goto } from \"$app/navigation\";\n import { deLocalizeDefault } from \"wuchale/url\";\n import { defaultLocale, translateUrl } from \"$lib/url\";\n\n let locale: Locale = $derived.by(() => {\n const [_, locale] = deLocalizeDefault(page.url.pathname, locales);\n return locale ?? defaultLocale;\n });\n\n function localeDisplayName(code: Locale): string {\n const names = new Intl.DisplayNames([code], { type: \"language\" });\n const raw = names.of(code);\n if (!raw) return code;\n return raw.charAt(0).toLocaleUpperCase(code) + raw.slice(1);\n }\n\n const localeNames: Record<string, string> = locales.reduce(\n (acc, loc) => {\n acc[loc] = localeDisplayName(loc);\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const handleValueChange = (value: string) => {\n const translatedUrl = translateUrl(\n page.url.pathname,\n locale,\n value as Locale,\n );\n goto(translatedUrl, { invalidateAll: true });\n };\n\n let { class: className }: { class?: string } = $props();\n<\/script>\n\n<Select.Root type=\"single\" value={locale} onValueChange={handleValueChange}>\n <Select.Trigger class={className}>{localeNames[locale]}</Select.Trigger>\n <Select.Content>\n {#each locales as locale}\n <Select.Item value={locale}>{localeNames[locale]}</Select.Item>\n {/each}\n </Select.Content>\n</Select.Root>\n",
|
|
4213
4218
|
"./creates/src/lib/url.ts": "import { deLocalizeDefault, fillParams } from \"wuchale/url\";\nimport type { Locale } from \"../locales/data\";\nimport { matchUrl } from \"../locales/main.url\";\nimport { locales } from \"../locales/data\";\n\nexport const defaultLocale = \"en\";\n\nexport function localize(path: string, locale: Locale) {\n if (locale === defaultLocale) {\n return path;\n }\n\n return `/${locale}${path}`;\n}\n\nexport function translateUrl(\n url: string,\n fromLocale: Locale,\n toLocale: Locale,\n) {\n const [pathOnly] = deLocalizeDefault(url, locales);\n const result = matchUrl(pathOnly, fromLocale);\n if (result.path !== null) {\n const targetPath = fillParams(result.params, result.altPatterns[toLocale]);\n return localize(targetPath, toLocale);\n }\n return localize(url, toLocale);\n}\n",
|
|
4214
4219
|
"./creates/wuchale.config.js": "// @ts-check\nimport { adapter as svelte } from \"@wuchale/svelte\";\nimport { adapter as js } from \"wuchale/adapter-vanilla\";\nimport { defineConfig } from \"wuchale\";\n\nexport default defineConfig({\n locales: [\"en\", \"es\"],\n adapters: {\n main: svelte({\n loader: \"sveltekit\",\n url: { localize: true, patterns: [\"/\"] },\n }),\n js: js({\n loader: \"vite\",\n files: [\n \"src/**/+{page,layout}.{js,ts}\",\n \"src/**/+{page,layout}.server.{js,ts}\",\n ],\n }),\n },\n});\n"
|
|
4215
|
-
}),
|
|
4216
|
-
async function
|
|
4220
|
+
}), ea = "./creates/";
|
|
4221
|
+
async function ta(e) {
|
|
4217
4222
|
return {
|
|
4218
|
-
creates: Object.entries(
|
|
4219
|
-
let r = i(e,
|
|
4223
|
+
creates: Object.entries($i).map(([e, t]) => {
|
|
4224
|
+
let r = i(e, ea);
|
|
4220
4225
|
return {
|
|
4221
4226
|
path: r,
|
|
4222
4227
|
language: n(r),
|
|
@@ -4234,19 +4239,19 @@ async function ea(e) {
|
|
|
4234
4239
|
}
|
|
4235
4240
|
//#endregion
|
|
4236
4241
|
//#region src/patterns/enable/i18n/generate.preview.ts
|
|
4237
|
-
var
|
|
4242
|
+
var na = /* @__PURE__ */ Object.assign({
|
|
4238
4243
|
"./preview-modifies/src/app.html": "<!doctype html>\n<!-- [!code highlight:1] -->\n<html lang=\"%sveltekit.lang%\">\n <head>\n <meta charset=\"utf-8\" />\n </head>\n\n <body>\n <div style=\"display: contents\">%sveltekit.body%</div>\n </body>\n</html>\n",
|
|
4239
4244
|
"./preview-modifies/src/hooks.server.ts": "import { env } from \"$env/dynamic/private\";\nimport { handlePocketbase } from \"@velastack/pocketbase\";\n// [!code highlight:6]\nimport { sequence } from \"@sveltejs/kit/hooks\";\nimport { runWithLocale, loadLocales } from \"wuchale/load-utils/server\";\nimport { getLocale } from \"$locales/main.url\";\nimport { locales } from \"$locales/data\";\nimport * as main from \"$locales/main.loader.server.svelte.js\";\nimport * as js from \"$locales/js.loader.server.js\";\n\n// [!code highlight:2]\nloadLocales(main.key, main.loadIDs, main.loadCatalog, locales);\nloadLocales(js.key, js.loadIDs, js.loadCatalog, locales);\n\n// [!code highlight:9]\nconst handleWuchale = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace(\"%sveltekit.lang%\", locale),\n }),\n );\n};\n\nexport const handle = sequence(\n // [!code highlight:1]\n handleWuchale,\n handlePocketbase({\n pocketbaseUrl: env.POCKETBASE_URL,\n superuserEmail: env.POCKETBASE_SUPERUSER_EMAIL,\n superuserPassword: env.POCKETBASE_SUPERUSER_PASSWORD,\n }),\n);\n",
|
|
4240
4245
|
"./preview-modifies/src/routes/(public)/root-layout.svelte": "<script lang=\"ts\">\n import { toggleMode } from 'mode-watcher';\n import * as Navbar from '$lib/components/ui/navbar';\n import { Button } from '$lib/components/ui/button';\n // [!code highlight]\n import LanguageSelect from '$lib/components/language-select.svelte';\n\n let { children, data } = $props();\n<\/script>\n\n<div class=\"min-h-dvh grid grid-rows-[max-content_1fr_max-content] root-layout\">\n <Navbar.Root>\n <Navbar.Brand href=\"/\">\n <Navbar.Logo src=\"/favicon.svg\" alt=\"Logo\" />\n </Navbar.Brand>\n\n <Navbar.MobileToggle />\n\n <Navbar.List>\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/\" variant=\"ghost\">\n Home\n </Button>\n </Navbar.Item>\n <!-- [!code highlight:3] -->\n <Navbar.Item>\n <LanguageSelect />\n </Navbar.Item>\n </Navbar.List>\n </Navbar.Root>\n\n {@render children?.()}\n\n <footer class=\"border-t border-border py-4\">\n <div\n class=\"mx-auto flex max-w-7xl px-4 flex-col items-center justify-between gap-3 sm:flex-row\"\n >\n <p class=\"text-muted-foreground text-sm\">\n © {new Date().getFullYear()}\n {data.meta.appName}. All rights reserved.\n </p>\n <nav class=\"flex items-center gap-4 text-sm\">\n <Button onclick={toggleMode} variant=\"ghost\" size=\"icon\">\n <Navbar.Mode />\n </Button>\n <a href=\"/privacy\" class=\"underline-offset-4 hover:underline\">Privacy</a>\n <a href=\"/terms\" class=\"underline-offset-4 hover:underline\">Terms</a>\n </nav>\n </div>\n </footer>\n</div>\n\n<style lang=\"postcss\">\n @reference \"tailwindcss\";\n\n .root-layout :global(section[data-role='content']) {\n @apply container mx-auto max-w-7xl px-4 py-8 w-full;\n }\n</style>\n",
|
|
4241
4246
|
"./preview-modifies/src/routes/+layout.ts": "import { browser } from \"$app/environment\";\n// [!code highlight:4]\nimport { loadLocale } from \"wuchale/load-utils\";\nimport { getLocale } from \"$locales/main.url\";\nimport \"$locales/main.loader.svelte\";\nimport \"$locales/js.loader\";\n\nexport const load = async ({ url, data }) => {\n // [!code highlight:5]\n const locale = getLocale(url);\n\n if (browser) {\n await loadLocale(locale);\n }\n\n return data;\n};\n",
|
|
4242
4247
|
"./preview-modifies/svelte.config.js": "import adapter from \"@sveltejs/adapter-auto\";\nimport { vitePreprocess } from \"@sveltejs/vite-plugin-svelte\";\n\nconst config = {\n preprocess: vitePreprocess(),\n kit: {\n adapter,\n // [!code highlight:3]\n alias: {\n $locales: \"src/locales\",\n },\n },\n};\n\nexport default config;\n",
|
|
4243
4248
|
"./preview-modifies/vite.config.ts": "import { defineConfig } from \"vite\";\nimport { sveltekit } from \"@sveltejs/kit/vite\";\nimport tailwindcss from \"@tailwindcss/vite\";\n// [!code highlight:1]\nimport { wuchale } from \"wuchale/vite\";\n\nexport default defineConfig({\n // [!code highlight:1]\n plugins: [wuchale(), tailwindcss(), sveltekit()],\n});\n"
|
|
4244
|
-
}),
|
|
4245
|
-
async function
|
|
4249
|
+
}), ra = "./preview-modifies/";
|
|
4250
|
+
async function ia(e) {
|
|
4246
4251
|
return {
|
|
4247
4252
|
creates: [],
|
|
4248
|
-
modifies: Object.entries(
|
|
4249
|
-
let r = i(e,
|
|
4253
|
+
modifies: Object.entries(na).map(([e, t]) => {
|
|
4254
|
+
let r = i(e, ra);
|
|
4250
4255
|
return {
|
|
4251
4256
|
path: r,
|
|
4252
4257
|
language: n(r),
|
|
@@ -4263,18 +4268,18 @@ async function ra(e) {
|
|
|
4263
4268
|
}
|
|
4264
4269
|
//#endregion
|
|
4265
4270
|
//#region src/patterns/enable/i18n/index.ts
|
|
4266
|
-
var
|
|
4267
|
-
async function
|
|
4268
|
-
let t = await
|
|
4269
|
-
if (e.env === "preview") return _(r([t, await
|
|
4270
|
-
let { generate: n } = await import("./chunks/generate.runtime-
|
|
4271
|
+
var aa = "enable-i18n", oa = "1.0.0", sa = "src/patterns/enable/i18n", ca = "/enable/i18n";
|
|
4272
|
+
async function la(e) {
|
|
4273
|
+
let t = await ta(e);
|
|
4274
|
+
if (e.env === "preview") return _(r([t, await ia(e)]));
|
|
4275
|
+
let { generate: n } = await import("./chunks/generate.runtime-D7ksYerH.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
4271
4276
|
return a(await _(r([t, i])), e);
|
|
4272
4277
|
}
|
|
4273
|
-
var
|
|
4274
|
-
version:
|
|
4275
|
-
slug:
|
|
4276
|
-
source:
|
|
4277
|
-
docs:
|
|
4278
|
+
var ua = {
|
|
4279
|
+
version: oa,
|
|
4280
|
+
slug: aa,
|
|
4281
|
+
source: sa,
|
|
4282
|
+
docs: ca,
|
|
4278
4283
|
plan: "open",
|
|
4279
4284
|
title: "Enable i18n",
|
|
4280
4285
|
summary: "Enables i18n with Wuchale and locale-aware routing.",
|
|
@@ -4302,47 +4307,47 @@ var la = {
|
|
|
4302
4307
|
examples: [],
|
|
4303
4308
|
tests: 0,
|
|
4304
4309
|
baseline: "velastack",
|
|
4305
|
-
generate:
|
|
4306
|
-
}, ua = "/// <reference path=\"../types.d.ts\" />\n\ncronAdd(\"stripe-products\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/products\");\n});\n\ncronAdd(\"stripe-prices\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/prices\");\n});\n", da = "/// <reference path=\"../types.d.ts\" />\n\nmodule.exports = {\n triggerJob: (jobUrl) => {\n $http.send({\n method: \"POST\",\n url: `${$app.settings().meta.appURL}${jobUrl}`,\n headers: {\n Authorization: `Bearer ${$os.getenv(\"INTERNAL_JOB_SECRET\")}`,\n },\n });\n },\n};\n", fa = "<script lang=\"ts\">\n import type { Stripe } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n brand?: string;\n last4?: string;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n brand,\n last4,\n clientSecret,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n const brandNames = {\n amex: 'American Express',\n cartes_bancaires: 'Cartes Bancaires',\n diners: 'Diners',\n discover: 'Discover',\n eftpos_au: 'Eftpos Au',\n jcb: 'Jcb',\n link: 'Link',\n mastercard: 'Mastercard',\n unionpay: 'Unionpay',\n visa: 'Visa',\n unknown: 'Unknown'\n };\n\n let isProcessing = $state(false);\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !clientSecret) return;\n\n isProcessing = true;\n\n try {\n const { error: confirmError } = await stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n return_url: page.url.toString()\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Confirm payment</Dialog.Title>\n <Dialog.Description>\n Are you sure you want to pay {amountFormatted} with your\n {brandNames[brand as keyof typeof brandNames]}\n credit card ending in **** {last4}?\n </Dialog.Description>\n </Dialog.Header>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", pa = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import PaymentDialog from '$lib/components/payments/payment-dialog.svelte';\n import ConfirmDialog from '$lib/components/payments/confirm-dialog.svelte';\n import { useStripe } from '$lib/components/payments/use-stripe.svelte';\n import { usePaymentIntent } from '$lib/components/payments/use-payment-intent.svelte';\n import type { ButtonProps } from '$lib/components/ui/button';\n\n interface Props {\n priceId: string;\n user?: { email: string; name: string } | null;\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n priceId,\n user,\n disabled = false,\n isProcessing = false,\n label = 'Purchase',\n processingLabel = 'Processing...',\n onsuccess,\n ...rest\n }: Props & ButtonProps = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let mode = $state<'payment' | 'confirm'>('payment');\n let showDialog = $state(false);\n let amount = $state<number>(0);\n let currency = $state<string>('usd');\n let clientSecret = $state<string>();\n let brand = $state<string>();\n let last4 = $state<string>();\n\n async function handleBuyClick() {\n const result = await paymentIntentManager.fetchPaymentIntent({\n priceId\n });\n\n if (!result) return;\n\n if (result.type === 'confirm') {\n mode = 'confirm';\n brand = result.brand;\n last4 = result.last4;\n } else if (result.type === 'payment') {\n mode = 'payment';\n }\n\n amount = result.amount || 0;\n currency = result.currency || 'usd';\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleBuyClick} {...rest}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n{#if mode === 'confirm'}\n <ConfirmDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {brand}\n {last4}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{:else if mode === 'payment'}\n <PaymentDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {clientSecret}\n {user}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{/if}\n", ma = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { Input } from '$lib/components/ui/input';\n import { Label } from '$lib/components/ui/label';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n clientSecret?: string;\n user?: { email: string; name: string } | null;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n clientSecret,\n user = null,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let savePaymentMethod = $state(false);\n let email = $state<string>();\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to pay for your purchase');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmPayment({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n billing_details: {\n email: email || user?.email\n },\n allow_redisplay: savePaymentMethod ? 'always' : 'unspecified'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>{amountFormatted}</Dialog.Title>\n <Dialog.Description>Enter your card details to pay for your purchase.</Dialog.Description>\n </Dialog.Header>\n {#if !user}\n <div class=\"space-y-2\">\n <Label for=\"email\">Email</Label>\n <Input type=\"email\" bind:value={email} />\n </div>\n {/if}\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"payment\"\n {stripe}\n {amount}\n {currency}\n {savePaymentMethod}\n {user}\n onchange={handleCardChange}\n />\n {/if}\n </div>\n {#if user}\n <div class=\"flex items-center gap-2\">\n <input type=\"checkbox\" id=\"savePaymentMethod\" bind:checked={savePaymentMethod} />\n <label for=\"savePaymentMethod\" class=\"text-sm text-muted-foreground\">\n Save payment method for future purchases\n </label>\n </div>\n {/if}\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", ha = "export const TERMS_AUTO = {\n applePay: \"auto\" as const,\n auBecsDebit: \"auto\" as const,\n bancontact: \"auto\" as const,\n card: \"auto\" as const,\n cashapp: \"auto\" as const,\n googlePay: \"auto\" as const,\n ideal: \"auto\" as const,\n paypal: \"auto\" as const,\n sepaDebit: \"auto\" as const,\n sofort: \"auto\" as const,\n usBankAccount: \"auto\" as const,\n};\n\nexport const TERMS_NEVER = {\n applePay: \"never\" as const,\n auBecsDebit: \"never\" as const,\n bancontact: \"never\" as const,\n card: \"never\" as const,\n cashapp: \"never\" as const,\n googlePay: \"never\" as const,\n ideal: \"never\" as const,\n paypal: \"never\" as const,\n sepaDebit: \"never\" as const,\n sofort: \"never\" as const,\n usBankAccount: \"never\" as const,\n};\n", ga = "<script lang=\"ts\">\n import type {\n Stripe,\n StripeElements,\n StripePaymentElement,\n StripeElementsOptionsMode\n } from '@stripe/stripe-js';\n import { mode as modeWatcher } from 'mode-watcher';\n import { TERMS_AUTO, TERMS_NEVER } from './stripe-constants';\n import { onMount } from 'svelte';\n\n interface Props {\n stripe: Stripe;\n mode: 'payment' | 'setup';\n amount?: number;\n currency?: string;\n savePaymentMethod?: boolean;\n user?: { email: string; name: string } | null;\n onchange: (complete: boolean) => void;\n }\n\n let {\n stripe,\n mode,\n amount = 0,\n currency = 'usd',\n savePaymentMethod = false,\n user,\n onchange\n }: Props = $props();\n\n let cardContainer = $state<HTMLDivElement | null>(null);\n let elements = $state<StripeElements | null>(null);\n let paymentElement = $state<StripePaymentElement | null>(null);\n\n function initializeElements() {\n if (!stripe) return;\n\n // Clean up previous elements\n if (paymentElement) {\n paymentElement.destroy();\n paymentElement = null;\n }\n\n const appearance = {\n theme: modeWatcher.current === 'dark' ? ('night' as const) : ('stripe' as const),\n inputs: 'condensed' as const,\n labels: 'floating' as const\n };\n\n elements = stripe.elements({\n mode,\n appearance,\n currency,\n ...(mode === 'payment' && {\n amount: amount\n }),\n ...(user || mode === 'setup'\n ? {\n setupFutureUsage: 'off_session' as const\n }\n : {})\n } as StripeElementsOptionsMode);\n\n paymentElement = elements.create('payment', {\n layout: 'tabs',\n defaultValues: {\n billingDetails: {\n email: user?.email,\n name: user?.name\n }\n },\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n\n if (cardContainer && paymentElement) {\n paymentElement.mount(cardContainer);\n paymentElement.on('change', (event: any) => {\n onchange(event.complete);\n });\n }\n }\n\n // Initialize elements when component mounts\n onMount(() => {\n initializeElements();\n\n return () => {\n if (paymentElement) {\n paymentElement.destroy();\n }\n };\n });\n\n // Update terms when savePaymentMethod changes\n $effect(() => {\n if (paymentElement) {\n paymentElement.update({\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n }\n });\n\n export function getElements() {\n return elements;\n }\n<\/script>\n\n<div bind:this={cardContainer}></div>\n", _a = "import { toast } from \"svelte-sonner\";\n\nexport interface PaymentIntentResult {\n type: \"payment\" | \"confirm\";\n amount?: number;\n currency?: string;\n clientSecret?: string;\n brand?: string;\n last4?: string;\n}\n\nexport function usePaymentIntent() {\n let isLoading = $state(false);\n\n async function fetchPaymentIntent({\n priceId,\n }: {\n priceId: string;\n }): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/payment-intent\", {\n method: \"POST\",\n body: JSON.stringify({\n priceId: priceId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize payment\");\n return null;\n }\n\n return res.json();\n }\n\n async function fetchSetupIntent(): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/setup-intent\", {\n method: \"POST\",\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize setup\");\n return null;\n }\n\n return res.json();\n }\n\n return {\n get isLoading() {\n return isLoading;\n },\n fetchPaymentIntent,\n fetchSetupIntent,\n };\n}\n", va = "import { loadStripe, type Stripe } from \"@stripe/stripe-js\";\nimport { toast } from \"svelte-sonner\";\nimport { PUBLIC_STRIPE_PUBLISHABLE_KEY } from \"$env/static/public\";\n\nexport function useStripe() {\n let stripe = $state<Stripe | null>(null);\n let isLoading = $state(true);\n let error = $state<string | null>(null);\n\n async function initialize() {\n try {\n stripe = await loadStripe(PUBLIC_STRIPE_PUBLISHABLE_KEY);\n isLoading = false;\n } catch (err) {\n console.error(\"Failed to load Stripe:\", err);\n error = \"Failed to initialize payment system\";\n toast.error(\"Failed to initialize payment system\");\n isLoading = false;\n }\n }\n\n // Auto-initialize\n initialize();\n\n return {\n get stripe() {\n return stripe;\n },\n get isLoading() {\n return isLoading;\n },\n get error() {\n return error;\n },\n };\n}\n", ya = "import { STRIPE_SECRET_KEY } from \"$env/static/private\";\nimport Stripe from \"stripe\";\n\nconst stripe = new Stripe(STRIPE_SECRET_KEY, {\n apiVersion: \"2025-09-30.clover\",\n});\n\nexport default stripe;\n", ba = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (price: Stripe.Price) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n try {\n const res = await createPaymentIntent(price);\n return json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return json({ error: errorMessage }, { status: 500 });\n }\n};\n", xa = "import { describe, it, expect, beforeAll } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"$lib/stripe\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", Sa = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const prices = await stripe.prices.list();\n\n for (const price of prices.data) {\n try {\n await locals.admin\n .collection(\"stripe_prices\")\n .getFirstListItem(`id = \"${price.id}\"`);\n continue;\n } catch {}\n\n await locals.admin.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 console.log(\"Prices synced\");\n return json({ message: \"Prices synced\" });\n};\n", Ca = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const products = await stripe.products.list();\n\n for (const product of products.data) {\n try {\n await locals.admin\n .collection(\"stripe_products\")\n .getFirstListItem(`id = \"${product.id}\"`);\n continue;\n } catch {}\n\n await locals.admin.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 console.log(\"Products synced\");\n return json({ message: \"Products synced\" });\n};\n", wa = "import Stripe from \"stripe\";\nimport { json } from \"@sveltejs/kit\";\nimport { STRIPE_WEBHOOK_SECRET } from \"$env/static/private\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./handlers/payment-intent/succeeded\";\n\nconst processedEvents = new Set<string>();\n\nasync function verifyWebhookSignature(\n request: Request,\n webhookSecret: string,\n): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get(\"stripe-signature\");\n\n if (!signature) {\n throw new Error(\"Missing stripe-signature header\");\n }\n\n if (!webhookSecret) {\n throw new Error(\"Missing webhook secret\");\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error(\"Webhook signature verification failed:\", err);\n throw new Error(\"Invalid signature\");\n }\n}\n\nexport const POST = async ({ request, locals }) => {\n try {\n const event = await verifyWebhookSignature(request, STRIPE_WEBHOOK_SECRET);\n\n if (processedEvents.has(event.id)) {\n console.log(`Event ${event.id} already processed, skipping`);\n return json({ received: true, message: \"Event already processed\" });\n }\n\n processedEvents.add(event.id);\n\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\n\n switch (event.type) {\n case \"payment_intent.succeeded\":\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n return json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n });\n } catch (error) {\n console.error(\"Webhook processing error:\", error);\n\n return json(\n {\n error: \"Webhook processing failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 400 },\n );\n }\n};\n", Ta = "import { describe, it, expect } from \"vitest\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n it(\"handles a payment intent successfully\", async (context) => {\n const paymentIntent = await stripe.paymentIntents.create({\n amount: 2000,\n currency: \"usd\",\n });\n const locals = { admin: context.admin } as App.Locals;\n const result = await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n expect(result).toEqual({});\n });\n});\n", Ea = "import Stripe from \"stripe\";\n\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n return {};\n}\n", Da = "import { describe, it, expect } from \"vitest\";\nimport type { RouteId } from \"./$types\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n\ndescribe(\"POST /webhooks/stripe\", () => {\n it(\"accepts valid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(200);\n expect(response.body.received).toBe(true);\n expect(response.body.eventId).toBe(event.id);\n expect(response.body.eventType).toBe(\"test.event\");\n });\n\n it(\"rejects invalid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", \"invalid_signature\")\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n });\n\n it(\"rejects request without signature header\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n expect(response.body.message).toBe(\"Missing stripe-signature header\");\n });\n\n it(\"handles duplicate webhook events\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n // Send first webhook\n const response1 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response1.status).toBe(200);\n expect(response1.body.received).toBe(true);\n\n // Send duplicate webhook\n const response2 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response2.status).toBe(200);\n expect(response2.body.received).toBe(true);\n expect(response2.body.message).toBe(\"Event already processed\");\n });\n});\n", Oa = "/// <reference path=\"../types.d.ts\" />\n\ncronAdd(\"stripe-products\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/products\");\n});\n\ncronAdd(\"stripe-prices\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/prices\");\n});\n\ncronAdd(\"stripe-customers\", \"* * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/customers\");\n});\n", ka = "/// <reference path=\"../types.d.ts\" />\n\nmodule.exports = {\n triggerJob: (jobUrl) => {\n $http.send({\n method: \"POST\",\n url: `${$app.settings().meta.appURL}${jobUrl}`,\n headers: {\n Authorization: `Bearer ${$os.getenv(\"INTERNAL_JOB_SECRET\")}`,\n },\n });\n },\n};\n", Aa = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import SetupDialog from '$lib/components/payments/setup-dialog.svelte';\n import { useStripe } from '$lib/components/payments/use-stripe.svelte';\n import { usePaymentIntent } from '$lib/components/payments/use-payment-intent.svelte';\n\n interface Props {\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n disabled = false,\n isProcessing = false,\n label,\n processingLabel,\n onsuccess\n }: Props = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let showDialog = $state(false);\n let clientSecret = $state<string>();\n\n async function handleSetupClick() {\n const result = await paymentIntentManager.fetchSetupIntent();\n\n if (!result) return;\n\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleSetupClick}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n<SetupDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n/>\n", ja = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let { stripe, open = $bindable(), clientSecret, onopenchange, onsuccess }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handleSetupPaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to add payment method');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmSetup({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n allow_redisplay: 'always'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to add payment method');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment method added successfully');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error adding payment method:', err);\n toast.error('Failed to add payment method');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Add payment method</Dialog.Title>\n <Dialog.Description>Enter your card details to add a new payment method.</Dialog.Description>\n </Dialog.Header>\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"setup\"\n {stripe}\n onchange={handleCardChange}\n savePaymentMethod={true}\n />\n {/if}\n </div>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handleSetupPaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Add Card'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", Ma = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", Na = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(locals.admin.filter(\"user = {:user}\", { user: user.id }));\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n depends(\"app:billing\");\n\n return {\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n };\n};\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n};\n", Pa = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import SetupButton from '$lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate } from '$app/navigation';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", Fa = "# Billing Page - Stripe Payment Methods\n\nThis billing page provides a modern UI for managing payment methods with Stripe.\n\n## Features\n\n✅ **Display Payment Methods** - Shows all saved cards with brand, last 4 digits, and expiration\n✅ **Add Payment Methods** - Secure card input using Stripe Elements\n✅ **Remove Payment Methods** - Delete cards with confirmation dialog\n✅ **Default Payment Method** - Set and display the default payment method\n✅ **Responsive Design** - Mobile-friendly layout\n✅ **Error Handling** - Toast notifications for user feedback\n\n## Current Status\n\nThe frontend is **fully functional** with mock data. To connect to your backend, follow the integration steps below.\n\n## Backend Integration\n\n### 1. Update Stripe Publishable Key\n\nIn `+page.svelte`, replace the placeholder with your actual Stripe publishable key:\n\n```typescript\nconst STRIPE_PUBLISHABLE_KEY = \"pk_test_YOUR_KEY_HERE\";\n```\n\nOr better yet, load it from environment variables:\n\n```typescript\nimport { PUBLIC_STRIPE_PUBLISHABLE_KEY } from \"$env/static/public\";\nconst STRIPE_PUBLISHABLE_KEY = PUBLIC_STRIPE_PUBLISHABLE_KEY;\n```\n\n### 2. Fetch Payment Methods on Load\n\nUpdate `+page.server.ts` to fetch payment methods:\n\n```typescript\nexport const load: PageServerLoad = async ({ locals }) => {\n const user = locals.user;\n\n if (!user?.stripeCustomerId) {\n return { paymentMethods: [] };\n }\n\n // Fetch payment methods from Stripe\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n const paymentMethods = await stripe.paymentMethods.list({\n customer: user.stripeCustomerId,\n type: \"card\",\n });\n\n return {\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card?.brand || \"unknown\",\n last4: pm.card?.last4 || \"0000\",\n expMonth: pm.card?.exp_month || 1,\n expYear: pm.card?.exp_year || 2025,\n isDefault: false, // You'll need to track this separately\n })),\n };\n};\n```\n\n### 3. Create API Endpoints\n\nCreate the following server endpoints:\n\n#### Add Payment Method: `+page.server.ts`\n\n```typescript\nexport const actions = {\n addPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Attach payment method to customer\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.paymentMethods.attach(paymentMethodId, {\n customer: locals.user.stripeCustomerId,\n });\n\n return { success: true };\n },\n\n removePaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Detach payment method from customer\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.paymentMethods.detach(paymentMethodId);\n\n return { success: true };\n },\n\n setDefaultPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Update customer's default payment method\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.customers.update(locals.user.stripeCustomerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n return { success: true };\n },\n};\n```\n\n### 4. Update Frontend to Use Actions\n\nReplace the mock functions in `+page.svelte`:\n\n```typescript\nasync function handleAddPaymentMethod() {\n if (!stripe || !cardElement || !cardComplete) return;\n\n isProcessing = true;\n\n try {\n const { error, paymentMethod } = await stripe.createPaymentMethod({\n type: \"card\",\n card: cardElement,\n });\n\n if (error) {\n toast.error(error.message);\n return;\n }\n\n // Submit to your backend\n const formData = new FormData();\n formData.append(\"paymentMethodId\", paymentMethod.id);\n\n const response = await fetch(\"?/addPaymentMethod\", {\n method: \"POST\",\n body: formData,\n });\n\n if (response.ok) {\n toast.success(\"Payment method added\");\n // Reload page to fetch updated payment methods\n window.location.reload();\n }\n } finally {\n isProcessing = false;\n }\n}\n```\n\n## Security Considerations\n\n⚠️ **Important**: Never expose your Stripe secret key on the frontend\n✅ All sensitive operations should happen on your backend\n✅ Use Stripe's publishable key for frontend operations\n✅ Validate user permissions before modifying payment methods\n✅ Use HTTPS in production\n\n## Testing\n\nUse [Stripe's test cards](https://stripe.com/docs/testing) for testing:\n\n- **Success**: 4242 4242 4242 4242\n- **Decline**: 4000 0000 0000 0002\n- **Requires authentication**: 4000 0025 0000 3155\n\nUse any future expiration date and any 3-digit CVC.\n\n## Styling\n\nThe page uses Tailwind CSS and shadcn/ui components. All components are styled to match your existing design system with support for light/dark modes.\n\n### Stripe Elements Styling\n\nSince Stripe Elements render in an iframe, they cannot access CSS variables directly. Additionally, Stripe only accepts HEX, RGB, or HSL colors (not modern formats like OKLCH).\n\nThe implementation:\n\n1. **Creates temporary DOM elements** with CSS variables applied\n2. **Lets the browser compute colors** - converts OKLCH/HSL/any format to RGB\n3. **Extracts RGB values** that Stripe Elements can understand\n4. **Passes computed colors** to Stripe Elements on initialization\n5. **Matches the current theme** automatically (light/dark mode)\n\nThis approach works with any CSS color format (oklch, hsl, rgb, hex) and ensures Stripe Elements always match your theme when the \"Add Payment Method\" dialog opens.\n\n## Dependencies\n\n- `@stripe/stripe-js` - Stripe.js for frontend\n- `stripe` - Stripe Node.js SDK for backend\n- `svelte-sonner` - Toast notifications\n- `@lucide/svelte` - Icons\n- shadcn/ui components\n", Ia = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (\n price: Stripe.Price,\n customer?: { id: string; default_payment_method?: string },\n) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n // Guest\n if (!customer) {\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n }\n\n // Customer with saved payment method\n if (customer.default_payment_method) {\n const paymentMethod = await stripe.customers.retrievePaymentMethod(\n customer.id,\n customer.default_payment_method,\n );\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n payment_method: customer.default_payment_method,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return {\n type: \"confirm\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n };\n }\n\n // Customer without saved payment method\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n setup_future_usage: \"off_session\",\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n const user = locals.pb.authStore.record?.id;\n\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n let customer;\n\n if (user) {\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user }),\n );\n } catch (error) {\n // Customer not found is expected for new users, log for debugging only\n console.log(\"No Stripe customer found for user:\", user);\n }\n }\n\n try {\n const res = await createPaymentIntent(price, customer);\n return json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return json({ error: errorMessage }, { status: 500 });\n }\n};\n", La = "import { describe, it, expect, beforeAll, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"$lib/stripe\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n beforeEach(async (context) => {\n // Create a Stripe customer for authenticated user tests\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Create a payment method for the customer\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n });\n\n afterEach(async () => {\n if (paymentMethod?.id) {\n await stripe.paymentMethods.detach(paymentMethod.id);\n }\n\n if (stripeCustomer?.id) {\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user without Stripe customer\", () => {\n it(\"should create payment intent for user without Stripe customer\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n\n // Verify the payment intent\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.setup_future_usage).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user with Stripe customer\", () => {\n let customerRecord: { id: string };\n\n beforeEach(async (context) => {\n // Link the Stripe customer to the PocketBase user\n customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .create({\n user: context.user.id,\n id: stripeCustomer.id,\n email: stripeCustomer.email,\n });\n });\n\n afterEach(async (context) => {\n // Clean up the PocketBase customer record\n await context.admin\n .collection(\"stripe_customers\")\n .delete(customerRecord.id);\n });\n\n it(\"should create payment intent with setup_future_usage for user without default payment method\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent has setup_future_usage\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.setup_future_usage).toBe(\"off_session\");\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n\n it(\"should create payment intent with default payment method for customer with saved payment method\", async (context) => {\n // Set default payment method\n await stripe.customers.update(stripeCustomer.id, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n const customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n context.admin.filter(\"user = {:user}\", { user: context.user.id }),\n );\n\n await context.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customerRecord.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 await context.admin\n .collection(\"stripe_customers\")\n .update(customerRecord.id, {\n default_payment_method: paymentMethod.id,\n });\n\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"confirm\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBe(\"visa\");\n expect(response.body.last4).toBeDefined();\n expect(response.body.last4).toMatch(/^\\d{4}$/);\n\n // Verify the payment intent has the payment method attached\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.payment_method).toBe(paymentMethod.id);\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", Ra = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\nexport const POST = async ({ locals }) => {\n const user = locals.pb.authStore.record?.id;\n\n if (!user) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(locals.admin.filter(\"user = {:user}\", { user }));\n\n if (!customer) {\n return json({ error: \"Customer not found\" }, { status: 404 });\n }\n\n const setupIntent = await stripe.setupIntents.create({\n customer: customer.id,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return json({ clientSecret: setupIntent.client_secret });\n};\n", za = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"POST /api/stripe/setup-intent\", () => {\n let stripeCustomer: Stripe.Customer;\n\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n });\n\n afterEach(async (context) => {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n });\n\n it(\"creates a setup intent\", async (context) => {\n const response = await context.agent.post(\n \"/api/stripe/setup-intent\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n expect(response.body.clientSecret).toBeDefined();\n });\n});\n", Ba = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\n// Sync users to Stripe customers\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n // Ensure all users have a Stripe customer\n const users = await locals.admin\n .collection(\"users\")\n .getFullList({ filter: \"stripe_customers_via_user.id = null\" });\n\n for (const user of users) {\n const customer = await stripe.customers.create({\n email: user.email,\n name: user.name,\n });\n\n await locals.admin.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n }\n\n console.log(\"Customers synced\");\n return json({ message: \"Customers synced\" });\n};\n", Va = "import Stripe from \"stripe\";\nimport { json } from \"@sveltejs/kit\";\nimport { STRIPE_WEBHOOK_SECRET } from \"$env/static/private\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./handlers/payment-intent/succeeded\";\nimport { handlePaymentMethodAttached } from \"./handlers/payment-method/attached\";\n\nconst processedEvents = new Set<string>();\n\nasync function verifyWebhookSignature(\n request: Request,\n webhookSecret: string,\n): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get(\"stripe-signature\");\n\n if (!signature) {\n throw new Error(\"Missing stripe-signature header\");\n }\n\n if (!webhookSecret) {\n throw new Error(\"Missing webhook secret\");\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error(\"Webhook signature verification failed:\", err);\n throw new Error(\"Invalid signature\");\n }\n}\n\nexport const POST = async ({ request, locals }) => {\n try {\n const event = await verifyWebhookSignature(request, STRIPE_WEBHOOK_SECRET);\n\n if (processedEvents.has(event.id)) {\n console.log(`Event ${event.id} already processed, skipping`);\n return json({ received: true, message: \"Event already processed\" });\n }\n\n processedEvents.add(event.id);\n\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\n\n switch (event.type) {\n case \"payment_intent.succeeded\":\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case \"payment_method.attached\":\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n return json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n });\n } catch (error) {\n console.error(\"Webhook processing error:\", error);\n\n return json(\n {\n error: \"Webhook processing failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 400 },\n );\n }\n};\n", Ha = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentIntent: Stripe.PaymentIntent;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n // Create a Stripe customer\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Link the Stripe customer to the test user\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n // Create a payment method for testing\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n // Attach payment method to customer\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n // Create a payment intent\n paymentIntent = await stripe.paymentIntents.create({\n amount: 2000, // $20.00\n currency: \"usd\",\n customer: stripeCustomer.id,\n payment_method: paymentMethod.id,\n confirm: true,\n return_url: \"https://example.com/return\",\n });\n });\n\n afterEach(async (context) => {\n // Clean up transactions\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\"stripe_customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n for (const transaction of transactions) {\n await context.admin.collection(\"transactions\").delete(transaction.id);\n }\n\n // Clean up Stripe resources\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch (e) {\n // Payment method may already be detached\n }\n }\n\n // Delete customer (this will also delete associated payment methods)\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a transaction record when payment intent succeeds\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_customer).toBe(stripeCustomer.id);\n expect(transaction.amount).toBe(2000);\n expect(transaction.currency).toBe(\"usd\");\n expect(transaction.user).toBe(context.user.id);\n expect(transaction.stripe_charge).toBeDefined();\n expect(transaction.last4).toBeDefined();\n expect(transaction.brand).toBeDefined();\n expect(transaction.created).toBeDefined();\n expect(transaction.receipt_url).toBeDefined();\n });\n\n it(\"handles payment intent with charge object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded charge\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"latest_charge\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_charge).toBeDefined();\n });\n\n it(\"handles payment intent with customer object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded customer\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n expect(transactions[0].stripe_customer).toBe(stripeCustomer.id);\n });\n\n it(\"handles missing charge ID gracefully\", async (context) => {\n const paymentIntentWithoutCharge = {\n ...paymentIntent,\n latest_charge: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCharge, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n\n it(\"handles missing customer ID gracefully\", async (context) => {\n const paymentIntentWithoutCustomer = {\n ...paymentIntent,\n customer: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCustomer, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n});\n", Ua = "import Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n const chargeId =\n typeof paymentIntent.latest_charge === \"string\"\n ? paymentIntent.latest_charge\n : paymentIntent.latest_charge?.id;\n\n if (!chargeId) {\n console.error(\"No charge ID found for payment intent\");\n return;\n }\n\n const charge = await stripe.charges.retrieve(chargeId);\n\n const customerId =\n typeof paymentIntent.customer === \"string\"\n ? paymentIntent.customer\n : paymentIntent.customer?.id;\n\n if (!customerId) {\n console.error(\"No customer ID found for payment intent\");\n return;\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n const created = new Date(charge.created * 1000);\n\n await locals.admin.collection(\"transactions\").create({\n stripe_payment_intent: paymentIntent.id,\n stripe_charge: chargeId,\n stripe_customer: customerId,\n amount: paymentIntent.amount,\n currency: paymentIntent.currency,\n created: created.toISOString(),\n last4: charge.payment_method_details?.card?.last4,\n brand: charge.payment_method_details?.card?.brand,\n receipt_url: charge.receipt_url,\n user: customer.user,\n });\n}\n", Wa = "import Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n\n/**\n * Handles payment_method.attached event\n */\nexport async function handlePaymentMethodAttached(\n paymentMethod: Stripe.PaymentMethod,\n locals: App.Locals,\n) {\n if (\n paymentMethod.allow_redisplay === \"unspecified\" ||\n !paymentMethod.customer\n ) {\n return;\n }\n\n const customer =\n typeof paymentMethod.customer === \"string\"\n ? paymentMethod.customer\n : paymentMethod.customer?.id;\n\n await locals.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer,\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 const paymentMethodRecords = await locals.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: locals.admin.filter(\"customer = {:customer}\", {\n customer: customer,\n }),\n });\n\n if (paymentMethodRecords.length === 1) {\n const paymentMethod = paymentMethodRecords[0];\n\n await stripe.customers.update(customer, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer, {\n default_payment_method: paymentMethod.id,\n });\n }\n}\n", Ga = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentMethodAttached } from \"./attached\";\n\ndescribe(\"payment_method.attached\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n paymentMethod = await stripe.paymentMethods.update(paymentMethod.id, {\n allow_redisplay: \"always\",\n });\n });\n\n afterEach(async (context) => {\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n\n for (const pm of paymentMethods) {\n await context.admin.collection(\"stripe_payment_methods\").delete(pm.id);\n }\n\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch {}\n }\n\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a payment method record when payment method is attached\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n const pm = paymentMethods[0];\n\n expect(pm.id).toBe(paymentMethod.id);\n expect(pm.customer).toBe(stripeCustomer.id);\n expect(pm.brand).toBe(paymentMethod.card?.brand);\n expect(pm.last4).toBe(paymentMethod.card?.last4);\n expect(pm.exp_month).toBe(paymentMethod.card?.exp_month);\n expect(pm.exp_year).toBe(paymentMethod.card?.exp_year);\n });\n\n it(\"sets payment method as default when it is the first one\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default in database\n const customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Verify it was set as default in Stripe\n const stripeCustomerUpdated = await stripe.customers.retrieve(\n stripeCustomer.id,\n );\n if (\"deleted\" in stripeCustomerUpdated) {\n throw new Error(\"Customer should not be deleted\");\n }\n expect(stripeCustomerUpdated.invoice_settings.default_payment_method).toBe(\n paymentMethod.id,\n );\n });\n\n it(\"does not set as default when there are already payment methods\", async (context) => {\n // Handle the first payment method\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default\n let customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Create and attach a first payment method\n let secondPaymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_mastercard\",\n },\n });\n\n await stripe.paymentMethods.attach(secondPaymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n secondPaymentMethod = await stripe.paymentMethods.update(\n secondPaymentMethod.id,\n {\n allow_redisplay: \"always\",\n },\n );\n\n // Now handle the second payment method\n await handlePaymentMethodAttached(secondPaymentMethod, locals);\n\n // Verify the default did NOT change\n customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Clean up the second payment method\n await context.admin\n .collection(\"stripe_payment_methods\")\n .delete(secondPaymentMethod.id);\n await stripe.paymentMethods.detach(secondPaymentMethod.id);\n });\n\n it(\"handles payment method with customer object instead of string\", async (context) => {\n // Retrieve the payment method with expanded customer\n const expandedPaymentMethod = await stripe.paymentMethods.retrieve(\n paymentMethod.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(expandedPaymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n expect(paymentMethods[0].customer).toBe(stripeCustomer.id);\n });\n\n it(\"does not create record when allow_redisplay is unspecified\", async (context) => {\n // Update payment method to have unspecified allow_redisplay\n const unspecifiedPaymentMethod = await stripe.paymentMethods.update(\n paymentMethod.id,\n {\n allow_redisplay: \"unspecified\",\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(unspecifiedPaymentMethod, locals);\n\n // Verify no payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(0);\n });\n});\n", Ka = /* @__PURE__ */ Object.assign({
|
|
4307
|
-
"./creates/data/hooks/stripe.pb.js":
|
|
4308
|
-
"./creates/data/hooks/utils.js":
|
|
4309
|
-
"./creates/src/lib/components/payments/confirm-dialog.svelte":
|
|
4310
|
-
"./creates/src/lib/components/payments/payment-button.svelte":
|
|
4311
|
-
"./creates/src/lib/components/payments/payment-dialog.svelte":
|
|
4312
|
-
"./creates/src/lib/components/payments/stripe-constants.ts":
|
|
4313
|
-
"./creates/src/lib/components/payments/stripe-payment-form.svelte":
|
|
4314
|
-
"./creates/src/lib/components/payments/use-payment-intent.svelte.ts":
|
|
4315
|
-
"./creates/src/lib/components/payments/use-stripe.svelte.ts":
|
|
4316
|
-
"./creates/src/lib/stripe.ts":
|
|
4317
|
-
"./creates/src/routes/api/stripe/payment-intent/+server.ts":
|
|
4318
|
-
"./creates/src/routes/api/stripe/payment-intent/server.test.ts":
|
|
4319
|
-
"./creates/src/routes/api/stripe/sync/prices/+server.ts":
|
|
4320
|
-
"./creates/src/routes/api/stripe/sync/products/+server.ts":
|
|
4321
|
-
"./creates/src/routes/webhooks/stripe/+server.ts":
|
|
4322
|
-
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts":
|
|
4323
|
-
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts":
|
|
4324
|
-
"./creates/src/routes/webhooks/stripe/server.test.ts":
|
|
4325
|
-
}),
|
|
4326
|
-
"./creates-app-mode/data/hooks/stripe.pb.js":
|
|
4327
|
-
"./creates-app-mode/data/hooks/utils.js":
|
|
4328
|
-
"./creates-app-mode/src/lib/components/payments/setup-button.svelte":
|
|
4329
|
-
"./creates-app-mode/src/lib/components/payments/setup-dialog.svelte":
|
|
4330
|
-
"./creates-app-mode/src/routes/(app)/billing/+layout.server.ts":
|
|
4331
|
-
"./creates-app-mode/src/routes/(app)/billing/+page.server.ts":
|
|
4332
|
-
"./creates-app-mode/src/routes/(app)/billing/+page.svelte":
|
|
4333
|
-
"./creates-app-mode/src/routes/(app)/billing/README.md":
|
|
4334
|
-
"./creates-app-mode/src/routes/api/stripe/payment-intent/+server.ts":
|
|
4335
|
-
"./creates-app-mode/src/routes/api/stripe/payment-intent/server.test.ts":
|
|
4336
|
-
"./creates-app-mode/src/routes/api/stripe/setup-intent/+server.ts":
|
|
4337
|
-
"./creates-app-mode/src/routes/api/stripe/setup-intent/server.test.ts":
|
|
4338
|
-
"./creates-app-mode/src/routes/api/stripe/sync/customers/+server.ts":
|
|
4339
|
-
"./creates-app-mode/src/routes/webhooks/stripe/+server.ts":
|
|
4340
|
-
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts":
|
|
4341
|
-
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts":
|
|
4342
|
-
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/attached.ts":
|
|
4343
|
-
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts":
|
|
4344
|
-
}),
|
|
4345
|
-
function
|
|
4310
|
+
generate: la
|
|
4311
|
+
}, da = "/// <reference path=\"../types.d.ts\" />\n\ncronAdd(\"stripe-products\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/products\");\n});\n\ncronAdd(\"stripe-prices\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/prices\");\n});\n", fa = "/// <reference path=\"../types.d.ts\" />\n\nmodule.exports = {\n triggerJob: (jobUrl) => {\n $http.send({\n method: \"POST\",\n url: `${$app.settings().meta.appURL}${jobUrl}`,\n headers: {\n Authorization: `Bearer ${$os.getenv(\"INTERNAL_JOB_SECRET\")}`,\n },\n });\n },\n};\n", pa = "<script lang=\"ts\">\n import type { Stripe } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n brand?: string;\n last4?: string;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n brand,\n last4,\n clientSecret,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n const brandNames = {\n amex: 'American Express',\n cartes_bancaires: 'Cartes Bancaires',\n diners: 'Diners',\n discover: 'Discover',\n eftpos_au: 'Eftpos Au',\n jcb: 'Jcb',\n link: 'Link',\n mastercard: 'Mastercard',\n unionpay: 'Unionpay',\n visa: 'Visa',\n unknown: 'Unknown'\n };\n\n let isProcessing = $state(false);\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !clientSecret) return;\n\n isProcessing = true;\n\n try {\n const { error: confirmError } = await stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n return_url: page.url.toString()\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Confirm payment</Dialog.Title>\n <Dialog.Description>\n Are you sure you want to pay {amountFormatted} with your\n {brandNames[brand as keyof typeof brandNames]}\n credit card ending in **** {last4}?\n </Dialog.Description>\n </Dialog.Header>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", ma = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import PaymentDialog from '$lib/components/payments/payment-dialog.svelte';\n import ConfirmDialog from '$lib/components/payments/confirm-dialog.svelte';\n import { useStripe } from '$lib/components/payments/use-stripe.svelte';\n import { usePaymentIntent } from '$lib/components/payments/use-payment-intent.svelte';\n import type { ButtonProps } from '$lib/components/ui/button';\n\n interface Props {\n priceId: string;\n user?: { email: string; name: string } | null;\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n priceId,\n user,\n disabled = false,\n isProcessing = false,\n label = 'Purchase',\n processingLabel = 'Processing...',\n onsuccess,\n ...rest\n }: Props & ButtonProps = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let mode = $state<'payment' | 'confirm'>('payment');\n let showDialog = $state(false);\n let amount = $state<number>(0);\n let currency = $state<string>('usd');\n let clientSecret = $state<string>();\n let brand = $state<string>();\n let last4 = $state<string>();\n\n async function handleBuyClick() {\n const result = await paymentIntentManager.fetchPaymentIntent({\n priceId\n });\n\n if (!result) return;\n\n if (result.type === 'confirm') {\n mode = 'confirm';\n brand = result.brand;\n last4 = result.last4;\n } else if (result.type === 'payment') {\n mode = 'payment';\n }\n\n amount = result.amount || 0;\n currency = result.currency || 'usd';\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleBuyClick} {...rest}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n{#if mode === 'confirm'}\n <ConfirmDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {brand}\n {last4}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{:else if mode === 'payment'}\n <PaymentDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {clientSecret}\n {user}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{/if}\n", ha = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { Input } from '$lib/components/ui/input';\n import { Label } from '$lib/components/ui/label';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n clientSecret?: string;\n user?: { email: string; name: string } | null;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n clientSecret,\n user = null,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let savePaymentMethod = $state(false);\n let email = $state<string>();\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to pay for your purchase');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmPayment({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n billing_details: {\n email: email || user?.email\n },\n allow_redisplay: savePaymentMethod ? 'always' : 'unspecified'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>{amountFormatted}</Dialog.Title>\n <Dialog.Description>Enter your card details to pay for your purchase.</Dialog.Description>\n </Dialog.Header>\n {#if !user}\n <div class=\"space-y-2\">\n <Label for=\"email\">Email</Label>\n <Input type=\"email\" bind:value={email} />\n </div>\n {/if}\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"payment\"\n {stripe}\n {amount}\n {currency}\n {savePaymentMethod}\n {user}\n onchange={handleCardChange}\n />\n {/if}\n </div>\n {#if user}\n <div class=\"flex items-center gap-2\">\n <input type=\"checkbox\" id=\"savePaymentMethod\" bind:checked={savePaymentMethod} />\n <label for=\"savePaymentMethod\" class=\"text-sm text-muted-foreground\">\n Save payment method for future purchases\n </label>\n </div>\n {/if}\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", ga = "export const TERMS_AUTO = {\n applePay: \"auto\" as const,\n auBecsDebit: \"auto\" as const,\n bancontact: \"auto\" as const,\n card: \"auto\" as const,\n cashapp: \"auto\" as const,\n googlePay: \"auto\" as const,\n ideal: \"auto\" as const,\n paypal: \"auto\" as const,\n sepaDebit: \"auto\" as const,\n sofort: \"auto\" as const,\n usBankAccount: \"auto\" as const,\n};\n\nexport const TERMS_NEVER = {\n applePay: \"never\" as const,\n auBecsDebit: \"never\" as const,\n bancontact: \"never\" as const,\n card: \"never\" as const,\n cashapp: \"never\" as const,\n googlePay: \"never\" as const,\n ideal: \"never\" as const,\n paypal: \"never\" as const,\n sepaDebit: \"never\" as const,\n sofort: \"never\" as const,\n usBankAccount: \"never\" as const,\n};\n", _a = "<script lang=\"ts\">\n import type {\n Stripe,\n StripeElements,\n StripePaymentElement,\n StripeElementsOptionsMode\n } from '@stripe/stripe-js';\n import { mode as modeWatcher } from 'mode-watcher';\n import { TERMS_AUTO, TERMS_NEVER } from './stripe-constants';\n import { onMount } from 'svelte';\n\n interface Props {\n stripe: Stripe;\n mode: 'payment' | 'setup';\n amount?: number;\n currency?: string;\n savePaymentMethod?: boolean;\n user?: { email: string; name: string } | null;\n onchange: (complete: boolean) => void;\n }\n\n let {\n stripe,\n mode,\n amount = 0,\n currency = 'usd',\n savePaymentMethod = false,\n user,\n onchange\n }: Props = $props();\n\n let cardContainer = $state<HTMLDivElement | null>(null);\n let elements = $state<StripeElements | null>(null);\n let paymentElement = $state<StripePaymentElement | null>(null);\n\n function initializeElements() {\n if (!stripe) return;\n\n // Clean up previous elements\n if (paymentElement) {\n paymentElement.destroy();\n paymentElement = null;\n }\n\n const appearance = {\n theme: modeWatcher.current === 'dark' ? ('night' as const) : ('stripe' as const),\n inputs: 'condensed' as const,\n labels: 'floating' as const\n };\n\n elements = stripe.elements({\n mode,\n appearance,\n currency,\n ...(mode === 'payment' && {\n amount: amount\n }),\n ...(user || mode === 'setup'\n ? {\n setupFutureUsage: 'off_session' as const\n }\n : {})\n } as StripeElementsOptionsMode);\n\n paymentElement = elements.create('payment', {\n layout: 'tabs',\n defaultValues: {\n billingDetails: {\n email: user?.email,\n name: user?.name\n }\n },\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n\n if (cardContainer && paymentElement) {\n paymentElement.mount(cardContainer);\n paymentElement.on('change', (event: any) => {\n onchange(event.complete);\n });\n }\n }\n\n // Initialize elements when component mounts\n onMount(() => {\n initializeElements();\n\n return () => {\n if (paymentElement) {\n paymentElement.destroy();\n }\n };\n });\n\n // Update terms when savePaymentMethod changes\n $effect(() => {\n if (paymentElement) {\n paymentElement.update({\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n }\n });\n\n export function getElements() {\n return elements;\n }\n<\/script>\n\n<div bind:this={cardContainer}></div>\n", va = "import { toast } from \"svelte-sonner\";\n\nexport interface PaymentIntentResult {\n type: \"payment\" | \"confirm\";\n amount?: number;\n currency?: string;\n clientSecret?: string;\n brand?: string;\n last4?: string;\n}\n\nexport function usePaymentIntent() {\n let isLoading = $state(false);\n\n async function fetchPaymentIntent({\n priceId,\n }: {\n priceId: string;\n }): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/payment-intent\", {\n method: \"POST\",\n body: JSON.stringify({\n priceId: priceId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize payment\");\n return null;\n }\n\n return res.json();\n }\n\n async function fetchSetupIntent(): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/setup-intent\", {\n method: \"POST\",\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize setup\");\n return null;\n }\n\n return res.json();\n }\n\n return {\n get isLoading() {\n return isLoading;\n },\n fetchPaymentIntent,\n fetchSetupIntent,\n };\n}\n", ya = "import { loadStripe, type Stripe } from \"@stripe/stripe-js\";\nimport { toast } from \"svelte-sonner\";\nimport { PUBLIC_STRIPE_PUBLISHABLE_KEY } from \"$env/static/public\";\n\nexport function useStripe() {\n let stripe = $state<Stripe | null>(null);\n let isLoading = $state(true);\n let error = $state<string | null>(null);\n\n async function initialize() {\n try {\n stripe = await loadStripe(PUBLIC_STRIPE_PUBLISHABLE_KEY);\n isLoading = false;\n } catch (err) {\n console.error(\"Failed to load Stripe:\", err);\n error = \"Failed to initialize payment system\";\n toast.error(\"Failed to initialize payment system\");\n isLoading = false;\n }\n }\n\n // Auto-initialize\n initialize();\n\n return {\n get stripe() {\n return stripe;\n },\n get isLoading() {\n return isLoading;\n },\n get error() {\n return error;\n },\n };\n}\n", ba = "import { STRIPE_SECRET_KEY } from \"$env/static/private\";\nimport Stripe from \"stripe\";\n\nconst stripe = new Stripe(STRIPE_SECRET_KEY, {\n apiVersion: \"2025-09-30.clover\",\n});\n\nexport default stripe;\n", xa = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (price: Stripe.Price) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n try {\n const res = await createPaymentIntent(price);\n return json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return json({ error: errorMessage }, { status: 500 });\n }\n};\n", Sa = "import { describe, it, expect, beforeAll } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"$lib/stripe\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", Ca = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const prices = await stripe.prices.list();\n\n for (const price of prices.data) {\n try {\n await locals.admin\n .collection(\"stripe_prices\")\n .getFirstListItem(`id = \"${price.id}\"`);\n continue;\n } catch {}\n\n await locals.admin.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 console.log(\"Prices synced\");\n return json({ message: \"Prices synced\" });\n};\n", wa = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const products = await stripe.products.list();\n\n for (const product of products.data) {\n try {\n await locals.admin\n .collection(\"stripe_products\")\n .getFirstListItem(`id = \"${product.id}\"`);\n continue;\n } catch {}\n\n await locals.admin.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 console.log(\"Products synced\");\n return json({ message: \"Products synced\" });\n};\n", Ta = "import Stripe from \"stripe\";\nimport { json } from \"@sveltejs/kit\";\nimport { STRIPE_WEBHOOK_SECRET } from \"$env/static/private\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./handlers/payment-intent/succeeded\";\n\nconst processedEvents = new Set<string>();\n\nasync function verifyWebhookSignature(\n request: Request,\n webhookSecret: string,\n): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get(\"stripe-signature\");\n\n if (!signature) {\n throw new Error(\"Missing stripe-signature header\");\n }\n\n if (!webhookSecret) {\n throw new Error(\"Missing webhook secret\");\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error(\"Webhook signature verification failed:\", err);\n throw new Error(\"Invalid signature\");\n }\n}\n\nexport const POST = async ({ request, locals }) => {\n try {\n const event = await verifyWebhookSignature(request, STRIPE_WEBHOOK_SECRET);\n\n if (processedEvents.has(event.id)) {\n console.log(`Event ${event.id} already processed, skipping`);\n return json({ received: true, message: \"Event already processed\" });\n }\n\n processedEvents.add(event.id);\n\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\n\n switch (event.type) {\n case \"payment_intent.succeeded\":\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n return json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n });\n } catch (error) {\n console.error(\"Webhook processing error:\", error);\n\n return json(\n {\n error: \"Webhook processing failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 400 },\n );\n }\n};\n", Ea = "import { describe, it, expect } from \"vitest\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n it(\"handles a payment intent successfully\", async (context) => {\n const paymentIntent = await stripe.paymentIntents.create({\n amount: 2000,\n currency: \"usd\",\n });\n const locals = { admin: context.admin } as App.Locals;\n const result = await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n expect(result).toEqual({});\n });\n});\n", Da = "import Stripe from \"stripe\";\n\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n return {};\n}\n", Oa = "import { describe, it, expect } from \"vitest\";\nimport type { RouteId } from \"./$types\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n\ndescribe(\"POST /webhooks/stripe\", () => {\n it(\"accepts valid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(200);\n expect(response.body.received).toBe(true);\n expect(response.body.eventId).toBe(event.id);\n expect(response.body.eventType).toBe(\"test.event\");\n });\n\n it(\"rejects invalid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", \"invalid_signature\")\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n });\n\n it(\"rejects request without signature header\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n expect(response.body.message).toBe(\"Missing stripe-signature header\");\n });\n\n it(\"handles duplicate webhook events\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2024-11-20.acacia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n // Send first webhook\n const response1 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response1.status).toBe(200);\n expect(response1.body.received).toBe(true);\n\n // Send duplicate webhook\n const response2 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response2.status).toBe(200);\n expect(response2.body.received).toBe(true);\n expect(response2.body.message).toBe(\"Event already processed\");\n });\n});\n", ka = "/// <reference path=\"../types.d.ts\" />\n\ncronAdd(\"stripe-products\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/products\");\n});\n\ncronAdd(\"stripe-prices\", \"*/2 * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/prices\");\n});\n\ncronAdd(\"stripe-customers\", \"* * * * *\", () => {\n const utils = require(`${__hooks}/utils.js`);\n utils.triggerJob(\"/api/stripe/sync/customers\");\n});\n", Aa = "/// <reference path=\"../types.d.ts\" />\n\nmodule.exports = {\n triggerJob: (jobUrl) => {\n $http.send({\n method: \"POST\",\n url: `${$app.settings().meta.appURL}${jobUrl}`,\n headers: {\n Authorization: `Bearer ${$os.getenv(\"INTERNAL_JOB_SECRET\")}`,\n },\n });\n },\n};\n", ja = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import SetupDialog from '$lib/components/payments/setup-dialog.svelte';\n import { useStripe } from '$lib/components/payments/use-stripe.svelte';\n import { usePaymentIntent } from '$lib/components/payments/use-payment-intent.svelte';\n\n interface Props {\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n disabled = false,\n isProcessing = false,\n label,\n processingLabel,\n onsuccess\n }: Props = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let showDialog = $state(false);\n let clientSecret = $state<string>();\n\n async function handleSetupClick() {\n const result = await paymentIntentManager.fetchSetupIntent();\n\n if (!result) return;\n\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleSetupClick}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n<SetupDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n/>\n", Ma = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '$lib/components/ui/button';\n import * as Dialog from '$lib/components/ui/dialog';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let { stripe, open = $bindable(), clientSecret, onopenchange, onsuccess }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handleSetupPaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to add payment method');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmSetup({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n allow_redisplay: 'always'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to add payment method');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment method added successfully');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error adding payment method:', err);\n toast.error('Failed to add payment method');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <Dialog.Content class=\"sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Add payment method</Dialog.Title>\n <Dialog.Description>Enter your card details to add a new payment method.</Dialog.Description>\n </Dialog.Header>\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"setup\"\n {stripe}\n onchange={handleCardChange}\n savePaymentMethod={true}\n />\n {/if}\n </div>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handleSetupPaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Add Card'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", Na = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", Pa = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(locals.admin.filter(\"user = {:user}\", { user: user.id }));\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n depends(\"app:billing\");\n\n return {\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n };\n};\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n};\n", Fa = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import SetupButton from '$lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate } from '$app/navigation';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", Ia = "# Billing Page - Stripe Payment Methods\n\nThis billing page provides a modern UI for managing payment methods with Stripe.\n\n## Features\n\n✅ **Display Payment Methods** - Shows all saved cards with brand, last 4 digits, and expiration\n✅ **Add Payment Methods** - Secure card input using Stripe Elements\n✅ **Remove Payment Methods** - Delete cards with confirmation dialog\n✅ **Default Payment Method** - Set and display the default payment method\n✅ **Responsive Design** - Mobile-friendly layout\n✅ **Error Handling** - Toast notifications for user feedback\n\n## Current Status\n\nThe frontend is **fully functional** with mock data. To connect to your backend, follow the integration steps below.\n\n## Backend Integration\n\n### 1. Update Stripe Publishable Key\n\nIn `+page.svelte`, replace the placeholder with your actual Stripe publishable key:\n\n```typescript\nconst STRIPE_PUBLISHABLE_KEY = \"pk_test_YOUR_KEY_HERE\";\n```\n\nOr better yet, load it from environment variables:\n\n```typescript\nimport { PUBLIC_STRIPE_PUBLISHABLE_KEY } from \"$env/static/public\";\nconst STRIPE_PUBLISHABLE_KEY = PUBLIC_STRIPE_PUBLISHABLE_KEY;\n```\n\n### 2. Fetch Payment Methods on Load\n\nUpdate `+page.server.ts` to fetch payment methods:\n\n```typescript\nexport const load: PageServerLoad = async ({ locals }) => {\n const user = locals.user;\n\n if (!user?.stripeCustomerId) {\n return { paymentMethods: [] };\n }\n\n // Fetch payment methods from Stripe\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n const paymentMethods = await stripe.paymentMethods.list({\n customer: user.stripeCustomerId,\n type: \"card\",\n });\n\n return {\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card?.brand || \"unknown\",\n last4: pm.card?.last4 || \"0000\",\n expMonth: pm.card?.exp_month || 1,\n expYear: pm.card?.exp_year || 2025,\n isDefault: false, // You'll need to track this separately\n })),\n };\n};\n```\n\n### 3. Create API Endpoints\n\nCreate the following server endpoints:\n\n#### Add Payment Method: `+page.server.ts`\n\n```typescript\nexport const actions = {\n addPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Attach payment method to customer\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.paymentMethods.attach(paymentMethodId, {\n customer: locals.user.stripeCustomerId,\n });\n\n return { success: true };\n },\n\n removePaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Detach payment method from customer\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.paymentMethods.detach(paymentMethodId);\n\n return { success: true };\n },\n\n setDefaultPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Update customer's default payment method\n const stripe = await import(\"$lib/stripe\").then((m) => m.default);\n await stripe.customers.update(locals.user.stripeCustomerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n return { success: true };\n },\n};\n```\n\n### 4. Update Frontend to Use Actions\n\nReplace the mock functions in `+page.svelte`:\n\n```typescript\nasync function handleAddPaymentMethod() {\n if (!stripe || !cardElement || !cardComplete) return;\n\n isProcessing = true;\n\n try {\n const { error, paymentMethod } = await stripe.createPaymentMethod({\n type: \"card\",\n card: cardElement,\n });\n\n if (error) {\n toast.error(error.message);\n return;\n }\n\n // Submit to your backend\n const formData = new FormData();\n formData.append(\"paymentMethodId\", paymentMethod.id);\n\n const response = await fetch(\"?/addPaymentMethod\", {\n method: \"POST\",\n body: formData,\n });\n\n if (response.ok) {\n toast.success(\"Payment method added\");\n // Reload page to fetch updated payment methods\n window.location.reload();\n }\n } finally {\n isProcessing = false;\n }\n}\n```\n\n## Security Considerations\n\n⚠️ **Important**: Never expose your Stripe secret key on the frontend\n✅ All sensitive operations should happen on your backend\n✅ Use Stripe's publishable key for frontend operations\n✅ Validate user permissions before modifying payment methods\n✅ Use HTTPS in production\n\n## Testing\n\nUse [Stripe's test cards](https://stripe.com/docs/testing) for testing:\n\n- **Success**: 4242 4242 4242 4242\n- **Decline**: 4000 0000 0000 0002\n- **Requires authentication**: 4000 0025 0000 3155\n\nUse any future expiration date and any 3-digit CVC.\n\n## Styling\n\nThe page uses Tailwind CSS and shadcn/ui components. All components are styled to match your existing design system with support for light/dark modes.\n\n### Stripe Elements Styling\n\nSince Stripe Elements render in an iframe, they cannot access CSS variables directly. Additionally, Stripe only accepts HEX, RGB, or HSL colors (not modern formats like OKLCH).\n\nThe implementation:\n\n1. **Creates temporary DOM elements** with CSS variables applied\n2. **Lets the browser compute colors** - converts OKLCH/HSL/any format to RGB\n3. **Extracts RGB values** that Stripe Elements can understand\n4. **Passes computed colors** to Stripe Elements on initialization\n5. **Matches the current theme** automatically (light/dark mode)\n\nThis approach works with any CSS color format (oklch, hsl, rgb, hex) and ensures Stripe Elements always match your theme when the \"Add Payment Method\" dialog opens.\n\n## Dependencies\n\n- `@stripe/stripe-js` - Stripe.js for frontend\n- `stripe` - Stripe Node.js SDK for backend\n- `svelte-sonner` - Toast notifications\n- `@lucide/svelte` - Icons\n- shadcn/ui components\n", La = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (\n price: Stripe.Price,\n customer?: { id: string; default_payment_method?: string },\n) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n // Guest\n if (!customer) {\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n }\n\n // Customer with saved payment method\n if (customer.default_payment_method) {\n const paymentMethod = await stripe.customers.retrievePaymentMethod(\n customer.id,\n customer.default_payment_method,\n );\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n payment_method: customer.default_payment_method,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return {\n type: \"confirm\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n };\n }\n\n // Customer without saved payment method\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n setup_future_usage: \"off_session\",\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n const user = locals.pb.authStore.record?.id;\n\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n let customer;\n\n if (user) {\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user }),\n );\n } catch (error) {\n // Customer not found is expected for new users, log for debugging only\n console.log(\"No Stripe customer found for user:\", user);\n }\n }\n\n try {\n const res = await createPaymentIntent(price, customer);\n return json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return json({ error: errorMessage }, { status: 500 });\n }\n};\n", Ra = "import { describe, it, expect, beforeAll, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"$lib/stripe\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n beforeEach(async (context) => {\n // Create a Stripe customer for authenticated user tests\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Create a payment method for the customer\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n });\n\n afterEach(async () => {\n if (paymentMethod?.id) {\n await stripe.paymentMethods.detach(paymentMethod.id);\n }\n\n if (stripeCustomer?.id) {\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user without Stripe customer\", () => {\n it(\"should create payment intent for user without Stripe customer\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n\n // Verify the payment intent\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.setup_future_usage).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user with Stripe customer\", () => {\n let customerRecord: { id: string };\n\n beforeEach(async (context) => {\n // Link the Stripe customer to the PocketBase user\n customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .create({\n user: context.user.id,\n id: stripeCustomer.id,\n email: stripeCustomer.email,\n });\n });\n\n afterEach(async (context) => {\n // Clean up the PocketBase customer record\n await context.admin\n .collection(\"stripe_customers\")\n .delete(customerRecord.id);\n });\n\n it(\"should create payment intent with setup_future_usage for user without default payment method\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n\n // Verify the payment intent has setup_future_usage\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.setup_future_usage).toBe(\"off_session\");\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n\n it(\"should create payment intent with default payment method for customer with saved payment method\", async (context) => {\n // Set default payment method\n await stripe.customers.update(stripeCustomer.id, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n const customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n context.admin.filter(\"user = {:user}\", { user: context.user.id }),\n );\n\n await context.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customerRecord.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 await context.admin\n .collection(\"stripe_customers\")\n .update(customerRecord.id, {\n default_payment_method: paymentMethod.id,\n });\n\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"confirm\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBe(\"visa\");\n expect(response.body.last4).toBeDefined();\n expect(response.body.last4).toMatch(/^\\d{4}$/);\n\n // Verify the payment intent has the payment method attached\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.payment_method).toBe(paymentMethod.id);\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", za = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\nexport const POST = async ({ locals }) => {\n const user = locals.pb.authStore.record?.id;\n\n if (!user) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(locals.admin.filter(\"user = {:user}\", { user }));\n\n if (!customer) {\n return json({ error: \"Customer not found\" }, { status: 404 });\n }\n\n const setupIntent = await stripe.setupIntents.create({\n customer: customer.id,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return json({ clientSecret: setupIntent.client_secret });\n};\n", Ba = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"POST /api/stripe/setup-intent\", () => {\n let stripeCustomer: Stripe.Customer;\n\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n });\n\n afterEach(async (context) => {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n });\n\n it(\"creates a setup intent\", async (context) => {\n const response = await context.agent.post(\n \"/api/stripe/setup-intent\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n expect(response.body.clientSecret).toBeDefined();\n });\n});\n", Va = "import { json } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\nimport { INTERNAL_JOB_SECRET } from \"$env/static/private\";\n\n// Sync users to Stripe customers\nexport const POST = async ({ request, locals }) => {\n const authHeader = request.headers.get(\"Authorization\");\n if (authHeader !== `Bearer ${INTERNAL_JOB_SECRET}`) {\n return json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n // Ensure all users have a Stripe customer\n const users = await locals.admin\n .collection(\"users\")\n .getFullList({ filter: \"stripe_customers_via_user.id = null\" });\n\n for (const user of users) {\n const customer = await stripe.customers.create({\n email: user.email,\n name: user.name,\n });\n\n await locals.admin.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n }\n\n console.log(\"Customers synced\");\n return json({ message: \"Customers synced\" });\n};\n", Ha = "import Stripe from \"stripe\";\nimport { json } from \"@sveltejs/kit\";\nimport { STRIPE_WEBHOOK_SECRET } from \"$env/static/private\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./handlers/payment-intent/succeeded\";\nimport { handlePaymentMethodAttached } from \"./handlers/payment-method/attached\";\n\nconst processedEvents = new Set<string>();\n\nasync function verifyWebhookSignature(\n request: Request,\n webhookSecret: string,\n): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get(\"stripe-signature\");\n\n if (!signature) {\n throw new Error(\"Missing stripe-signature header\");\n }\n\n if (!webhookSecret) {\n throw new Error(\"Missing webhook secret\");\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error(\"Webhook signature verification failed:\", err);\n throw new Error(\"Invalid signature\");\n }\n}\n\nexport const POST = async ({ request, locals }) => {\n try {\n const event = await verifyWebhookSignature(request, STRIPE_WEBHOOK_SECRET);\n\n if (processedEvents.has(event.id)) {\n console.log(`Event ${event.id} already processed, skipping`);\n return json({ received: true, message: \"Event already processed\" });\n }\n\n processedEvents.add(event.id);\n\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\n\n switch (event.type) {\n case \"payment_intent.succeeded\":\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case \"payment_method.attached\":\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n\n return json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n });\n } catch (error) {\n console.error(\"Webhook processing error:\", error);\n\n return json(\n {\n error: \"Webhook processing failed\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 400 },\n );\n }\n};\n", Ua = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentIntent: Stripe.PaymentIntent;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n // Create a Stripe customer\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Link the Stripe customer to the test user\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n // Create a payment method for testing\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n // Attach payment method to customer\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n // Create a payment intent\n paymentIntent = await stripe.paymentIntents.create({\n amount: 2000, // $20.00\n currency: \"usd\",\n customer: stripeCustomer.id,\n payment_method: paymentMethod.id,\n confirm: true,\n return_url: \"https://example.com/return\",\n });\n });\n\n afterEach(async (context) => {\n // Clean up transactions\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\"stripe_customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n for (const transaction of transactions) {\n await context.admin.collection(\"transactions\").delete(transaction.id);\n }\n\n // Clean up Stripe resources\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch (e) {\n // Payment method may already be detached\n }\n }\n\n // Delete customer (this will also delete associated payment methods)\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a transaction record when payment intent succeeds\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_customer).toBe(stripeCustomer.id);\n expect(transaction.amount).toBe(2000);\n expect(transaction.currency).toBe(\"usd\");\n expect(transaction.user).toBe(context.user.id);\n expect(transaction.stripe_charge).toBeDefined();\n expect(transaction.last4).toBeDefined();\n expect(transaction.brand).toBeDefined();\n expect(transaction.created).toBeDefined();\n expect(transaction.receipt_url).toBeDefined();\n });\n\n it(\"handles payment intent with charge object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded charge\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"latest_charge\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_charge).toBeDefined();\n });\n\n it(\"handles payment intent with customer object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded customer\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n expect(transactions[0].stripe_customer).toBe(stripeCustomer.id);\n });\n\n it(\"handles missing charge ID gracefully\", async (context) => {\n const paymentIntentWithoutCharge = {\n ...paymentIntent,\n latest_charge: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCharge, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n\n it(\"handles missing customer ID gracefully\", async (context) => {\n const paymentIntentWithoutCustomer = {\n ...paymentIntent,\n customer: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCustomer, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n});\n", Wa = "import Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n const chargeId =\n typeof paymentIntent.latest_charge === \"string\"\n ? paymentIntent.latest_charge\n : paymentIntent.latest_charge?.id;\n\n if (!chargeId) {\n console.error(\"No charge ID found for payment intent\");\n return;\n }\n\n const charge = await stripe.charges.retrieve(chargeId);\n\n const customerId =\n typeof paymentIntent.customer === \"string\"\n ? paymentIntent.customer\n : paymentIntent.customer?.id;\n\n if (!customerId) {\n console.error(\"No customer ID found for payment intent\");\n return;\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n const created = new Date(charge.created * 1000);\n\n await locals.admin.collection(\"transactions\").create({\n stripe_payment_intent: paymentIntent.id,\n stripe_charge: chargeId,\n stripe_customer: customerId,\n amount: paymentIntent.amount,\n currency: paymentIntent.currency,\n created: created.toISOString(),\n last4: charge.payment_method_details?.card?.last4,\n brand: charge.payment_method_details?.card?.brand,\n receipt_url: charge.receipt_url,\n user: customer.user,\n });\n}\n", Ga = "import Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\n\n/**\n * Handles payment_method.attached event\n */\nexport async function handlePaymentMethodAttached(\n paymentMethod: Stripe.PaymentMethod,\n locals: App.Locals,\n) {\n if (\n paymentMethod.allow_redisplay === \"unspecified\" ||\n !paymentMethod.customer\n ) {\n return;\n }\n\n const customer =\n typeof paymentMethod.customer === \"string\"\n ? paymentMethod.customer\n : paymentMethod.customer?.id;\n\n await locals.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer,\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 const paymentMethodRecords = await locals.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: locals.admin.filter(\"customer = {:customer}\", {\n customer: customer,\n }),\n });\n\n if (paymentMethodRecords.length === 1) {\n const paymentMethod = paymentMethodRecords[0];\n\n await stripe.customers.update(customer, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer, {\n default_payment_method: paymentMethod.id,\n });\n }\n}\n", Ka = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"$lib/stripe\";\nimport { handlePaymentMethodAttached } from \"./attached\";\n\ndescribe(\"payment_method.attached\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n paymentMethod = await stripe.paymentMethods.update(paymentMethod.id, {\n allow_redisplay: \"always\",\n });\n });\n\n afterEach(async (context) => {\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n\n for (const pm of paymentMethods) {\n await context.admin.collection(\"stripe_payment_methods\").delete(pm.id);\n }\n\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch {}\n }\n\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a payment method record when payment method is attached\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n const pm = paymentMethods[0];\n\n expect(pm.id).toBe(paymentMethod.id);\n expect(pm.customer).toBe(stripeCustomer.id);\n expect(pm.brand).toBe(paymentMethod.card?.brand);\n expect(pm.last4).toBe(paymentMethod.card?.last4);\n expect(pm.exp_month).toBe(paymentMethod.card?.exp_month);\n expect(pm.exp_year).toBe(paymentMethod.card?.exp_year);\n });\n\n it(\"sets payment method as default when it is the first one\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default in database\n const customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Verify it was set as default in Stripe\n const stripeCustomerUpdated = await stripe.customers.retrieve(\n stripeCustomer.id,\n );\n if (\"deleted\" in stripeCustomerUpdated) {\n throw new Error(\"Customer should not be deleted\");\n }\n expect(stripeCustomerUpdated.invoice_settings.default_payment_method).toBe(\n paymentMethod.id,\n );\n });\n\n it(\"does not set as default when there are already payment methods\", async (context) => {\n // Handle the first payment method\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default\n let customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Create and attach a first payment method\n let secondPaymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_mastercard\",\n },\n });\n\n await stripe.paymentMethods.attach(secondPaymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n secondPaymentMethod = await stripe.paymentMethods.update(\n secondPaymentMethod.id,\n {\n allow_redisplay: \"always\",\n },\n );\n\n // Now handle the second payment method\n await handlePaymentMethodAttached(secondPaymentMethod, locals);\n\n // Verify the default did NOT change\n customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Clean up the second payment method\n await context.admin\n .collection(\"stripe_payment_methods\")\n .delete(secondPaymentMethod.id);\n await stripe.paymentMethods.detach(secondPaymentMethod.id);\n });\n\n it(\"handles payment method with customer object instead of string\", async (context) => {\n // Retrieve the payment method with expanded customer\n const expandedPaymentMethod = await stripe.paymentMethods.retrieve(\n paymentMethod.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(expandedPaymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n expect(paymentMethods[0].customer).toBe(stripeCustomer.id);\n });\n\n it(\"does not create record when allow_redisplay is unspecified\", async (context) => {\n // Update payment method to have unspecified allow_redisplay\n const unspecifiedPaymentMethod = await stripe.paymentMethods.update(\n paymentMethod.id,\n {\n allow_redisplay: \"unspecified\",\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(unspecifiedPaymentMethod, locals);\n\n // Verify no payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(0);\n });\n});\n", qa = /* @__PURE__ */ Object.assign({
|
|
4312
|
+
"./creates/data/hooks/stripe.pb.js": da,
|
|
4313
|
+
"./creates/data/hooks/utils.js": fa,
|
|
4314
|
+
"./creates/src/lib/components/payments/confirm-dialog.svelte": pa,
|
|
4315
|
+
"./creates/src/lib/components/payments/payment-button.svelte": ma,
|
|
4316
|
+
"./creates/src/lib/components/payments/payment-dialog.svelte": ha,
|
|
4317
|
+
"./creates/src/lib/components/payments/stripe-constants.ts": ga,
|
|
4318
|
+
"./creates/src/lib/components/payments/stripe-payment-form.svelte": _a,
|
|
4319
|
+
"./creates/src/lib/components/payments/use-payment-intent.svelte.ts": va,
|
|
4320
|
+
"./creates/src/lib/components/payments/use-stripe.svelte.ts": ya,
|
|
4321
|
+
"./creates/src/lib/stripe.ts": ba,
|
|
4322
|
+
"./creates/src/routes/api/stripe/payment-intent/+server.ts": xa,
|
|
4323
|
+
"./creates/src/routes/api/stripe/payment-intent/server.test.ts": Sa,
|
|
4324
|
+
"./creates/src/routes/api/stripe/sync/prices/+server.ts": Ca,
|
|
4325
|
+
"./creates/src/routes/api/stripe/sync/products/+server.ts": wa,
|
|
4326
|
+
"./creates/src/routes/webhooks/stripe/+server.ts": Ta,
|
|
4327
|
+
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": Ea,
|
|
4328
|
+
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": Da,
|
|
4329
|
+
"./creates/src/routes/webhooks/stripe/server.test.ts": Oa
|
|
4330
|
+
}), Ja = /* @__PURE__ */ Object.assign({
|
|
4331
|
+
"./creates-app-mode/data/hooks/stripe.pb.js": ka,
|
|
4332
|
+
"./creates-app-mode/data/hooks/utils.js": Aa,
|
|
4333
|
+
"./creates-app-mode/src/lib/components/payments/setup-button.svelte": ja,
|
|
4334
|
+
"./creates-app-mode/src/lib/components/payments/setup-dialog.svelte": Ma,
|
|
4335
|
+
"./creates-app-mode/src/routes/(app)/billing/+layout.server.ts": Na,
|
|
4336
|
+
"./creates-app-mode/src/routes/(app)/billing/+page.server.ts": Pa,
|
|
4337
|
+
"./creates-app-mode/src/routes/(app)/billing/+page.svelte": Fa,
|
|
4338
|
+
"./creates-app-mode/src/routes/(app)/billing/README.md": Ia,
|
|
4339
|
+
"./creates-app-mode/src/routes/api/stripe/payment-intent/+server.ts": La,
|
|
4340
|
+
"./creates-app-mode/src/routes/api/stripe/payment-intent/server.test.ts": Ra,
|
|
4341
|
+
"./creates-app-mode/src/routes/api/stripe/setup-intent/+server.ts": za,
|
|
4342
|
+
"./creates-app-mode/src/routes/api/stripe/setup-intent/server.test.ts": Ba,
|
|
4343
|
+
"./creates-app-mode/src/routes/api/stripe/sync/customers/+server.ts": Va,
|
|
4344
|
+
"./creates-app-mode/src/routes/webhooks/stripe/+server.ts": Ha,
|
|
4345
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": Ua,
|
|
4346
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": Wa,
|
|
4347
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/attached.ts": Ga,
|
|
4348
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts": Ka
|
|
4349
|
+
}), Ya = "./creates/", Xa = "./creates-app-mode/";
|
|
4350
|
+
function Za(e, t) {
|
|
4346
4351
|
let r = {};
|
|
4347
4352
|
for (let [a, o] of Object.entries(e)) {
|
|
4348
4353
|
let e = i(a, t);
|
|
@@ -4355,10 +4360,10 @@ function Xa(e, t) {
|
|
|
4355
4360
|
}
|
|
4356
4361
|
return r;
|
|
4357
4362
|
}
|
|
4358
|
-
async function
|
|
4359
|
-
let t = e.features.auth, n = { ...
|
|
4363
|
+
async function Qa(e) {
|
|
4364
|
+
let t = e.features.auth, n = { ...Za(qa, Ya) };
|
|
4360
4365
|
if (t) {
|
|
4361
|
-
let e =
|
|
4366
|
+
let e = Za(Ja, Xa);
|
|
4362
4367
|
Object.assign(n, e);
|
|
4363
4368
|
}
|
|
4364
4369
|
let r = Object.values(n).sort((e, t) => e.path.localeCompare(t.path)), i = [
|
|
@@ -4378,7 +4383,7 @@ async function Za(e) {
|
|
|
4378
4383
|
}
|
|
4379
4384
|
//#endregion
|
|
4380
4385
|
//#region src/patterns/enable/payments/preview-modifies/src/lib/components/nav-user.svelte?raw
|
|
4381
|
-
var
|
|
4386
|
+
var $a = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n // [!code highlight:1]\n import CreditCardIcon from '@lucide/svelte/icons/credit-card';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n // [!code highlight:5]\n {\n title: 'Billing',\n url: '/billing',\n icon: CreditCardIcon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", eo = "import { redirect } from \"@sveltejs/kit\";\nimport { fail, superValidate } from \"sveltekit-superforms\";\nimport { zod4 } from \"sveltekit-superforms/adapters\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { setPocketbaseErrors } from \"@velastack/pocketbase\";\nimport { dev } from \"$app/environment\";\nimport { signupSchema } from \"$lib/schemas/signup\";\n// [!code highlight:1]\nimport stripe from \"$lib/stripe\";\n\nexport const load = async ({ locals }) => {\n const authMethods = await locals.admin.collection(\"users\").listAuthMethods();\n\n if (locals.pb.authStore.isValid) {\n redirect(303, \"/dashboard\");\n }\n\n return { form: await superValidate(zod4(signupSchema)), authMethods };\n};\n\nexport const actions = {\n default: async ({ locals, request, cookies, url }) => {\n const form = await superValidate(request, zod4(signupSchema));\n\n if (!form.valid) {\n return fail(400, { form });\n }\n\n let user;\n\n try {\n user = await locals.admin.collection(\"users\").create({\n email: form.data.email,\n password: form.data.password,\n passwordConfirm: form.data.passwordConfirm,\n });\n } catch (error) {\n setPocketbaseErrors(form, error);\n return fail(400, { form });\n }\n\n // [!code highlight:1]\n await linkStripeCustomer(form.data.email, user, locals);\n\n await locals.pb.collection(\"users\").requestVerification(user.email);\n await locals.pb\n .collection(\"users\")\n .authWithPassword(form.data.email, form.data.password);\n\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n const cookie = locals.pb.authStore.getCookie();\n cookies.set(\"pb_auth\", cookie, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n setFlash(\n { type: \"toast\", message: \"We sent a confirmation link to your email.\" },\n cookies,\n );\n return redirect(303, redirectUrl);\n },\n};\n\n// [!code highlight:66]\nconst linkStripeCustomer = async (\n email: string,\n user: { id: string },\n locals: App.Locals,\n) => {\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(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\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 =\n 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", to = "users", no = "stripe_customers", ro = "stripe_payment_methods", io = {
|
|
4382
4387
|
name: "stripe_products",
|
|
4383
4388
|
type: "base",
|
|
4384
4389
|
fields: [
|
|
@@ -4417,7 +4422,7 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4417
4422
|
type: "autodate"
|
|
4418
4423
|
}
|
|
4419
4424
|
]
|
|
4420
|
-
},
|
|
4425
|
+
}, ao = {
|
|
4421
4426
|
name: "stripe_prices",
|
|
4422
4427
|
type: "base",
|
|
4423
4428
|
fields: [
|
|
@@ -4476,8 +4481,8 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4476
4481
|
type: "autodate"
|
|
4477
4482
|
}
|
|
4478
4483
|
]
|
|
4479
|
-
},
|
|
4480
|
-
name:
|
|
4484
|
+
}, oo = {
|
|
4485
|
+
name: no,
|
|
4481
4486
|
type: "base",
|
|
4482
4487
|
fields: [
|
|
4483
4488
|
{
|
|
@@ -4488,7 +4493,7 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4488
4493
|
type: "text"
|
|
4489
4494
|
},
|
|
4490
4495
|
{
|
|
4491
|
-
collectionId:
|
|
4496
|
+
collectionId: to,
|
|
4492
4497
|
maxSelect: 1,
|
|
4493
4498
|
minSelect: 0,
|
|
4494
4499
|
name: "user",
|
|
@@ -4496,7 +4501,7 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4496
4501
|
type: "relation"
|
|
4497
4502
|
},
|
|
4498
4503
|
{
|
|
4499
|
-
collectionId:
|
|
4504
|
+
collectionId: ro,
|
|
4500
4505
|
maxSelect: 1,
|
|
4501
4506
|
minSelect: 0,
|
|
4502
4507
|
name: "default_payment_method",
|
|
@@ -4516,8 +4521,8 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4516
4521
|
type: "autodate"
|
|
4517
4522
|
}
|
|
4518
4523
|
]
|
|
4519
|
-
},
|
|
4520
|
-
name:
|
|
4524
|
+
}, so = {
|
|
4525
|
+
name: ro,
|
|
4521
4526
|
type: "base",
|
|
4522
4527
|
fields: [
|
|
4523
4528
|
{
|
|
@@ -4548,7 +4553,7 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4548
4553
|
type: "number"
|
|
4549
4554
|
},
|
|
4550
4555
|
{
|
|
4551
|
-
collectionId:
|
|
4556
|
+
collectionId: no,
|
|
4552
4557
|
maxSelect: 1,
|
|
4553
4558
|
minSelect: 0,
|
|
4554
4559
|
name: "customer",
|
|
@@ -4569,7 +4574,7 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4569
4574
|
type: "autodate"
|
|
4570
4575
|
}
|
|
4571
4576
|
]
|
|
4572
|
-
},
|
|
4577
|
+
}, co = {
|
|
4573
4578
|
name: "transactions",
|
|
4574
4579
|
type: "base",
|
|
4575
4580
|
fields: [
|
|
@@ -4624,7 +4629,7 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4624
4629
|
type: "text"
|
|
4625
4630
|
},
|
|
4626
4631
|
{
|
|
4627
|
-
collectionId:
|
|
4632
|
+
collectionId: to,
|
|
4628
4633
|
maxSelect: 1,
|
|
4629
4634
|
minSelect: 0,
|
|
4630
4635
|
name: "user",
|
|
@@ -4637,20 +4642,20 @@ var Qa = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4637
4642
|
type: "url"
|
|
4638
4643
|
}
|
|
4639
4644
|
]
|
|
4640
|
-
},
|
|
4641
|
-
ao,
|
|
4645
|
+
}, lo = [io, ao], uo = [
|
|
4642
4646
|
oo,
|
|
4643
|
-
so
|
|
4644
|
-
|
|
4645
|
-
|
|
4646
|
-
"./preview-modifies/src/
|
|
4647
|
-
|
|
4648
|
-
|
|
4649
|
-
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
|
|
4653
|
-
|
|
4647
|
+
so,
|
|
4648
|
+
co
|
|
4649
|
+
], fo, po = /* @__PURE__ */ Object.assign({
|
|
4650
|
+
"./preview-modifies/src/lib/components/nav-user.svelte": $a,
|
|
4651
|
+
"./preview-modifies/src/routes/(public)/signup/+page.server.ts": eo
|
|
4652
|
+
}), mo = "./preview-modifies/", ho = "price_preview_placeholder";
|
|
4653
|
+
function go(e) {
|
|
4654
|
+
return t(fo ||= s(["\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=\"", "\" />\n </section>\n "]), e);
|
|
4655
|
+
}
|
|
4656
|
+
async function _o(e) {
|
|
4657
|
+
let t = e.features.auth, r = Object.entries(po).map(([e, t]) => {
|
|
4658
|
+
let r = i(e, mo);
|
|
4654
4659
|
return {
|
|
4655
4660
|
path: r,
|
|
4656
4661
|
language: n(r),
|
|
@@ -4660,9 +4665,9 @@ async function go(e) {
|
|
|
4660
4665
|
}).sort((e, t) => e.path.localeCompare(t.path)), a = {
|
|
4661
4666
|
path: "src/routes/(public)/payment/+page.svelte",
|
|
4662
4667
|
language: "svelte",
|
|
4663
|
-
content: ho
|
|
4668
|
+
content: go(ho),
|
|
4664
4669
|
status: "success"
|
|
4665
|
-
}, o = [...
|
|
4670
|
+
}, o = [...lo, ...t ? uo : []];
|
|
4666
4671
|
return {
|
|
4667
4672
|
creates: [a],
|
|
4668
4673
|
modifies: r,
|
|
@@ -4675,18 +4680,18 @@ async function go(e) {
|
|
|
4675
4680
|
}
|
|
4676
4681
|
//#endregion
|
|
4677
4682
|
//#region src/patterns/enable/payments/index.ts
|
|
4678
|
-
var
|
|
4679
|
-
async function
|
|
4680
|
-
let t = await
|
|
4681
|
-
if (e.env === "preview") return _(r([t, await
|
|
4682
|
-
let { generate: n } = await import("./chunks/generate.runtime-
|
|
4683
|
+
var vo = "enable-payments", yo = "1.0.0", bo = "src/patterns/enable/payments", xo = "/enable/payments";
|
|
4684
|
+
async function So(e) {
|
|
4685
|
+
let t = await Qa(e);
|
|
4686
|
+
if (e.env === "preview") return _(r([t, await _o(e)]));
|
|
4687
|
+
let { generate: n } = await import("./chunks/generate.runtime-BZ-KaCUr.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
4683
4688
|
return a(await _(r([t, i])), e);
|
|
4684
4689
|
}
|
|
4685
|
-
var
|
|
4686
|
-
version:
|
|
4687
|
-
slug:
|
|
4688
|
-
source:
|
|
4689
|
-
docs:
|
|
4690
|
+
var Co = {
|
|
4691
|
+
version: yo,
|
|
4692
|
+
slug: vo,
|
|
4693
|
+
source: bo,
|
|
4694
|
+
docs: xo,
|
|
4690
4695
|
plan: "pro",
|
|
4691
4696
|
title: "Enable payments",
|
|
4692
4697
|
summary: "Adds Stripe payments with product/price sync, checkout flow, and optional saved payment methods when auth is enabled.",
|
|
@@ -4715,8 +4720,8 @@ var So = {
|
|
|
4715
4720
|
examples: [],
|
|
4716
4721
|
tests: 0,
|
|
4717
4722
|
baseline: "velastack",
|
|
4718
|
-
generate:
|
|
4719
|
-
},
|
|
4723
|
+
generate: So
|
|
4724
|
+
}, wo = /* @__PURE__ */ Object.assign({
|
|
4720
4725
|
"./creates/src/lib/components/team-switcher.svelte": "<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';\n import * as Sidebar from '$lib/components/ui/sidebar/index.js';\n import { useSidebar } from '$lib/components/ui/sidebar/index.js';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import UsersIcon from '@lucide/svelte/icons/users';\n import { page } from '$app/state';\n import { goto, invalidate } from '$app/navigation';\n\n let { teams, children }: { teams: { id: string; name: string }[] } & { children: Snippet } =\n $props();\n\n const switchTeam = async (teamId: string) => {\n await goto(`/teams/switch/${teamId}?redirect=${encodeURIComponent(page.url.pathname)}`);\n invalidate('app:team');\n };\n\n const sidebar = useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n {...props}\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n >\n {@render children?.()}\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n align=\"start\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"text-muted-foreground text-xs\">Teams</DropdownMenu.Label>\n {#each teams as team (team.name)}\n <DropdownMenu.Item onSelect={() => switchTeam(team.id)} class=\"gap-2 p-2\">\n <div class=\"flex size-6 items-center justify-center rounded-md border\">\n <UsersIcon class=\"size-3.5 shrink-0\" />\n </div>\n {team.name}\n </DropdownMenu.Item>\n {/each}\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"gap-2 p-2\">\n <div class=\"flex size-6 items-center justify-center rounded-md border bg-transparent\">\n <PlusIcon class=\"size-4\" />\n </div>\n <a href=\"/teams/new\" class=\"text-muted-foreground font-medium\">Add team</a>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n",
|
|
4721
4726
|
"./creates/src/lib/schemas/team.ts": "import { z } from \"zod\";\n\nexport const teamSchema = z.object({\n name: z.string(),\n});\n",
|
|
4722
4727
|
"./creates/src/lib/schemas/teamInvite.ts": "import { z } from \"zod\";\n\nexport const teamInviteSchema = z.object({\n email: z.email(),\n});\n",
|
|
@@ -4749,11 +4754,11 @@ var So = {
|
|
|
4749
4754
|
"./creates/src/routes/(app)/teams/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /teams\", () => {\n it(\"authenticated user should be able to access the teams page\", async (context) => {\n await context.agent.authenticateUser();\n const response = await context.agent.get(\"/teams\" satisfies Match<RouteId>);\n expect(response.status).toBe(200);\n });\n});\n",
|
|
4750
4755
|
"./creates/src/routes/(app)/teams/switch/[id]/+page.server.ts": "import { error, redirect } from \"@sveltejs/kit\";\nimport { dev } from \"$app/environment\";\n\nexport const load = async ({ params, cookies, url, locals }) => {\n const { id } = params;\n const redirectUrl = url.searchParams.get(\"redirect\") ?? \"/dashboard\";\n\n try {\n await locals.pb.collection(\"teams\").getOne(id);\n } catch {\n return error(404, { message: \"Team not found\" });\n }\n\n cookies.set(\"team\", id, {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\",\n secure: !dev,\n maxAge: 60 * 60 * 24 * 30,\n });\n\n return redirect(303, redirectUrl);\n};\n",
|
|
4751
4756
|
"./creates/src/routes/(app)/teams/switch/[id]/server.test.ts": "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\nlet team: { id: string; name: string; owner: string };\n\nbeforeEach(async (context) => {\n await context.agent.authenticateUser();\n\n // Create a test team for the user\n const teamName = `Test Team ${Math.random().toString(36).slice(2)}`;\n team = await context.admin.collection(\"teams\").create({\n name: teamName,\n owner: context.user.id,\n });\n\n // Create team membership\n await context.admin.collection(\"team_memberships\").create({\n user: context.user.id,\n team: team.id,\n role: \"owner\",\n });\n});\n\nafterEach(async (context) => {\n try {\n await context.admin.collection(\"teams\").delete(team.id);\n } catch {}\n});\n\ndescribe(\"GET /teams/switch/[id]\", () => {\n it(\"should set team cookie and redirect to dashboard for valid team\", async (context) => {\n const response = await context.agent.get(\n `/teams/switch/${team.id}` satisfies Match<RouteId>,\n );\n\n expect(response.status).toBe(303);\n expect(response.headers.location).toBe(\"/dashboard\");\n\n // Check that the team cookie is set\n const cookies = response.headers[\"set-cookie\"]?.[0];\n expect(cookies).toBeDefined();\n expect(cookies).toContain(`team=${team.id}`);\n });\n\n it(\"should redirect to custom redirect URL when provided\", async (context) => {\n const customRedirect = \"/teams\";\n const response = await context.agent.get(\n `/teams/switch/${team.id}?redirect=${encodeURIComponent(customRedirect)}` satisfies Match<RouteId>,\n );\n\n expect(response.status).toBe(303);\n expect(response.headers.location).toBe(customRedirect);\n\n // Check that the team cookie is still set\n const cookies = response.headers[\"set-cookie\"]?.[0];\n expect(cookies).toBeDefined();\n expect(cookies).toContain(\"team=\" + team.id);\n });\n\n it(\"should return 404 error for non-existent team\", async (context) => {\n const nonExistentTeamId = \"non-existent-team-id\";\n const response = await context.agent.get(\n `/teams/switch/${nonExistentTeamId}` satisfies Match<RouteId>,\n );\n\n expect(response.status).toBe(404);\n\n const cookies = response.headers[\"set-cookie\"]?.[0];\n expect(cookies).toBeUndefined();\n });\n\n it(\"should return 404 error for invalid team ID format\", async (context) => {\n const invalidTeamId = \"invalid-id-format\";\n const response = await context.agent.get(\n `/teams/switch/${invalidTeamId}` satisfies Match<RouteId>,\n );\n\n expect(response.status).toBe(404);\n\n // Check that no team cookie is set\n const cookies = response.headers[\"set-cookie\"]?.[0];\n expect(cookies).toBeUndefined();\n });\n});\n"
|
|
4752
|
-
}),
|
|
4753
|
-
async function
|
|
4757
|
+
}), To = "./creates/";
|
|
4758
|
+
async function Eo(e) {
|
|
4754
4759
|
return {
|
|
4755
|
-
creates: Object.entries(
|
|
4756
|
-
let r = i(e,
|
|
4760
|
+
creates: Object.entries(wo).map(([e, t]) => {
|
|
4761
|
+
let r = i(e, To);
|
|
4757
4762
|
return {
|
|
4758
4763
|
path: r,
|
|
4759
4764
|
language: n(r),
|
|
@@ -4783,9 +4788,9 @@ async function To(e) {
|
|
|
4783
4788
|
}
|
|
4784
4789
|
//#endregion
|
|
4785
4790
|
//#region src/patterns/enable/teams/preview-modifies/src/lib/components/app-sidebar.svelte?raw
|
|
4786
|
-
var
|
|
4791
|
+
var Do = "<script lang=\"ts\">\n import type { ComponentProps } from 'svelte';\n import HomeIcon from '@lucide/svelte/icons/home';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n // [!code highlight:3]\n import TeamSwitcher from '$lib/components/team-switcher.svelte';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import * as Avatar from '$lib/components/ui/avatar';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n\n let {\n user,\n meta,\n team,\n teams = [],\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n meta: any;\n team?: string | undefined;\n teams?: { id: string; name: string }[];\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <TeamSwitcher {teams}>\n {#snippet children()}\n {@const activeTeam = teams.find((t) => t.id === team)}\n {#if activeTeam}\n <Avatar.Root class=\"size-8 rounded-lg\">\n <Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n {activeTeam.name?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {activeTeam.name}\n </span>\n </div>\n {:else}\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src=\"/favicon.svg\" alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{meta.appName}</span>\n </div>\n {/if}\n <ChevronsUpDownIcon class=\"ml-auto\" />\n {/snippet}\n </TeamSwitcher>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", Oo = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n // [!code highlight:1]\n import UsersIcon from '@lucide/svelte/icons/users';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import * as Avatar from '$lib/components/ui/avatar';\n import * as DropdownMenu from '$lib/components/ui/dropdown-menu';\n import * as Sidebar from '$lib/components/ui/sidebar';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n // [!code highlight:5]\n {\n title: 'Teams',\n url: '/teams',\n icon: UsersIcon\n }\n ]\n };\n\n let {\n user\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n } = $props();\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? 'bottom' : 'right'}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image src=\"/api/files/users/{user.id}/{user.avatar}\" alt={user.name} />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{user.name}</span>\n <span class=\"truncate text-xs\">{user.email}</span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === 'dark'}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", ko = "export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n // [!code highlight:3]\n const team = locals.team;\n const teams = await locals.pb.collection(\"teams\").getFullList();\n depends(\"app:team\");\n\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n\n return { user, team, teams, breadcrumbs };\n};\n", Ao = "<script lang=\"ts\">\n import * as Sidebar from '$lib/components/ui/sidebar';\n import { Separator } from '$lib/components/ui/separator';\n import AppSidebar from '$lib/components/app-sidebar.svelte';\n import * as Breadcrumb from '$lib/components/ui/breadcrumb';\n import { page } from '$app/state';\n\n let breadcrumbs = $derived(page.data.breadcrumbs || []) as { title: string; url: string }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:1] -->\n <AppSidebar user={data.user} meta={data.meta} team={data.team} teams={data.teams ?? []} />\n <Sidebar.Inset>\n <header class=\"flex h-16 shrink-0 items-center gap-2\">\n <div class=\"flex items-center gap-2 px-4\">\n <Sidebar.Trigger class=\"-ml-1\" />\n <Separator orientation=\"vertical\" class=\"mr-2 data-[orientation=vertical]:h-4\" />\n {#if breadcrumbs.length > 0}\n <Breadcrumb.Root>\n <Breadcrumb.List>\n {#if breadcrumbs.length > 1}\n {#each breadcrumbs.slice(0, -1) as breadcrumb}\n <Breadcrumb.Item>\n <Breadcrumb.Link href={breadcrumb.url}>{breadcrumb.title}</Breadcrumb.Link>\n </Breadcrumb.Item>\n <Breadcrumb.Separator />\n {/each}\n {/if}\n <Breadcrumb.Page>\n {breadcrumbs[breadcrumbs.length - 1].title}\n </Breadcrumb.Page>\n </Breadcrumb.List>\n </Breadcrumb.Root>\n {/if}\n </div>\n </header>\n <div class=\"flex flex-1 flex-col p-4 pt-0\">\n {@render children?.()}\n </div>\n </Sidebar.Inset>\n </Sidebar.Provider>\n</div>\n\n<style>\n :global(body:has(div.dashboard)) {\n background-color: var(--color-sidebar);\n }\n</style>\n", jo = "users", Q = "teams", Mo = "team_memberships";
|
|
4787
4792
|
function $(e) {
|
|
4788
|
-
let t =
|
|
4793
|
+
let t = l.find((t) => t.collectionName === e);
|
|
4789
4794
|
if (!t) throw Error(`teams: missing TEAM_RULE_PATCHES entry for "${e}"`);
|
|
4790
4795
|
return {
|
|
4791
4796
|
listRule: t.listRule,
|
|
@@ -4795,7 +4800,7 @@ function $(e) {
|
|
|
4795
4800
|
deleteRule: t.deleteRule
|
|
4796
4801
|
};
|
|
4797
4802
|
}
|
|
4798
|
-
var
|
|
4803
|
+
var No = [
|
|
4799
4804
|
{
|
|
4800
4805
|
name: "teams",
|
|
4801
4806
|
type: "base",
|
|
@@ -4820,7 +4825,7 @@ var Mo = [
|
|
|
4820
4825
|
name: "owner",
|
|
4821
4826
|
type: "relation",
|
|
4822
4827
|
cascadeDelete: !1,
|
|
4823
|
-
collectionId:
|
|
4828
|
+
collectionId: jo,
|
|
4824
4829
|
maxSelect: 1,
|
|
4825
4830
|
minSelect: 0,
|
|
4826
4831
|
required: !0
|
|
@@ -4866,7 +4871,7 @@ var Mo = [
|
|
|
4866
4871
|
{
|
|
4867
4872
|
name: "user",
|
|
4868
4873
|
cascadeDelete: !0,
|
|
4869
|
-
collectionId:
|
|
4874
|
+
collectionId: jo,
|
|
4870
4875
|
maxSelect: 1,
|
|
4871
4876
|
minSelect: 0,
|
|
4872
4877
|
required: !0,
|
|
@@ -4926,7 +4931,7 @@ var Mo = [
|
|
|
4926
4931
|
{
|
|
4927
4932
|
name: "membership_id",
|
|
4928
4933
|
cascadeDelete: !1,
|
|
4929
|
-
collectionId:
|
|
4934
|
+
collectionId: Mo,
|
|
4930
4935
|
maxSelect: 1,
|
|
4931
4936
|
minSelect: 0,
|
|
4932
4937
|
required: !1,
|
|
@@ -5036,17 +5041,17 @@ var Mo = [
|
|
|
5036
5041
|
}
|
|
5037
5042
|
]
|
|
5038
5043
|
}
|
|
5039
|
-
],
|
|
5040
|
-
"./preview-modifies/src/lib/components/app-sidebar.svelte":
|
|
5041
|
-
"./preview-modifies/src/lib/components/nav-user.svelte":
|
|
5042
|
-
"./preview-modifies/src/routes/(app)/+layout.server.ts":
|
|
5043
|
-
"./preview-modifies/src/routes/(app)/+layout.svelte":
|
|
5044
|
-
}),
|
|
5045
|
-
async function
|
|
5044
|
+
], Po = /* @__PURE__ */ Object.assign({
|
|
5045
|
+
"./preview-modifies/src/lib/components/app-sidebar.svelte": Do,
|
|
5046
|
+
"./preview-modifies/src/lib/components/nav-user.svelte": Oo,
|
|
5047
|
+
"./preview-modifies/src/routes/(app)/+layout.server.ts": ko,
|
|
5048
|
+
"./preview-modifies/src/routes/(app)/+layout.svelte": Ao
|
|
5049
|
+
}), Fo = "./preview-modifies/";
|
|
5050
|
+
async function Io(e) {
|
|
5046
5051
|
return {
|
|
5047
5052
|
creates: [],
|
|
5048
|
-
modifies: Object.entries(
|
|
5049
|
-
let r = i(e,
|
|
5053
|
+
modifies: Object.entries(Po).map(([e, t]) => {
|
|
5054
|
+
let r = i(e, Fo);
|
|
5050
5055
|
return {
|
|
5051
5056
|
path: r,
|
|
5052
5057
|
language: n(r),
|
|
@@ -5057,24 +5062,24 @@ async function Fo(e) {
|
|
|
5057
5062
|
deletes: [],
|
|
5058
5063
|
components: [],
|
|
5059
5064
|
packages: [],
|
|
5060
|
-
collections:
|
|
5065
|
+
collections: No,
|
|
5061
5066
|
collectionPatches: []
|
|
5062
5067
|
};
|
|
5063
5068
|
}
|
|
5064
5069
|
//#endregion
|
|
5065
5070
|
//#region src/patterns/enable/teams/index.ts
|
|
5066
|
-
var
|
|
5067
|
-
async function
|
|
5068
|
-
let t = await
|
|
5069
|
-
if (e.env === "preview") return _(r([t, await
|
|
5070
|
-
let { generate: n } = await import("./chunks/generate.runtime-
|
|
5071
|
+
var Lo = "enable-teams", Ro = "1.0.0", zo = "src/patterns/enable/teams", Bo = "/enable/teams";
|
|
5072
|
+
async function Vo(e) {
|
|
5073
|
+
let t = await Eo(e);
|
|
5074
|
+
if (e.env === "preview") return _(r([t, await Io(e)]));
|
|
5075
|
+
let { generate: n } = await import("./chunks/generate.runtime-BCz-NNqq.js"), i = await n(e), { writeResult: a } = await import("./chunks/write-result-B0-q-egx.js");
|
|
5071
5076
|
return a(await _(r([t, i])), e);
|
|
5072
5077
|
}
|
|
5073
|
-
var
|
|
5074
|
-
version:
|
|
5075
|
-
slug:
|
|
5076
|
-
source:
|
|
5077
|
-
docs:
|
|
5078
|
+
var Ho = {
|
|
5079
|
+
version: Ro,
|
|
5080
|
+
slug: Lo,
|
|
5081
|
+
source: zo,
|
|
5082
|
+
docs: Bo,
|
|
5078
5083
|
plan: "pro",
|
|
5079
5084
|
title: "Enable teams",
|
|
5080
5085
|
summary: "Adds multi-tenant teams with memberships, invites, and a sidebar team switcher.",
|
|
@@ -5103,27 +5108,27 @@ var Vo = {
|
|
|
5103
5108
|
examples: [],
|
|
5104
5109
|
tests: 36,
|
|
5105
5110
|
baseline: "velastack",
|
|
5106
|
-
generate:
|
|
5107
|
-
},
|
|
5108
|
-
|
|
5109
|
-
|
|
5110
|
-
|
|
5111
|
-
|
|
5112
|
-
|
|
5113
|
-
|
|
5114
|
-
|
|
5115
|
-
|
|
5116
|
-
|
|
5117
|
-
|
|
5118
|
-
|
|
5119
|
-
|
|
5120
|
-
|
|
5121
|
-
|
|
5122
|
-
],
|
|
5111
|
+
generate: Vo
|
|
5112
|
+
}, Uo = ae.version, Wo = [
|
|
5113
|
+
Yt,
|
|
5114
|
+
wn,
|
|
5115
|
+
Fn,
|
|
5116
|
+
ii,
|
|
5117
|
+
Wn,
|
|
5118
|
+
gr,
|
|
5119
|
+
Yr,
|
|
5120
|
+
gi,
|
|
5121
|
+
Oi,
|
|
5122
|
+
Bi,
|
|
5123
|
+
Qi,
|
|
5124
|
+
ua,
|
|
5125
|
+
Co,
|
|
5126
|
+
Ho
|
|
5127
|
+
], Go = Object.fromEntries(Wo.map((e) => [e.slug, e])), Ko = Wo.reduce((e, t) => {
|
|
5123
5128
|
let n = t.category;
|
|
5124
5129
|
return e[n] ??= [], e[n].push(t), e;
|
|
5125
5130
|
}, {});
|
|
5126
5131
|
//#endregion
|
|
5127
|
-
export { e as InvalidArgumentError,
|
|
5132
|
+
export { e as InvalidArgumentError, Ko as byCategory, Go as bySlug, Wo as patterns, Uo as version };
|
|
5128
5133
|
|
|
5129
5134
|
//# sourceMappingURL=index.js.map
|