@velastack/patterns 0.0.29 → 0.0.30
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-CwH8DO-2.js → collections-Bs9xy7nU.js} +1 -1
- package/dist/chunks/{collections-CwH8DO-2.js.map → collections-Bs9xy7nU.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B3WXGKZY.js → generate.runtime-6QnXtCSG.js} +2 -2
- package/dist/chunks/{generate.runtime-B3WXGKZY.js.map → generate.runtime-6QnXtCSG.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BS_l-k-A.js → generate.runtime-B8_5O6Qr.js} +3 -3
- package/dist/chunks/{generate.runtime-BS_l-k-A.js.map → generate.runtime-B8_5O6Qr.js.map} +1 -1
- package/dist/chunks/generate.runtime-BUbI1GmK.js +292 -0
- package/dist/chunks/generate.runtime-BUbI1GmK.js.map +1 -0
- package/dist/chunks/{generate.runtime-CzKWz6BN.js → generate.runtime-BayXS2PL.js} +2 -2
- package/dist/chunks/{generate.runtime-CzKWz6BN.js.map → generate.runtime-BayXS2PL.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DVRoiEhh.js → generate.runtime-BpZPXyba.js} +186 -130
- package/dist/chunks/{generate.runtime-DVRoiEhh.js.map → generate.runtime-BpZPXyba.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bhqdiykw.js → generate.runtime-DpT7Jzh4.js} +2 -2
- package/dist/chunks/{generate.runtime-Bhqdiykw.js.map → generate.runtime-DpT7Jzh4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-V7jzalbO.js → generate.runtime-InE8X2Ly.js} +2 -2
- package/dist/chunks/{generate.runtime-V7jzalbO.js.map → generate.runtime-InE8X2Ly.js.map} +1 -1
- package/dist/chunks/{modify-file-Drki52pc.js → modify-file-CpqC7kMR.js} +2 -2
- package/dist/chunks/{modify-file-Drki52pc.js.map → modify-file-CpqC7kMR.js.map} +1 -1
- package/dist/chunks/modify-svelte-config-remote-DWsScM6m.js +128 -0
- package/dist/chunks/modify-svelte-config-remote-DWsScM6m.js.map +1 -0
- package/dist/chunks/{write-result-C3SCX65t.js → write-result-ENWLDQtP.js} +1 -1
- package/dist/chunks/{write-result-C3SCX65t.js.map → write-result-ENWLDQtP.js.map} +1 -1
- package/dist/index.d.ts +66 -10
- package/dist/index.js +781 -520
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -20,7 +20,7 @@ var u = Object.create, d = Object.defineProperty, f = Object.getOwnPropertyDescr
|
|
|
20
20
|
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.");
|
|
21
21
|
}), re = {
|
|
22
22
|
name: "@velastack/patterns",
|
|
23
|
-
version: "0.0.
|
|
23
|
+
version: "0.0.30",
|
|
24
24
|
type: "module",
|
|
25
25
|
private: !1,
|
|
26
26
|
main: "./dist/index.js",
|
|
@@ -335,7 +335,7 @@ function he(t) {
|
|
|
335
335
|
</Form.Field>
|
|
336
336
|
`;
|
|
337
337
|
}
|
|
338
|
-
function
|
|
338
|
+
function ge(e) {
|
|
339
339
|
switch (e.type) {
|
|
340
340
|
case "text": return S(e, "text");
|
|
341
341
|
case "number": return S(e, "number");
|
|
@@ -354,7 +354,7 @@ function C(e) {
|
|
|
354
354
|
default: return e;
|
|
355
355
|
}
|
|
356
356
|
}
|
|
357
|
-
function
|
|
357
|
+
function _e(t) {
|
|
358
358
|
let n = t.options.map((t) => e`
|
|
359
359
|
${JSON.stringify(t.value)}: {
|
|
360
360
|
label: ${JSON.stringify(t.label)},
|
|
@@ -367,17 +367,17 @@ function w(t) {
|
|
|
367
367
|
} as const;
|
|
368
368
|
`;
|
|
369
369
|
}
|
|
370
|
-
function
|
|
370
|
+
function C(e) {
|
|
371
371
|
let t = e.flatMap((e) => se[e.type]);
|
|
372
372
|
return [...new Set(t)];
|
|
373
373
|
}
|
|
374
|
-
function
|
|
374
|
+
function ve(e) {
|
|
375
375
|
return [...new Set(e.flatMap((e) => ce[e]))];
|
|
376
376
|
}
|
|
377
|
-
function
|
|
377
|
+
function w(e, t) {
|
|
378
378
|
return `data.${e.name}.${t.name}`;
|
|
379
379
|
}
|
|
380
|
-
function
|
|
380
|
+
function T(t, n, r) {
|
|
381
381
|
return e`
|
|
382
382
|
<div class="space-y-2">
|
|
383
383
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -385,8 +385,8 @@ function _e(t, n, r) {
|
|
|
385
385
|
</div>
|
|
386
386
|
`;
|
|
387
387
|
}
|
|
388
|
-
function
|
|
389
|
-
let r =
|
|
388
|
+
function ye(t, n) {
|
|
389
|
+
let r = w(t, n), i = `<p class="text-muted-foreground">{new Date(${r}).toLocaleDateString()}</p>`, a = n.required ? i : e`
|
|
390
390
|
{#if ${r}}
|
|
391
391
|
${i}
|
|
392
392
|
{/if}
|
|
@@ -398,8 +398,8 @@ function ve(t, n) {
|
|
|
398
398
|
</div>
|
|
399
399
|
`;
|
|
400
400
|
}
|
|
401
|
-
function
|
|
402
|
-
let r =
|
|
401
|
+
function be(t, n) {
|
|
402
|
+
let r = w(t, n), i = e`
|
|
403
403
|
<a href={${r}} target="_blank" rel="noopener noreferrer">
|
|
404
404
|
{${r}}
|
|
405
405
|
</a>
|
|
@@ -417,8 +417,8 @@ function ye(t, n) {
|
|
|
417
417
|
</div>
|
|
418
418
|
`;
|
|
419
419
|
}
|
|
420
|
-
function
|
|
421
|
-
let r =
|
|
420
|
+
function xe(t, n) {
|
|
421
|
+
let r = w(t, n);
|
|
422
422
|
if (n.maxSelect > 1) return e`
|
|
423
423
|
<div class="space-y-2">
|
|
424
424
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -439,8 +439,8 @@ function be(t, n) {
|
|
|
439
439
|
</div>
|
|
440
440
|
`;
|
|
441
441
|
}
|
|
442
|
-
function
|
|
443
|
-
let r =
|
|
442
|
+
function Se(t, n) {
|
|
443
|
+
let r = w(t, n);
|
|
444
444
|
return n.maxSelect > 1 ? e`
|
|
445
445
|
<div class="space-y-2">
|
|
446
446
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -485,11 +485,11 @@ function xe(t, n) {
|
|
|
485
485
|
</div>
|
|
486
486
|
`;
|
|
487
487
|
}
|
|
488
|
-
function
|
|
488
|
+
function Ce(e) {
|
|
489
489
|
return `/${e.relatedModel.routeSegment}`;
|
|
490
490
|
}
|
|
491
|
-
function
|
|
492
|
-
let r = `data.${t.name}.expand?.${n.name}`, i =
|
|
491
|
+
function we(t, n) {
|
|
492
|
+
let r = `data.${t.name}.expand?.${n.name}`, i = Ce(n);
|
|
493
493
|
return n.maxSelect > 1 ? e`
|
|
494
494
|
<div class="space-y-2">
|
|
495
495
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -516,8 +516,8 @@ function Ce(t, n) {
|
|
|
516
516
|
</div>
|
|
517
517
|
`;
|
|
518
518
|
}
|
|
519
|
-
function
|
|
520
|
-
let r =
|
|
519
|
+
function Te(t, n) {
|
|
520
|
+
let r = w(t, n), i = e`
|
|
521
521
|
{#await import("$lib/components/ui/leaflet/leaflet.svelte")}
|
|
522
522
|
<div class="h-56.25 w-full bg-input rounded-md"></div>
|
|
523
523
|
{:then { default: Leaflet }}
|
|
@@ -538,12 +538,12 @@ function we(t, n) {
|
|
|
538
538
|
</div>
|
|
539
539
|
`;
|
|
540
540
|
}
|
|
541
|
-
function
|
|
541
|
+
function Ee(t, n) {
|
|
542
542
|
switch (n.type) {
|
|
543
543
|
case "text":
|
|
544
544
|
case "number":
|
|
545
545
|
case "email":
|
|
546
|
-
case "editor": return
|
|
546
|
+
case "editor": return T(t, n, `{${w(t, n)}}`);
|
|
547
547
|
case "password": return e`
|
|
548
548
|
<div class="space-y-2">
|
|
549
549
|
<h3 class="font-medium leading-none">${n.title}</h3>
|
|
@@ -552,34 +552,34 @@ function Te(t, n) {
|
|
|
552
552
|
</p>
|
|
553
553
|
</div>
|
|
554
554
|
`;
|
|
555
|
-
case "bool": return
|
|
555
|
+
case "bool": return T(t, n, `{${w(t, n)} ? "Yes" : "No"}`);
|
|
556
556
|
case "date":
|
|
557
|
-
case "autodate": return
|
|
558
|
-
case "url": return
|
|
559
|
-
case "select": return
|
|
560
|
-
case "file": return
|
|
561
|
-
case "json": return
|
|
562
|
-
case "geoPoint": return
|
|
563
|
-
case "relation": return
|
|
557
|
+
case "autodate": return ye(t, n);
|
|
558
|
+
case "url": return be(t, n);
|
|
559
|
+
case "select": return xe(t, n);
|
|
560
|
+
case "file": return Se(t, n);
|
|
561
|
+
case "json": return T(t, n, `{JSON.stringify(${w(t, n)})}`);
|
|
562
|
+
case "geoPoint": return Te(t, n);
|
|
563
|
+
case "relation": return we(t, n);
|
|
564
564
|
default: return n;
|
|
565
565
|
}
|
|
566
566
|
}
|
|
567
567
|
//#endregion
|
|
568
568
|
//#region node_modules/change-case/dist/index.js
|
|
569
|
-
var
|
|
570
|
-
function
|
|
569
|
+
var De = /([\p{Ll}\d])(\p{Lu})/gu, Oe = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu, ke = /(\d)\p{Ll}|(\p{L})\d/u, Ae = /[^\p{L}\d]+/giu, je = "$1\0$2", Me = "";
|
|
570
|
+
function Ne(e) {
|
|
571
571
|
let t = e.trim();
|
|
572
|
-
t = t.replace(
|
|
572
|
+
t = t.replace(De, je).replace(Oe, je), t = t.replace(Ae, "\0");
|
|
573
573
|
let n = 0, r = t.length;
|
|
574
574
|
for (; t.charAt(n) === "\0";) n++;
|
|
575
575
|
if (n === r) return [];
|
|
576
576
|
for (; t.charAt(r - 1) === "\0";) r--;
|
|
577
577
|
return t.slice(n, r).split(/\0/g);
|
|
578
578
|
}
|
|
579
|
-
function
|
|
580
|
-
let t =
|
|
579
|
+
function Pe(e) {
|
|
580
|
+
let t = Ne(e);
|
|
581
581
|
for (let e = 0; e < t.length; e++) {
|
|
582
|
-
let n = t[e], r =
|
|
582
|
+
let n = t[e], r = ke.exec(n);
|
|
583
583
|
if (r) {
|
|
584
584
|
let i = r.index + (r[1] ?? r[2]).length;
|
|
585
585
|
t.splice(e, 1, n.slice(0, i), n.slice(i));
|
|
@@ -587,51 +587,51 @@ function Ne(e) {
|
|
|
587
587
|
}
|
|
588
588
|
return t;
|
|
589
589
|
}
|
|
590
|
-
function
|
|
591
|
-
let [n, r, i] =
|
|
592
|
-
return n + r.map(
|
|
590
|
+
function Fe(e, t) {
|
|
591
|
+
let [n, r, i] = O(e, t);
|
|
592
|
+
return n + r.map(D(t?.locale)).join(t?.delimiter ?? " ") + i;
|
|
593
593
|
}
|
|
594
|
-
function
|
|
595
|
-
let [n, r, i] =
|
|
594
|
+
function E(e, t) {
|
|
595
|
+
let [n, r, i] = O(e, t), a = D(t?.locale), o = Be(t?.locale), s = t?.mergeAmbiguousCharacters ? Ve(a, o) : He(a, o);
|
|
596
596
|
return n + r.map((e, t) => t === 0 ? a(e) : s(e, t)).join(t?.delimiter ?? "") + i;
|
|
597
597
|
}
|
|
598
|
-
function Fe(e, t) {
|
|
599
|
-
let [n, r, i] = k(e, t), a = O(t?.locale), o = ze(t?.locale), s = t?.mergeAmbiguousCharacters ? Be(a, o) : Ve(a, o);
|
|
600
|
-
return n + r.map(s).join(t?.delimiter ?? "") + i;
|
|
601
|
-
}
|
|
602
598
|
function Ie(e, t) {
|
|
603
|
-
let [n, r, i] =
|
|
604
|
-
return n + r.map(
|
|
599
|
+
let [n, r, i] = O(e, t), a = D(t?.locale), o = Be(t?.locale), s = t?.mergeAmbiguousCharacters ? Ve(a, o) : He(a, o);
|
|
600
|
+
return n + r.map(s).join(t?.delimiter ?? "") + i;
|
|
605
601
|
}
|
|
606
602
|
function Le(e, t) {
|
|
607
|
-
|
|
603
|
+
let [n, r, i] = O(e, t), a = D(t?.locale), o = Be(t?.locale);
|
|
604
|
+
return n + r.map(Ve(a, o)).join(t?.delimiter ?? " ") + i;
|
|
605
|
+
}
|
|
606
|
+
function Re(e, t) {
|
|
607
|
+
return Fe(e, {
|
|
608
608
|
delimiter: "-",
|
|
609
609
|
...t
|
|
610
610
|
});
|
|
611
611
|
}
|
|
612
|
-
function
|
|
613
|
-
return
|
|
612
|
+
function ze(e, t) {
|
|
613
|
+
return Fe(e, {
|
|
614
614
|
delimiter: "_",
|
|
615
615
|
...t
|
|
616
616
|
});
|
|
617
617
|
}
|
|
618
|
-
function
|
|
618
|
+
function D(e) {
|
|
619
619
|
return e === !1 ? (e) => e.toLowerCase() : (t) => t.toLocaleLowerCase(e);
|
|
620
620
|
}
|
|
621
|
-
function
|
|
621
|
+
function Be(e) {
|
|
622
622
|
return e === !1 ? (e) => e.toUpperCase() : (t) => t.toLocaleUpperCase(e);
|
|
623
623
|
}
|
|
624
|
-
function
|
|
624
|
+
function Ve(e, t) {
|
|
625
625
|
return (n) => `${t(n[0])}${e(n.slice(1))}`;
|
|
626
626
|
}
|
|
627
|
-
function
|
|
627
|
+
function He(e, t) {
|
|
628
628
|
return (n, r) => {
|
|
629
629
|
let i = n[0];
|
|
630
630
|
return (r > 0 && i >= "0" && i <= "9" ? "_" + i : t(i)) + e(n.slice(1));
|
|
631
631
|
};
|
|
632
632
|
}
|
|
633
|
-
function
|
|
634
|
-
let n = t.split ?? (t.separateNumbers ?
|
|
633
|
+
function O(e, t = {}) {
|
|
634
|
+
let n = t.split ?? (t.separateNumbers ? Pe : Ne), r = t.prefixCharacters ?? Me, i = t.suffixCharacters ?? Me, a = 0, o = e.length;
|
|
635
635
|
for (; a < e.length;) {
|
|
636
636
|
let t = e.charAt(a);
|
|
637
637
|
if (!r.includes(t)) break;
|
|
@@ -650,7 +650,7 @@ function k(e, t = {}) {
|
|
|
650
650
|
}
|
|
651
651
|
//#endregion
|
|
652
652
|
//#region src/parse/model.ts
|
|
653
|
-
var
|
|
653
|
+
var k = /* @__PURE__ */ te((/* @__PURE__ */ ee(((e, t) => {
|
|
654
654
|
(function(n, r) {
|
|
655
655
|
/* istanbul ignore else */
|
|
656
656
|
typeof ne == "function" && typeof e == "object" && typeof t == "object" ? t.exports = r() : typeof define == "function" && define.amd ? define(function() {
|
|
@@ -920,7 +920,7 @@ var A = /* @__PURE__ */ te((/* @__PURE__ */ ee(((e, t) => {
|
|
|
920
920
|
/sheep$/i
|
|
921
921
|
].forEach(f.addUncountableRule), f;
|
|
922
922
|
});
|
|
923
|
-
})))(), 1),
|
|
923
|
+
})))(), 1), Ue = 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(".")), We = {
|
|
924
924
|
function: "fn",
|
|
925
925
|
interface: "iface",
|
|
926
926
|
type: "type_",
|
|
@@ -969,30 +969,30 @@ var A = /* @__PURE__ */ te((/* @__PURE__ */ ee(((e, t) => {
|
|
|
969
969
|
arguments: "args",
|
|
970
970
|
constructor: "ctor"
|
|
971
971
|
};
|
|
972
|
-
function We(e) {
|
|
973
|
-
return He.has(e) ? Ue[e] ?? `${e}_` : e;
|
|
974
|
-
}
|
|
975
972
|
function Ge(e) {
|
|
976
|
-
|
|
973
|
+
return Ue.has(e) ? We[e] ?? `${e}_` : e;
|
|
977
974
|
}
|
|
978
975
|
function Ke(e) {
|
|
976
|
+
if (!/^[a-zA-Z][a-zA-Z0-9-_/]*$/.test(e)) throw new _("Model path must start with a letter and contain only alphanumeric characters, dash, slash, or underscore");
|
|
977
|
+
}
|
|
978
|
+
function qe(e) {
|
|
979
979
|
return e.features.auth ? `src/routes/${a}` : `src/routes/${i}`;
|
|
980
980
|
}
|
|
981
|
-
function
|
|
982
|
-
let n = e.split("/"), r = n[n.length - 1], i = n.slice(0, -1), a =
|
|
981
|
+
function A(e, t) {
|
|
982
|
+
let n = e.split("/"), r = n[n.length - 1], i = n.slice(0, -1), a = k.default.singular(Le(r)), o = k.default.plural(a), s = E(a), c = Re(o), l = [...i, c].join("/");
|
|
983
983
|
return {
|
|
984
|
-
name:
|
|
985
|
-
pluralName:
|
|
986
|
-
typeName:
|
|
987
|
-
tableName:
|
|
984
|
+
name: Ge(s),
|
|
985
|
+
pluralName: Ge(E(o)),
|
|
986
|
+
typeName: Ie(a),
|
|
987
|
+
tableName: ze(o),
|
|
988
988
|
displayName: a,
|
|
989
989
|
pluralDisplayName: o,
|
|
990
|
-
schemaName: `${
|
|
990
|
+
schemaName: `${Ge(s)}Schema`,
|
|
991
991
|
routeSegment: l,
|
|
992
|
-
routesDir:
|
|
992
|
+
routesDir: qe(t)
|
|
993
993
|
};
|
|
994
994
|
}
|
|
995
|
-
function
|
|
995
|
+
function Je(e) {
|
|
996
996
|
let t = `${e.routesDir}/${e.routeSegment}`;
|
|
997
997
|
return {
|
|
998
998
|
list: t,
|
|
@@ -1001,7 +1001,7 @@ function qe(e) {
|
|
|
1001
1001
|
edit: `${t}/[id]/edit`
|
|
1002
1002
|
};
|
|
1003
1003
|
}
|
|
1004
|
-
function
|
|
1004
|
+
function Ye(e) {
|
|
1005
1005
|
let t = `/${e.routeSegment}`;
|
|
1006
1006
|
return {
|
|
1007
1007
|
list: t,
|
|
@@ -1012,23 +1012,23 @@ function Je(e) {
|
|
|
1012
1012
|
}
|
|
1013
1013
|
//#endregion
|
|
1014
1014
|
//#region src/parse/collections.ts
|
|
1015
|
-
var
|
|
1016
|
-
function
|
|
1017
|
-
for (let t of
|
|
1015
|
+
var Xe = /* @__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(".");
|
|
1016
|
+
function Ze(e) {
|
|
1017
|
+
for (let t of Xe) if (e.some((e) => e.name === t)) return t;
|
|
1018
1018
|
return "id";
|
|
1019
1019
|
}
|
|
1020
|
-
function
|
|
1020
|
+
function Qe(e) {
|
|
1021
1021
|
return e.map((e) => e.name).filter((e) => !e.startsWith("_"));
|
|
1022
1022
|
}
|
|
1023
|
-
function
|
|
1023
|
+
function $e(e) {
|
|
1024
1024
|
return Object.fromEntries(e.map((e) => [e.name, e.id]));
|
|
1025
1025
|
}
|
|
1026
|
-
function
|
|
1027
|
-
return Object.fromEntries(e.map((e) => [e.name,
|
|
1026
|
+
function et(e) {
|
|
1027
|
+
return Object.fromEntries(e.map((e) => [e.name, Ze(e.fields)]));
|
|
1028
1028
|
}
|
|
1029
1029
|
//#endregion
|
|
1030
1030
|
//#region src/parse/permissions.ts
|
|
1031
|
-
var
|
|
1031
|
+
var tt = [
|
|
1032
1032
|
"user",
|
|
1033
1033
|
"owner",
|
|
1034
1034
|
"created_by",
|
|
@@ -1037,10 +1037,10 @@ var et = [
|
|
|
1037
1037
|
"account",
|
|
1038
1038
|
"creator"
|
|
1039
1039
|
];
|
|
1040
|
-
function
|
|
1040
|
+
function j(e) {
|
|
1041
1041
|
return e.toLowerCase();
|
|
1042
1042
|
}
|
|
1043
|
-
function
|
|
1043
|
+
function nt(e) {
|
|
1044
1044
|
return {
|
|
1045
1045
|
rule: "@request.auth.id != \"\"",
|
|
1046
1046
|
ownershipChainCollections: [e],
|
|
@@ -1048,18 +1048,18 @@ function tt(e) {
|
|
|
1048
1048
|
operator: "="
|
|
1049
1049
|
};
|
|
1050
1050
|
}
|
|
1051
|
-
function
|
|
1052
|
-
let r = new Set((n.authCollections ?? ["users"]).map(
|
|
1051
|
+
function rt(e, t, n = {}) {
|
|
1052
|
+
let r = new Set((n.authCollections ?? ["users"]).map(j)), i = new Set((n.userFieldHints ?? tt).map(j)), a = n.maxDepth ?? 8, o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
|
|
1053
1053
|
for (let t of e) o.set(t.name, t), s.set(t.id, t);
|
|
1054
|
-
if (!o.has(t)) return
|
|
1055
|
-
if (r.has(
|
|
1054
|
+
if (!o.has(t)) return nt(t);
|
|
1055
|
+
if (r.has(j(t))) return {
|
|
1056
1056
|
rule: "@request.auth.id = id",
|
|
1057
1057
|
ownershipChainCollections: [t],
|
|
1058
1058
|
ownershipChainFields: [],
|
|
1059
1059
|
operator: "="
|
|
1060
1060
|
};
|
|
1061
1061
|
function c(e) {
|
|
1062
|
-
let t =
|
|
1062
|
+
let t = j(e);
|
|
1063
1063
|
return t === "user" ? 50 : i.has(t) ? 20 : 0;
|
|
1064
1064
|
}
|
|
1065
1065
|
function l(e) {
|
|
@@ -1080,7 +1080,7 @@ function nt(e, t, n = {}) {
|
|
|
1080
1080
|
return n.sort((e, t) => e.fieldName.localeCompare(t.fieldName)), n;
|
|
1081
1081
|
}
|
|
1082
1082
|
function u(e) {
|
|
1083
|
-
return r.has(
|
|
1083
|
+
return r.has(j(e));
|
|
1084
1084
|
}
|
|
1085
1085
|
function d(e) {
|
|
1086
1086
|
if (e.length === 0) return !1;
|
|
@@ -1088,7 +1088,7 @@ function nt(e, t, n = {}) {
|
|
|
1088
1088
|
return u(e[e.length - 1].to);
|
|
1089
1089
|
}
|
|
1090
1090
|
function f(e) {
|
|
1091
|
-
let t = e[e.length - 1], n = +!!t.isMulti, r = +!!e.every((e) => !e.isMulti), i = e.reduce((e, t) => e + t.hintScore, 0), a = +(
|
|
1091
|
+
let t = e[e.length - 1], n = +!!t.isMulti, r = +!!e.every((e) => !e.isMulti), i = e.reduce((e, t) => e + t.hintScore, 0), a = +(j(t.fieldName) === "user");
|
|
1092
1092
|
return 100 * e.length + 50 * n - 40 * a - 15 * r - i;
|
|
1093
1093
|
}
|
|
1094
1094
|
function p(e) {
|
|
@@ -1104,7 +1104,7 @@ function nt(e, t, n = {}) {
|
|
|
1104
1104
|
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));
|
|
1105
1105
|
}
|
|
1106
1106
|
}
|
|
1107
|
-
if (ee(t, [], 0), m.length === 0) return
|
|
1107
|
+
if (ee(t, [], 0), m.length === 0) return nt(t);
|
|
1108
1108
|
m.sort((e, t) => {
|
|
1109
1109
|
let n = f(e) - f(t);
|
|
1110
1110
|
return n === 0 ? p(e).localeCompare(p(t)) : n;
|
|
@@ -1119,7 +1119,7 @@ function nt(e, t, n = {}) {
|
|
|
1119
1119
|
}
|
|
1120
1120
|
//#endregion
|
|
1121
1121
|
//#region src/parse/fields.ts
|
|
1122
|
-
function
|
|
1122
|
+
function it(e) {
|
|
1123
1123
|
let t = null, n = !1, r = 0;
|
|
1124
1124
|
for (let i = 0; i < e.length; i++) {
|
|
1125
1125
|
let a = e[i];
|
|
@@ -1151,11 +1151,11 @@ function rt(e) {
|
|
|
1151
1151
|
}
|
|
1152
1152
|
return [e, ""];
|
|
1153
1153
|
}
|
|
1154
|
-
function
|
|
1154
|
+
function at(e) {
|
|
1155
1155
|
let t = e.trim();
|
|
1156
1156
|
return t.startsWith("\"") && t.endsWith("\"") || t.startsWith("'") && t.endsWith("'") ? t.slice(1, -1).replace(/\\(["'])/g, "$1") : t;
|
|
1157
1157
|
}
|
|
1158
|
-
function
|
|
1158
|
+
function ot(e) {
|
|
1159
1159
|
let t = -1, n = null, r = !1;
|
|
1160
1160
|
for (let i = 0; i < e.length; i++) {
|
|
1161
1161
|
let a = e[i];
|
|
@@ -1182,11 +1182,11 @@ function at(e) {
|
|
|
1182
1182
|
}
|
|
1183
1183
|
let i, a;
|
|
1184
1184
|
return t >= 0 ? (i = e.slice(0, t).trim(), a = e.slice(t + 1).trim()) : (i = e.trim(), a = i), {
|
|
1185
|
-
label:
|
|
1186
|
-
value:
|
|
1185
|
+
label: at(a),
|
|
1186
|
+
value: at(i)
|
|
1187
1187
|
};
|
|
1188
1188
|
}
|
|
1189
|
-
function
|
|
1189
|
+
function st(e) {
|
|
1190
1190
|
let t = [], n = "", r = null, i = !1;
|
|
1191
1191
|
for (let a = 0; a < e.length; a++) {
|
|
1192
1192
|
let o = e[a];
|
|
@@ -1212,15 +1212,15 @@ function ot(e) {
|
|
|
1212
1212
|
}
|
|
1213
1213
|
if (o === ",") {
|
|
1214
1214
|
let e = n.trim();
|
|
1215
|
-
e.length > 0 && t.push(
|
|
1215
|
+
e.length > 0 && t.push(ot(e)), n = "";
|
|
1216
1216
|
continue;
|
|
1217
1217
|
}
|
|
1218
1218
|
n += o;
|
|
1219
1219
|
}
|
|
1220
1220
|
let a = n.trim();
|
|
1221
|
-
return a.length > 0 && t.push(
|
|
1221
|
+
return a.length > 0 && t.push(ot(a)), t;
|
|
1222
1222
|
}
|
|
1223
|
-
var
|
|
1223
|
+
var ct = {
|
|
1224
1224
|
string: "text",
|
|
1225
1225
|
boolean: "bool",
|
|
1226
1226
|
geopoint: "geoPoint",
|
|
@@ -1233,37 +1233,37 @@ var st = {
|
|
|
1233
1233
|
datetime: "date",
|
|
1234
1234
|
timestamp: "date"
|
|
1235
1235
|
};
|
|
1236
|
-
function
|
|
1236
|
+
function lt(e) {
|
|
1237
1237
|
let t = e.endsWith("!"), n = t ? e.slice(0, -1) : e, r = [];
|
|
1238
|
-
return n.startsWith("select(") && n.endsWith(")") && (r =
|
|
1238
|
+
return n.startsWith("select(") && n.endsWith(")") && (r = st(n.slice(7, -1)), n = "select"), n === "files" ? {
|
|
1239
1239
|
type: "file",
|
|
1240
1240
|
required: t,
|
|
1241
1241
|
selectOptions: r
|
|
1242
|
-
} : (n in
|
|
1242
|
+
} : (n in ct && (n = ct[n]), {
|
|
1243
1243
|
type: n,
|
|
1244
1244
|
required: t,
|
|
1245
1245
|
selectOptions: r
|
|
1246
1246
|
});
|
|
1247
1247
|
}
|
|
1248
|
-
function
|
|
1249
|
-
let t =
|
|
1250
|
-
return e ===
|
|
1248
|
+
function ut(e) {
|
|
1249
|
+
let t = k.default.singular(e);
|
|
1250
|
+
return e === k.default.plural(t) ? 99 : 1;
|
|
1251
1251
|
}
|
|
1252
|
-
function
|
|
1253
|
-
let o =
|
|
1252
|
+
function M(e, t, n, r, i, a) {
|
|
1253
|
+
let o = A(t, a), s = k.default.singular(e), c = k.default.plural(s);
|
|
1254
1254
|
return {
|
|
1255
1255
|
collectionId: r[t],
|
|
1256
1256
|
displayField: i[t] ?? "id",
|
|
1257
1257
|
relatedModel: o,
|
|
1258
|
-
singularRelationName:
|
|
1259
|
-
pluralRelationName:
|
|
1258
|
+
singularRelationName: E(`${n.displayName} ${o.displayName}`),
|
|
1259
|
+
pluralRelationName: E(`${n.displayName} ${o.pluralDisplayName}`),
|
|
1260
1260
|
maxSelect: e === c ? 999 : 1
|
|
1261
1261
|
};
|
|
1262
1262
|
}
|
|
1263
|
-
function
|
|
1264
|
-
let a =
|
|
1263
|
+
function dt(e, t, n, r, i) {
|
|
1264
|
+
let a = Le(e), { type: o, required: s, selectOptions: c } = t, l = Qe(r), u = $e(r), d = et(r), f = l.map((e) => k.default.singular(e));
|
|
1265
1265
|
if (i.features.auth && o === "current_user" && u.users) {
|
|
1266
|
-
let t =
|
|
1266
|
+
let t = M(e, "users", n, u, d, i);
|
|
1267
1267
|
return {
|
|
1268
1268
|
type: "relation",
|
|
1269
1269
|
name: e,
|
|
@@ -1295,7 +1295,7 @@ function ut(e, t, n, r, i) {
|
|
|
1295
1295
|
name: e,
|
|
1296
1296
|
title: a,
|
|
1297
1297
|
required: s,
|
|
1298
|
-
maxSelect:
|
|
1298
|
+
maxSelect: ut(e),
|
|
1299
1299
|
options: c
|
|
1300
1300
|
};
|
|
1301
1301
|
if (o === "file") return {
|
|
@@ -1303,17 +1303,17 @@ function ut(e, t, n, r, i) {
|
|
|
1303
1303
|
name: e,
|
|
1304
1304
|
title: a,
|
|
1305
1305
|
required: s,
|
|
1306
|
-
maxSelect:
|
|
1306
|
+
maxSelect: ut(e)
|
|
1307
1307
|
};
|
|
1308
1308
|
if (o === "relation") {
|
|
1309
|
-
let t =
|
|
1309
|
+
let t = k.default.singular(e), r = k.default.plural(t);
|
|
1310
1310
|
if (!l.includes(r)) throw new _(`Invalid relation field: ${e}. Must be one of ${l.join(", ")} (singular or plural)`);
|
|
1311
1311
|
return {
|
|
1312
1312
|
type: "relation",
|
|
1313
1313
|
name: e,
|
|
1314
1314
|
title: a,
|
|
1315
1315
|
required: s,
|
|
1316
|
-
...
|
|
1316
|
+
...M(e, r, n, u, d, i),
|
|
1317
1317
|
isCurrentUser: !1
|
|
1318
1318
|
};
|
|
1319
1319
|
}
|
|
@@ -1322,13 +1322,13 @@ function ut(e, t, n, r, i) {
|
|
|
1322
1322
|
name: e,
|
|
1323
1323
|
title: a,
|
|
1324
1324
|
required: s,
|
|
1325
|
-
...
|
|
1325
|
+
...M(e, o, n, u, d, i),
|
|
1326
1326
|
isCurrentUser: !1
|
|
1327
1327
|
};
|
|
1328
1328
|
if (f.includes(o)) {
|
|
1329
|
-
let t =
|
|
1329
|
+
let t = k.default.plural(o);
|
|
1330
1330
|
if (l.includes(t)) {
|
|
1331
|
-
let r =
|
|
1331
|
+
let r = M(e, t, n, u, d, i);
|
|
1332
1332
|
return {
|
|
1333
1333
|
type: "relation",
|
|
1334
1334
|
name: e,
|
|
@@ -1381,18 +1381,18 @@ function ut(e, t, n, r, i) {
|
|
|
1381
1381
|
required: s
|
|
1382
1382
|
};
|
|
1383
1383
|
}
|
|
1384
|
-
function
|
|
1384
|
+
function ft(e, t, n, r) {
|
|
1385
1385
|
let i = [];
|
|
1386
1386
|
for (let a of e) {
|
|
1387
|
-
let [e, o] =
|
|
1387
|
+
let [e, o] = it(a);
|
|
1388
1388
|
if (!e || !o) throw new _(`Invalid field format: ${a}. Expected format: name:type or name:type!`);
|
|
1389
1389
|
if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(e)) throw new _(`Invalid field name: ${e}. Must start with a letter and contain only alphanumeric characters`);
|
|
1390
|
-
let s =
|
|
1391
|
-
i.push(
|
|
1390
|
+
let s = lt(o);
|
|
1391
|
+
i.push(dt(e, s, t, n, r));
|
|
1392
1392
|
}
|
|
1393
1393
|
return {
|
|
1394
1394
|
fields: i,
|
|
1395
|
-
auth: r.features.auth ?
|
|
1395
|
+
auth: r.features.auth ? rt([...n, {
|
|
1396
1396
|
id: "new",
|
|
1397
1397
|
name: t.tableName,
|
|
1398
1398
|
type: "base",
|
|
@@ -1407,16 +1407,16 @@ function dt(e, t, n, r) {
|
|
|
1407
1407
|
}
|
|
1408
1408
|
//#endregion
|
|
1409
1409
|
//#region src/core/tests.ts
|
|
1410
|
-
var
|
|
1410
|
+
var pt = "2024-01-01T00:00:00.000Z", N = class {
|
|
1411
1411
|
constructor(e) {
|
|
1412
1412
|
this.expression = e;
|
|
1413
1413
|
}
|
|
1414
1414
|
};
|
|
1415
|
-
function
|
|
1416
|
-
return e instanceof
|
|
1415
|
+
function P(e) {
|
|
1416
|
+
return e instanceof N ? e.expression : Array.isArray(e) ? `[${e.map((e) => P(e)).join(", ")}]` : e && typeof e == "object" ? `{ ${Object.entries(e).map(([e, t]) => `${JSON.stringify(e)}: ${P(t)}`).join(", ")} }` : JSON.stringify(e);
|
|
1417
1417
|
}
|
|
1418
|
-
function
|
|
1419
|
-
return `{ ${Object.entries(e).map(([e, t]) => `${JSON.stringify(e)}: ${
|
|
1418
|
+
function F(e) {
|
|
1419
|
+
return `{ ${Object.entries(e).map(([e, t]) => `${JSON.stringify(e)}: ${P(t)}`).join(", ")} }`;
|
|
1420
1420
|
}
|
|
1421
1421
|
function mt(e) {
|
|
1422
1422
|
switch (e) {
|
|
@@ -1456,7 +1456,7 @@ function ht(e, t, n) {
|
|
|
1456
1456
|
case "editor": return `${e.name} value`;
|
|
1457
1457
|
case "number": return 42;
|
|
1458
1458
|
case "bool": return !0;
|
|
1459
|
-
case "date": return
|
|
1459
|
+
case "date": return pt;
|
|
1460
1460
|
case "email": return `test-${e.name}@example.com`;
|
|
1461
1461
|
case "password": return "password";
|
|
1462
1462
|
case "url": return "https://example.com";
|
|
@@ -1473,9 +1473,9 @@ function ht(e, t, n) {
|
|
|
1473
1473
|
return e.maxSelect && e.maxSelect > 1 ? [t] : t;
|
|
1474
1474
|
}
|
|
1475
1475
|
case "relation": {
|
|
1476
|
-
if (n.authEnabled && (e.isCurrentUser || e.relatedModel?.tableName === "users")) return new
|
|
1476
|
+
if (n.authEnabled && (e.isCurrentUser || e.relatedModel?.tableName === "users")) return new N("context.user.id");
|
|
1477
1477
|
let r = e.collectionId ? t[e.collectionId] : void 0;
|
|
1478
|
-
return r ? new
|
|
1478
|
+
return r ? new N(r) : "missing-relation-id";
|
|
1479
1479
|
}
|
|
1480
1480
|
case "file":
|
|
1481
1481
|
case "autodate": return;
|
|
@@ -1487,7 +1487,7 @@ function gt(e, t, n) {
|
|
|
1487
1487
|
for (let i of e) {
|
|
1488
1488
|
if (i.type === "file" || i.type === "autodate") continue;
|
|
1489
1489
|
if (n.authEnabled && i.type === "relation" && i.isCurrentUser) {
|
|
1490
|
-
n.forForm || (r[i.name] = new
|
|
1490
|
+
n.forForm || (r[i.name] = new N("context.user.id"));
|
|
1491
1491
|
continue;
|
|
1492
1492
|
}
|
|
1493
1493
|
let e = ht(i, t, n);
|
|
@@ -1502,7 +1502,7 @@ function _t(e, t, n) {
|
|
|
1502
1502
|
let e = mt(i.type);
|
|
1503
1503
|
if (!e || e === "file" || e === "autodate" || e === "relation" && !i.collectionId) continue;
|
|
1504
1504
|
let a;
|
|
1505
|
-
if (e === "relation") a = i.collectionId ? new
|
|
1505
|
+
if (e === "relation") a = i.collectionId ? new N(t[i.collectionId] ?? "\"missing-relation-id\"") : void 0;
|
|
1506
1506
|
else if (e === "select") {
|
|
1507
1507
|
let e = i.values?.[0] ?? "default";
|
|
1508
1508
|
a = (i.maxSelect ?? 1) > 1 ? [e] : e;
|
|
@@ -1518,7 +1518,7 @@ function _t(e, t, n) {
|
|
|
1518
1518
|
return r;
|
|
1519
1519
|
}
|
|
1520
1520
|
function vt(e) {
|
|
1521
|
-
e.email = new
|
|
1521
|
+
e.email = new N("`test-${Math.random().toString(36).slice(2)}@example.com`"), e.password = "password", e.passwordConfirm = "password";
|
|
1522
1522
|
}
|
|
1523
1523
|
function yt(e, t) {
|
|
1524
1524
|
if (!e) return [];
|
|
@@ -1569,7 +1569,7 @@ function xt(e, t) {
|
|
|
1569
1569
|
function L(t, n, r, i) {
|
|
1570
1570
|
let a = yt(i.find((e) => e.name === t.tableName) ?? xt(t, n), i).filter((e) => !(r.features.auth && e.name === "users")), o = {}, s = [], c = /* @__PURE__ */ new Set();
|
|
1571
1571
|
for (let e of a) {
|
|
1572
|
-
let t = bt(
|
|
1572
|
+
let t = bt(A(e.name, r).name, c);
|
|
1573
1573
|
s.push({
|
|
1574
1574
|
varName: t,
|
|
1575
1575
|
collection: e
|
|
@@ -1577,7 +1577,7 @@ function L(t, n, r, i) {
|
|
|
1577
1577
|
}
|
|
1578
1578
|
let l = s.length ? `${s.map((e) => `let ${e.varName}: { id: string };`).join("\n")}\n\n` : "", u = s.map(({ varName: e, collection: t }) => {
|
|
1579
1579
|
let n = _t(t.fields, o, r);
|
|
1580
|
-
return t.type === "auth" && vt(n), `${e} = await context.admin.collection("${t.name}").create(${
|
|
1580
|
+
return t.type === "auth" && vt(n), `${e} = await context.admin.collection("${t.name}").create(${F(n)});`;
|
|
1581
1581
|
}), 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 = "";
|
|
1582
1582
|
return (u.length > 0 || r.features.auth) && (m += e`
|
|
1583
1583
|
beforeEach(async (context) => {
|
|
@@ -1591,11 +1591,11 @@ function L(t, n, r, i) {
|
|
|
1591
1591
|
declarations: l,
|
|
1592
1592
|
setupSection: m,
|
|
1593
1593
|
requestAgent: f,
|
|
1594
|
-
modelDbData:
|
|
1594
|
+
modelDbData: F(gt(n, o, {
|
|
1595
1595
|
forForm: !1,
|
|
1596
1596
|
authEnabled: r.features.auth
|
|
1597
1597
|
})),
|
|
1598
|
-
modelFormData:
|
|
1598
|
+
modelFormData: F(gt(n, o, {
|
|
1599
1599
|
forForm: !0,
|
|
1600
1600
|
authEnabled: r.features.auth
|
|
1601
1601
|
}))
|
|
@@ -1876,10 +1876,10 @@ async function kt(e) {
|
|
|
1876
1876
|
return t(e);
|
|
1877
1877
|
}
|
|
1878
1878
|
async function z(e, t, n) {
|
|
1879
|
-
|
|
1880
|
-
let r =
|
|
1879
|
+
Ke(t);
|
|
1880
|
+
let r = A(t, e), i = await kt(e);
|
|
1881
1881
|
if (n.length > 0) {
|
|
1882
|
-
let { fields: t, auth: a } =
|
|
1882
|
+
let { fields: t, auth: a } = ft(n, r, i, e);
|
|
1883
1883
|
return {
|
|
1884
1884
|
model: r,
|
|
1885
1885
|
fields: t,
|
|
@@ -1952,14 +1952,14 @@ function At(e) {
|
|
|
1952
1952
|
function jt(e, t, n) {
|
|
1953
1953
|
let r = t.find((t) => t.name === e.tableName);
|
|
1954
1954
|
if (!r) throw Error(`Collection "${e.tableName}" not found`);
|
|
1955
|
-
let i =
|
|
1955
|
+
let i = et(t), a = new Map(t.map((e) => [e.id, e])), o = [];
|
|
1956
1956
|
for (let t of r.fields) {
|
|
1957
1957
|
if (t.name === "id" || t.system) continue;
|
|
1958
|
-
let r = At(t.type), s = !!t.required, c =
|
|
1958
|
+
let r = At(t.type), s = !!t.required, c = Le(t.name);
|
|
1959
1959
|
if (r === "relation") {
|
|
1960
1960
|
let r = t.collectionId ? a.get(t.collectionId) : void 0;
|
|
1961
1961
|
if (!r) continue;
|
|
1962
|
-
let l =
|
|
1962
|
+
let l = A(r.name, n);
|
|
1963
1963
|
o.push({
|
|
1964
1964
|
name: t.name,
|
|
1965
1965
|
title: c,
|
|
@@ -1969,8 +1969,8 @@ function jt(e, t, n) {
|
|
|
1969
1969
|
maxSelect: t.maxSelect ?? 1,
|
|
1970
1970
|
displayField: i[r.name] ?? "id",
|
|
1971
1971
|
relatedModel: l,
|
|
1972
|
-
singularRelationName:
|
|
1973
|
-
pluralRelationName:
|
|
1972
|
+
singularRelationName: E(`${e.displayName} ${l.displayName}`),
|
|
1973
|
+
pluralRelationName: E(`${e.displayName} ${l.pluralDisplayName}`),
|
|
1974
1974
|
isCurrentUser: n.features.auth && r.name === "users" && /user|owner|author/i.test(t.name)
|
|
1975
1975
|
});
|
|
1976
1976
|
continue;
|
|
@@ -2089,18 +2089,18 @@ function Lt(e) {
|
|
|
2089
2089
|
return e.some((e) => e.type === "file");
|
|
2090
2090
|
}
|
|
2091
2091
|
function Rt(e, t) {
|
|
2092
|
-
let n =
|
|
2092
|
+
let n = C(t), r = [
|
|
2093
2093
|
"import { untrack } from \"svelte\";",
|
|
2094
2094
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
2095
2095
|
"import { zod4Client } from \"sveltekit-superforms/adapters\";",
|
|
2096
2096
|
`import { ${e.schemaName} } from "$lib/schemas/${e.name}";`,
|
|
2097
|
-
...
|
|
2097
|
+
...ve(n)
|
|
2098
2098
|
];
|
|
2099
2099
|
return [...new Set(r)];
|
|
2100
2100
|
}
|
|
2101
2101
|
function zt(t, n) {
|
|
2102
2102
|
return e`
|
|
2103
|
-
${n.filter((e) => e.type === "select").map((e) =>
|
|
2103
|
+
${n.filter((e) => e.type === "select").map((e) => _e(e)).join("\n\n")}
|
|
2104
2104
|
|
|
2105
2105
|
const form = superForm(untrack(() => data.form), {
|
|
2106
2106
|
validators: zod4Client(${t.schemaName}),
|
|
@@ -2110,7 +2110,7 @@ function zt(t, n) {
|
|
|
2110
2110
|
`;
|
|
2111
2111
|
}
|
|
2112
2112
|
function Bt(t, n) {
|
|
2113
|
-
let r = Rt(t, n).join("\n"), i = zt(t, n), a = n.map((e) =>
|
|
2113
|
+
let r = Rt(t, n).join("\n"), i = zt(t, n), a = n.map((e) => ge(e)).join("\n"), s = Lt(n) ? " enctype=\"multipart/form-data\"" : "";
|
|
2114
2114
|
return e(Pt ||= o([
|
|
2115
2115
|
"\n <script lang=\"ts\">\n ",
|
|
2116
2116
|
"\n\n let { data } = $props();\n ",
|
|
@@ -2172,7 +2172,7 @@ async function Ht(e) {
|
|
|
2172
2172
|
],
|
|
2173
2173
|
modifies: [],
|
|
2174
2174
|
deletes: [],
|
|
2175
|
-
components:
|
|
2175
|
+
components: C(i),
|
|
2176
2176
|
packages: [],
|
|
2177
2177
|
collections: []
|
|
2178
2178
|
};
|
|
@@ -2183,7 +2183,7 @@ var Ut = "generate-form", Wt = "1.0.7", Gt = "src/patterns/generate/form", Kt =
|
|
|
2183
2183
|
async function qt(e) {
|
|
2184
2184
|
let t = await Ht(e);
|
|
2185
2185
|
if (e.env !== "runtime") return v(t);
|
|
2186
|
-
let { writeResult: n } = await import("./chunks/write-result-
|
|
2186
|
+
let { writeResult: n } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
2187
2187
|
return n(await v(t), e);
|
|
2188
2188
|
}
|
|
2189
2189
|
var Jt = {
|
|
@@ -2441,19 +2441,44 @@ async function mn(e) {
|
|
|
2441
2441
|
};
|
|
2442
2442
|
}
|
|
2443
2443
|
//#endregion
|
|
2444
|
+
//#region src/patterns/generate/form-remote/generate.preview.ts
|
|
2445
|
+
var hn = /* @__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" }), gn = "./preview-modifies/";
|
|
2446
|
+
async function _n(e) {
|
|
2447
|
+
return {
|
|
2448
|
+
creates: [],
|
|
2449
|
+
modifies: Object.entries(hn).map(([e, n]) => {
|
|
2450
|
+
let i = r(e, gn);
|
|
2451
|
+
return {
|
|
2452
|
+
path: i,
|
|
2453
|
+
language: t(i),
|
|
2454
|
+
content: n,
|
|
2455
|
+
status: "success"
|
|
2456
|
+
};
|
|
2457
|
+
}).sort((e, t) => e.path.localeCompare(t.path)),
|
|
2458
|
+
deletes: [],
|
|
2459
|
+
components: [],
|
|
2460
|
+
packages: [],
|
|
2461
|
+
collections: []
|
|
2462
|
+
};
|
|
2463
|
+
}
|
|
2464
|
+
//#endregion
|
|
2444
2465
|
//#region src/patterns/generate/form-remote/index.ts
|
|
2445
|
-
var
|
|
2446
|
-
async function
|
|
2466
|
+
var vn = "generate-form-remote", yn = "1.0.0", bn = "src/patterns/generate/form-remote", xn = "/generate/form-remote";
|
|
2467
|
+
async function Sn(e) {
|
|
2447
2468
|
let t = await mn(e);
|
|
2469
|
+
if (e.env === "preview") return v(n([t, await _n(e)]));
|
|
2448
2470
|
if (e.env !== "runtime") return v(t);
|
|
2449
|
-
let {
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2471
|
+
let { modifyOutcomeToFile: r } = await import("./chunks/modify-file-CpqC7kMR.js"), { findSvelteConfigPath: i, modifySvelteConfigRemote: a } = await import("./chunks/modify-svelte-config-remote-DWsScM6m.js"), o = i(e.root), s = r(o, a(o)), c = {
|
|
2472
|
+
...t,
|
|
2473
|
+
modifies: [...t.modifies, ...s ? [s] : []]
|
|
2474
|
+
}, { writeResult: l } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
2475
|
+
return l(await v(c), e);
|
|
2476
|
+
}
|
|
2477
|
+
var Cn = {
|
|
2478
|
+
version: yn,
|
|
2479
|
+
slug: vn,
|
|
2480
|
+
source: bn,
|
|
2481
|
+
docs: xn,
|
|
2457
2482
|
plan: "open",
|
|
2458
2483
|
title: "Generate a form (remote functions)",
|
|
2459
2484
|
summary: "Generates a form using SvelteKit remote functions instead of sveltekit-superforms.",
|
|
@@ -2498,11 +2523,11 @@ var bn = {
|
|
|
2498
2523
|
],
|
|
2499
2524
|
tests: 1,
|
|
2500
2525
|
baseline: "velastack",
|
|
2501
|
-
generate:
|
|
2526
|
+
generate: Sn
|
|
2502
2527
|
};
|
|
2503
2528
|
//#endregion
|
|
2504
2529
|
//#region src/patterns/generate/resource/generate.ts
|
|
2505
|
-
function
|
|
2530
|
+
function wn(e) {
|
|
2506
2531
|
let [t, ...n] = e;
|
|
2507
2532
|
if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
|
|
2508
2533
|
return {
|
|
@@ -2510,7 +2535,7 @@ function xn(e) {
|
|
|
2510
2535
|
fields: n
|
|
2511
2536
|
};
|
|
2512
2537
|
}
|
|
2513
|
-
function
|
|
2538
|
+
function Tn(e, n) {
|
|
2514
2539
|
return {
|
|
2515
2540
|
path: e,
|
|
2516
2541
|
language: t(e),
|
|
@@ -2518,10 +2543,10 @@ function Sn(e, n) {
|
|
|
2518
2543
|
status: "success"
|
|
2519
2544
|
};
|
|
2520
2545
|
}
|
|
2521
|
-
async function
|
|
2522
|
-
let { modelPath: t, fields: n } =
|
|
2546
|
+
async function En(e) {
|
|
2547
|
+
let { modelPath: t, fields: n } = wn(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o } = await z(e, t, n);
|
|
2523
2548
|
return {
|
|
2524
|
-
creates: [
|
|
2549
|
+
creates: [Tn(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2525
2550
|
includeModelFields: !0,
|
|
2526
2551
|
forForm: !0
|
|
2527
2552
|
}))],
|
|
@@ -2534,21 +2559,21 @@ async function Cn(e) {
|
|
|
2534
2559
|
}
|
|
2535
2560
|
//#endregion
|
|
2536
2561
|
//#region src/patterns/generate/resource/index.ts
|
|
2537
|
-
var
|
|
2538
|
-
async function
|
|
2539
|
-
let t = await
|
|
2562
|
+
var Dn = "generate-resource", On = "1.0.7", kn = "src/patterns/generate/resource", An = "/generate/resource";
|
|
2563
|
+
async function jn(e) {
|
|
2564
|
+
let t = await En(e);
|
|
2540
2565
|
if (e.env !== "runtime") return v(t);
|
|
2541
|
-
let { createCollections: n } = await import("./chunks/collections-
|
|
2566
|
+
let { createCollections: n } = await import("./chunks/collections-Bs9xy7nU.js"), r = await n(t.collections, e), i = {
|
|
2542
2567
|
...t,
|
|
2543
2568
|
creates: [...t.creates, ...r]
|
|
2544
|
-
}, { writeResult: a } = await import("./chunks/write-result-
|
|
2569
|
+
}, { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
2545
2570
|
return a(await v(i), e);
|
|
2546
2571
|
}
|
|
2547
|
-
var
|
|
2548
|
-
version:
|
|
2549
|
-
slug:
|
|
2550
|
-
source:
|
|
2551
|
-
docs:
|
|
2572
|
+
var Mn = {
|
|
2573
|
+
version: On,
|
|
2574
|
+
slug: Dn,
|
|
2575
|
+
source: kn,
|
|
2576
|
+
docs: An,
|
|
2552
2577
|
plan: "open",
|
|
2553
2578
|
title: "Generate a resource",
|
|
2554
2579
|
summary: "Generates model schema resources.",
|
|
@@ -2591,9 +2616,9 @@ var kn = {
|
|
|
2591
2616
|
],
|
|
2592
2617
|
tests: 0,
|
|
2593
2618
|
baseline: "velastack",
|
|
2594
|
-
generate:
|
|
2595
|
-
},
|
|
2596
|
-
function
|
|
2619
|
+
generate: jn
|
|
2620
|
+
}, Nn, Pn, Fn, In;
|
|
2621
|
+
function Ln(e) {
|
|
2597
2622
|
let [t, ...n] = e;
|
|
2598
2623
|
if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
|
|
2599
2624
|
return {
|
|
@@ -2612,24 +2637,24 @@ function Y(e, n) {
|
|
|
2612
2637
|
function X(e) {
|
|
2613
2638
|
return e.some((e) => e.type === "file");
|
|
2614
2639
|
}
|
|
2615
|
-
function
|
|
2640
|
+
function Rn(e) {
|
|
2616
2641
|
return [...new Set(e.filter(Boolean))];
|
|
2617
2642
|
}
|
|
2618
|
-
function
|
|
2619
|
-
return e.filter((e) => e.type === "select").map((e) =>
|
|
2643
|
+
function zn(e) {
|
|
2644
|
+
return e.filter((e) => e.type === "select").map((e) => _e(e)).join("\n\n");
|
|
2620
2645
|
}
|
|
2621
|
-
function
|
|
2646
|
+
function Bn(e, t) {
|
|
2622
2647
|
return H(e).map((e) => `const ${e.pluralName} = await ${t}.collection("${e.tableName}").getFullList();`).join("\n ");
|
|
2623
2648
|
}
|
|
2624
|
-
function
|
|
2649
|
+
function Vn(e) {
|
|
2625
2650
|
return H(e).map((e) => e.pluralName).join(", ");
|
|
2626
2651
|
}
|
|
2627
|
-
function
|
|
2652
|
+
function Hn(e) {
|
|
2628
2653
|
return e.features.auth ? "locals.pb" : "locals.admin";
|
|
2629
2654
|
}
|
|
2630
|
-
function
|
|
2655
|
+
function Un(t, n, r = !1) {
|
|
2631
2656
|
return e`
|
|
2632
|
-
${
|
|
2657
|
+
${zn(n)}
|
|
2633
2658
|
${r ? "let { data, params } = $props();" : "let { data } = $props();"}
|
|
2634
2659
|
|
|
2635
2660
|
const form = superForm(untrack(() => data.form), {
|
|
@@ -2639,19 +2664,19 @@ function Bn(t, n, r = !1) {
|
|
|
2639
2664
|
const { form: formData } = form;
|
|
2640
2665
|
`;
|
|
2641
2666
|
}
|
|
2642
|
-
function
|
|
2643
|
-
let i = r.some((e) => e.type === "select"), a =
|
|
2667
|
+
function Wn(t, n, r) {
|
|
2668
|
+
let i = r.some((e) => e.type === "select"), a = Rn([
|
|
2644
2669
|
"import { untrack } from \"svelte\";",
|
|
2645
2670
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
2646
2671
|
"import { zod4Client } from \"sveltekit-superforms/adapters\";",
|
|
2647
2672
|
`import { ${t.schemaName} } from "$lib/schemas/${t.name}";`,
|
|
2648
|
-
...
|
|
2673
|
+
...ve(C(r)),
|
|
2649
2674
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
2650
2675
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2651
2676
|
"import * as Form from \"$lib/components/ui/form\";",
|
|
2652
2677
|
i ? "import type { Models } from \"@velastack/pocketbase\";" : ""
|
|
2653
|
-
]).join("\n"), s = r.map((e) =>
|
|
2654
|
-
return e(
|
|
2678
|
+
]).join("\n"), s = r.map((e) => ge(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
2679
|
+
return e(Nn ||= o([
|
|
2655
2680
|
"\n <script lang=\"ts\">\n ",
|
|
2656
2681
|
"\n ",
|
|
2657
2682
|
"\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 ",
|
|
@@ -2660,21 +2685,21 @@ function Vn(t, n, r) {
|
|
|
2660
2685
|
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
2661
2686
|
"\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=\"",
|
|
2662
2687
|
"\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
2663
|
-
]), a,
|
|
2688
|
+
]), a, Un(t, r), t.displayName.toLowerCase(), n.list, c, s, n.list);
|
|
2664
2689
|
}
|
|
2665
|
-
function
|
|
2666
|
-
let i = r.some((e) => e.type === "select"), a =
|
|
2690
|
+
function Gn(t, n, r) {
|
|
2691
|
+
let i = r.some((e) => e.type === "select"), a = Rn([
|
|
2667
2692
|
"import { untrack } from \"svelte\";",
|
|
2668
2693
|
"import { superForm } from \"sveltekit-superforms\";",
|
|
2669
2694
|
"import { zod4Client } from \"sveltekit-superforms/adapters\";",
|
|
2670
2695
|
`import { ${t.schemaName} } from "$lib/schemas/${t.name}";`,
|
|
2671
|
-
...
|
|
2696
|
+
...ve(C(r)),
|
|
2672
2697
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
2673
2698
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2674
2699
|
"import * as Form from \"$lib/components/ui/form\";",
|
|
2675
2700
|
i ? "import type { Models } from \"@velastack/pocketbase\";" : ""
|
|
2676
|
-
]).join("\n"), s = r.map((e) =>
|
|
2677
|
-
return e(
|
|
2701
|
+
]).join("\n"), s = r.map((e) => ge(e)).join("\n"), c = X(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
2702
|
+
return e(Pn ||= o([
|
|
2678
2703
|
"\n <script lang=\"ts\">\n ",
|
|
2679
2704
|
"\n ",
|
|
2680
2705
|
"\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 ",
|
|
@@ -2692,10 +2717,10 @@ function Hn(t, n, r) {
|
|
|
2692
2717
|
">\n <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n ",
|
|
2693
2718
|
"\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=\"",
|
|
2694
2719
|
"/\\${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
2695
|
-
]), a,
|
|
2720
|
+
]), a, Un(t, r, !0), t.displayName.toLowerCase(), n.list, c, s, n.list);
|
|
2696
2721
|
}
|
|
2697
|
-
function
|
|
2698
|
-
let i = r.some((e) => e.type === "select"), a = i ? `${
|
|
2722
|
+
function Kn(t, n, r) {
|
|
2723
|
+
let i = r.some((e) => e.type === "select"), a = i ? `${zn(r)}` : "", s = r.map((t) => {
|
|
2699
2724
|
let n = "{ getValue }", r = "{ value: getValue() }";
|
|
2700
2725
|
return t.type === "relation" && (n = "{ getValue, row }", r = `{ value: getValue(), expanded: row.original.expand?.${t.name}, displayField: "${t.displayField}" }`), t.type === "select" && (r = `{ value: getValue(), options: ${t.name}Labels }`), t.type === "file" && (n = "{ getValue, row }", r = "{ value: getValue(), collectionId: row.original.collectionId, id: row.original.id }"), e`
|
|
2701
2726
|
columnHelper.accessor("${t.name}", {
|
|
@@ -2704,7 +2729,7 @@ function Un(t, n, r) {
|
|
|
2704
2729
|
})
|
|
2705
2730
|
`;
|
|
2706
2731
|
}).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");
|
|
2707
|
-
return e(
|
|
2732
|
+
return e(Fn ||= o([
|
|
2708
2733
|
"\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 ",
|
|
2709
2734
|
"\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 ",
|
|
2710
2735
|
"\n\n const columnHelper = createColumnHelper<Models[\"",
|
|
@@ -2719,7 +2744,7 @@ function Un(t, n, r) {
|
|
|
2719
2744
|
"...\"\n value={(table.getColumn(\"name\")?.getFilterValue() as string) ?? \"\"}\n oninput={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n onchange={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n class=\"h-8 w-[150px] lg:w-[250px]\"\n />\n ",
|
|
2720
2745
|
"\n {#if table.getState().columnFilters.length > 0}\n <Button variant=\"ghost\" onclick={() => table.resetColumnFilters()} class=\"h-8 px-2 lg:px-3\">\n Reset\n <XIcon />\n </Button>\n {/if}\n </div>\n\n <Button href=\"",
|
|
2721
2746
|
"\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
|
|
2722
|
-
"\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}>\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>\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 "
|
|
2747
|
+
"\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 "
|
|
2723
2748
|
], [
|
|
2724
2749
|
"\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 ",
|
|
2725
2750
|
"\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 ",
|
|
@@ -2735,10 +2760,10 @@ function Un(t, n, r) {
|
|
|
2735
2760
|
"...\"\n value={(table.getColumn(\"name\")?.getFilterValue() as string) ?? \"\"}\n oninput={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n onchange={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n class=\"h-8 w-[150px] lg:w-[250px]\"\n />\n ",
|
|
2736
2761
|
"\n {#if table.getState().columnFilters.length > 0}\n <Button variant=\"ghost\" onclick={() => table.resetColumnFilters()} class=\"h-8 px-2 lg:px-3\">\n Reset\n <XIcon />\n </Button>\n {/if}\n </div>\n\n <Button href=\"",
|
|
2737
2762
|
"\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
|
|
2738
|
-
"\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}>\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>\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 "
|
|
2763
|
+
"\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 "
|
|
2739
2764
|
]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, t.tableName, s, r.length > 0 ? "," : "", n.list, n.list, n.list, t.pluralName, t.pluralDisplayName, t.pluralDisplayName.toLowerCase(), c, n.new, t.displayName.toLowerCase());
|
|
2740
2765
|
}
|
|
2741
|
-
function
|
|
2766
|
+
function qn(t, n, r) {
|
|
2742
2767
|
let i = V(n), a = i ? `{ expand: "${i}" }` : "";
|
|
2743
2768
|
return e`
|
|
2744
2769
|
export const load = async ({ locals }) => {
|
|
@@ -2747,8 +2772,8 @@ function Wn(t, n, r) {
|
|
|
2747
2772
|
};
|
|
2748
2773
|
`;
|
|
2749
2774
|
}
|
|
2750
|
-
function
|
|
2751
|
-
let o = X(r), s =
|
|
2775
|
+
function Jn(t, n, r, i, a) {
|
|
2776
|
+
let o = X(r), s = Bn(r, i), c = Vn(r), l = c ? `, ${c}` : "", u = r.find((e) => e.type === "relation" && e.isCurrentUser), d = a && u ? e`
|
|
2752
2777
|
{
|
|
2753
2778
|
...form.data,
|
|
2754
2779
|
${u.name}: locals.pb.authStore.record?.id
|
|
@@ -2790,7 +2815,7 @@ function Gn(t, n, r, i, a) {
|
|
|
2790
2815
|
};
|
|
2791
2816
|
`;
|
|
2792
2817
|
}
|
|
2793
|
-
function
|
|
2818
|
+
function Yn(t, n, r, i) {
|
|
2794
2819
|
let a = V(r), o = a ? `, { expand: "${a}" }` : "";
|
|
2795
2820
|
return e`
|
|
2796
2821
|
import { error, redirect } from "@sveltejs/kit";
|
|
@@ -2812,15 +2837,15 @@ function Kn(t, n, r, i) {
|
|
|
2812
2837
|
};
|
|
2813
2838
|
`;
|
|
2814
2839
|
}
|
|
2815
|
-
function
|
|
2840
|
+
function Xn(t, n, r) {
|
|
2816
2841
|
let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), s = r.some((e) => e.type === "file"), c = [
|
|
2817
2842
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
2818
2843
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
2819
2844
|
i || a ? "import { Badge } from \"$lib/components/ui/badge\";" : "",
|
|
2820
2845
|
a ? "import CircleArrowRightIcon from \"@lucide/svelte/icons/circle-arrow-right\";" : "",
|
|
2821
2846
|
s ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
|
|
2822
|
-
].filter(Boolean).join("\n"), l =
|
|
2823
|
-
return e(
|
|
2847
|
+
].filter(Boolean).join("\n"), l = zn(r), u = r.map((e) => Ee(t, e)).join("\n");
|
|
2848
|
+
return e(In ||= o([
|
|
2824
2849
|
"\n <script lang=\"ts\">\n ",
|
|
2825
2850
|
"\n ",
|
|
2826
2851
|
"\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\">",
|
|
@@ -2831,8 +2856,8 @@ function qn(t, n, r) {
|
|
|
2831
2856
|
".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 "
|
|
2832
2857
|
]), c, l, t.displayName, n.list, u, n.list, t.name);
|
|
2833
2858
|
}
|
|
2834
|
-
function
|
|
2835
|
-
let a = X(r), o =
|
|
2859
|
+
function Zn(t, n, r, i) {
|
|
2860
|
+
let a = X(r), o = Bn(r, i), s = Vn(r), c = s ? `, ${s}` : "";
|
|
2836
2861
|
return e`
|
|
2837
2862
|
import { error, fail, redirect } from "@sveltejs/kit";
|
|
2838
2863
|
import { setPocketbaseErrors, setDefaultData } from "@velastack/pocketbase";
|
|
@@ -2873,23 +2898,23 @@ function Jn(t, n, r, i) {
|
|
|
2873
2898
|
};
|
|
2874
2899
|
`;
|
|
2875
2900
|
}
|
|
2876
|
-
async function
|
|
2877
|
-
let { modelPath: t, fields: n } =
|
|
2901
|
+
async function Qn(e) {
|
|
2902
|
+
let { modelPath: t, fields: n } = Ln(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = Je(r), l = Ye(r), u = Hn(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
|
|
2878
2903
|
Y(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
2879
2904
|
includeModelFields: !0,
|
|
2880
2905
|
forForm: !0
|
|
2881
2906
|
})),
|
|
2882
|
-
Y(`${c.list}/+page.server.ts`,
|
|
2883
|
-
Y(`${c.list}/+page.svelte`,
|
|
2884
|
-
Y(`${c.new}/+page.server.ts`,
|
|
2885
|
-
Y(`${c.new}/+page.svelte`,
|
|
2886
|
-
Y(`${c.show}/+page.server.ts`,
|
|
2887
|
-
Y(`${c.show}/+page.svelte`,
|
|
2888
|
-
Y(`${c.edit}/+page.server.ts`,
|
|
2889
|
-
Y(`${c.edit}/+page.svelte`,
|
|
2907
|
+
Y(`${c.list}/+page.server.ts`, qn(r, d, u)),
|
|
2908
|
+
Y(`${c.list}/+page.svelte`, Kn(r, l, d)),
|
|
2909
|
+
Y(`${c.new}/+page.server.ts`, Jn(r, l, d, u, e.features.auth)),
|
|
2910
|
+
Y(`${c.new}/+page.svelte`, Wn(r, l, d)),
|
|
2911
|
+
Y(`${c.show}/+page.server.ts`, Yn(r, l, d, u)),
|
|
2912
|
+
Y(`${c.show}/+page.svelte`, Xn(r, l, d)),
|
|
2913
|
+
Y(`${c.edit}/+page.server.ts`, Zn(r, l, d, u)),
|
|
2914
|
+
Y(`${c.edit}/+page.svelte`, Gn(r, l, d)),
|
|
2890
2915
|
Y(`${c.list}/server.test.ts`, St(r, l, i, e, s))
|
|
2891
2916
|
], p = [
|
|
2892
|
-
...
|
|
2917
|
+
...C(d),
|
|
2893
2918
|
"button",
|
|
2894
2919
|
"table",
|
|
2895
2920
|
"data-table",
|
|
@@ -2917,21 +2942,21 @@ async function Yn(e) {
|
|
|
2917
2942
|
}
|
|
2918
2943
|
//#endregion
|
|
2919
2944
|
//#region src/patterns/generate/scaffold/index.ts
|
|
2920
|
-
var
|
|
2921
|
-
async function
|
|
2922
|
-
let t = await
|
|
2945
|
+
var $n = "generate-scaffold", er = "1.0.7", tr = "src/patterns/generate/scaffold", nr = "/generate/scaffold";
|
|
2946
|
+
async function rr(e) {
|
|
2947
|
+
let t = await Qn(e);
|
|
2923
2948
|
if (e.env !== "runtime") return v(t);
|
|
2924
|
-
let { createCollections: n } = await import("./chunks/collections-
|
|
2949
|
+
let { createCollections: n } = await import("./chunks/collections-Bs9xy7nU.js"), r = await n(t.collections, e), i = {
|
|
2925
2950
|
...t,
|
|
2926
2951
|
creates: [...t.creates, ...r]
|
|
2927
|
-
}, { writeResult: a } = await import("./chunks/write-result-
|
|
2952
|
+
}, { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
2928
2953
|
return a(await v(i), e);
|
|
2929
2954
|
}
|
|
2930
|
-
var
|
|
2931
|
-
version:
|
|
2932
|
-
slug:
|
|
2933
|
-
source:
|
|
2934
|
-
docs:
|
|
2955
|
+
var ir = {
|
|
2956
|
+
version: er,
|
|
2957
|
+
slug: $n,
|
|
2958
|
+
source: tr,
|
|
2959
|
+
docs: nr,
|
|
2935
2960
|
plan: "open",
|
|
2936
2961
|
title: "Generate a scaffold",
|
|
2937
2962
|
summary: "Generates CRUD routes and schema.",
|
|
@@ -2975,9 +3000,9 @@ var tr = {
|
|
|
2975
3000
|
],
|
|
2976
3001
|
tests: 8,
|
|
2977
3002
|
baseline: "velastack",
|
|
2978
|
-
generate:
|
|
2979
|
-
},
|
|
2980
|
-
function
|
|
3003
|
+
generate: rr
|
|
3004
|
+
}, ar, or, sr, cr;
|
|
3005
|
+
function lr(e) {
|
|
2981
3006
|
let [t, ...n] = e;
|
|
2982
3007
|
if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
|
|
2983
3008
|
return {
|
|
@@ -2993,38 +3018,38 @@ function Z(e, n) {
|
|
|
2993
3018
|
status: "success"
|
|
2994
3019
|
};
|
|
2995
3020
|
}
|
|
2996
|
-
function
|
|
3021
|
+
function ur(e) {
|
|
2997
3022
|
return e.some((e) => e.type === "file");
|
|
2998
3023
|
}
|
|
2999
|
-
function
|
|
3000
|
-
return e.filter((e) => e.type === "select").map((e) =>
|
|
3024
|
+
function dr(e) {
|
|
3025
|
+
return e.filter((e) => e.type === "select").map((e) => _e(e)).join("\n\n");
|
|
3001
3026
|
}
|
|
3002
|
-
function
|
|
3027
|
+
function fr(e, t) {
|
|
3003
3028
|
return H(e).map((e) => `const ${e.pluralName} = await ${t}.collection("${e.tableName}").getFullList();`).join("\n ");
|
|
3004
3029
|
}
|
|
3005
|
-
function
|
|
3030
|
+
function pr(e) {
|
|
3006
3031
|
return H(e).map((e) => e.pluralName).join(", ");
|
|
3007
3032
|
}
|
|
3008
|
-
function
|
|
3033
|
+
function mr(e) {
|
|
3009
3034
|
return e.features.auth ? "locals.pb" : "locals.admin";
|
|
3010
3035
|
}
|
|
3011
|
-
function
|
|
3036
|
+
function hr(e) {
|
|
3012
3037
|
return `create${e.typeName}Form`;
|
|
3013
3038
|
}
|
|
3014
|
-
function
|
|
3039
|
+
function gr(e) {
|
|
3015
3040
|
return `update${e.typeName}Form`;
|
|
3016
3041
|
}
|
|
3017
|
-
function
|
|
3042
|
+
function _r(e) {
|
|
3018
3043
|
return H(e).length > 0;
|
|
3019
3044
|
}
|
|
3020
|
-
function
|
|
3021
|
-
let i =
|
|
3045
|
+
function vr(t, n, r) {
|
|
3046
|
+
let i = hr(t), a = W(r), s = [
|
|
3022
3047
|
`import { ${i} } from "./form.remote";`,
|
|
3023
3048
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
3024
3049
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3025
3050
|
...Zt(a)
|
|
3026
|
-
].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l =
|
|
3027
|
-
return e(
|
|
3051
|
+
].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l = ur(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
3052
|
+
return e(ar ||= o([
|
|
3028
3053
|
"\n <script lang=\"ts\">\n ",
|
|
3029
3054
|
"\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 ",
|
|
3030
3055
|
"</h1>\n <Button href=\"",
|
|
@@ -3035,14 +3060,14 @@ function hr(t, n, r) {
|
|
|
3035
3060
|
"\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
3036
3061
|
]), s, t.displayName.toLowerCase(), n.list, i, l, c, n.list);
|
|
3037
3062
|
}
|
|
3038
|
-
function
|
|
3039
|
-
let i =
|
|
3063
|
+
function yr(t, n, r) {
|
|
3064
|
+
let i = gr(t), a = W(r), s = [
|
|
3040
3065
|
`import { ${i} } from "./form.remote";`,
|
|
3041
3066
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
3042
3067
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3043
3068
|
...Zt(a)
|
|
3044
|
-
].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l =
|
|
3045
|
-
return e(
|
|
3069
|
+
].join("\n"), c = r.map((e) => an(e, { formVar: i })).join("\n"), l = ur(r) ? " enctype=\"multipart/form-data\"" : "";
|
|
3070
|
+
return e(or ||= o([
|
|
3046
3071
|
"\n <script lang=\"ts\">\n ",
|
|
3047
3072
|
"\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 ",
|
|
3048
3073
|
"</h1>\n <Button href=\"",
|
|
@@ -3064,8 +3089,8 @@ function gr(t, n, r) {
|
|
|
3064
3089
|
"/\\${params.id}\" variant=\"outline\" size=\"sm\">Cancel</Button>\n </div>\n </form>\n </div>\n </section>\n "
|
|
3065
3090
|
]), s, t.displayName.toLowerCase(), n.list, i, l, t.name, c, n.list);
|
|
3066
3091
|
}
|
|
3067
|
-
function
|
|
3068
|
-
let i = r.some((e) => e.type === "select"), a = i ? `${
|
|
3092
|
+
function br(t, n, r) {
|
|
3093
|
+
let i = r.some((e) => e.type === "select"), a = i ? `${dr(r)}` : "", s = r.map((t) => {
|
|
3069
3094
|
let n = "{ getValue }", r = "{ value: getValue() }";
|
|
3070
3095
|
return t.type === "relation" && (n = "{ getValue, row }", r = `{ value: getValue(), expanded: row.original.expand?.${t.name}, displayField: "${t.displayField}" }`), t.type === "select" && (r = `{ value: getValue(), options: ${t.name}Labels }`), t.type === "file" && (n = "{ getValue, row }", r = "{ value: getValue(), collectionId: row.original.collectionId, id: row.original.id }"), e`
|
|
3071
3096
|
columnHelper.accessor("${t.name}", {
|
|
@@ -3074,7 +3099,7 @@ function _r(t, n, r) {
|
|
|
3074
3099
|
})
|
|
3075
3100
|
`;
|
|
3076
3101
|
}).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");
|
|
3077
|
-
return e(
|
|
3102
|
+
return e(sr ||= o([
|
|
3078
3103
|
"\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 ",
|
|
3079
3104
|
"\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 ",
|
|
3080
3105
|
"\n\n const columnHelper = createColumnHelper<Models[\"",
|
|
@@ -3089,7 +3114,7 @@ function _r(t, n, r) {
|
|
|
3089
3114
|
"...\"\n value={(table.getColumn(\"name\")?.getFilterValue() as string) ?? \"\"}\n oninput={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n onchange={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n class=\"h-8 w-[150px] lg:w-[250px]\"\n />\n ",
|
|
3090
3115
|
"\n {#if table.getState().columnFilters.length > 0}\n <Button variant=\"ghost\" onclick={() => table.resetColumnFilters()} class=\"h-8 px-2 lg:px-3\">\n Reset\n <XIcon />\n </Button>\n {/if}\n </div>\n\n <Button href=\"",
|
|
3091
3116
|
"\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
|
|
3092
|
-
"\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}>\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>\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 "
|
|
3117
|
+
"\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 "
|
|
3093
3118
|
], [
|
|
3094
3119
|
"\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 ",
|
|
3095
3120
|
"\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 ",
|
|
@@ -3105,10 +3130,10 @@ function _r(t, n, r) {
|
|
|
3105
3130
|
"...\"\n value={(table.getColumn(\"name\")?.getFilterValue() as string) ?? \"\"}\n oninput={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n onchange={(e) => {\n table.getColumn(\"name\")?.setFilterValue(e.currentTarget.value);\n }}\n class=\"h-8 w-[150px] lg:w-[250px]\"\n />\n ",
|
|
3106
3131
|
"\n {#if table.getState().columnFilters.length > 0}\n <Button variant=\"ghost\" onclick={() => table.resetColumnFilters()} class=\"h-8 px-2 lg:px-3\">\n Reset\n <XIcon />\n </Button>\n {/if}\n </div>\n\n <Button href=\"",
|
|
3107
3132
|
"\" variant=\"outline\" size=\"sm\">\n <PlusIcon class=\"w-4 h-4\" />\n New ",
|
|
3108
|
-
"\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}>\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>\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 "
|
|
3133
|
+
"\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 "
|
|
3109
3134
|
]), i ? "import { FacetedFilter } from \"$lib/components/ui/faceted-filter\";" : "", a, t.tableName, s, r.length > 0 ? "," : "", n.list, n.list, n.list, t.pluralName, t.pluralDisplayName, t.pluralDisplayName.toLowerCase(), c, n.new, t.displayName.toLowerCase());
|
|
3110
3135
|
}
|
|
3111
|
-
function
|
|
3136
|
+
function xr(t, n, r) {
|
|
3112
3137
|
let i = V(n), a = i ? `{ expand: "${i}" }` : "";
|
|
3113
3138
|
return e`
|
|
3114
3139
|
export const load = async ({ locals }) => {
|
|
@@ -3117,16 +3142,16 @@ function vr(t, n, r) {
|
|
|
3117
3142
|
};
|
|
3118
3143
|
`;
|
|
3119
3144
|
}
|
|
3120
|
-
function
|
|
3121
|
-
return
|
|
3145
|
+
function Sr(t, n, r) {
|
|
3146
|
+
return _r(n) ? e`
|
|
3122
3147
|
export const load = async ({ locals }) => {
|
|
3123
|
-
${
|
|
3124
|
-
return { ${
|
|
3148
|
+
${fr(n, r)}
|
|
3149
|
+
return { ${pr(n)} };
|
|
3125
3150
|
};
|
|
3126
3151
|
` : "";
|
|
3127
3152
|
}
|
|
3128
|
-
function
|
|
3129
|
-
let o =
|
|
3153
|
+
function Cr(t, n, r, i, a) {
|
|
3154
|
+
let o = hr(t), s = r.find((e) => e.type === "relation" && e.isCurrentUser), c = a && s ? e`
|
|
3130
3155
|
{
|
|
3131
3156
|
...data,
|
|
3132
3157
|
${s.name}: locals.pb.authStore.record?.id
|
|
@@ -3146,7 +3171,7 @@ function br(t, n, r, i, a) {
|
|
|
3146
3171
|
});
|
|
3147
3172
|
`;
|
|
3148
3173
|
}
|
|
3149
|
-
function
|
|
3174
|
+
function wr(t, n, r, i) {
|
|
3150
3175
|
let a = V(r), o = a ? `, { expand: "${a}" }` : "";
|
|
3151
3176
|
return e`
|
|
3152
3177
|
import { error, redirect } from "@sveltejs/kit";
|
|
@@ -3168,15 +3193,15 @@ function xr(t, n, r, i) {
|
|
|
3168
3193
|
};
|
|
3169
3194
|
`;
|
|
3170
3195
|
}
|
|
3171
|
-
function
|
|
3196
|
+
function Tr(t, n, r) {
|
|
3172
3197
|
let i = r.some((e) => e.type === "select"), a = r.some((e) => e.type === "relation"), s = r.some((e) => e.type === "file"), c = [
|
|
3173
3198
|
"import { Button } from \"$lib/components/ui/button\";",
|
|
3174
3199
|
"import ArrowLeftIcon from \"@lucide/svelte/icons/arrow-left\";",
|
|
3175
3200
|
i || a ? "import { Badge } from \"$lib/components/ui/badge\";" : "",
|
|
3176
3201
|
a ? "import CircleArrowRightIcon from \"@lucide/svelte/icons/circle-arrow-right\";" : "",
|
|
3177
3202
|
s ? "import FileIcon from \"@lucide/svelte/icons/file\";" : ""
|
|
3178
|
-
].filter(Boolean).join("\n"), l =
|
|
3179
|
-
return e(
|
|
3203
|
+
].filter(Boolean).join("\n"), l = dr(r), u = r.map((e) => Ee(t, e)).join("\n");
|
|
3204
|
+
return e(cr ||= o([
|
|
3180
3205
|
"\n <script lang=\"ts\">\n ",
|
|
3181
3206
|
"\n ",
|
|
3182
3207
|
"\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\">",
|
|
@@ -3187,8 +3212,8 @@ function Sr(t, n, r) {
|
|
|
3187
3212
|
".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 "
|
|
3188
3213
|
]), c, l, t.displayName, n.list, u, n.list, t.name);
|
|
3189
3214
|
}
|
|
3190
|
-
function
|
|
3191
|
-
let i =
|
|
3215
|
+
function Er(t, n, r) {
|
|
3216
|
+
let i = fr(n, r), a = pr(n), o = a ? `, ${a}` : "";
|
|
3192
3217
|
return e`
|
|
3193
3218
|
import { error } from "@sveltejs/kit";
|
|
3194
3219
|
|
|
@@ -3204,8 +3229,8 @@ function Cr(t, n, r) {
|
|
|
3204
3229
|
};
|
|
3205
3230
|
`;
|
|
3206
3231
|
}
|
|
3207
|
-
function
|
|
3208
|
-
let i =
|
|
3232
|
+
function Dr(t, n, r) {
|
|
3233
|
+
let i = gr(t);
|
|
3209
3234
|
return e`
|
|
3210
3235
|
import { form, getRequestEvent, error } from "$app/server";
|
|
3211
3236
|
import { redirect } from "@sveltejs/kit";
|
|
@@ -3220,16 +3245,16 @@ function wr(t, n, r) {
|
|
|
3220
3245
|
});
|
|
3221
3246
|
`;
|
|
3222
3247
|
}
|
|
3223
|
-
async function
|
|
3224
|
-
let { modelPath: t, fields: n } =
|
|
3248
|
+
async function Or(e) {
|
|
3249
|
+
let { modelPath: t, fields: n } = lr(e.argv), { model: r, fields: i, auth: a, shouldCreateCollection: o, collections: s } = await z(e, t, n), c = Je(r), l = Ye(r), u = mr(e), d = i.filter((e) => !(e.type === "relation" && e.isCurrentUser)), f = [
|
|
3225
3250
|
Z(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
3226
3251
|
includeModelFields: !0,
|
|
3227
3252
|
forForm: !0
|
|
3228
3253
|
})),
|
|
3229
|
-
Z(`${c.list}/+page.server.ts`,
|
|
3230
|
-
Z(`${c.list}/+page.svelte`,
|
|
3231
|
-
], p =
|
|
3232
|
-
p && f.push(Z(`${c.new}/+page.server.ts`, p)), f.push(Z(`${c.new}/form.remote.ts`,
|
|
3254
|
+
Z(`${c.list}/+page.server.ts`, xr(r, d, u)),
|
|
3255
|
+
Z(`${c.list}/+page.svelte`, br(r, l, d))
|
|
3256
|
+
], p = Sr(r, d, u);
|
|
3257
|
+
p && f.push(Z(`${c.new}/+page.server.ts`, p)), f.push(Z(`${c.new}/form.remote.ts`, Cr(r, l, i, u, e.features.auth)), Z(`${c.new}/+page.svelte`, vr(r, l, d)), Z(`${c.show}/+page.server.ts`, wr(r, l, d, u)), Z(`${c.show}/+page.svelte`, Tr(r, l, d)), Z(`${c.edit}/+page.server.ts`, Er(r, d, u)), Z(`${c.edit}/form.remote.ts`, Dr(r, l, u)), Z(`${c.edit}/+page.svelte`, yr(r, l, d)), Z(`${c.list}/server.test.ts`, Ct(r, l, i, e, s)));
|
|
3233
3258
|
let m = [
|
|
3234
3259
|
...W(d),
|
|
3235
3260
|
"button",
|
|
@@ -3257,22 +3282,45 @@ async function Tr(e) {
|
|
|
3257
3282
|
};
|
|
3258
3283
|
}
|
|
3259
3284
|
//#endregion
|
|
3285
|
+
//#region src/patterns/generate/scaffold-remote/generate.preview.ts
|
|
3286
|
+
var kr = /* @__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" }), Ar = "./preview-modifies/";
|
|
3287
|
+
async function jr(e) {
|
|
3288
|
+
return {
|
|
3289
|
+
creates: [],
|
|
3290
|
+
modifies: Object.entries(kr).map(([e, n]) => {
|
|
3291
|
+
let i = r(e, Ar);
|
|
3292
|
+
return {
|
|
3293
|
+
path: i,
|
|
3294
|
+
language: t(i),
|
|
3295
|
+
content: n,
|
|
3296
|
+
status: "success"
|
|
3297
|
+
};
|
|
3298
|
+
}).sort((e, t) => e.path.localeCompare(t.path)),
|
|
3299
|
+
deletes: [],
|
|
3300
|
+
components: [],
|
|
3301
|
+
packages: [],
|
|
3302
|
+
collections: []
|
|
3303
|
+
};
|
|
3304
|
+
}
|
|
3305
|
+
//#endregion
|
|
3260
3306
|
//#region src/patterns/generate/scaffold-remote/index.ts
|
|
3261
|
-
var
|
|
3262
|
-
async function
|
|
3263
|
-
let t = await
|
|
3307
|
+
var Mr = "generate-scaffold-remote", Nr = "1.0.0", Pr = "src/patterns/generate/scaffold-remote", Fr = "/generate/scaffold-remote";
|
|
3308
|
+
async function Ir(e) {
|
|
3309
|
+
let t = await Or(e);
|
|
3310
|
+
if (e.env === "preview") return v(n([t, await jr(e)]));
|
|
3264
3311
|
if (e.env !== "runtime") return v(t);
|
|
3265
|
-
let { createCollections:
|
|
3312
|
+
let { createCollections: r } = await import("./chunks/collections-Bs9xy7nU.js"), i = await r(t.collections, e), { modifyOutcomeToFile: a } = await import("./chunks/modify-file-CpqC7kMR.js"), { findSvelteConfigPath: o, modifySvelteConfigRemote: s } = await import("./chunks/modify-svelte-config-remote-DWsScM6m.js"), c = o(e.root), l = a(c, s(c)), u = {
|
|
3266
3313
|
...t,
|
|
3267
|
-
creates: [...t.creates, ...
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3314
|
+
creates: [...t.creates, ...i],
|
|
3315
|
+
modifies: [...t.modifies, ...l ? [l] : []]
|
|
3316
|
+
}, { writeResult: d } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
3317
|
+
return d(await v(u), e);
|
|
3318
|
+
}
|
|
3319
|
+
var Lr = {
|
|
3320
|
+
version: Nr,
|
|
3321
|
+
slug: Mr,
|
|
3322
|
+
source: Pr,
|
|
3323
|
+
docs: Fr,
|
|
3276
3324
|
plan: "open",
|
|
3277
3325
|
title: "Generate a scaffold (remote functions)",
|
|
3278
3326
|
summary: "Generates CRUD routes and schema using SvelteKit remote functions for create/update forms.",
|
|
@@ -3317,11 +3365,11 @@ var jr = {
|
|
|
3317
3365
|
],
|
|
3318
3366
|
tests: 6,
|
|
3319
3367
|
baseline: "velastack",
|
|
3320
|
-
generate:
|
|
3368
|
+
generate: Ir
|
|
3321
3369
|
};
|
|
3322
3370
|
//#endregion
|
|
3323
3371
|
//#region src/patterns/generate/schema/generate.ts
|
|
3324
|
-
function
|
|
3372
|
+
function Rr(e) {
|
|
3325
3373
|
let [t, ...n] = e;
|
|
3326
3374
|
if (!t) throw new _("Invalid command arguments. Expected: <model> [fields...]");
|
|
3327
3375
|
return {
|
|
@@ -3329,7 +3377,7 @@ function Mr(e) {
|
|
|
3329
3377
|
fields: n
|
|
3330
3378
|
};
|
|
3331
3379
|
}
|
|
3332
|
-
function
|
|
3380
|
+
function zr(e, n) {
|
|
3333
3381
|
return {
|
|
3334
3382
|
path: e,
|
|
3335
3383
|
language: t(e),
|
|
@@ -3337,10 +3385,10 @@ function Nr(e, n) {
|
|
|
3337
3385
|
status: "success"
|
|
3338
3386
|
};
|
|
3339
3387
|
}
|
|
3340
|
-
async function
|
|
3341
|
-
let { modelPath: t, fields: n } =
|
|
3388
|
+
async function Br(e) {
|
|
3389
|
+
let { modelPath: t, fields: n } = Rr(e.argv), { model: r, fields: i, shouldCreateCollection: a } = await z(e, t, n);
|
|
3342
3390
|
return {
|
|
3343
|
-
creates: [
|
|
3391
|
+
creates: [zr(`src/lib/schemas/${r.name}.ts`, B(r, i, {
|
|
3344
3392
|
includeModelFields: !a,
|
|
3345
3393
|
forForm: !0
|
|
3346
3394
|
}))],
|
|
@@ -3353,18 +3401,18 @@ async function Pr(e) {
|
|
|
3353
3401
|
}
|
|
3354
3402
|
//#endregion
|
|
3355
3403
|
//#region src/patterns/generate/schema/index.ts
|
|
3356
|
-
var
|
|
3357
|
-
async function
|
|
3358
|
-
let t = await
|
|
3404
|
+
var Vr = "generate-schema", Hr = "1.0.7", Ur = "src/patterns/generate/schema", Wr = "/generate/schema";
|
|
3405
|
+
async function Gr(e) {
|
|
3406
|
+
let t = await Br(e);
|
|
3359
3407
|
if (e.env !== "runtime") return v(t);
|
|
3360
|
-
let { writeResult: n } = await import("./chunks/write-result-
|
|
3408
|
+
let { writeResult: n } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
3361
3409
|
return n(await v(t), e);
|
|
3362
3410
|
}
|
|
3363
|
-
var
|
|
3364
|
-
version:
|
|
3365
|
-
slug:
|
|
3366
|
-
source:
|
|
3367
|
-
docs:
|
|
3411
|
+
var Kr = {
|
|
3412
|
+
version: Hr,
|
|
3413
|
+
slug: Vr,
|
|
3414
|
+
source: Ur,
|
|
3415
|
+
docs: Wr,
|
|
3368
3416
|
plan: "open",
|
|
3369
3417
|
title: "Generate a schema",
|
|
3370
3418
|
summary: "Generates a zod schema.",
|
|
@@ -3407,8 +3455,8 @@ var Br = {
|
|
|
3407
3455
|
],
|
|
3408
3456
|
tests: 0,
|
|
3409
3457
|
baseline: "velastack",
|
|
3410
|
-
generate:
|
|
3411
|
-
},
|
|
3458
|
+
generate: Gr
|
|
3459
|
+
}, qr = /* @__PURE__ */ Object.assign({
|
|
3412
3460
|
"./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",
|
|
3413
3461
|
"./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",
|
|
3414
3462
|
"./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",
|
|
@@ -3450,10 +3498,10 @@ var Br = {
|
|
|
3450
3498
|
"./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",
|
|
3451
3499
|
"./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",
|
|
3452
3500
|
"./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"
|
|
3453
|
-
}),
|
|
3454
|
-
async function
|
|
3455
|
-
let n = Object.entries(
|
|
3456
|
-
let i = r(e,
|
|
3501
|
+
}), Jr = "./creates/";
|
|
3502
|
+
async function Yr(e) {
|
|
3503
|
+
let n = Object.entries(qr).map(([e, n]) => {
|
|
3504
|
+
let i = r(e, Jr);
|
|
3457
3505
|
return {
|
|
3458
3506
|
path: i,
|
|
3459
3507
|
language: t(i),
|
|
@@ -3545,16 +3593,16 @@ async function Ur(e) {
|
|
|
3545
3593
|
}
|
|
3546
3594
|
//#endregion
|
|
3547
3595
|
//#region src/patterns/enable/auth/generate.preview.ts
|
|
3548
|
-
var
|
|
3596
|
+
var Xr = /* @__PURE__ */ Object.assign({
|
|
3549
3597
|
"./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",
|
|
3550
3598
|
"./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",
|
|
3551
3599
|
"./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"
|
|
3552
|
-
}),
|
|
3553
|
-
async function
|
|
3600
|
+
}), Zr = "./preview-modifies/";
|
|
3601
|
+
async function Qr(e) {
|
|
3554
3602
|
return {
|
|
3555
3603
|
creates: [],
|
|
3556
|
-
modifies: Object.entries(
|
|
3557
|
-
let i = r(e,
|
|
3604
|
+
modifies: Object.entries(Xr).map(([e, n]) => {
|
|
3605
|
+
let i = r(e, Zr);
|
|
3558
3606
|
return {
|
|
3559
3607
|
path: i,
|
|
3560
3608
|
language: t(i),
|
|
@@ -3570,18 +3618,18 @@ async function Kr(e) {
|
|
|
3570
3618
|
}
|
|
3571
3619
|
//#endregion
|
|
3572
3620
|
//#region src/patterns/enable/auth/index.ts
|
|
3573
|
-
var
|
|
3574
|
-
async function
|
|
3575
|
-
let t = await
|
|
3576
|
-
if (e.env === "preview") return v(n([t, await
|
|
3577
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
3621
|
+
var $r = "enable-auth", ei = "1.0.7", ti = "src/patterns/enable/auth", ni = "/enable/auth";
|
|
3622
|
+
async function ri(e) {
|
|
3623
|
+
let t = await Yr(e);
|
|
3624
|
+
if (e.env === "preview") return v(n([t, await Qr(e)]));
|
|
3625
|
+
let { generate: r } = await import("./chunks/generate.runtime-6QnXtCSG.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
3578
3626
|
return a(await v(n([t, i])), e);
|
|
3579
3627
|
}
|
|
3580
|
-
var
|
|
3581
|
-
version:
|
|
3582
|
-
slug:
|
|
3583
|
-
source:
|
|
3584
|
-
docs:
|
|
3628
|
+
var ii = {
|
|
3629
|
+
version: ei,
|
|
3630
|
+
slug: $r,
|
|
3631
|
+
source: ti,
|
|
3632
|
+
docs: ni,
|
|
3585
3633
|
plan: "open",
|
|
3586
3634
|
title: "Enable authentication",
|
|
3587
3635
|
summary: "Enables authentication.",
|
|
@@ -3610,12 +3658,222 @@ var Qr = {
|
|
|
3610
3658
|
examples: [],
|
|
3611
3659
|
tests: 18,
|
|
3612
3660
|
baseline: "velastack",
|
|
3613
|
-
generate:
|
|
3614
|
-
},
|
|
3615
|
-
|
|
3661
|
+
generate: ri
|
|
3662
|
+
}, ai = /* @__PURE__ */ Object.assign({
|
|
3663
|
+
"./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",
|
|
3664
|
+
"./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",
|
|
3665
|
+
"./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",
|
|
3666
|
+
"./creates/src/lib/schemas/changeEmail.ts": "import { z } from \"zod\";\n\nexport const changeEmailSchema = z.object({\n email: z.email(),\n});\n",
|
|
3667
|
+
"./creates/src/lib/schemas/changePassword.ts": "import { z } from \"zod\";\n\nexport const changePasswordSchema = z\n .object({\n password: z.string(),\n passwordConfirm: z.string(),\n })\n .refine((data) => data.password === data.passwordConfirm, {\n message: \"Passwords don't match\",\n path: [\"passwordConfirm\"],\n });\n",
|
|
3668
|
+
"./creates/src/lib/schemas/confirmEmailChange.ts": "import { z } from \"zod\";\n\nexport const confirmEmailChangeSchema = z.object({\n password: z.string(),\n});\n",
|
|
3669
|
+
"./creates/src/lib/schemas/confirmReset.ts": "import { z } from \"zod\";\n\nexport const confirmResetSchema = z.object({\n password: z.string(),\n passwordConfirm: z.string(),\n});\n",
|
|
3670
|
+
"./creates/src/lib/schemas/login.ts": "import { z } from \"zod\";\n\nconst otpSchema = z.object({\n type: z.literal(\"otp\"),\n email: z.email(),\n});\n\nconst passwordSchema = z.object({\n type: z.literal(\"password\"),\n email: z.email(),\n password: z.string(),\n});\n\nconst oAuth2Schema = z.object({\n type: z.literal(\"oauth2\"),\n email: z.email(),\n});\n\nexport const loginSchema = z.discriminatedUnion(\"type\", [\n otpSchema,\n passwordSchema,\n oAuth2Schema,\n]);\n",
|
|
3671
|
+
"./creates/src/lib/schemas/otp.ts": "import { z } from \"zod\";\n\nexport const otpSchema = z.object({\n otp: z.string(),\n});\n",
|
|
3672
|
+
"./creates/src/lib/schemas/profile.ts": "import { z } from \"zod\";\n\nexport const profileSchema = z.object({\n name: z.string().optional(),\n avatar: z.union([z.instanceof(File), z.string()]).optional(),\n emailVisibility: z.boolean().optional(),\n});\n",
|
|
3673
|
+
"./creates/src/lib/schemas/reset.ts": "import { z } from \"zod\";\n\nexport const resetSchema = z.object({\n email: z.email(),\n});\n",
|
|
3674
|
+
"./creates/src/lib/schemas/signup.ts": "import { z } from \"zod\";\n\nexport const signupSchema = z.object({\n email: z.email(),\n password: z.string(),\n passwordConfirm: z.string(),\n});\n",
|
|
3675
|
+
"./creates/src/routes/(app)/+layout.server.ts": "export const load = ({ locals }) => {\n const user = locals.pb.authStore.record!;\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n\n return { user, breadcrumbs };\n};\n",
|
|
3676
|
+
"./creates/src/routes/(app)/+layout.svelte": "<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 <AppSidebar user={data.user} meta={data.meta} />\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",
|
|
3677
|
+
"./creates/src/routes/(app)/dashboard/+page.svelte": "",
|
|
3678
|
+
"./creates/src/routes/(app)/dashboard/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"dashboard\", () => {\n it(\"should redirect to the login page\", async (context) => {\n const response = await context.request.get(\n \"/dashboard\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(302);\n expect(response.headers.location).toBe(\"/login?redirect=%2Fdashboard\");\n });\n\n it(\"authenticated user should be able to access the dashboard\", async (context) => {\n await context.agent.authenticateUser();\n const response = await context.agent.get(\n \"/dashboard\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n",
|
|
3679
|
+
"./creates/src/routes/(app)/settings/+layout.server.ts": "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Settings\", url: \"/settings\" }],\n };\n};\n",
|
|
3680
|
+
"./creates/src/routes/(app)/settings/+page.server.ts": "export const load = async ({ parent }) => {\n const { user } = await parent();\n\n return { user };\n};\n",
|
|
3681
|
+
"./creates/src/routes/(app)/settings/+page.svelte": "<script lang=\"ts\">\n import { Button, buttonVariants } from \"$lib/components/ui/button\";\n import * as Card from \"$lib/components/ui/card\";\n import { Input } from \"$lib/components/ui/input\";\n import { Badge } from \"$lib/components/ui/badge\";\n import * as Dialog from \"$lib/components/ui/dialog\";\n import { Checkbox } from \"$lib/components/ui/checkbox\";\n import * as Avatar from \"$lib/components/ui/avatar\";\n import {\n updateProfileForm,\n changeEmailForm,\n changePasswordForm,\n resendVerificationForm,\n } from \"./form.remote\";\n\n let { data } = $props();\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\">\n Profile\n </h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Your profile information.\n </p>\n </div>\n\n <form\n {...updateProfileForm}\n enctype=\"multipart/form-data\"\n class=\"md:col-span-2\"\n >\n <Card.Root>\n <Card.Content class=\"flex flex-col gap-6\">\n <div class=\"flex items-center gap-3 justify-between\">\n <div class=\"flex items-center gap-3\">\n <Avatar.Root class=\"size-16\">\n <Avatar.Fallback>\n {data.user.email.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div>\n <span class=\"text-sm font-medium leading-none\">Avatar</span>\n <p class=\"text-muted-foreground text-sm\">\n Upload a new avatar for your profile.\n </p>\n </div>\n </div>\n <label class={buttonVariants({ variant: \"outline\" })}>\n Upload new picture\n <input\n {...updateProfileForm.fields.avatar.as(\"file\")}\n type=\"file\"\n class=\"hidden\"\n />\n </label>\n </div>\n {#each updateProfileForm.fields.avatar.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n\n <div class=\"grid gap-6\">\n <div class=\"grid gap-3\">\n <label for=\"name\" class=\"text-sm font-medium\">Name</label>\n <Input\n id=\"name\"\n {...updateProfileForm.fields.name.as(\"text\")}\n type=\"text\"\n />\n {#each updateProfileForm.fields.name.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n </div>\n <div class=\"grid gap-6\">\n <div class=\"grid gap-3\">\n <div class=\"flex items-start gap-2\">\n <Checkbox\n {...updateProfileForm.fields.emailVisibility.as(\"checkbox\")}\n />\n <div class=\"grid gap-2\">\n <label\n for=\"emailVisibility\"\n class=\"text-sm font-medium leading-none\"\n >Display email publicly</label\n >\n <p class=\"text-muted-foreground text-sm\">\n By clicking this checkbox, your email will be displayed\n publicly.\n </p>\n </div>\n </div>\n {#each updateProfileForm.fields.emailVisibility.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n </div>\n </Card.Content>\n <Card.Footer class=\"border-t justify-end\">\n <Button type=\"submit\" class=\"w-fit\">Save changes</Button>\n </Card.Footer>\n </Card.Root>\n </form>\n </div>\n\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\">\n Email\n </h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n The email address associated with your account.\n </p>\n </div>\n\n <Card.Root class=\"md:col-span-2\">\n <Card.Content class=\"flex flex-col gap-6\">\n <div class=\"flex justify-between items-center\">\n <span class=\"text-sm flex items-center gap-2\">\n {data.user.email}\n <Badge variant=\"secondary\"\n >{data.user.verified ? \"Verified\" : \"Unverified\"}</Badge\n >\n </span>\n <div class=\"flex items-center gap-3\">\n {#if !data.user.verified}\n <form {...resendVerificationForm}>\n <Button type=\"submit\" variant=\"outline\" class=\"w-fit\"\n >Resend verification email</Button\n >\n </form>\n {/if}\n\n <Dialog.Root>\n <Dialog.Trigger class={buttonVariants({ variant: \"outline\" })}>\n Change email\n </Dialog.Trigger>\n <Dialog.Content>\n <Dialog.Header>\n <Dialog.Title>Change email</Dialog.Title>\n <Dialog.Description>\n Enter your new email address. You will receive a\n verification email.\n </Dialog.Description>\n </Dialog.Header>\n <form {...changeEmailForm}>\n <div class=\"grid gap-6\">\n <div class=\"grid gap-3\">\n <label for=\"email\" class=\"text-sm font-medium\"\n >Email</label\n >\n <Input\n id=\"email\"\n {...changeEmailForm.fields.email.as(\"text\")}\n type=\"email\"\n required\n />\n {#each changeEmailForm.fields.email.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n </div>\n <Dialog.Footer>\n <Button type=\"submit\" class=\"w-fit\">Change email</Button>\n </Dialog.Footer>\n </form>\n </Dialog.Content>\n </Dialog.Root>\n </div>\n </div>\n </Card.Content>\n </Card.Root>\n </div>\n\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\">\n Password\n </h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Your password is used to log in to your account.\n </p>\n </div>\n\n <form {...changePasswordForm} class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content class=\"flex flex-col gap-6\">\n <div class=\"grid gap-6\">\n <div class=\"grid gap-3\">\n <label for=\"password\" class=\"text-sm font-medium\"\n >New password</label\n >\n <Input\n id=\"password\"\n {...changePasswordForm.fields.password.as(\"text\")}\n type=\"password\"\n autocomplete=\"new-password\"\n required\n />\n {#each changePasswordForm.fields.password.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n <div class=\"grid gap-3\">\n <label for=\"passwordConfirm\" class=\"text-sm font-medium\"\n >Confirm new password</label\n >\n <Input\n id=\"passwordConfirm\"\n {...changePasswordForm.fields.passwordConfirm.as(\"text\")}\n type=\"password\"\n autocomplete=\"new-password\"\n required\n />\n {#each changePasswordForm.fields.passwordConfirm.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n </div>\n </Card.Content>\n <Card.Footer class=\"border-t justify-end\">\n <Button type=\"submit\" class=\"w-fit\">Update password</Button>\n </Card.Footer>\n </Card.Root>\n </form>\n </div>\n</div>\n",
|
|
3682
|
+
"./creates/src/routes/(app)/settings/form.remote.ts": "import { form, getRequestEvent } from \"$app/server\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { profileSchema } from \"$lib/schemas/profile\";\nimport { changeEmailSchema } from \"$lib/schemas/changeEmail\";\nimport { changePasswordSchema } from \"$lib/schemas/changePassword\";\n\nexport const updateProfileForm = form(profileSchema, async (data) => {\n const { locals, cookies } = getRequestEvent();\n\n await locals.pb.collection(\"users\").update(locals.pb.authStore.record!.id, {\n name: data.name,\n avatar: data.avatar,\n emailVisibility: data.emailVisibility,\n });\n\n setFlash(\n { type: \"toast\", message: \"Profile updated successfully.\" },\n cookies,\n );\n return { success: true };\n});\n\nexport const changeEmailForm = form(changeEmailSchema, async (data) => {\n const { locals, cookies } = getRequestEvent();\n\n await locals.pb.collection(\"users\").requestEmailChange(data.email);\n setFlash(\n {\n type: \"toast\",\n message: \"We sent a confirmation link to your new email.\",\n },\n cookies,\n );\n return { success: true };\n});\n\nexport const changePasswordForm = form(changePasswordSchema, async (data) => {\n const { locals, cookies } = getRequestEvent();\n\n await locals.admin\n .collection(\"users\")\n .update(locals.pb.authStore.record!.id, {\n password: data.password,\n passwordConfirm: data.passwordConfirm,\n });\n\n setFlash(\n { type: \"toast\", message: \"Password updated successfully.\" },\n cookies,\n );\n return { success: true };\n});\n\nexport const resendVerificationForm = form(async () => {\n const { locals, cookies } = getRequestEvent();\n await locals.pb\n .collection(\"users\")\n .requestVerification(locals.pb.authStore.record!.email);\n setFlash(\n { type: \"toast\", message: \"We sent a verification email to your email.\" },\n cookies,\n );\n return { success: true };\n});\n",
|
|
3683
|
+
"./creates/src/routes/(public)/confirm-email-change/[token]/+page.server.ts": "export const load = async () => {\n return {};\n};\n",
|
|
3684
|
+
"./creates/src/routes/(public)/confirm-email-change/[token]/+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 { confirmEmailChangeForm } from \"./form.remote\";\n\n let { data } = $props();\n<\/script>\n\n<div class=\"flex flex-col flex-1 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 <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Confirm your email change</Card.Title>\n <Card.Description\n >Enter your password to confirm your email change</Card.Description\n >\n </Card.Header>\n <Card.Content>\n <form {...confirmEmailChangeForm}>\n <div class=\"grid gap-6\">\n <div class=\"grid gap-2\">\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 {...confirmEmailChangeForm.fields.password.as(\"text\")}\n type=\"password\"\n required\n autocomplete=\"current-password\"\n />\n {#each confirmEmailChangeForm.fields.password.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n <Button type=\"submit\" class=\"w-full\">Confirm email change</Button>\n </div>\n </div>\n </form>\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n",
|
|
3685
|
+
"./creates/src/routes/(public)/confirm-email-change/[token]/form.remote.ts": "import { form, getRequestEvent } from \"$app/server\";\nimport { redirect } from \"@sveltejs/kit\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { confirmEmailChangeSchema } from \"$lib/schemas/confirmEmailChange\";\n\nexport const confirmEmailChangeForm = form(\n confirmEmailChangeSchema,\n async (data) => {\n const { locals, cookies, params } = getRequestEvent();\n\n await locals.admin\n .collection(\"users\")\n .confirmEmailChange(params.token as string, data.password);\n\n locals.pb.authStore.clear();\n locals.pb.authStore.clearCookie(cookies);\n\n setFlash(\n { type: \"toast\", message: \"Email changed successfully.\" },\n cookies,\n );\n redirect(303, \"/login\");\n },\n);\n",
|
|
3686
|
+
"./creates/src/routes/(public)/confirm-email-change/[token]/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /confirm-email-change/[token]\", () => {\n it(\"should render the confirm-email-change page\", async (context) => {\n const response = await context.request.get(\n \"/confirm-email-change/123456\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n",
|
|
3687
|
+
"./creates/src/routes/(public)/confirm-reset/[token]/+page.server.ts": "export const load = async () => {\n return {};\n};\n",
|
|
3688
|
+
"./creates/src/routes/(public)/confirm-reset/[token]/+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 { confirmResetForm } from \"./form.remote\";\n\n let { data } = $props();\n<\/script>\n\n<div class=\"flex flex-col flex-1 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 <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Reset your password</Card.Title>\n <Card.Description>Enter your new password</Card.Description>\n </Card.Header>\n <Card.Content>\n <form {...confirmResetForm}>\n <div class=\"grid gap-6\">\n <div class=\"grid gap-2\">\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 {...confirmResetForm.fields.password.as(\"text\")}\n type=\"password\"\n required\n autocomplete=\"new-password\"\n />\n {#each confirmResetForm.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 {...confirmResetForm.fields.passwordConfirm.as(\"text\")}\n type=\"password\"\n required\n autocomplete=\"new-password\"\n />\n {#each confirmResetForm.fields.passwordConfirm.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n <Button type=\"submit\" class=\"w-full\">Reset password</Button>\n </div>\n </div>\n </form>\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n",
|
|
3689
|
+
"./creates/src/routes/(public)/confirm-reset/[token]/form.remote.ts": "import { form, getRequestEvent } from \"$app/server\";\nimport { redirect } from \"@sveltejs/kit\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { confirmResetSchema } from \"$lib/schemas/confirmReset\";\n\nexport const confirmResetForm = form(confirmResetSchema, async (data) => {\n const { locals, cookies, params } = getRequestEvent();\n\n await locals.admin\n .collection(\"users\")\n .confirmPasswordReset(\n params.token as string,\n data.password,\n data.passwordConfirm,\n );\n\n locals.pb.authStore.clear();\n locals.pb.authStore.clearCookie(cookies);\n\n setFlash({ type: \"toast\", message: \"Password reset successfully.\" }, cookies);\n redirect(303, \"/login\");\n});\n",
|
|
3690
|
+
"./creates/src/routes/(public)/confirm-reset/[token]/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /confirm-reset/[token]\", () => {\n it(\"should render the confirm-reset page\", async (context) => {\n const response = await context.request.get(\n \"/confirm-reset/123456\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n",
|
|
3691
|
+
"./creates/src/routes/(public)/confirm-verification/[token]/+server.ts": "import { redirect } from \"@sveltejs/kit\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\n\nexport const GET = async ({ params, locals, cookies }) => {\n let message = \"\";\n let redirectPath = \"\";\n\n try {\n await locals.admin.collection(\"users\").confirmVerification(params.token);\n message = \"Email verified successfully.\";\n redirectPath = \"/dashboard\";\n } catch (error: any) {\n message =\n \"Invalid or expired verification token. Please request a new verification email.\";\n redirectPath = \"/login\";\n }\n\n setFlash({ type: \"toast\", message }, cookies);\n redirect(303, redirectPath);\n};\n",
|
|
3692
|
+
"./creates/src/routes/(public)/confirm-verification/[token]/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /confirm-verification/[token]\", () => {\n it(\"should redirect if the token is invalid\", async (context) => {\n const response = await context.request.get(\n \"/confirm-verification/123456\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(303);\n expect(response.headers[\"location\"]).toBe(\"/login\");\n });\n});\n",
|
|
3693
|
+
"./creates/src/routes/(public)/login/+page.server.ts": "import { redirect } from \"@sveltejs/kit\";\n\nexport const load = async ({ locals }) => {\n if (locals.pb.authStore.isValid) {\n redirect(303, \"/dashboard\");\n }\n\n const authMethods = await locals.admin.collection(\"users\").listAuthMethods();\n\n return { authMethods };\n};\n",
|
|
3694
|
+
"./creates/src/routes/(public)/login/+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 { loginForm } 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 initialType: \"password\" | \"otp\" | \"oauth2\" = $derived(\n authMethods.otp.enabled\n ? \"otp\"\n : authMethods.password.enabled\n ? \"password\"\n : \"oauth2\",\n );\n let mode = $state<\"password\" | \"otp\" | \"oauth2\">(\"password\");\n $effect(() => {\n mode = initialType;\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\">Welcome back</Card.Title>\n {#if hasOAuth2}\n <Card.Description>Choose a login method</Card.Description>\n {:else}\n <Card.Description>Use your email to login</Card.Description>\n {/if}\n </Card.Header>\n {:else}\n <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Login is disabled</Card.Title>\n <Card.Description\n >Check back later for login options</Card.Description\n >\n </Card.Header>\n {/if}\n <Card.Content>\n <form {...loginForm}>\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 || authMethods.otp.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 {...loginForm.fields.email.as(\"text\")}\n type=\"email\"\n required\n />\n {#each loginForm.fields.email.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n {#if mode === \"password\" && authMethods.password.enabled}\n <div class=\"space-y-2 col-span-1\">\n <div class=\"flex justify-between\">\n <label for=\"password\" class=\"text-sm font-medium\"\n >Password</label\n >\n <a\n href=\"/reset\"\n class=\"ml-auto text-sm underline-offset-4 hover:underline\"\n >Forgot your password?</a\n >\n </div>\n <Input\n id=\"password\"\n {...loginForm.fields.password.as(\"text\")}\n type=\"password\"\n required\n autocomplete=\"current-password\"\n />\n {#each loginForm.fields.password.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n {#if loginForm.result?.message}\n <div class=\"text-destructive text-sm font-medium -mt-2\">\n {loginForm.result.message}\n </div>\n {/if}\n\n <Button type=\"submit\" class=\"w-full\">Login</Button>\n {#if authMethods.otp.enabled}\n <Button\n variant=\"outline\"\n class=\"w-full\"\n onclick={() => (mode = \"otp\")}\n type=\"button\"\n >Use one-time code instead</Button\n >\n {/if}\n {:else if mode === \"otp\" && authMethods.otp.enabled}\n <Button type=\"submit\" class=\"w-full\"\n >Send one-time code</Button\n >\n {#if authMethods.password.enabled}\n <Button\n variant=\"outline\"\n class=\"w-full\"\n onclick={() => (mode = \"password\")}\n type=\"button\"\n >Continue with password</Button\n >\n {/if}\n {/if}\n </div>\n\n <input\n type=\"hidden\"\n {...loginForm.fields.type.as(\"text\")}\n value={mode}\n />\n {/if}\n\n <div class=\"text-center text-sm\">\n Don't have an account?\n <a\n href=\"/signup{redirect\n ? `?redirect=${encodeURIComponent(redirect)}`\n : ''}\"\n class=\"underline underline-offset-4\">Sign up</a\n >\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",
|
|
3695
|
+
"./creates/src/routes/(public)/login/form.remote.ts": "import { form, getRequestEvent } from \"$app/server\";\nimport { error, redirect } from \"@sveltejs/kit\";\nimport { dev } from \"$app/environment\";\nimport { loginSchema } from \"$lib/schemas/login\";\n\nexport const loginForm = form(loginSchema, async (data) => {\n const { locals, cookies, url } = getRequestEvent();\n\n const redirectParam = url.searchParams.get(\"redirect\");\n if (data.type === \"otp\") {\n const req = await locals.pb.collection(\"users\").requestOTP(data.email);\n redirect(\n 303,\n `/otp/${req.otpId}${redirectParam ? `?redirect=${encodeURIComponent(redirectParam)}` : \"\"}`,\n );\n } else if (data.type === \"password\") {\n try {\n await locals.pb\n .collection(\"users\")\n .authWithPassword(data.email, data.password);\n } catch (err: any) {\n error(400, err.response?.message ?? \"Failed to authenticate.\");\n }\n }\n\n const redirectUrl = redirectParam ?? \"/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 redirect(303, redirectUrl);\n});\n",
|
|
3696
|
+
"./creates/src/routes/(public)/login/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /login\", () => {\n it(\"should render the login page\", async (context) => {\n const response = await context.agent.get(\"/login\" satisfies Match<RouteId>);\n expect(response.status).toBe(200);\n });\n\n it(\"should redirect to the dashboard if the user is already authenticated\", async (context) => {\n await context.agent.authenticateUser();\n const response = await context.agent.get(\"/login\" satisfies Match<RouteId>);\n expect(response.status).toBe(303);\n expect(response.headers.location).toBe(\"/dashboard\");\n });\n});\n",
|
|
3697
|
+
"./creates/src/routes/(public)/logout/+server.ts": "import { redirect } from \"@sveltejs/kit\";\n\nexport const POST = ({ cookies, locals }) => {\n locals.pb.authStore.clear();\n locals.pb.authStore.clearCookie(cookies);\n throw redirect(303, \"/\");\n};\n",
|
|
3698
|
+
"./creates/src/routes/(public)/logout/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"POST /logout\", () => {\n it(\"should logout the user\", async (context) => {\n await context.agent.authenticateUser();\n const response = await context.agent.post(\n \"/logout\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(303);\n expect(response.headers.location).toBe(\"/\");\n });\n});\n",
|
|
3699
|
+
"./creates/src/routes/(public)/otp/[token]/+page.server.ts": "import { redirect } from \"@sveltejs/kit\";\n\nexport const load = async ({ locals }) => {\n if (locals.pb.authStore.isValid) {\n redirect(303, \"/dashboard\");\n }\n\n return {};\n};\n",
|
|
3700
|
+
"./creates/src/routes/(public)/otp/[token]/+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 { otpForm } from \"./form.remote\";\n\n let { data } = $props();\n<\/script>\n\n<div class=\"flex flex-col flex-1 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 <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Enter your OTP code</Card.Title>\n <Card.Description\n >Enter the code sent to your email</Card.Description\n >\n </Card.Header>\n <Card.Content>\n <form {...otpForm}>\n <div class=\"grid gap-6\">\n <div class=\"grid gap-2\">\n <div class=\"space-y-2 col-span-1\">\n <label for=\"otp\" class=\"text-sm font-medium\">OTP code</label>\n <Input\n id=\"otp\"\n {...otpForm.fields.otp.as(\"text\")}\n type=\"text\"\n required\n />\n {#each otpForm.fields.otp.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n {#if otpForm.result?.message}\n <div class=\"text-destructive text-sm font-medium -mt-2\">\n {otpForm.result.message}\n </div>\n {/if}\n\n <Button type=\"submit\" class=\"w-full\">Verify code</Button>\n </div>\n </div>\n </form>\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n",
|
|
3701
|
+
"./creates/src/routes/(public)/otp/[token]/form.remote.ts": "import { form, getRequestEvent } from \"$app/server\";\nimport { error, redirect } from \"@sveltejs/kit\";\nimport { dev } from \"$app/environment\";\nimport { otpSchema } from \"$lib/schemas/otp\";\n\nexport const otpForm = form(otpSchema, async (data) => {\n const { locals, cookies, params, url } = getRequestEvent();\n\n try {\n await locals.pb\n .collection(\"users\")\n .authWithOTP(params.token as string, data.otp);\n } catch (err: any) {\n error(400, err.response?.message ?? \"Failed to verify code.\");\n }\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 redirect(303, redirectUrl);\n});\n",
|
|
3702
|
+
"./creates/src/routes/(public)/otp/[token]/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /otp/[token]\", () => {\n it(\"should render the otp page\", async (context) => {\n const response = await context.request.get(\n \"/otp/123456\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n",
|
|
3703
|
+
"./creates/src/routes/(public)/reset/+page.server.ts": "import { redirect } from \"@sveltejs/kit\";\n\nexport const load = async ({ locals }) => {\n if (locals.pb.authStore.isValid) {\n redirect(303, \"/dashboard\");\n }\n\n return {};\n};\n",
|
|
3704
|
+
"./creates/src/routes/(public)/reset/+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 { resetForm } from \"./form.remote\";\n\n let { data } = $props();\n<\/script>\n\n<div class=\"flex flex-col flex-1 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 <Card.Header class=\"text-center\">\n <Card.Title class=\"text-xl\">Reset your password</Card.Title>\n <Card.Description\n >Enter your email to reset your password</Card.Description\n >\n </Card.Header>\n <Card.Content>\n <form {...resetForm}>\n <div class=\"grid gap-6\">\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 {...resetForm.fields.email.as(\"text\")}\n type=\"email\"\n required\n />\n {#each resetForm.fields.email.issues() as issue}\n <p class=\"text-destructive text-sm\">{issue.message}</p>\n {/each}\n </div>\n\n <Button type=\"submit\" class=\"w-full\">Send reset link</Button>\n </div>\n\n <div class=\"text-center text-sm\">\n Remembered your password?\n <a href=\"/login\" class=\"underline underline-offset-4\">Log in</a>\n </div>\n </div>\n </form>\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n",
|
|
3705
|
+
"./creates/src/routes/(public)/reset/form.remote.ts": "import { form, getRequestEvent } from \"$app/server\";\nimport { setFlash } from \"sveltekit-flash-message/server\";\nimport { resetSchema } from \"$lib/schemas/reset\";\n\nexport const resetForm = form(resetSchema, async (data) => {\n const { locals, cookies } = getRequestEvent();\n\n await locals.pb.collection(\"users\").requestPasswordReset(data.email);\n setFlash(\n {\n type: \"toast\",\n message: \"We sent a password reset link to your email.\",\n },\n cookies,\n );\n\n return { success: true };\n});\n",
|
|
3706
|
+
"./creates/src/routes/(public)/reset/server.test.ts": "import { describe, it, expect } from \"vitest\";\nimport type { Match } from \"@velastack/pocketbase\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"GET /reset\", () => {\n it(\"should render the reset page\", async (context) => {\n const response = await context.request.get(\n \"/reset\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n });\n});\n",
|
|
3707
|
+
"./creates/src/routes/(public)/signup/+page.server.ts": "import { redirect } from \"@sveltejs/kit\";\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 { authMethods };\n};\n",
|
|
3708
|
+
"./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",
|
|
3709
|
+
"./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",
|
|
3710
|
+
"./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"
|
|
3711
|
+
}), oi = "./creates/";
|
|
3712
|
+
async function si(e) {
|
|
3713
|
+
let n = Object.entries(ai).map(([e, n]) => {
|
|
3714
|
+
let i = r(e, oi);
|
|
3715
|
+
return {
|
|
3716
|
+
path: i,
|
|
3717
|
+
language: t(i),
|
|
3718
|
+
content: n,
|
|
3719
|
+
status: "success"
|
|
3720
|
+
};
|
|
3721
|
+
}).sort((e, t) => e.path.localeCompare(t.path)), i = [
|
|
3722
|
+
"sidebar",
|
|
3723
|
+
"breadcrumb",
|
|
3724
|
+
"separator",
|
|
3725
|
+
"collapsible",
|
|
3726
|
+
"avatar",
|
|
3727
|
+
"dropdown-menu",
|
|
3728
|
+
"card",
|
|
3729
|
+
"input",
|
|
3730
|
+
"label",
|
|
3731
|
+
"button",
|
|
3732
|
+
"badge",
|
|
3733
|
+
"dialog",
|
|
3734
|
+
"checkbox",
|
|
3735
|
+
"auth-menu"
|
|
3736
|
+
];
|
|
3737
|
+
return e.features.payments && i.push("alert-dialog"), {
|
|
3738
|
+
creates: n,
|
|
3739
|
+
modifies: [],
|
|
3740
|
+
deletes: [],
|
|
3741
|
+
components: i,
|
|
3742
|
+
packages: [],
|
|
3743
|
+
collections: [{
|
|
3744
|
+
listRule: "@request.auth.id = user.id",
|
|
3745
|
+
viewRule: "@request.auth.id = user.id",
|
|
3746
|
+
name: "oauth_accounts",
|
|
3747
|
+
type: "base",
|
|
3748
|
+
fields: [
|
|
3749
|
+
{
|
|
3750
|
+
collectionId: "_pb_users_auth_",
|
|
3751
|
+
name: "user",
|
|
3752
|
+
type: "relation",
|
|
3753
|
+
required: !0,
|
|
3754
|
+
maxSelect: 1
|
|
3755
|
+
},
|
|
3756
|
+
{
|
|
3757
|
+
name: "providerId",
|
|
3758
|
+
required: !0,
|
|
3759
|
+
type: "text"
|
|
3760
|
+
},
|
|
3761
|
+
{
|
|
3762
|
+
name: "provider",
|
|
3763
|
+
required: !0,
|
|
3764
|
+
type: "text"
|
|
3765
|
+
},
|
|
3766
|
+
{
|
|
3767
|
+
name: "accessToken",
|
|
3768
|
+
type: "text"
|
|
3769
|
+
},
|
|
3770
|
+
{
|
|
3771
|
+
name: "refreshToken",
|
|
3772
|
+
type: "text"
|
|
3773
|
+
},
|
|
3774
|
+
{
|
|
3775
|
+
name: "avatarURL",
|
|
3776
|
+
type: "text"
|
|
3777
|
+
},
|
|
3778
|
+
{
|
|
3779
|
+
name: "expiry",
|
|
3780
|
+
type: "date"
|
|
3781
|
+
},
|
|
3782
|
+
{
|
|
3783
|
+
name: "email",
|
|
3784
|
+
type: "text"
|
|
3785
|
+
},
|
|
3786
|
+
{
|
|
3787
|
+
name: "name",
|
|
3788
|
+
type: "text"
|
|
3789
|
+
},
|
|
3790
|
+
{
|
|
3791
|
+
name: "username",
|
|
3792
|
+
type: "text"
|
|
3793
|
+
},
|
|
3794
|
+
{
|
|
3795
|
+
name: "rawUser",
|
|
3796
|
+
type: "json"
|
|
3797
|
+
}
|
|
3798
|
+
]
|
|
3799
|
+
}]
|
|
3800
|
+
};
|
|
3801
|
+
}
|
|
3802
|
+
//#endregion
|
|
3803
|
+
//#region src/patterns/enable/auth-remote/generate.preview.ts
|
|
3804
|
+
var ci = /* @__PURE__ */ Object.assign({
|
|
3805
|
+
"./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",
|
|
3806
|
+
"./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",
|
|
3807
|
+
"./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",
|
|
3808
|
+
"./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"
|
|
3809
|
+
}), li = "./preview-modifies/";
|
|
3810
|
+
async function ui(e) {
|
|
3811
|
+
return {
|
|
3812
|
+
creates: [],
|
|
3813
|
+
modifies: Object.entries(ci).map(([e, n]) => {
|
|
3814
|
+
let i = r(e, li);
|
|
3815
|
+
return {
|
|
3816
|
+
path: i,
|
|
3817
|
+
language: t(i),
|
|
3818
|
+
content: n,
|
|
3819
|
+
status: "success"
|
|
3820
|
+
};
|
|
3821
|
+
}).sort((e, t) => e.path.localeCompare(t.path)),
|
|
3822
|
+
deletes: [],
|
|
3823
|
+
components: [],
|
|
3824
|
+
packages: [],
|
|
3825
|
+
collections: []
|
|
3826
|
+
};
|
|
3827
|
+
}
|
|
3828
|
+
//#endregion
|
|
3829
|
+
//#region src/patterns/enable/auth-remote/index.ts
|
|
3830
|
+
var di = "enable-auth-remote", fi = "1.0.0", pi = "src/patterns/enable/auth-remote", mi = "/enable/auth-remote";
|
|
3831
|
+
async function hi(e) {
|
|
3832
|
+
let t = await si(e);
|
|
3833
|
+
if (e.env === "preview") return v(n([t, await ui(e)]));
|
|
3834
|
+
let { generate: r } = await import("./chunks/generate.runtime-BUbI1GmK.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
3835
|
+
return a(await v(n([t, i])), e);
|
|
3836
|
+
}
|
|
3837
|
+
var gi = {
|
|
3838
|
+
version: fi,
|
|
3839
|
+
slug: di,
|
|
3840
|
+
source: pi,
|
|
3841
|
+
docs: mi,
|
|
3842
|
+
plan: "open",
|
|
3843
|
+
title: "Enable authentication (remote functions)",
|
|
3844
|
+
summary: "Enables authentication using SvelteKit remote functions for login, signup, reset, and settings forms.",
|
|
3845
|
+
requires: {
|
|
3846
|
+
auth: !1,
|
|
3847
|
+
api: !1,
|
|
3848
|
+
apiKeys: !1,
|
|
3849
|
+
i18n: !1,
|
|
3850
|
+
teams: !1,
|
|
3851
|
+
payments: !1
|
|
3852
|
+
},
|
|
3853
|
+
category: "auth",
|
|
3854
|
+
tags: [
|
|
3855
|
+
"sveltekit",
|
|
3856
|
+
"authentication",
|
|
3857
|
+
"auth",
|
|
3858
|
+
"velastack",
|
|
3859
|
+
"oauth",
|
|
3860
|
+
"pocketbase",
|
|
3861
|
+
"remote-functions"
|
|
3862
|
+
],
|
|
3863
|
+
command: {
|
|
3864
|
+
raw: "vela enable auth --remote",
|
|
3865
|
+
base: "vela enable auth --remote",
|
|
3866
|
+
argv: []
|
|
3867
|
+
},
|
|
3868
|
+
examples: [],
|
|
3869
|
+
tests: 18,
|
|
3870
|
+
baseline: "velastack",
|
|
3871
|
+
generate: hi
|
|
3872
|
+
}, _i = /* @__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" }), vi = "./creates/";
|
|
3873
|
+
async function yi(e) {
|
|
3616
3874
|
return {
|
|
3617
|
-
creates: Object.entries(
|
|
3618
|
-
let i = r(e,
|
|
3875
|
+
creates: Object.entries(_i).map(([e, n]) => {
|
|
3876
|
+
let i = r(e, vi);
|
|
3619
3877
|
return {
|
|
3620
3878
|
path: i,
|
|
3621
3879
|
language: t(i),
|
|
@@ -3632,12 +3890,12 @@ async function ti(e) {
|
|
|
3632
3890
|
}
|
|
3633
3891
|
//#endregion
|
|
3634
3892
|
//#region src/patterns/enable/api/generate.preview.ts
|
|
3635
|
-
var
|
|
3636
|
-
async function
|
|
3893
|
+
var bi = /* @__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" }), xi = "./preview-modifies/";
|
|
3894
|
+
async function Si(e) {
|
|
3637
3895
|
return {
|
|
3638
3896
|
creates: [],
|
|
3639
|
-
modifies: Object.entries(
|
|
3640
|
-
let i = r(e,
|
|
3897
|
+
modifies: Object.entries(bi).map(([e, n]) => {
|
|
3898
|
+
let i = r(e, xi);
|
|
3641
3899
|
return {
|
|
3642
3900
|
path: i,
|
|
3643
3901
|
language: t(i),
|
|
@@ -3653,18 +3911,18 @@ async function ii(e) {
|
|
|
3653
3911
|
}
|
|
3654
3912
|
//#endregion
|
|
3655
3913
|
//#region src/patterns/enable/api/index.ts
|
|
3656
|
-
var
|
|
3657
|
-
async function
|
|
3658
|
-
let t = await
|
|
3659
|
-
if (e.env === "preview") return v(n([t, await
|
|
3660
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
3914
|
+
var Ci = "enable-api", wi = "1.0.7", Ti = "src/patterns/enable/api", Ei = "/enable/api";
|
|
3915
|
+
async function Di(e) {
|
|
3916
|
+
let t = await yi(e);
|
|
3917
|
+
if (e.env === "preview") return v(n([t, await Si(e)]));
|
|
3918
|
+
let { generate: r } = await import("./chunks/generate.runtime-DpT7Jzh4.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
3661
3919
|
return a(await v(n([t, i])), e);
|
|
3662
3920
|
}
|
|
3663
|
-
var
|
|
3664
|
-
version:
|
|
3665
|
-
slug:
|
|
3666
|
-
source:
|
|
3667
|
-
docs:
|
|
3921
|
+
var Oi = {
|
|
3922
|
+
version: wi,
|
|
3923
|
+
slug: Ci,
|
|
3924
|
+
source: Ti,
|
|
3925
|
+
docs: Ei,
|
|
3668
3926
|
plan: "open",
|
|
3669
3927
|
title: "Enable API",
|
|
3670
3928
|
summary: "Enables the PocketBase API.",
|
|
@@ -3693,8 +3951,8 @@ var ui = {
|
|
|
3693
3951
|
examples: [],
|
|
3694
3952
|
tests: 1,
|
|
3695
3953
|
baseline: "velastack",
|
|
3696
|
-
generate:
|
|
3697
|
-
},
|
|
3954
|
+
generate: Di
|
|
3955
|
+
}, ki = /* @__PURE__ */ Object.assign({
|
|
3698
3956
|
"./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",
|
|
3699
3957
|
"./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",
|
|
3700
3958
|
"./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",
|
|
@@ -3704,11 +3962,11 @@ var ui = {
|
|
|
3704
3962
|
"./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",
|
|
3705
3963
|
"./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",
|
|
3706
3964
|
"./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"
|
|
3707
|
-
}),
|
|
3708
|
-
async function
|
|
3965
|
+
}), Ai = "./creates/";
|
|
3966
|
+
async function ji(e) {
|
|
3709
3967
|
return {
|
|
3710
|
-
creates: Object.entries(
|
|
3711
|
-
let i = r(e,
|
|
3968
|
+
creates: Object.entries(ki).map(([e, n]) => {
|
|
3969
|
+
let i = r(e, Ai);
|
|
3712
3970
|
return {
|
|
3713
3971
|
path: i,
|
|
3714
3972
|
language: t(i),
|
|
@@ -3729,12 +3987,12 @@ async function pi(e) {
|
|
|
3729
3987
|
}
|
|
3730
3988
|
//#endregion
|
|
3731
3989
|
//#region src/patterns/enable/api-keys/generate.preview.ts
|
|
3732
|
-
var
|
|
3733
|
-
async function
|
|
3990
|
+
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 api: {\n enabled: true,\n // [!code highlight:1]\n apiKeys: { enabled: true },\n },\n});\n" }), Ni = "./preview-modifies/";
|
|
3991
|
+
async function Pi(e) {
|
|
3734
3992
|
return {
|
|
3735
3993
|
creates: [],
|
|
3736
|
-
modifies: Object.entries(
|
|
3737
|
-
let i = r(e,
|
|
3994
|
+
modifies: Object.entries(Mi).map(([e, n]) => {
|
|
3995
|
+
let i = r(e, Ni);
|
|
3738
3996
|
return {
|
|
3739
3997
|
path: i,
|
|
3740
3998
|
language: t(i),
|
|
@@ -3750,18 +4008,18 @@ async function gi(e) {
|
|
|
3750
4008
|
}
|
|
3751
4009
|
//#endregion
|
|
3752
4010
|
//#region src/patterns/enable/api-keys/index.ts
|
|
3753
|
-
var
|
|
3754
|
-
async function
|
|
3755
|
-
let t = await
|
|
3756
|
-
if (e.env === "preview") return v(n([t, await
|
|
3757
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
4011
|
+
var Fi = "enable-api-keys", Ii = "1.0.0", Li = "src/patterns/enable/api-keys", Ri = "/enable/api-keys";
|
|
4012
|
+
async function zi(e) {
|
|
4013
|
+
let t = await ji(e);
|
|
4014
|
+
if (e.env === "preview") return v(n([t, await Pi(e)]));
|
|
4015
|
+
let { generate: r } = await import("./chunks/generate.runtime-BayXS2PL.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
3758
4016
|
return a(await v(n([t, i])), e);
|
|
3759
4017
|
}
|
|
3760
|
-
var
|
|
3761
|
-
version:
|
|
3762
|
-
slug:
|
|
3763
|
-
source:
|
|
3764
|
-
docs:
|
|
4018
|
+
var Bi = {
|
|
4019
|
+
version: Ii,
|
|
4020
|
+
slug: Fi,
|
|
4021
|
+
source: Li,
|
|
4022
|
+
docs: Ri,
|
|
3765
4023
|
plan: "open",
|
|
3766
4024
|
title: "Enable API keys",
|
|
3767
4025
|
summary: "Adds API key management for authenticated users and PocketBase API access.",
|
|
@@ -3790,16 +4048,17 @@ var Si = {
|
|
|
3790
4048
|
examples: [],
|
|
3791
4049
|
tests: 6,
|
|
3792
4050
|
baseline: "velastack",
|
|
3793
|
-
generate:
|
|
3794
|
-
},
|
|
4051
|
+
generate: zi
|
|
4052
|
+
}, Vi = /* @__PURE__ */ Object.assign({
|
|
3795
4053
|
"./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",
|
|
4054
|
+
"./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",
|
|
3796
4055
|
"./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",
|
|
3797
4056
|
"./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"
|
|
3798
|
-
}),
|
|
3799
|
-
async function
|
|
4057
|
+
}), Hi = "./creates/";
|
|
4058
|
+
async function Ui(e) {
|
|
3800
4059
|
return {
|
|
3801
|
-
creates: Object.entries(
|
|
3802
|
-
let i = r(e,
|
|
4060
|
+
creates: Object.entries(Vi).map(([e, n]) => {
|
|
4061
|
+
let i = r(e, Hi);
|
|
3803
4062
|
return {
|
|
3804
4063
|
path: i,
|
|
3805
4064
|
language: t(i),
|
|
@@ -3809,25 +4068,26 @@ async function Ti(e) {
|
|
|
3809
4068
|
}).sort((e, t) => e.path.localeCompare(t.path)),
|
|
3810
4069
|
modifies: [],
|
|
3811
4070
|
deletes: [],
|
|
3812
|
-
components: [],
|
|
4071
|
+
components: ["select"],
|
|
3813
4072
|
packages: ["wuchale", "@wuchale/svelte"],
|
|
3814
4073
|
collections: []
|
|
3815
4074
|
};
|
|
3816
4075
|
}
|
|
3817
4076
|
//#endregion
|
|
3818
4077
|
//#region src/patterns/enable/i18n/generate.preview.ts
|
|
3819
|
-
var
|
|
4078
|
+
var Wi = /* @__PURE__ */ Object.assign({
|
|
3820
4079
|
"./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",
|
|
3821
4080
|
"./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",
|
|
4081
|
+
"./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 </Navbar.List>\n\n <!-- [!code highlight] -->\n <LanguageSelect />\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",
|
|
3822
4082
|
"./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",
|
|
3823
4083
|
"./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",
|
|
3824
4084
|
"./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"
|
|
3825
|
-
}),
|
|
3826
|
-
async function
|
|
4085
|
+
}), Gi = "./preview-modifies/";
|
|
4086
|
+
async function Ki(e) {
|
|
3827
4087
|
return {
|
|
3828
4088
|
creates: [],
|
|
3829
|
-
modifies: Object.entries(
|
|
3830
|
-
let i = r(e,
|
|
4089
|
+
modifies: Object.entries(Wi).map(([e, n]) => {
|
|
4090
|
+
let i = r(e, Gi);
|
|
3831
4091
|
return {
|
|
3832
4092
|
path: i,
|
|
3833
4093
|
language: t(i),
|
|
@@ -3843,18 +4103,18 @@ async function Oi(e) {
|
|
|
3843
4103
|
}
|
|
3844
4104
|
//#endregion
|
|
3845
4105
|
//#region src/patterns/enable/i18n/index.ts
|
|
3846
|
-
var
|
|
3847
|
-
async function
|
|
3848
|
-
let t = await
|
|
3849
|
-
if (e.env === "preview") return v(n([t, await
|
|
3850
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
4106
|
+
var qi = "enable-i18n", Ji = "1.0.0", Yi = "src/patterns/enable/i18n", Xi = "/enable/i18n";
|
|
4107
|
+
async function Zi(e) {
|
|
4108
|
+
let t = await Ui(e);
|
|
4109
|
+
if (e.env === "preview") return v(n([t, await Ki(e)]));
|
|
4110
|
+
let { generate: r } = await import("./chunks/generate.runtime-BpZPXyba.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
3851
4111
|
return a(await v(n([t, i])), e);
|
|
3852
4112
|
}
|
|
3853
|
-
var
|
|
3854
|
-
version:
|
|
3855
|
-
slug:
|
|
3856
|
-
source:
|
|
3857
|
-
docs:
|
|
4113
|
+
var Qi = {
|
|
4114
|
+
version: Ji,
|
|
4115
|
+
slug: qi,
|
|
4116
|
+
source: Yi,
|
|
4117
|
+
docs: Xi,
|
|
3858
4118
|
plan: "open",
|
|
3859
4119
|
title: "Enable i18n",
|
|
3860
4120
|
summary: "Enables i18n with Wuchale and locale-aware routing.",
|
|
@@ -3882,47 +4142,47 @@ var Pi = {
|
|
|
3882
4142
|
examples: [],
|
|
3883
4143
|
tests: 0,
|
|
3884
4144
|
baseline: "velastack",
|
|
3885
|
-
generate:
|
|
3886
|
-
}, Fi = "/// <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", Ii = "/// <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", Li = "<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", Ri = "<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", zi = "<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", Bi = "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", Vi = "<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", Hi = "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", Ui = "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", Wi = "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", Gi = "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", Ki = "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", qi = "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", Ji = "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", Yi = "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", Xi = "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", Zi = "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", Qi = "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", $i = "/// <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", ea = "/// <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", ta = "<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", na = "<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", ra = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", ia = "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", aa = "<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", oa = "# 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", sa = "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", ca = "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", la = "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", ua = "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", da = "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", fa = "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", pa = "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", ma = "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", ha = "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", _a = /* @__PURE__ */ Object.assign({
|
|
3887
|
-
"./creates/data/hooks/stripe.pb.js":
|
|
3888
|
-
"./creates/data/hooks/utils.js":
|
|
3889
|
-
"./creates/src/lib/components/payments/confirm-dialog.svelte":
|
|
3890
|
-
"./creates/src/lib/components/payments/payment-button.svelte":
|
|
3891
|
-
"./creates/src/lib/components/payments/payment-dialog.svelte":
|
|
3892
|
-
"./creates/src/lib/components/payments/stripe-constants.ts":
|
|
3893
|
-
"./creates/src/lib/components/payments/stripe-payment-form.svelte":
|
|
3894
|
-
"./creates/src/lib/components/payments/use-payment-intent.svelte.ts":
|
|
3895
|
-
"./creates/src/lib/components/payments/use-stripe.svelte.ts":
|
|
3896
|
-
"./creates/src/lib/stripe.ts":
|
|
3897
|
-
"./creates/src/routes/api/stripe/payment-intent/+server.ts":
|
|
3898
|
-
"./creates/src/routes/api/stripe/payment-intent/server.test.ts":
|
|
3899
|
-
"./creates/src/routes/api/stripe/sync/prices/+server.ts":
|
|
3900
|
-
"./creates/src/routes/api/stripe/sync/products/+server.ts":
|
|
3901
|
-
"./creates/src/routes/webhooks/stripe/+server.ts":
|
|
3902
|
-
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts":
|
|
3903
|
-
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts":
|
|
3904
|
-
"./creates/src/routes/webhooks/stripe/server.test.ts":
|
|
3905
|
-
}),
|
|
3906
|
-
"./creates-app-mode/data/hooks/stripe.pb.js":
|
|
3907
|
-
"./creates-app-mode/data/hooks/utils.js":
|
|
3908
|
-
"./creates-app-mode/src/lib/components/payments/setup-button.svelte":
|
|
3909
|
-
"./creates-app-mode/src/lib/components/payments/setup-dialog.svelte":
|
|
3910
|
-
"./creates-app-mode/src/routes/(app)/billing/+layout.server.ts":
|
|
3911
|
-
"./creates-app-mode/src/routes/(app)/billing/+page.server.ts":
|
|
3912
|
-
"./creates-app-mode/src/routes/(app)/billing/+page.svelte":
|
|
3913
|
-
"./creates-app-mode/src/routes/(app)/billing/README.md":
|
|
3914
|
-
"./creates-app-mode/src/routes/api/stripe/payment-intent/+server.ts":
|
|
3915
|
-
"./creates-app-mode/src/routes/api/stripe/payment-intent/server.test.ts":
|
|
3916
|
-
"./creates-app-mode/src/routes/api/stripe/setup-intent/+server.ts":
|
|
3917
|
-
"./creates-app-mode/src/routes/api/stripe/setup-intent/server.test.ts":
|
|
3918
|
-
"./creates-app-mode/src/routes/api/stripe/sync/customers/+server.ts":
|
|
3919
|
-
"./creates-app-mode/src/routes/webhooks/stripe/+server.ts":
|
|
3920
|
-
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts":
|
|
3921
|
-
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts":
|
|
3922
|
-
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/attached.ts":
|
|
3923
|
-
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts":
|
|
3924
|
-
}),
|
|
3925
|
-
function
|
|
4145
|
+
generate: Zi
|
|
4146
|
+
}, $i = "/// <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", ea = "/// <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", ta = "<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", na = "<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", ra = "<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", ia = "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", aa = "<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", oa = "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", sa = "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", ca = "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", la = "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", ua = "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", da = "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", fa = "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", pa = "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", ma = "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", ha = "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", ga = "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", _a = "/// <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", va = "/// <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", ya = "<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", ba = "<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", xa = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", Sa = "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", Ca = "<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", wa = "# 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", Ta = "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", Ea = "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", Da = "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", Oa = "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", ka = "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", Aa = "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", ja = "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", Ma = "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", Na = "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", Pa = "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", Fa = /* @__PURE__ */ Object.assign({
|
|
4147
|
+
"./creates/data/hooks/stripe.pb.js": $i,
|
|
4148
|
+
"./creates/data/hooks/utils.js": ea,
|
|
4149
|
+
"./creates/src/lib/components/payments/confirm-dialog.svelte": ta,
|
|
4150
|
+
"./creates/src/lib/components/payments/payment-button.svelte": na,
|
|
4151
|
+
"./creates/src/lib/components/payments/payment-dialog.svelte": ra,
|
|
4152
|
+
"./creates/src/lib/components/payments/stripe-constants.ts": ia,
|
|
4153
|
+
"./creates/src/lib/components/payments/stripe-payment-form.svelte": aa,
|
|
4154
|
+
"./creates/src/lib/components/payments/use-payment-intent.svelte.ts": oa,
|
|
4155
|
+
"./creates/src/lib/components/payments/use-stripe.svelte.ts": sa,
|
|
4156
|
+
"./creates/src/lib/stripe.ts": ca,
|
|
4157
|
+
"./creates/src/routes/api/stripe/payment-intent/+server.ts": la,
|
|
4158
|
+
"./creates/src/routes/api/stripe/payment-intent/server.test.ts": ua,
|
|
4159
|
+
"./creates/src/routes/api/stripe/sync/prices/+server.ts": da,
|
|
4160
|
+
"./creates/src/routes/api/stripe/sync/products/+server.ts": fa,
|
|
4161
|
+
"./creates/src/routes/webhooks/stripe/+server.ts": pa,
|
|
4162
|
+
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": ma,
|
|
4163
|
+
"./creates/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": ha,
|
|
4164
|
+
"./creates/src/routes/webhooks/stripe/server.test.ts": ga
|
|
4165
|
+
}), Ia = /* @__PURE__ */ Object.assign({
|
|
4166
|
+
"./creates-app-mode/data/hooks/stripe.pb.js": _a,
|
|
4167
|
+
"./creates-app-mode/data/hooks/utils.js": va,
|
|
4168
|
+
"./creates-app-mode/src/lib/components/payments/setup-button.svelte": ya,
|
|
4169
|
+
"./creates-app-mode/src/lib/components/payments/setup-dialog.svelte": ba,
|
|
4170
|
+
"./creates-app-mode/src/routes/(app)/billing/+layout.server.ts": xa,
|
|
4171
|
+
"./creates-app-mode/src/routes/(app)/billing/+page.server.ts": Sa,
|
|
4172
|
+
"./creates-app-mode/src/routes/(app)/billing/+page.svelte": Ca,
|
|
4173
|
+
"./creates-app-mode/src/routes/(app)/billing/README.md": wa,
|
|
4174
|
+
"./creates-app-mode/src/routes/api/stripe/payment-intent/+server.ts": Ta,
|
|
4175
|
+
"./creates-app-mode/src/routes/api/stripe/payment-intent/server.test.ts": Ea,
|
|
4176
|
+
"./creates-app-mode/src/routes/api/stripe/setup-intent/+server.ts": Da,
|
|
4177
|
+
"./creates-app-mode/src/routes/api/stripe/setup-intent/server.test.ts": Oa,
|
|
4178
|
+
"./creates-app-mode/src/routes/api/stripe/sync/customers/+server.ts": ka,
|
|
4179
|
+
"./creates-app-mode/src/routes/webhooks/stripe/+server.ts": Aa,
|
|
4180
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": ja,
|
|
4181
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": Ma,
|
|
4182
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/attached.ts": Na,
|
|
4183
|
+
"./creates-app-mode/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts": Pa
|
|
4184
|
+
}), La = "./creates/", Ra = "./creates-app-mode/";
|
|
4185
|
+
function za(e, n) {
|
|
3926
4186
|
let i = {};
|
|
3927
4187
|
for (let [a, o] of Object.entries(e)) {
|
|
3928
4188
|
let e = r(a, n);
|
|
@@ -3935,10 +4195,10 @@ function xa(e, n) {
|
|
|
3935
4195
|
}
|
|
3936
4196
|
return i;
|
|
3937
4197
|
}
|
|
3938
|
-
async function
|
|
3939
|
-
let t = e.features.auth, n = { ...
|
|
4198
|
+
async function Ba(e) {
|
|
4199
|
+
let t = e.features.auth, n = { ...za(Fa, La) };
|
|
3940
4200
|
if (t) {
|
|
3941
|
-
let e =
|
|
4201
|
+
let e = za(Ia, Ra);
|
|
3942
4202
|
Object.assign(n, e);
|
|
3943
4203
|
}
|
|
3944
4204
|
let r = Object.values(n).sort((e, t) => e.path.localeCompare(t.path)), i = [
|
|
@@ -3957,7 +4217,7 @@ async function Sa(e) {
|
|
|
3957
4217
|
}
|
|
3958
4218
|
//#endregion
|
|
3959
4219
|
//#region src/patterns/enable/payments/preview-modifies/src/lib/components/nav-user.svelte?raw
|
|
3960
|
-
var
|
|
4220
|
+
var Va = "<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", Ha = "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", Ua = "users", Wa = "stripe_customers", Ga = "stripe_payment_methods", Ka = {
|
|
3961
4221
|
name: "stripe_products",
|
|
3962
4222
|
type: "base",
|
|
3963
4223
|
fields: [
|
|
@@ -3996,7 +4256,7 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
3996
4256
|
type: "autodate"
|
|
3997
4257
|
}
|
|
3998
4258
|
]
|
|
3999
|
-
},
|
|
4259
|
+
}, qa = {
|
|
4000
4260
|
name: "stripe_prices",
|
|
4001
4261
|
type: "base",
|
|
4002
4262
|
fields: [
|
|
@@ -4055,8 +4315,8 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4055
4315
|
type: "autodate"
|
|
4056
4316
|
}
|
|
4057
4317
|
]
|
|
4058
|
-
},
|
|
4059
|
-
name:
|
|
4318
|
+
}, Ja = {
|
|
4319
|
+
name: Wa,
|
|
4060
4320
|
type: "base",
|
|
4061
4321
|
fields: [
|
|
4062
4322
|
{
|
|
@@ -4067,7 +4327,7 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4067
4327
|
type: "text"
|
|
4068
4328
|
},
|
|
4069
4329
|
{
|
|
4070
|
-
collectionId:
|
|
4330
|
+
collectionId: Ua,
|
|
4071
4331
|
maxSelect: 1,
|
|
4072
4332
|
minSelect: 0,
|
|
4073
4333
|
name: "user",
|
|
@@ -4075,7 +4335,7 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4075
4335
|
type: "relation"
|
|
4076
4336
|
},
|
|
4077
4337
|
{
|
|
4078
|
-
collectionId:
|
|
4338
|
+
collectionId: Ga,
|
|
4079
4339
|
maxSelect: 1,
|
|
4080
4340
|
minSelect: 0,
|
|
4081
4341
|
name: "default_payment_method",
|
|
@@ -4095,8 +4355,8 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4095
4355
|
type: "autodate"
|
|
4096
4356
|
}
|
|
4097
4357
|
]
|
|
4098
|
-
},
|
|
4099
|
-
name:
|
|
4358
|
+
}, Ya = {
|
|
4359
|
+
name: Ga,
|
|
4100
4360
|
type: "base",
|
|
4101
4361
|
fields: [
|
|
4102
4362
|
{
|
|
@@ -4127,7 +4387,7 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4127
4387
|
type: "number"
|
|
4128
4388
|
},
|
|
4129
4389
|
{
|
|
4130
|
-
collectionId:
|
|
4390
|
+
collectionId: Wa,
|
|
4131
4391
|
maxSelect: 1,
|
|
4132
4392
|
minSelect: 0,
|
|
4133
4393
|
name: "customer",
|
|
@@ -4148,7 +4408,7 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4148
4408
|
type: "autodate"
|
|
4149
4409
|
}
|
|
4150
4410
|
]
|
|
4151
|
-
},
|
|
4411
|
+
}, Xa = {
|
|
4152
4412
|
name: "transactions",
|
|
4153
4413
|
type: "base",
|
|
4154
4414
|
fields: [
|
|
@@ -4203,7 +4463,7 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4203
4463
|
type: "text"
|
|
4204
4464
|
},
|
|
4205
4465
|
{
|
|
4206
|
-
collectionId:
|
|
4466
|
+
collectionId: Ua,
|
|
4207
4467
|
maxSelect: 1,
|
|
4208
4468
|
minSelect: 0,
|
|
4209
4469
|
name: "user",
|
|
@@ -4216,20 +4476,20 @@ var Ca = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher'
|
|
|
4216
4476
|
type: "url"
|
|
4217
4477
|
}
|
|
4218
4478
|
]
|
|
4219
|
-
},
|
|
4220
|
-
|
|
4221
|
-
|
|
4222
|
-
|
|
4223
|
-
],
|
|
4224
|
-
"./preview-modifies/src/lib/components/nav-user.svelte":
|
|
4225
|
-
"./preview-modifies/src/routes/(public)/signup/+page.server.ts":
|
|
4226
|
-
}),
|
|
4227
|
-
function
|
|
4228
|
-
return e(
|
|
4229
|
-
}
|
|
4230
|
-
async function
|
|
4231
|
-
let n = e.features.auth, i = Object.entries(
|
|
4232
|
-
let i = r(e,
|
|
4479
|
+
}, Za = [Ka, qa], Qa = [
|
|
4480
|
+
Ja,
|
|
4481
|
+
Ya,
|
|
4482
|
+
Xa
|
|
4483
|
+
], $a, eo = /* @__PURE__ */ Object.assign({
|
|
4484
|
+
"./preview-modifies/src/lib/components/nav-user.svelte": Va,
|
|
4485
|
+
"./preview-modifies/src/routes/(public)/signup/+page.server.ts": Ha
|
|
4486
|
+
}), to = "./preview-modifies/", no = "price_preview_placeholder";
|
|
4487
|
+
function ro(t) {
|
|
4488
|
+
return e($a ||= o(["\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 "]), t);
|
|
4489
|
+
}
|
|
4490
|
+
async function io(e) {
|
|
4491
|
+
let n = e.features.auth, i = Object.entries(eo).map(([e, n]) => {
|
|
4492
|
+
let i = r(e, to);
|
|
4233
4493
|
return {
|
|
4234
4494
|
path: i,
|
|
4235
4495
|
language: t(i),
|
|
@@ -4239,9 +4499,9 @@ async function Ba(e) {
|
|
|
4239
4499
|
}).sort((e, t) => e.path.localeCompare(t.path)), a = {
|
|
4240
4500
|
path: "src/routes/(public)/payment/+page.svelte",
|
|
4241
4501
|
language: "svelte",
|
|
4242
|
-
content:
|
|
4502
|
+
content: ro(no),
|
|
4243
4503
|
status: "success"
|
|
4244
|
-
}, o = [...
|
|
4504
|
+
}, o = [...Za, ...n ? Qa : []];
|
|
4245
4505
|
return {
|
|
4246
4506
|
creates: [a],
|
|
4247
4507
|
modifies: i,
|
|
@@ -4253,18 +4513,18 @@ async function Ba(e) {
|
|
|
4253
4513
|
}
|
|
4254
4514
|
//#endregion
|
|
4255
4515
|
//#region src/patterns/enable/payments/index.ts
|
|
4256
|
-
var
|
|
4257
|
-
async function
|
|
4258
|
-
let t = await
|
|
4259
|
-
if (e.env === "preview") return v(n([t, await
|
|
4260
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
4516
|
+
var ao = "enable-payments", oo = "1.0.0", so = "src/patterns/enable/payments", co = "/enable/payments";
|
|
4517
|
+
async function lo(e) {
|
|
4518
|
+
let t = await Ba(e);
|
|
4519
|
+
if (e.env === "preview") return v(n([t, await io(e)]));
|
|
4520
|
+
let { generate: r } = await import("./chunks/generate.runtime-InE8X2Ly.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
4261
4521
|
return a(await v(n([t, i])), e);
|
|
4262
4522
|
}
|
|
4263
|
-
var
|
|
4264
|
-
version:
|
|
4265
|
-
slug:
|
|
4266
|
-
source:
|
|
4267
|
-
docs:
|
|
4523
|
+
var uo = {
|
|
4524
|
+
version: oo,
|
|
4525
|
+
slug: ao,
|
|
4526
|
+
source: so,
|
|
4527
|
+
docs: co,
|
|
4268
4528
|
plan: "pro",
|
|
4269
4529
|
title: "Enable payments",
|
|
4270
4530
|
summary: "Adds Stripe payments with product/price sync, checkout flow, and optional saved payment methods when auth is enabled.",
|
|
@@ -4293,8 +4553,8 @@ var Ka = {
|
|
|
4293
4553
|
examples: [],
|
|
4294
4554
|
tests: 0,
|
|
4295
4555
|
baseline: "velastack",
|
|
4296
|
-
generate:
|
|
4297
|
-
},
|
|
4556
|
+
generate: lo
|
|
4557
|
+
}, fo = /* @__PURE__ */ Object.assign({
|
|
4298
4558
|
"./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",
|
|
4299
4559
|
"./creates/src/lib/schemas/team.ts": "import { z } from \"zod\";\n\nexport const teamSchema = z.object({\n name: z.string(),\n});\n",
|
|
4300
4560
|
"./creates/src/lib/schemas/teamInvite.ts": "import { z } from \"zod\";\n\nexport const teamInviteSchema = z.object({\n email: z.email(),\n});\n",
|
|
@@ -4327,11 +4587,11 @@ var Ka = {
|
|
|
4327
4587
|
"./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",
|
|
4328
4588
|
"./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",
|
|
4329
4589
|
"./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"
|
|
4330
|
-
}),
|
|
4331
|
-
async function
|
|
4590
|
+
}), po = "./creates/";
|
|
4591
|
+
async function mo(e) {
|
|
4332
4592
|
return {
|
|
4333
|
-
creates: Object.entries(
|
|
4334
|
-
let i = r(e,
|
|
4593
|
+
creates: Object.entries(fo).map(([e, n]) => {
|
|
4594
|
+
let i = r(e, po);
|
|
4335
4595
|
return {
|
|
4336
4596
|
path: i,
|
|
4337
4597
|
language: t(i),
|
|
@@ -4360,7 +4620,7 @@ async function Ya(e) {
|
|
|
4360
4620
|
}
|
|
4361
4621
|
//#endregion
|
|
4362
4622
|
//#region src/patterns/enable/teams/preview-modifies/src/lib/components/app-sidebar.svelte?raw
|
|
4363
|
-
var
|
|
4623
|
+
var ho = "<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", go = "<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", _o = "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", vo = "<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", yo = "users", Q = "teams", bo = "team_memberships";
|
|
4364
4624
|
function $(e) {
|
|
4365
4625
|
let t = s.find((t) => t.collectionName === e);
|
|
4366
4626
|
if (!t) throw Error(`teams: missing TEAM_RULE_PATCHES entry for "${e}"`);
|
|
@@ -4372,7 +4632,7 @@ function $(e) {
|
|
|
4372
4632
|
deleteRule: t.deleteRule
|
|
4373
4633
|
};
|
|
4374
4634
|
}
|
|
4375
|
-
var
|
|
4635
|
+
var xo = [
|
|
4376
4636
|
{
|
|
4377
4637
|
name: "teams",
|
|
4378
4638
|
type: "base",
|
|
@@ -4397,7 +4657,7 @@ var no = [
|
|
|
4397
4657
|
name: "owner",
|
|
4398
4658
|
type: "relation",
|
|
4399
4659
|
cascadeDelete: !1,
|
|
4400
|
-
collectionId:
|
|
4660
|
+
collectionId: yo,
|
|
4401
4661
|
maxSelect: 1,
|
|
4402
4662
|
minSelect: 0,
|
|
4403
4663
|
required: !0
|
|
@@ -4443,7 +4703,7 @@ var no = [
|
|
|
4443
4703
|
{
|
|
4444
4704
|
name: "user",
|
|
4445
4705
|
cascadeDelete: !0,
|
|
4446
|
-
collectionId:
|
|
4706
|
+
collectionId: yo,
|
|
4447
4707
|
maxSelect: 1,
|
|
4448
4708
|
minSelect: 0,
|
|
4449
4709
|
required: !0,
|
|
@@ -4503,7 +4763,7 @@ var no = [
|
|
|
4503
4763
|
{
|
|
4504
4764
|
name: "membership_id",
|
|
4505
4765
|
cascadeDelete: !1,
|
|
4506
|
-
collectionId:
|
|
4766
|
+
collectionId: bo,
|
|
4507
4767
|
maxSelect: 1,
|
|
4508
4768
|
minSelect: 0,
|
|
4509
4769
|
required: !1,
|
|
@@ -4613,17 +4873,17 @@ var no = [
|
|
|
4613
4873
|
}
|
|
4614
4874
|
]
|
|
4615
4875
|
}
|
|
4616
|
-
],
|
|
4617
|
-
"./preview-modifies/src/lib/components/app-sidebar.svelte":
|
|
4618
|
-
"./preview-modifies/src/lib/components/nav-user.svelte":
|
|
4619
|
-
"./preview-modifies/src/routes/(app)/+layout.server.ts":
|
|
4620
|
-
"./preview-modifies/src/routes/(app)/+layout.svelte":
|
|
4621
|
-
}),
|
|
4622
|
-
async function
|
|
4876
|
+
], So = /* @__PURE__ */ Object.assign({
|
|
4877
|
+
"./preview-modifies/src/lib/components/app-sidebar.svelte": ho,
|
|
4878
|
+
"./preview-modifies/src/lib/components/nav-user.svelte": go,
|
|
4879
|
+
"./preview-modifies/src/routes/(app)/+layout.server.ts": _o,
|
|
4880
|
+
"./preview-modifies/src/routes/(app)/+layout.svelte": vo
|
|
4881
|
+
}), Co = "./preview-modifies/";
|
|
4882
|
+
async function wo(e) {
|
|
4623
4883
|
return {
|
|
4624
4884
|
creates: [],
|
|
4625
|
-
modifies: Object.entries(
|
|
4626
|
-
let i = r(e,
|
|
4885
|
+
modifies: Object.entries(So).map(([e, n]) => {
|
|
4886
|
+
let i = r(e, Co);
|
|
4627
4887
|
return {
|
|
4628
4888
|
path: i,
|
|
4629
4889
|
language: t(i),
|
|
@@ -4634,23 +4894,23 @@ async function ao(e) {
|
|
|
4634
4894
|
deletes: [],
|
|
4635
4895
|
components: [],
|
|
4636
4896
|
packages: [],
|
|
4637
|
-
collections:
|
|
4897
|
+
collections: xo
|
|
4638
4898
|
};
|
|
4639
4899
|
}
|
|
4640
4900
|
//#endregion
|
|
4641
4901
|
//#region src/patterns/enable/teams/index.ts
|
|
4642
|
-
var
|
|
4643
|
-
async function
|
|
4644
|
-
let t = await
|
|
4645
|
-
if (e.env === "preview") return v(n([t, await
|
|
4646
|
-
let { generate: r } = await import("./chunks/generate.runtime-
|
|
4902
|
+
var To = "enable-teams", Eo = "1.0.0", Do = "src/patterns/enable/teams", Oo = "/enable/teams";
|
|
4903
|
+
async function ko(e) {
|
|
4904
|
+
let t = await mo(e);
|
|
4905
|
+
if (e.env === "preview") return v(n([t, await wo(e)]));
|
|
4906
|
+
let { generate: r } = await import("./chunks/generate.runtime-B8_5O6Qr.js"), i = await r(e), { writeResult: a } = await import("./chunks/write-result-ENWLDQtP.js");
|
|
4647
4907
|
return a(await v(n([t, i])), e);
|
|
4648
4908
|
}
|
|
4649
|
-
var
|
|
4650
|
-
version:
|
|
4651
|
-
slug:
|
|
4652
|
-
source:
|
|
4653
|
-
docs:
|
|
4909
|
+
var Ao = {
|
|
4910
|
+
version: Eo,
|
|
4911
|
+
slug: To,
|
|
4912
|
+
source: Do,
|
|
4913
|
+
docs: Oo,
|
|
4654
4914
|
plan: "pro",
|
|
4655
4915
|
title: "Enable teams",
|
|
4656
4916
|
summary: "Adds multi-tenant teams with memberships, invites, and a sidebar team switcher.",
|
|
@@ -4679,25 +4939,26 @@ var fo = {
|
|
|
4679
4939
|
examples: [],
|
|
4680
4940
|
tests: 36,
|
|
4681
4941
|
baseline: "velastack",
|
|
4682
|
-
generate:
|
|
4683
|
-
},
|
|
4942
|
+
generate: ko
|
|
4943
|
+
}, jo = re.version, Mo = [
|
|
4684
4944
|
Jt,
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
4688
|
-
|
|
4689
|
-
|
|
4690
|
-
|
|
4691
|
-
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
|
|
4695
|
-
|
|
4696
|
-
|
|
4945
|
+
Cn,
|
|
4946
|
+
Kr,
|
|
4947
|
+
Mn,
|
|
4948
|
+
ir,
|
|
4949
|
+
Lr,
|
|
4950
|
+
ii,
|
|
4951
|
+
gi,
|
|
4952
|
+
Oi,
|
|
4953
|
+
Bi,
|
|
4954
|
+
Qi,
|
|
4955
|
+
uo,
|
|
4956
|
+
Ao
|
|
4957
|
+
], No = Object.fromEntries(Mo.map((e) => [e.slug, e])), Po = Mo.reduce((e, t) => {
|
|
4697
4958
|
let n = t.category;
|
|
4698
4959
|
return e[n] ??= [], e[n].push(t), e;
|
|
4699
4960
|
}, {});
|
|
4700
4961
|
//#endregion
|
|
4701
|
-
export { _ as InvalidArgumentError,
|
|
4962
|
+
export { _ as InvalidArgumentError, Po as byCategory, No as bySlug, Mo as patterns, jo as version };
|
|
4702
4963
|
|
|
4703
4964
|
//# sourceMappingURL=index.js.map
|