rivet-design 0.9.8 → 0.9.9
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/mcp/agent-variants/createZeroToOneTool.d.ts +16 -0
- package/dist/mcp/agent-variants/createZeroToOneTool.d.ts.map +1 -1
- package/dist/mcp/agent-variants/createZeroToOneTool.js +31 -2
- package/dist/mcp/agent-variants/createZeroToOneTool.js.map +1 -1
- package/package.json +1 -1
- package/src/ui/dist/assets/{main-CFoJAn2T.js → main-DXMHtjqM.js} +2 -2
- package/src/ui/dist/index.html +1 -1
|
@@ -196,6 +196,22 @@ export type CreateZeroToOneInput = {
|
|
|
196
196
|
* suffix so concurrent calls with the same prompt don't collide.
|
|
197
197
|
*/
|
|
198
198
|
export declare const slugifyPrompt: (prompt: string) => string;
|
|
199
|
+
/**
|
|
200
|
+
* Collapse a candidate workspace root back to the real workspace when it points
|
|
201
|
+
* inside a `.rivet/` tree.
|
|
202
|
+
*
|
|
203
|
+
* The editor bridge can become bound to a previously generated subproject
|
|
204
|
+
* (`<root>/.rivet/<slug>`) — e.g. after the user opens that subproject in the
|
|
205
|
+
* visual editor. Without this guard the next zero-to-one session would resolve
|
|
206
|
+
* its `destinationParent` to that subproject and join `.rivet/<slug>` onto it,
|
|
207
|
+
* producing a nested `<root>/.rivet/<slug>/.rivet/<slug2>`. That nesting breaks
|
|
208
|
+
* preview/history path resolution (everything is rooted at `workspaceRoot`), so
|
|
209
|
+
* generated variants land on disk but render blank on click.
|
|
210
|
+
*
|
|
211
|
+
* Truncating at the segment before the first `.rivet` keeps the single-`.rivet`
|
|
212
|
+
* invariant. Idempotent: a path with no `.rivet` segment is returned unchanged.
|
|
213
|
+
*/
|
|
214
|
+
export declare const normalizeWorkspaceRoot: (candidate: string) => string;
|
|
199
215
|
interface CreateZeroToOneDeps extends ToolDeps {
|
|
200
216
|
/** Optional homedir resolver — overridden in tests. */
|
|
201
217
|
homedir?: () => string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createZeroToOneTool.d.ts","sourceRoot":"","sources":["../../../src/mcp/agent-variants/createZeroToOneTool.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAC3B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAGzE,OAAO,EAEL,wBAAwB,EAIxB,KAAK,sBAAsB,EAC5B,MAAM,aAAa,CAAC;AAQrB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAOxC,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAOhC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;IACzD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAOF;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAI,QAAQ,MAAM,KAAG,MAQ9C,CAAC;
|
|
1
|
+
{"version":3,"file":"createZeroToOneTool.d.ts","sourceRoot":"","sources":["../../../src/mcp/agent-variants/createZeroToOneTool.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAC3B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAGzE,OAAO,EAEL,wBAAwB,EAIxB,KAAK,sBAAsB,EAC5B,MAAM,aAAa,CAAC;AAQrB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAOxC,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAOhC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;IACzD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAOF;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAI,QAAQ,MAAM,KAAG,MAQ9C,CAAC;AAQF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,sBAAsB,GAAI,WAAW,MAAM,KAAG,MAM1D,CAAC;AAeF,UAAU,mBAAoB,SAAQ,QAAQ;IAC5C,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,MAAM,CAAC;IACvB,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IACrC;;;2EAGuE;IACvE,sBAAsB,CAAC,EAAE,CAAC,KAAK,EAAE;QAC/B,WAAW,EAAE,MAAM,CAAC;QACpB,aAAa,EAAE,MAAM,CAAC;QACtB,SAAS,EAAE,MAAM,GAAG,QAAQ,CAAC;KAC9B,KAAK,OAAO,CAAC,sBAAsB,CAAC,CAAC;IACtC,SAAS,CAAC,EAAE;QACV,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;QAChE,sCAAsC,CAAC,EAAE,CAAC,IAAI,EAAE;YAC9C,SAAS,EAAE,MAAM,CAAC;YAClB,cAAc,EAAE,MAAM,CAAC;YACvB,aAAa,EAAE,MAAM,CAAC;YACtB,uBAAuB,EAAE,OAAO,CAAC;YACjC,aAAa,EAAE,OAAO,CAAC;SACxB,KAAK,IAAI,CAAC;QACX;;;;;;WAMG;QACH,uCAAuC,CAAC,EAAE,CAAC,IAAI,EAAE;YAC/C,SAAS,EAAE,MAAM,CAAC;YAClB,oBAAoB,EAAE,MAAM,CAAC;YAC7B,kBAAkB,EAAE,MAAM,CAAC;YAC3B,qBAAqB,EAAE,MAAM,CAAC;YAC9B,cAAc,EAAE,MAAM,CAAC;YACvB,iBAAiB,EAAE,MAAM,CAAC;YAC1B,kBAAkB,EAAE,MAAM,CAAC;YAC3B,aAAa,EAAE,OAAO,GAAG,UAAU,GAAG,MAAM,CAAC;YAC7C,aAAa,EAAE,MAAM,CAAC;YACtB,cAAc,EAAE,MAAM,CAAC;YACvB,eAAe,EAAE,MAAM,CAAC;YACxB,yBAAyB,EAAE,MAAM,CAAC;YAClC,uBAAuB,EAAE,MAAM,CAAC;YAChC,sBAAsB,EAAE,MAAM,CAAC;YAC/B,kBAAkB,EAAE,OAAO,CAAC;YAC5B,mBAAmB,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAC;YACzE,0BAA0B,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;SACxD,KAAK,IAAI,CAAC;KACZ,CAAC;CACH;AAED;;;;;GAKG;AACH,eAAO,MAAM,2BAA2B,GACtC,KAAK,SAAS,EACd,MAAM,mBAAmB,KACxB,IA8LF,CAAC"}
|
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.registerCreateZeroToOneTool = exports.slugifyPrompt = exports.createZeroToOneInput = void 0;
|
|
6
|
+
exports.registerCreateZeroToOneTool = exports.normalizeWorkspaceRoot = exports.slugifyPrompt = exports.createZeroToOneInput = void 0;
|
|
7
7
|
const crypto_1 = require("crypto");
|
|
8
8
|
const fs_1 = __importDefault(require("fs"));
|
|
9
9
|
const os_1 = __importDefault(require("os"));
|
|
@@ -47,6 +47,30 @@ const failed = (code, message) => ({
|
|
|
47
47
|
errorCode: code,
|
|
48
48
|
message,
|
|
49
49
|
});
|
|
50
|
+
/**
|
|
51
|
+
* Collapse a candidate workspace root back to the real workspace when it points
|
|
52
|
+
* inside a `.rivet/` tree.
|
|
53
|
+
*
|
|
54
|
+
* The editor bridge can become bound to a previously generated subproject
|
|
55
|
+
* (`<root>/.rivet/<slug>`) — e.g. after the user opens that subproject in the
|
|
56
|
+
* visual editor. Without this guard the next zero-to-one session would resolve
|
|
57
|
+
* its `destinationParent` to that subproject and join `.rivet/<slug>` onto it,
|
|
58
|
+
* producing a nested `<root>/.rivet/<slug>/.rivet/<slug2>`. That nesting breaks
|
|
59
|
+
* preview/history path resolution (everything is rooted at `workspaceRoot`), so
|
|
60
|
+
* generated variants land on disk but render blank on click.
|
|
61
|
+
*
|
|
62
|
+
* Truncating at the segment before the first `.rivet` keeps the single-`.rivet`
|
|
63
|
+
* invariant. Idempotent: a path with no `.rivet` segment is returned unchanged.
|
|
64
|
+
*/
|
|
65
|
+
const normalizeWorkspaceRoot = (candidate) => {
|
|
66
|
+
const resolved = path_1.default.resolve(candidate);
|
|
67
|
+
const segments = resolved.split(path_1.default.sep);
|
|
68
|
+
const idx = segments.indexOf('.rivet');
|
|
69
|
+
if (idx <= 0)
|
|
70
|
+
return resolved;
|
|
71
|
+
return segments.slice(0, idx).join(path_1.default.sep) || path_1.default.sep;
|
|
72
|
+
};
|
|
73
|
+
exports.normalizeWorkspaceRoot = normalizeWorkspaceRoot;
|
|
50
74
|
/**
|
|
51
75
|
* Returns true when a file-copy root is specific enough to authorize asset
|
|
52
76
|
* reads. Broad roots such as the home directory or filesystem root would let
|
|
@@ -101,7 +125,12 @@ const registerCreateZeroToOneTool = (mcp, deps) => {
|
|
|
101
125
|
// so the user's working dir stays clean — every Rivet artifact
|
|
102
126
|
// (subprojects, variant history, create-project manifests, snapshots)
|
|
103
127
|
// sits inside the single `.rivet/` directory.
|
|
104
|
-
|
|
128
|
+
//
|
|
129
|
+
// Normalize first: if the resolved parent already sits inside a
|
|
130
|
+
// `.rivet/` tree (e.g. the editor was bound to a prior subproject),
|
|
131
|
+
// collapse back to the real workspace root so we never nest one
|
|
132
|
+
// `.rivet/` inside another — which would break preview resolution.
|
|
133
|
+
const workspaceRoot = (0, exports.normalizeWorkspaceRoot)(destinationParent);
|
|
105
134
|
const destinationPath = path_1.default.join(workspaceRoot, '.rivet', slug);
|
|
106
135
|
if (!(0, viteReactTs_1.isDestinationEmpty)(destinationPath)) {
|
|
107
136
|
return jsonResponse(failed('DESTINATION_NOT_EMPTY', `Destination '${destinationPath}' is not empty.`));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createZeroToOneTool.js","sourceRoot":"","sources":["../../../src/mcp/agent-variants/createZeroToOneTool.ts"],"names":[],"mappings":";;;;;;AAAA,mCAAqC;AACrC,4CAAoB;AACpB,4CAAoB;AACpB,gDAAwB;AACxB,+BAA2B;AAG3B,sEAA0E;AAC1E,2CAOqB;AACrB,qCAA8D;AAC9D,iDAA2D;AAC3D,mDAIyB;AAGzB,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAEf,QAAA,oBAAoB,GAAG;IAClC,MAAM,EAAE,MAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACzB,KAAK,EAAE,MAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE;IAChF,iBAAiB,EAAE,MAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACxC,SAAS,EAAE,MAAC,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,EAAE;IACtC,aAAa,EAAE,oCAAwB,CAAC,QAAQ,EAAE;IAClD,SAAS,EAAE,MAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACjC,CAAC;AAWF,MAAM,wBAAwB,GAAG,4BAAoD,CAAC;AACtF,MAAM,0BAA0B,GAAG,MAAC,CAAC,MAAM,CACzC,gCAAgD,CACjD,CAAC;AAEF;;;GAGG;AACI,MAAM,aAAa,GAAG,CAAC,MAAc,EAAU,EAAE;IACtD,MAAM,IAAI,GAAG,MAAM;SAChB,WAAW,EAAE;SACb,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC;SAC3B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAChB,MAAM,MAAM,GAAG,IAAA,oBAAW,EAAC,iBAAiB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC9D,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,MAAM,EAAE,CAAC,CAAC,CAAC,aAAa,MAAM,EAAE,CAAC;AAC5D,CAAC,CAAC;AARW,QAAA,aAAa,iBAQxB;AAEF,MAAM,MAAM,GAAG,CAAC,IAAe,EAAE,OAAe,EAAyB,EAAE,CAAC,CAAC;IAC3E,KAAK,EAAE,QAAQ;IACf,SAAS,EAAE,IAAI;IACf,OAAO;CACR,CAAC,CAAC;AAEH;;;;GAIG;AACH,MAAM,yBAAyB,GAAG,CAAC,IAAY,EAAE,QAAgB,EAAW,EAAE;IAC5E,MAAM,YAAY,GAAG,cAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,CACL,YAAY,KAAK,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;QACvC,YAAY,KAAK,cAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,IAAI,CAC/C,CAAC;AACJ,CAAC,CAAC;AA8DF;;;;;GAKG;AACI,MAAM,2BAA2B,GAAG,CACzC,GAAc,EACd,IAAyB,EACnB,EAAE;IACR,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,YAAE,CAAC,OAAO,CAAC;IAC3C,GAAG,CAAC,IAAI,CACN,4BAA4B,EAC5B,g/BAAg/B,EACh/B,wBAAwB,EACxB,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,MAAM,IAAI,GAAG,OAA+B,CAAC;QAC7C,IAAI,CAAC;YACH,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC;YAC3C,IAAI,SAAS,KAAK,MAAM,EAAE,CAAC;gBACzB,OAAO,YAAY,CACjB,MAAM,CACJ,uBAAuB,EACvB,yEAAyE,SAAS,IAAI,CACvF,CACF,CAAC;YACJ,CAAC;YAED,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACrC,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,EAAE,UAAU,IAAI,EAAE,CAAC;YAC7D,MAAM,UAAU,GAAG,IAAA,iCAAiB,EAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;YACtE,gEAAgE;YAChE,mEAAmE;YACnE,8CAA8C;YAC9C,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;YACxC,MAAM,WAAW,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE;gBAC/C,MAAM,UAAU,GAAG,IAAA,4BAAY,EAAC,CAAC,CAAC,CAAC;gBACnC,OAAO,UAAU,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YAC7D,CAAC,CAAC,CAAC;YACH,MAAM,QAAQ,GAAa,WAAW,CAAC,GAAG,CACxC,CAAC,GAAG,EAAE,EAAE,CACN,uBAAuB,GAAG,8EAA8E,CAC3G,CAAC;YACF,MAAM,eAAe,GAAG,IAAA,wCAAwB,EAC9C,IAAI,CAAC,aAAa,EAAE,eAAe,CACpC,CAAC;YAEF,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,EAAE,IAAI,SAAS,CAAC;YACzD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;YAC9C,gEAAgE;YAChE,+DAA+D;YAC/D,8DAA8D;YAC9D,+DAA+D;YAC/D,oBAAoB;YACpB,MAAM,iBAAiB,GACrB,IAAI,CAAC,iBAAiB,IAAI,WAAW,IAAI,GAAG,EAAE,CAAC;YACjD,IAAI,CAAC,cAAI,CAAC,UAAU,CAAC,iBAAiB,CAAC,EAAE,CAAC;gBACxC,OAAO,YAAY,CACjB,MAAM,CACJ,0BAA0B,EAC1B,4CAA4C,iBAAiB,IAAI,CAClE,CACF,CAAC;YACJ,CAAC;YAED,MAAM,IAAI,GAAG,IAAA,qBAAa,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACxC,wEAAwE;YACxE,+DAA+D;YAC/D,sEAAsE;YACtE,8CAA8C;YAC9C,MAAM,aAAa,GAAG,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"createZeroToOneTool.js","sourceRoot":"","sources":["../../../src/mcp/agent-variants/createZeroToOneTool.ts"],"names":[],"mappings":";;;;;;AAAA,mCAAqC;AACrC,4CAAoB;AACpB,4CAAoB;AACpB,gDAAwB;AACxB,+BAA2B;AAG3B,sEAA0E;AAC1E,2CAOqB;AACrB,qCAA8D;AAC9D,iDAA2D;AAC3D,mDAIyB;AAGzB,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAEf,QAAA,oBAAoB,GAAG;IAClC,MAAM,EAAE,MAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACzB,KAAK,EAAE,MAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE;IAChF,iBAAiB,EAAE,MAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACxC,SAAS,EAAE,MAAC,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,EAAE;IACtC,aAAa,EAAE,oCAAwB,CAAC,QAAQ,EAAE;IAClD,SAAS,EAAE,MAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACjC,CAAC;AAWF,MAAM,wBAAwB,GAAG,4BAAoD,CAAC;AACtF,MAAM,0BAA0B,GAAG,MAAC,CAAC,MAAM,CACzC,gCAAgD,CACjD,CAAC;AAEF;;;GAGG;AACI,MAAM,aAAa,GAAG,CAAC,MAAc,EAAU,EAAE;IACtD,MAAM,IAAI,GAAG,MAAM;SAChB,WAAW,EAAE;SACb,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC;SAC3B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAChB,MAAM,MAAM,GAAG,IAAA,oBAAW,EAAC,iBAAiB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC9D,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,MAAM,EAAE,CAAC,CAAC,CAAC,aAAa,MAAM,EAAE,CAAC;AAC5D,CAAC,CAAC;AARW,QAAA,aAAa,iBAQxB;AAEF,MAAM,MAAM,GAAG,CAAC,IAAe,EAAE,OAAe,EAAyB,EAAE,CAAC,CAAC;IAC3E,KAAK,EAAE,QAAQ;IACf,SAAS,EAAE,IAAI;IACf,OAAO;CACR,CAAC,CAAC;AAEH;;;;;;;;;;;;;;GAcG;AACI,MAAM,sBAAsB,GAAG,CAAC,SAAiB,EAAU,EAAE;IAClE,MAAM,QAAQ,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACzC,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,cAAI,CAAC,GAAG,CAAC,CAAC;IAC1C,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACvC,IAAI,GAAG,IAAI,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC9B,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,cAAI,CAAC,GAAG,CAAC,IAAI,cAAI,CAAC,GAAG,CAAC;AAC3D,CAAC,CAAC;AANW,QAAA,sBAAsB,0BAMjC;AAEF;;;;GAIG;AACH,MAAM,yBAAyB,GAAG,CAAC,IAAY,EAAE,QAAgB,EAAW,EAAE;IAC5E,MAAM,YAAY,GAAG,cAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,CACL,YAAY,KAAK,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;QACvC,YAAY,KAAK,cAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,IAAI,CAC/C,CAAC;AACJ,CAAC,CAAC;AA8DF;;;;;GAKG;AACI,MAAM,2BAA2B,GAAG,CACzC,GAAc,EACd,IAAyB,EACnB,EAAE;IACR,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,YAAE,CAAC,OAAO,CAAC;IAC3C,GAAG,CAAC,IAAI,CACN,4BAA4B,EAC5B,g/BAAg/B,EACh/B,wBAAwB,EACxB,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,MAAM,IAAI,GAAG,OAA+B,CAAC;QAC7C,IAAI,CAAC;YACH,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC;YAC3C,IAAI,SAAS,KAAK,MAAM,EAAE,CAAC;gBACzB,OAAO,YAAY,CACjB,MAAM,CACJ,uBAAuB,EACvB,yEAAyE,SAAS,IAAI,CACvF,CACF,CAAC;YACJ,CAAC;YAED,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACrC,MAAM,eAAe,GAAG,IAAI,CAAC,aAAa,EAAE,UAAU,IAAI,EAAE,CAAC;YAC7D,MAAM,UAAU,GAAG,IAAA,iCAAiB,EAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;YACtE,gEAAgE;YAChE,mEAAmE;YACnE,8CAA8C;YAC9C,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC;YACxC,MAAM,WAAW,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE;gBAC/C,MAAM,UAAU,GAAG,IAAA,4BAAY,EAAC,CAAC,CAAC,CAAC;gBACnC,OAAO,UAAU,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YAC7D,CAAC,CAAC,CAAC;YACH,MAAM,QAAQ,GAAa,WAAW,CAAC,GAAG,CACxC,CAAC,GAAG,EAAE,EAAE,CACN,uBAAuB,GAAG,8EAA8E,CAC3G,CAAC;YACF,MAAM,eAAe,GAAG,IAAA,wCAAwB,EAC9C,IAAI,CAAC,aAAa,EAAE,eAAe,CACpC,CAAC;YAEF,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,EAAE,IAAI,SAAS,CAAC;YACzD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;YAC9C,gEAAgE;YAChE,+DAA+D;YAC/D,8DAA8D;YAC9D,+DAA+D;YAC/D,oBAAoB;YACpB,MAAM,iBAAiB,GACrB,IAAI,CAAC,iBAAiB,IAAI,WAAW,IAAI,GAAG,EAAE,CAAC;YACjD,IAAI,CAAC,cAAI,CAAC,UAAU,CAAC,iBAAiB,CAAC,EAAE,CAAC;gBACxC,OAAO,YAAY,CACjB,MAAM,CACJ,0BAA0B,EAC1B,4CAA4C,iBAAiB,IAAI,CAClE,CACF,CAAC;YACJ,CAAC;YAED,MAAM,IAAI,GAAG,IAAA,qBAAa,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACxC,wEAAwE;YACxE,+DAA+D;YAC/D,sEAAsE;YACtE,8CAA8C;YAC9C,EAAE;YACF,gEAAgE;YAChE,oEAAoE;YACpE,gEAAgE;YAChE,mEAAmE;YACnE,MAAM,aAAa,GAAG,IAAA,8BAAsB,EAAC,iBAAiB,CAAC,CAAC;YAChE,MAAM,eAAe,GAAG,cAAI,CAAC,IAAI,CAAC,aAAa,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;YACjE,IAAI,CAAC,IAAA,gCAAkB,EAAC,eAAe,CAAC,EAAE,CAAC;gBACzC,OAAO,YAAY,CACjB,MAAM,CACJ,uBAAuB,EACvB,gBAAgB,eAAe,iBAAiB,CACjD,CACF,CAAC;YACJ,CAAC;YACD,MAAM,eAAe,GACnB,WAAW,IAAI,yBAAyB,CAAC,WAAW,EAAE,OAAO,EAAE,CAAC;gBAC9D,CAAC,CAAC,cAAI,CAAC,OAAO,CAAC,WAAW,CAAC;gBAC3B,CAAC,CAAC,SAAS,CAAC;YAEhB,MAAM,cAAc,GAAmB;gBACrC,IAAI,EAAE,OAAO;gBACb,aAAa,EAAE,eAAe;gBAC9B,aAAa;gBACb,SAAS,EAAE,MAAM;gBACjB,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC/C,GAAG,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC;oBACzB,eAAe,CAAC,MAAM,GAAG,CAAC;oBAC1B,IAAI,CAAC,aAAa,EAAE,aAAa,KAAK,SAAS;oBAC7C,CAAC,CAAC;wBACE,aAAa,EAAE;4BACb,GAAG,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;4BAChD,GAAG,CAAC,eAAe,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;4BAC1D,GAAG,CAAC,IAAI,CAAC,aAAa,EAAE,aAAa,KAAK,SAAS;gCACjD,CAAC,CAAC,EAAE,aAAa,EAAE,IAAI,CAAC,aAAa,CAAC,aAAa,EAAE;gCACrD,CAAC,CAAC,EAAE,CAAC;yBACR;qBACF;oBACH,CAAC,CAAC,EAAE,CAAC;aACR,CAAC;YAEF,qEAAqE;YACrE,kEAAkE;YAClE,8DAA8D;YAC9D,YAAE,CAAC,SAAS,CAAC,cAAI,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAEjE,MAAM,YAAY,GAAyB;gBACzC,SAAS,EAAE,IAAI,CAAC,SAAS;gBACzB,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,KAAK;gBACL,cAAc;aACf,CAAC;YAEF,qEAAqE;YACrE,+CAA+C;YAC/C,MAAM,MAAM,GAAG,0BAA0B,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;YAClE,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBACpB,OAAO,YAAY,CACjB,MAAM,CAAC,0BAA0B,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CACzD,CAAC;YACJ,CAAC;YAED,MAAM,YAAY,GAAG,IAAI,CAAC,sBAAsB;gBAC9C,CAAC,CAAC,MAAM,IAAI,CAAC,sBAAsB,CAAC;oBAChC,WAAW,EAAE,eAAe;oBAC5B,aAAa;oBACb,SAAS,EAAE,MAAM;iBAClB,CAAC;gBACJ,CAAC,CAAC,SAAS,CAAC;YAEd,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,IAA4B,CAAC,CAAC;YAC9E,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACxD,IAAI,CAAC,SAAS,EAAE,sCAAsC,EAAE,CAAC;oBACvD,SAAS,EAAE,MAAM,CAAC,SAAS;oBAC3B,cAAc,EAAE,UAAU,CAAC,MAAM;oBACjC,aAAa,EAAE,eAAe,CAAC,MAAM;oBACrC,uBAAuB,EAAE,eAAe,CAAC,IAAI,CAC3C,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,KAAK,iBAAiB,CAClD;oBACD,aAAa,EAAE,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,aAAa,CAAC;iBAC1D,CAAC,CAAC;YACL,CAAC;YACD,IAAI,MAAM,CAAC,KAAK,KAAK,sBAAsB,EAAE,CAAC;gBAC5C,OAAO,YAAY,CAAC;oBAClB,SAAS,EAAE,MAAM,CAAC,SAAS;oBAC3B,KAAK,EAAE,sBAAsB;oBAC7B,kBAAkB,EAAE;wBAClB,EAAE,EAAE,MAAM,CAAC,kBAAmB,CAAC,EAAE;wBACjC,IAAI,EAAE,aAAa;wBACnB,OAAO,EAAE,MAAM,CAAC,kBAAmB,CAAC,OAAO;wBAC3C,KAAK,EAAE,MAAM,CAAC,kBAAmB,CAAC,KAAK;wBACvC,aAAa,EAAE,wCAAyB;qBACzC;oBACD,UAAU,EAAE,mBAAmB;oBAC/B,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACzC,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;iBAC7C,CAAC,CAAC;YACL,CAAC;YACD,OAAO,YAAY,CAAC;gBAClB,SAAS,EAAE,MAAM,CAAC,SAAS;gBAC3B,KAAK,EAAE,iBAAiB;gBACxB,aAAa,EAAE;oBACb,EAAE,EAAE,MAAM,CAAC,aAAc,CAAC,EAAE;oBAC5B,IAAI,EAAE,OAAO;oBACb,OAAO,EAAE,MAAM,CAAC,aAAc,CAAC,OAAO;oBACtC,KAAK,EAAE,MAAM,CAAC,aAAc,CAAC,KAAK;oBAClC,aAAa,EAAE,EAAE,MAAM,EAAE,+BAA+B,EAAE;iBAC3D;gBACD,UAAU,EAAE,uBAAuB;gBACnC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACzC,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC7C,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,GACR,GAAG,YAAY,2BAAkB;gBAC/B,CAAC,CAAC,GAAG,CAAC,IAAI;gBACV,CAAC,CAAC,0BAA0B,CAAC;YACjC,MAAM,OAAO,GACX,GAAG,YAAY,KAAK;gBAClB,CAAC,CAAC,GAAG,CAAC,OAAO;gBACb,CAAC,CAAC,6CAA6C,CAAC;YACpD,OAAO,YAAY,CAAC;gBAClB,KAAK,EAAE,QAAQ;gBACf,SAAS,EAAE,IAAI;gBACf,OAAO;aACR,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CACF,CAAC;AACJ,CAAC,CAAC;AAjMW,QAAA,2BAA2B,+BAiMtC;AAEF,MAAM,UAAU,GAAG,CAAC,KAAyB,EAAU,EAAE;IACvD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,qBAAqB,CAAC;IACtD,IAAI,KAAK,GAAG,iBAAiB;QAAE,OAAO,iBAAiB,CAAC;IACxD,IAAI,KAAK,GAAG,iBAAiB;QAAE,OAAO,iBAAiB,CAAC;IACxD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAEF,MAAM,YAAY,GAAG,CAAI,OAAU,EAAE,EAAE,CAAC,CAAC;IACvC,OAAO,EAAE;QACP;YACE,IAAI,EAAE,MAAe;YACrB,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;SAC9B;KACF;CACF,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -345,7 +345,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${ns.d
|
|
|
345
345
|
pointer-events: none;
|
|
346
346
|
display: none;
|
|
347
347
|
`,this.iframeRef.parentElement.appendChild(ns)),ns}removeMouseCaptureOverlay(){var ss;if(!((ss=this.iframeRef)!=null&&ss.parentElement))return;const ns=this.iframeRef.parentElement.querySelector("#rivet-mouse-capture");ns&&ns.remove()}isOverlayInSidebar(ns,ss,os,ls){const us=document.querySelector('[data-cy="element-inspector"]');if(!us)return!1;const ps=us.getBoundingClientRect(),hs=ns+os,ws=ss+ls;return!(hs<=ps.left||ns>=ps.right||ws<=ps.top||ss>=ps.bottom)}getComputedStyles(){if(!this.currentElement||!this.iframeRef)return log$9.warn("Attempt to get computed styles failed: currentElement ",this.currentElement,"iFrameRef:",this.iframeRef),{};const ns=this.iframeRef.contentWindow;if(!ns)return log$9.warn("Attempt to get computed styles failed: iFrameWindow not defined"),{};const ss=ns.getComputedStyle(this.currentElement),os={};for(let ls=0;ls<ss.length;ls++){const us=ss[ls];os[us]=ss.getPropertyValue(us)}return os.background=addSyntheticBackground(os),os}onStylesChanged(ns){return this.onStylesChangedCallback=ns,()=>{this.onStylesChangedCallback=null}}refreshStyles(){const ns=this.getComputedStyles();this.notifyStylesChanged(ns)}setCurrentElement(ns){this.currentElement=ns,ns&&this.refreshStyles()}notifyStylesChanged(ns){this.onStylesChangedCallback&&this.onStylesChangedCallback(ns)}async applyStyle(ns,ss,os){const ls=await this.findElement(ns);if(!ls.ok)return Err(ls.error);const us=ls.value;ns.rivetId&&this.injectRivetId(us,ns.rivetId);try{return us.style[ss]=os,Ok(void 0)}catch(ps){return Err(new StyleApplicationError(ss,os,ps instanceof Error?ps.message:String(ps)))}}async getComputedStylesForElement(ns){const ss=await this.findElement(ns);if(!ss.ok)return Err(ss.error);const os=ss.value;if(!this.iframeRef)return Err(new ElementNotFoundError(ns,"Iframe ref is null"));const ls=this.iframeRef.contentWindow;if(!ls)return Err(new ElementNotFoundError(ns,"Iframe window is null"));try{const us=ls.getComputedStyle(os),ps={};for(let hs=0;hs<us.length;hs++){const ws=us[hs];ps[ws]=us.getPropertyValue(ws)}return ps.background=addSyntheticBackground(ps),Ok(ps)}catch(us){return Err(new ElementNotFoundError(ns,us instanceof Error?us.message:String(us)))}}async findElement(ns){if(!this.iframeRef)return Err(new ElementNotFoundError(ns,"Iframe ref is null"));const ss=getIframeDocument(this.iframeRef);if(!ss)return Err(new ElementNotFoundError(ns,"Cannot access iframe document"));if(ns.rivetId){const os=ss.querySelector(`[data-rivet-id="${ns.rivetId}"]`);if(os)return Ok(os)}if(ns.xpath){const os=getElementByXPath(ss,ns.xpath);if(os)return Ok(os)}if(ns.cssSelector)try{const os=ss.querySelector(ns.cssSelector);if(os)return Ok(os)}catch(os){log$9.warn("Invalid CSS selector:",ns.cssSelector,os)}return Err(new ElementNotFoundError(ns,"Element not found using any identifier strategy"))}injectRivetId(ns,ss){ns.setAttribute("data-rivet-id",ss)}createElementIdentifier(ns){const ss=ns.getAttribute("data-rivet-id"),os=getXPath(ns);let ls;if(ns.id)ls=`#${ns.id}`;else if(ns.className&&typeof ns.className=="string"){const us=ns.className.trim().split(/\s+/).join(".");us&&(ls=`${ns.tagName.toLowerCase()}.${us}`)}return{rivetId:ss||"",xpath:os,cssSelector:ls}}onHMR(ns){var ps;this.hmrCallbacks.push(ns);let ss=null,os=null;const ls=()=>{os&&clearTimeout(os),os=setTimeout(()=>{this.handleIframeLoad()},1e3)};this.iframeRef&&this.hmrCallbacks.length===1&&this.iframeRef.addEventListener("load",this.handleIframeLoad);const us=this.iframeRef?getIframeDocument(this.iframeRef):null;if(us){ss=new MutationObserver(ja=>{ja.some(Va=>{var Wa;const Ga=Va.target;return!((Wa=Ga.closest)!=null&&Wa.call(Ga,'[id^="rivet-"]'))})&&ls()});const hs=us.body??us.documentElement??us,ws=((ps=us.defaultView)==null?void 0:ps.Node)??Node;if(hs instanceof ws)try{ss.observe(hs,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","src","href"],characterData:!0})}catch{}}return()=>{const hs=this.hmrCallbacks.indexOf(ns);hs!==-1&&this.hmrCallbacks.splice(hs,1),ss==null||ss.disconnect(),os&&clearTimeout(os),this.hmrCallbacks.length===0&&this.iframeRef&&this.iframeRef.removeEventListener("load",this.handleIframeLoad)}}forceReload(){return new Promise((ns,ss)=>{var hs;if(!((hs=this.iframeRef)!=null&&hs.contentWindow)){ns();return}let os,ls=!1;const us=()=>{var ws;ls||(ls=!0,clearTimeout(os),(ws=this.iframeRef)==null||ws.removeEventListener("load",ps))},ps=()=>{us(),ns()};os=setTimeout(()=>{us(),ss(new Error("Iframe reload timeout after 10s"))},1e4),this.iframeRef.addEventListener("load",ps);try{this.iframeRef.contentWindow.location.reload()}catch(ws){us(),ss(ws)}})}}class StaticIframeAdapter extends IframeDisplayAdapter{}const STATUS_CIRCLE_BG={pending:"bg-primary",complete:"bg-accent-success",error:"bg-accent-error"},BUBBLE_W=36,BUBBLE_H=28,CARET_SIZE=10,CARET_HALF=CARET_SIZE/2,TIP_X=BUBBLE_W/2,TOTAL_H=BUBBLE_H+CARET_HALF,POPOVER_OFFSET_Y$1=8,ABOVE_THRESHOLD_PCT=.65,PREVIEW_W=200,VIEWPORT_PAD$1=8,clampLeft=($,ns)=>{const ss=$-ns/2,os=window.innerWidth-ns-VIEWPORT_PAD$1;return Math.max(VIEWPORT_PAD$1,Math.min(ss,os))},CommentMarker=({comment:$,index:ns,position:ss,stale:os=!1,onEdit:ls,onHover:us,onHoverEnd:ps})=>{var Ka;const[hs,ws]=reactExports.useState(!1),ja=reactExports.useCallback(Za=>{Za.stopPropagation(),ls($.id)},[$.id,ls]),Ha=ss.y/window.innerHeight>ABOVE_THRESHOLD_PCT,Va=$.instruction,Wa=clampLeft(ss.x,PREVIEW_W)-(ss.x-TIP_X);return jsxRuntimeExports.jsxs("div",{className:"fixed",style:{top:Ha?ss.y:ss.y-TOTAL_H,left:ss.x-TIP_X,zIndex:hs?55:36,opacity:os?.5:1},onMouseEnter:()=>{ws(!0),us==null||us()},onMouseLeave:()=>{ws(!1),ps==null||ps()},children:[jsxRuntimeExports.jsxs("div",{className:"relative cursor-pointer",style:{filter:"drop-shadow(0 1px 3px rgba(0,0,0,0.2))"},onClick:ja,children:[jsxRuntimeExports.jsx("div",{className:"absolute bg-main",style:{width:CARET_SIZE,height:CARET_SIZE,left:(BUBBLE_W-CARET_SIZE)/2,top:Ha?-CARET_HALF:BUBBLE_H-CARET_HALF,transform:"rotate(45deg)",borderRadius:3}}),jsxRuntimeExports.jsxs("div",{className:"relative flex items-center justify-center rounded-lg bg-main",style:{width:BUBBLE_W,height:BUBBLE_H},children:[jsxRuntimeExports.jsx("div",{className:`flex h-5 w-5 items-center justify-center rounded-full ${STATUS_CIRCLE_BG[$.status]}`,children:jsxRuntimeExports.jsx("span",{className:"text-[10px] font-bold leading-none text-white",children:ns+1})}),$.variantRequest?jsxRuntimeExports.jsx("div",{"aria-label":"Direction request","data-testid":"comment-marker-variant-glyph",className:"absolute -right-1 -top-1 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-primary text-white",children:jsxRuntimeExports.jsx(n$8,{className:"h-2.5 w-2.5",weight:"bold"})}):null]})]}),jsxRuntimeExports.jsx(AnimatePresence,{children:hs&&(Va||((Ka=$.images)==null?void 0:Ka.length))&&jsxRuntimeExports.jsxs(motion.div,{className:"absolute rounded-lg bg-main px-3 py-2 shadow-lg",style:{left:Wa,top:Ha?-POPOVER_OFFSET_Y$1:TOTAL_H+POPOVER_OFFSET_Y$1,transformOrigin:Ha?"bottom center":"top center",width:PREVIEW_W},initial:{scale:.96,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.96,opacity:0,transition:{duration:.06,ease:[.55,0,1,.45]}},transition:{duration:.08,ease:[.165,.84,.44,1]},children:[Va?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-left text-xs leading-snug text-content",children:Va}):null,$.images&&$.images.length>0?jsxRuntimeExports.jsx("div",{className:`flex flex-wrap justify-center gap-1 ${Va?"mt-1.5":""}`,children:$.images.map((Za,qa)=>jsxRuntimeExports.jsx("img",{src:Za,alt:`Reference ${qa+1}`,className:"max-h-10 rounded border border-divider"},qa))}):null]})})]})},CommentMarkerLayer=({onEditComment:$,target:ns,iframeRef:ss})=>{const[os,ls]=useAtom(commentsAtom),[us,ps]=reactExports.useState(null),[,hs]=reactExports.useState(0),ws=reactExports.useRef(null),ja=reactExports.useRef(new Map),Ha=reactExports.useRef(new Set),Va=reactExports.useCallback(()=>hs(sl=>sl+1),[]);reactExports.useEffect(()=>{const sl=ss==null?void 0:ss.current;if(!sl)return;let il=null;const al=()=>{const vl=getIframeDocument(sl);!vl||vl===il||(il&&il.removeEventListener("scroll",Va,!0),il=vl,vl.addEventListener("scroll",Va,!0))},cl=()=>{al(),Va()};al(),sl.addEventListener("load",cl),window.addEventListener("resize",Va);const ml=new ResizeObserver(Va);return ml.observe(sl),ws.current=()=>{sl.removeEventListener("load",cl),window.removeEventListener("resize",Va),ml.disconnect(),il&&il.removeEventListener("scroll",Va,!0)},()=>{var vl;return(vl=ws.current)==null?void 0:vl.call(ws)}},[ss,Va]);const Ga=reactExports.useCallback(sl=>{const il=ss==null?void 0:ss.current;il&&restoreCommentPreviewBaselines(il,os.values()),ls(al=>{const cl=new Map(al);return cl.delete(sl),cl})},[ls,ss,os]),Wa=Array.from(os.values()).filter(sl=>previewTargetsEqual(sl.target??BASE_TARGET,ns));if(Wa.length===0)return null;const Ka=(ss==null?void 0:ss.current)??null,Za=Ka?getIframeDocument(Ka):null,qa=(Ka==null?void 0:Ka.getBoundingClientRect())??null,Ja=(sl,il,al,cl)=>{const ml=ja.current.get(sl);if(!Za||!qa)return ml?{position:ml,stale:!0}:null;const vl=resolveElementFromContext(Za,il);if(!vl){if(!Ha.current.has(sl)){const El=resolveElementCandidatesFromContext(Za,il);console.warn("[CommentMarkerLayer] anchor unresolved",{commentId:sl,xpath:il.xpath,rivetId:il.rivetId,byRivetHit:!!El.byRivet,byXPathHit:!!El.byXPath,fallback:ml?"cached-position":"none"}),Ha.current.add(sl)}return ml?{position:ml,stale:!0}:null}Ha.current.delete(sl);const yl=vl.getBoundingClientRect();if(yl.bottom<0||yl.top>qa.height)return null;const wl={x:qa.left+yl.left+al*yl.width,y:qa.top+yl.top+cl*yl.height};return ja.current.set(sl,wl),{position:wl,stale:!1}},Ya=sl=>{if(!sl.dragBox||!qa||!Za)return null;const il=resolveElementFromContext(Za,sl.elementContext);if(!il)return null;const al=il.getBoundingClientRect(),{leftPct:cl,topPct:ml,widthPct:vl,heightPct:yl}=sl.dragBox;return{left:qa.left+al.left+cl*al.width,top:qa.top+al.top+ml*al.height,width:vl*al.width,height:yl*al.height}},Xa=sl=>{if(!qa||!Za)return null;const il=!sl.finalizedVariant&&(sl.selectedVariantIndex??0)===0;if(sl.dragBox&&il)return Ya(sl);const al=resolveElementFromContext(Za,sl.elementContext);if(!al)return null;const cl=al.getBoundingClientRect();return{left:qa.left+cl.left,top:qa.top+cl.top,width:cl.width,height:cl.height}},el=us!=null?os.get(us):void 0,nl=el?Xa(el):null,rl=!!(el!=null&&el.dragBox&&!el.finalizedVariant&&(el.selectedVariantIndex??0)===0);for(const sl of ja.current.keys())os.has(sl)||ja.current.delete(sl);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Wa.map((sl,il)=>{const al=Ja(sl.id,sl.elementContext,sl.pin.elementXPct,sl.pin.elementYPct);return al?jsxRuntimeExports.jsx(CommentMarker,{comment:sl,index:il,position:al.position,stale:al.stale,onDismiss:Ga,onEdit:$,onHover:()=>ps(sl.id),onHoverEnd:()=>ps(null)},sl.id):null}),nl&&jsxRuntimeExports.jsx("div",{"data-comment-hover-overlay":"true",style:{position:"fixed",pointerEvents:"none",zIndex:30,border:rl?"1px dashed var(--color-primary, #FF3300)":"1px solid var(--color-primary-border, #ff6b35)",background:rl?"rgba(255, 51, 0, 0.08)":"transparent",borderRadius:2,boxSizing:"border-box",left:nl.left,top:nl.top,width:nl.width,height:nl.height}})]})},log$8=createLogger("commentPersistence"),commentStorageKey=$=>`rivet:pending-comments:${$}`,appliedDiffStorageKey=$=>`rivet:applied-variant-diff:${$}`,persistAppliedDiff=($,ns)=>{const ss=appliedDiffStorageKey(ns);try{$?localStorage.setItem(ss,JSON.stringify($)):localStorage.removeItem(ss)}catch{}},restoreAppliedDiff=$=>{try{const ns=localStorage.getItem(appliedDiffStorageKey($));return ns?JSON.parse(ns):null}catch{return null}},useSetAppliedVariantDiff=()=>{const $=useSetAtom(appliedVariantDiffAtom),ns=useAtomValue(projectPathAtom);return reactExports.useCallback(ss=>{$(ss),ns&&persistAppliedDiff(ss,ns)},[$,ns])},serializeComments=($,ns)=>{const ss=Array.from($.values()).filter(os=>{var ls;return os.status==="pending"&&((ls=os.target)==null?void 0:ls.kind)!=="variant"}).map(os=>os.styleVariants?{...os,styleVariants:os.styleVariants.map(ls=>ls.codeStatus==="pending"||ls.codeStatus==="error"?{...ls,codeStatus:void 0,codeError:void 0}:{...ls,codeError:void 0}),variantSessionId:void 0}:os);try{localStorage.setItem(commentStorageKey(ns),JSON.stringify(ss))}catch(os){log$8.warn("Failed to persist comments to localStorage:",os)}},deserializeComments=$=>{const ns=commentStorageKey($);try{const ss=localStorage.getItem(ns);if(!ss)return new Map;const ls=JSON.parse(ss).filter(us=>us.status==="pending").map(us=>{var ja;const ps=us.pin,hs=(ps==null?void 0:ps.elementXPct)??(ps==null?void 0:ps.xPct)??.5,ws=(ps==null?void 0:ps.elementYPct)??(ps==null?void 0:ps.yPct)??.5;return{...us,pin:{elementXPct:Number.isFinite(hs)?hs:.5,elementYPct:Number.isFinite(ws)?ws:.5},variantGenerationStatus:us.variantGenerationStatus==="generating"?void 0:us.variantGenerationStatus,variantGenerationError:us.variantGenerationStatus==="generating"?void 0:us.variantGenerationError,styleVariants:(ja=us.styleVariants)!=null&&ja.every(Ha=>!Ha.changeSpec)?void 0:us.styleVariants,previewBaselineStyle:void 0}});return new Map(ls.map(us=>[us.id,us]))}catch(ss){log$8.warn("Failed to restore comments from localStorage, clearing bad key:",ss);try{localStorage.removeItem(ns)}catch{}return new Map}},intersectWithIframeViewport=($,ns,ss)=>{const os=Math.max(0,$.left),ls=Math.max(0,$.top),us=Math.min(ns,$.right),ps=Math.min(ss,$.bottom),hs=us-os,ws=ps-ls;return hs<=0||ws<=0?null:{left:os,top:ls,right:us,bottom:ps,width:hs,height:ws}},CAROUSEL_BAR_HEIGHT=36,CAROUSEL_BAR_GAP=8,carouselPillIsBelow=$=>$.top-8<CAROUSEL_BAR_HEIGHT+CAROUSEL_BAR_GAP,BAR_HEIGHT=CAROUSEL_BAR_HEIGHT,BAR_GAP=CAROUSEL_BAR_GAP,BAR_WIDTH=220,CONTROL_MARGIN=8,ORIGINAL_VARIANT_LABEL="Original",SPARKLE_FRAMES=["⡡⠊⢔⠡","⠊⡰⡡⡘","⢔⢅⠈⢢","⡁⢂⠆⡍","⢔⠨⢑⢐","⠨⡑⡠⠊"],clampToViewport=($,ns,ss)=>ns>ss?ns:Math.min(Math.max($,ns),ss),resolveOverlayPosition=($,ns,ss)=>{const os=ns.top+$.top,ls=os+$.height,us=ns.left+$.left+$.width/2,ps=window.innerWidth-ss-CONTROL_MARGIN,hs=clampToViewport(us-ss/2,CONTROL_MARGIN,ps),Ha=!(os-CONTROL_MARGIN>=BAR_HEIGHT+BAR_GAP),Va=Ha?ls+BAR_GAP:os-BAR_HEIGHT-BAR_GAP;return{top:clampToViewport(Va,CONTROL_MARGIN,window.innerHeight-BAR_HEIGHT-CONTROL_MARGIN),left:hs,below:Ha}},CommentCarouselLayer=({onCommentClose:$})=>{const ns=usePostHog(),[ss,os]=useAtom(commentsAtom),ls=useAtomValue(globalChangeTrackerAtom),us=useAtomValue(iframeRefAtom),ps=useAtomValue(activeCarouselCommentIdAtom),hs=useSetAtom(activeCarouselCommentIdAtom),ws=useSetAppliedVariantDiff(),ja=useStore(),[Ha,Va]=reactExports.useState(0),[Ga,Wa]=reactExports.useState(null),Ka=reactExports.useRef(null),Za=reactExports.useRef(!1),[qa,Ja]=reactExports.useState(0),Ya=reactExports.useRef(null),Xa=reactExports.useRef(!1),el=reactExports.useRef(ss);el.current=ss;const nl=reactExports.useRef(new Map),rl=reactExports.useRef(new Set),sl=reactExports.useCallback(()=>{Za.current||(Za.current=!0,requestAnimationFrame(()=>{Za.current=!1,Va(Ll=>Ll+1)}))},[]),il=reactExports.useCallback(Ll=>{Wa(Ll),Ka.current!==null&&window.clearTimeout(Ka.current),Ka.current=window.setTimeout(()=>{Wa(null)},160)},[]),al=reactExports.useCallback(async(Ll,Kl)=>{try{return(await fetch("/api/design/apply-variant-diff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({diff:Ll,reverse:Kl})})).ok}catch{return!1}},[]),cl=reactExports.useCallback(async(Ll,Kl)=>{var nc;if(!Xa.current){Xa.current=!0;try{const _l=ja.get(appliedVariantDiffAtom);if(_l)if(await al(_l.diff,!0))ws(null);else return;if(Kl>0){const uc=el.current.get(Ll),oc=(uc==null?void 0:uc.selectedVariantIndex)??0,fc=(nc=uc==null?void 0:uc.styleVariants)==null?void 0:nc[Kl-1];oc===Kl&&(fc==null?void 0:fc.codeStatus)==="ready"&&fc.codeDiff&&await al(fc.codeDiff,!1)&&ws({commentId:Ll,variantIndex:Kl,diff:fc.codeDiff})}}finally{Xa.current=!1}}},[al,ws,ja]),ml=reactExports.useCallback((Ll,Kl)=>{const nc=el.current.get(Ll);nc!=null&&nc.finalizedVariant||(os(_l=>{const uc=_l.get(Ll);if(!(uc!=null&&uc.styleVariants)||uc.styleVariants.length===0)return _l;const oc=uc.styleVariants.length+1,fc=Math.min(Math.max(uc.selectedVariantIndex??0,0),oc-1),Xl=((fc+Kl)%oc+oc)%oc;if(Xl===fc)return _l;ns==null||ns.capture("comment_carousel_navigate",{variant_index:Xl,variant_count:uc.styleVariants.length});const ec=new Map(_l);return ec.set(Ll,{...uc,selectedVariantIndex:Xl}),ec}),il(Ll),Ya.current!==null&&window.clearTimeout(Ya.current),Ya.current=window.setTimeout(()=>{const _l=el.current.get(Ll),uc=(_l==null?void 0:_l.selectedVariantIndex)??0;cl(Ll,uc)},300))},[ns,il,os,cl]),vl=reactExports.useCallback(Ll=>{const Kl=el.current.get(Ll);if(!(Kl!=null&&Kl.styleVariants)||Kl.styleVariants.length===0)return;const nc=Kl.styleVariants.length+1,_l=Math.min(Math.max(Kl.selectedVariantIndex??0,0),nc-1);ns==null||ns.capture("comment_variant_apply_clicked",{variant_index:_l,variant_count:Kl.styleVariants.length});const uc=_l===0?void 0:Kl.styleVariants[_l-1],oc=ja.get(appliedVariantDiffAtom);oc&&(oc.variantIndex!==_l&&al(oc.diff,!0),ws(null)),os(fc=>{const Xl=fc.get(Ll);if(!Xl)return fc;const ec=new Map(fc);return ec.set(Ll,{...Xl,finalizedVariant:uc,variantGenerationStatus:void 0,variantGenerationError:void 0}),ec}),Ya.current!==null&&(window.clearTimeout(Ya.current),Ya.current=null),hs(null),$==null||$()},[ns,os,al,ws,ja,$]);reactExports.useEffect(()=>{const Ll=us==null?void 0:us.current;if(!Ll)return;let Kl=null;const nc=()=>{const uc=getIframeDocument(Ll);!uc||uc===Kl||(Kl&&Kl.removeEventListener("scroll",sl,!0),Kl=uc,uc.addEventListener("scroll",sl,!0))},_l=()=>{nc(),sl()};return nc(),Ll.addEventListener("load",_l),window.addEventListener("resize",sl),()=>{Ll.removeEventListener("load",_l),window.removeEventListener("resize",sl),Kl&&Kl.removeEventListener("scroll",sl,!0)}},[us,sl]),reactExports.useEffect(()=>ls.onChange(()=>Ja(Kl=>Kl+1)),[ls]),reactExports.useEffect(()=>{const Ll=us==null?void 0:us.current,Kl=Ll?getIframeDocument(Ll):null;if(!Kl)return;const nc=ls.getStyleChanges(),_l=new Map;for(const oc of nc){const fc=oc.elementId.xpath,Xl=_l.get(fc);if(Xl){Xl.push(oc);continue}_l.set(fc,[oc])}const uc=[];for(const oc of ss.values()){const fc=oc.styleVariants;if(!fc||fc.length===0)continue;const Xl=getStylableElementFromContext(Kl,oc.elementContext);if(!Xl)continue;let ec=oc.previewBaselineStyle;if(ec===void 0){ec=Xl.getAttribute("style")??"";const Sc=Kl.defaultView,Cc=Xl.getBoundingClientRect();nl.current.set(oc.id,{pageLeft:((Sc==null?void 0:Sc.scrollX)??0)+Cc.left,pageTop:((Sc==null?void 0:Sc.scrollY)??0)+Cc.top,width:Cc.width,height:Cc.height}),uc.push({id:oc.id,baseline:ec})}Xl.setAttribute("style",ec);const Ac=_l.get(oc.elementContext.xpath)??[];for(const Sc of Ac)Xl.style.setProperty(toKebabProperty(String(Sc.property)),Sc.newValue)}uc.length>0&&os(oc=>{let fc=null;for(const{id:Xl,baseline:ec}of uc){const Ac=oc.get(Xl);!Ac||Ac.previewBaselineStyle!==void 0||(fc||(fc=new Map(oc)),fc.set(Xl,{...Ac,previewBaselineStyle:ec}))}return fc??oc}),sl()},[ss,us,os,ls,qa,sl]),reactExports.useEffect(()=>{if(!ps)return;const Ll=Kl=>{var oc;if(Kl.key!=="ArrowLeft"&&Kl.key!=="ArrowRight"&&Kl.key!=="Enter")return;const nc=(oc=Kl.target)==null?void 0:oc.tagName;if(nc==="INPUT"||nc==="TEXTAREA"||nc==="SELECT")return;const _l=el.current.get(ps);if(!(_l!=null&&_l.styleVariants)||_l.styleVariants.length===0)return;if(Kl.preventDefault(),Kl.key==="Enter"){vl(ps);return}const uc=Kl.key==="ArrowLeft"?-1:1;ml(ps,uc)};return window.addEventListener("keydown",Ll,{capture:!0}),()=>window.removeEventListener("keydown",Ll,{capture:!0})},[ps,ml,vl]),reactExports.useEffect(()=>()=>{Ka.current!==null&&window.clearTimeout(Ka.current),Ya.current!==null&&window.clearTimeout(Ya.current)},[]),reactExports.useEffect(()=>{if(ps)return()=>{const Kl=ja.get(appliedVariantDiffAtom);Kl&&(fetch("/api/design/apply-variant-diff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({diff:Kl.diff,reverse:!0})}),ws(null))}},[ps,ws,ja]);const yl=ps?ss.get(ps):void 0;if(!yl)return null;const wl=(us==null?void 0:us.current)??null;if(!wl)return null;const El=wl.getBoundingClientRect(),pl=getIframeDocument(wl);if(!pl)return null;const Al=getStylableElementFromContext(pl,yl.elementContext),ll=nl.current.get(yl.id);if(Al)rl.current.delete(yl.id);else if(!rl.current.has(yl.id)){const Ll=resolveElementCandidatesFromContext(pl,yl.elementContext);console.warn("[CommentCarouselLayer] anchor unresolved",{commentId:yl.id,xpath:yl.elementContext.xpath,rivetId:yl.elementContext.rivetId,byRivetHit:!!Ll.byRivet,byXPathHit:!!Ll.byXPath,fallback:ll?"baseline-rect":"none"}),rl.current.add(yl.id)}if(!Al&&!ll)return null;const dl=pl.defaultView,fl=(dl==null?void 0:dl.scrollX)??0,ul=(dl==null?void 0:dl.scrollY)??0,bl=Al?Al.getBoundingClientRect():{left:ll.pageLeft-fl,top:ll.pageTop-ul,width:ll.width,height:ll.height,right:ll.pageLeft-fl+ll.width,bottom:ll.pageTop-ul+ll.height},hl=intersectWithIframeViewport(bl,wl.clientWidth,wl.clientHeight);if(!hl)return null;const Sl=ll?{left:ll.pageLeft-fl,top:ll.pageTop-ul,width:ll.width,height:ll.height}:hl,kl=yl.styleVariants,Ol=!!kl&&kl.length>0&&kl.every(Ll=>Ll.changeSpec!=="")&&!yl.finalizedVariant,Tl=kl?kl.length+1:1,Il=kl?Math.min(Math.max(yl.selectedVariantIndex??0,0),Tl-1):0,zl=kl&&Il>0?kl[Il-1]:void 0,Nl=El.left+Sl.left,Bl=El.top+Sl.top,Zl=Sl.width,Gl=Sl.height,{dragBox:ql}=yl,cc=ql?El.left+bl.left+ql.leftPct*bl.width:0,gc=ql?El.top+bl.top+ql.topPct*bl.height:0,pc=ql?ql.widthPct*bl.width:0,Jl=ql?ql.heightPct*bl.height:0,bc=!!kl&&kl.some(Ll=>Ll.codeStatus==="pending"||Ll.changeSpec===""),Hl=!!kl&&kl.length>0&&Il===0,Ql=!yl.finalizedVariant&&bc,Yl=!yl.finalizedVariant&&!Ql&&Hl&&!!ql;if(!Ql&&!Yl&&!Ol)return null;let ac=null;if(Ol&&kl){const Ll=Il===0?ORIGINAL_VARIANT_LABEL:kl[Il-1].label,{top:Kl,left:nc}=resolveOverlayPosition(Sl,El,BAR_WIDTH),_l=Ga===yl.id,uc=yl.id;ac=jsxRuntimeExports.jsxs(motion.div,{"data-rivet-carousel-pill":!0,className:"pointer-events-none fixed z-[48] flex items-center gap-1 rounded-lg border border-primary-border bg-main px-1 py-1 shadow-lg",style:{top:Kl,left:nc,width:BAR_WIDTH},initial:{opacity:0,scale:.82,y:-4},animate:{opacity:1,scale:_l?.985:1,y:0},transition:{type:"spring",stiffness:500,damping:28,mass:.8},onClick:oc=>oc.stopPropagation(),onKeyDown:oc=>{if(oc.key==="ArrowLeft"){oc.preventDefault(),ml(uc,-1);return}if(oc.key==="ArrowRight"){oc.preventDefault(),ml(uc,1);return}(oc.key==="Enter"||oc.key===" ")&&(oc.preventDefault(),vl(uc))},children:[jsxRuntimeExports.jsx("button",{type:"button",className:"pointer-events-auto flex h-6 w-6 shrink-0 items-center justify-center rounded text-content-muted hover:text-content disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Previous variation",onClick:oc=>{oc.stopPropagation(),ml(uc,-1)},disabled:_l||!!yl.finalizedVariant,children:jsxRuntimeExports.jsx(s$9,{className:"h-3.5 w-3.5",weight:"bold"})}),jsxRuntimeExports.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:jsxRuntimeExports.jsx(AnimatePresence,{mode:"wait",initial:!1,children:jsxRuntimeExports.jsxs(motion.span,{className:"flex min-w-0 items-center truncate text-xs font-medium text-content",initial:{opacity:0,y:4},animate:{opacity:_l?.7:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.14},children:[jsxRuntimeExports.jsx("span",{className:"truncate",children:Ll}),(zl==null?void 0:zl.codeStatus)==="error"&&jsxRuntimeExports.jsx("span",{className:"ml-1.5 shrink-0 text-accent-error","aria-label":"Code generation failed",children:"!"})]},`overlay-variant-label-${uc}-${Il}`)})}),jsxRuntimeExports.jsx("button",{type:"button",className:"pointer-events-auto flex h-6 w-6 shrink-0 items-center justify-center rounded text-content-muted hover:text-content","aria-label":"Apply this direction",onClick:oc=>{oc.stopPropagation(),vl(uc)},children:jsxRuntimeExports.jsx(n$7,{className:"h-3.5 w-3.5",weight:"bold"})}),jsxRuntimeExports.jsx("button",{type:"button",className:"pointer-events-auto flex h-6 w-6 shrink-0 items-center justify-center rounded text-content-muted hover:text-content disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Next variation",onClick:oc=>{oc.stopPropagation(),ml(uc,1)},disabled:_l||!!yl.finalizedVariant,children:jsxRuntimeExports.jsx(s$8,{className:"h-3.5 w-3.5",weight:"bold"})})]},`pill-${uc}`)}const lc=Ql?jsxRuntimeExports.jsx(motion.div,{className:"pointer-events-none fixed z-[47]",style:{left:Nl,top:Bl,width:Zl,height:Gl,border:"1px dashed var(--color-primary, #FF3300)",background:"rgba(255, 51, 0, 0.06)",borderRadius:2,boxSizing:"border-box"},initial:{opacity:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:1.04},transition:{duration:.22,ease:[.32,.72,.34,1]},children:jsxRuntimeExports.jsx("div",{className:"rivet-sparkle absolute left-0 top-0 overflow-hidden font-mono text-sm leading-none text-primary",style:{transform:"translateY(-100%)",height:"1em"},"aria-hidden":"true",children:jsxRuntimeExports.jsx("div",{className:"rivet-sparkle-strip",children:SPARKLE_FRAMES.map((Ll,Kl)=>jsxRuntimeExports.jsx("span",{className:"block",style:{height:"1em",lineHeight:"1em"},children:Ll},Kl))})})},`gen-${yl.id}`):null,Dl=Yl?jsxRuntimeExports.jsx(motion.div,{className:"pointer-events-none fixed z-[47]",style:{left:cc,top:gc,width:pc,height:Jl,border:"1px dashed var(--color-primary, #FF3300)",background:"rgba(255, 51, 0, 0.08)",borderRadius:2,boxSizing:"border-box"},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15,ease:[.32,.72,.34,1]}},`drag-${yl.id}`):null;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(AnimatePresence,{children:lc??Dl}),jsxRuntimeExports.jsx(AnimatePresence,{children:ac})]})};function CommentReferenceChip({reference:$,onRemove:ns}){return jsxRuntimeExports.jsxs("span",{className:"inline-flex max-w-[180px] items-center gap-1 rounded-full border border-divider bg-main-light px-2 py-0.5 text-[11px] text-content",children:[jsxRuntimeExports.jsx(n$9,{className:"h-3 w-3 shrink-0 text-content-muted",weight:"bold"}),jsxRuntimeExports.jsx("span",{className:"truncate",title:$.label,children:$.label}),jsxRuntimeExports.jsx("button",{type:"button",onClick:ns,"aria-label":`Remove reference to ${$.label}`,className:"-mr-0.5 rounded-full p-0.5 text-content-muted transition-colors hover:bg-divider hover:text-content",children:jsxRuntimeExports.jsx(n$1,{className:"h-2.5 w-2.5",weight:"bold"})})]})}const log$7=createLogger("CommentReferencePicker"),dedupeKey=($,ns)=>`${$}:${ns}`,optionDomId=$=>`direction-reference-option-${$}`,targetsSelf=($,ns,ss)=>$.kind==="variant"&&$.sessionId===ns&&$.variantId===ss;function CommentReferencePicker({attached:$,commentTarget:ns,onChange:ss,onClose:os}){const ls=useAtomValue(agentVariantsSnapshotAtom),us=useAtomValue(projectPathAtom),ps=reactExports.useRef(null),hs=reactExports.useRef([]),ws=reactExports.useRef(!1),[ja,Ha]=reactExports.useState([]),[Va,Ga]=reactExports.useState(0),Wa=reactExports.useCallback(al=>{ps.current=al,al&&!ws.current&&(ws.current=!0,al.focus())},[]),Ka=reactExports.useMemo(()=>new Set($.map(al=>dedupeKey(al.sessionId,al.variantId))),[$]);reactExports.useEffect(()=>{let al=!1;const cl=us?`?projectPath=${encodeURIComponent(us)}`:"";return(async()=>{try{const ml=await fetch(`/api/variants/history${cl}`,{credentials:"same-origin"});if(!ml.ok)return;const vl=await ml.json();if(al)return;const yl=(vl.variants??[]).filter(wl=>{var El;return((El=wl.preview)==null?void 0:El.kind)==="static"});Ha(yl)}catch(ml){log$7.warn("failed to load past directions for picker",ml)}})(),()=>{al=!0}},[us]),reactExports.useEffect(()=>{const al=ml=>{const vl=ps.current;vl&&(vl.contains(ml.target)||os())},cl=ml=>{ml.key==="Escape"&&os()};return window.addEventListener("pointerdown",al),window.addEventListener("keydown",cl),()=>{window.removeEventListener("pointerdown",al),window.removeEventListener("keydown",cl)}},[os]);const Za=reactExports.useMemo(()=>ls.active?ls.variants.filter(al=>al.status==="succeeded").filter(al=>!targetsSelf(ns,ls.sessionId,al.workItemId)).map(al=>({key:dedupeKey(ls.sessionId,al.workItemId),reference:{sessionId:ls.sessionId,variantId:al.workItemId,label:al.label||"Direction",origin:"live"}})):[],[ls,ns]),qa=reactExports.useMemo(()=>ja.filter(al=>!targetsSelf(ns,al.sessionId,al.variantId)).map(al=>({key:dedupeKey(al.sessionId,al.variantId),reference:{sessionId:al.sessionId,variantId:al.variantId,label:al.label||"Direction",origin:"history"},brief:al.brief})),[ja,ns]),Ja=reactExports.useMemo(()=>{const al=new Set(Za.map(cl=>cl.key));return qa.filter(cl=>!al.has(cl.key))},[Za,qa]),Ya=reactExports.useMemo(()=>{const al=[];return Za.length>0&&al.push({heading:"This session",rows:Za}),Ja.length>0&&al.push({heading:"Directions",rows:Ja}),al},[Za,Ja]),Xa=reactExports.useMemo(()=>Ya.flatMap(al=>al.rows),[Ya]),el=reactExports.useMemo(()=>{const al=new Map;return Xa.forEach((cl,ml)=>al.set(cl.key,ml)),al},[Xa]),nl=reactExports.useCallback(al=>{const cl=al.key;Ka.has(cl)?ss($.filter(ml=>dedupeKey(ml.sessionId,ml.variantId)!==cl)):ss([...$,al.reference])},[$,Ka,ss]),rl=Va<Xa.length?Va:0,sl=al=>{var cl;Ga(al),(cl=hs.current[al])==null||cl.scrollIntoView({block:"nearest"})},il=al=>{if(al.key==="Escape"){al.preventDefault(),os();return}const cl=Xa.length;if(cl!==0)switch(al.key){case"ArrowDown":{al.preventDefault(),sl((rl+1)%cl);break}case"ArrowUp":{al.preventDefault(),sl((rl-1+cl)%cl);break}case"Enter":case" ":{al.preventDefault();const ml=Xa[rl];ml&&nl(ml);break}}};return jsxRuntimeExports.jsx("div",{ref:Wa,tabIndex:-1,onKeyDown:il,className:"max-h-72 w-72 overflow-y-auto rounded-lg border border-divider bg-main shadow-2xl focus:outline-none",role:"listbox","aria-label":"Reference a direction","aria-activedescendant":Xa.length>0?optionDomId(rl):void 0,children:Ya.length===0?jsxRuntimeExports.jsx("div",{className:"px-3 py-4 text-xs text-content-muted",children:"No directions available to reference yet."}):Ya.map(al=>jsxRuntimeExports.jsx(PickerSection,{section:al,attachedKeys:Ka,highlightedIndex:rl,indexOf:cl=>el.get(cl)??-1,itemRefs:hs,onToggle:nl,onHover:Ga},al.heading))})}function PickerSection({section:$,attachedKeys:ns,highlightedIndex:ss,indexOf:os,itemRefs:ls,onToggle:us,onHover:ps}){return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"sticky top-0 z-10 border-b border-divider bg-main px-3 py-1.5 text-[10px] font-medium uppercase tracking-wider text-content-muted",children:$.heading}),jsxRuntimeExports.jsx("ul",{className:"py-1",children:$.rows.map(hs=>{const ws=ns.has(hs.key),ja=os(hs.key),Ha=ja===ss;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",id:optionDomId(ja),ref:Va=>{ls.current[ja]=Va},role:"option",onClick:()=>us(hs),onMouseEnter:()=>ps(ja),"aria-selected":ws,className:`group flex w-full items-start gap-2 px-3 py-2 text-left transition-colors ${Ha?"bg-main-hover":"hover:bg-main-input"}`,children:[jsxRuntimeExports.jsx("span",{className:`mt-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded border ${ws?"border-primary bg-primary text-white":"border-divider text-transparent group-hover:border-content-muted"}`,children:jsxRuntimeExports.jsx(n$7,{className:"h-2.5 w-2.5",weight:"bold"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm text-content",children:hs.reference.label}),hs.brief?jsxRuntimeExports.jsx("span",{className:"block truncate text-[11px] leading-snug text-content-muted",children:hs.brief}):null]})]})},hs.key)})})]})}const MIN_VARIANT_COUNT=2,MAX_VARIANT_COUNT=5,clampVariantCount=$=>Math.min(Math.max($,MIN_VARIANT_COUNT),MAX_VARIANT_COUNT),useCommentVariantGeneration=()=>{const $=useSetAtom(commentsAtom),ns=usePostHog();return{generateVariantsForComment:reactExports.useCallback(async({commentId:os,instruction:ls,elementContext:us,requestedVariantCount:ps,onVariantsReady:hs})=>{const ws=clampVariantCount(ps);$(ja=>{const Ha=ja.get(os);if(!Ha)return ja;const Va=new Map(ja);return Va.set(os,{...Ha,variantGenerationStatus:"generating",variantGenerationError:void 0,requestedVariantCount:ws,styleVariants:Array.from({length:ws},(Ga,Wa)=>({label:`Direction ${Wa+1}`,summary:"",changeSpec:""})),selectedVariantIndex:1,finalizedVariant:void 0}),Va}),ns==null||ns.capture("variant_directions_generate_started",{instruction_length:ls.length,variant_count:ws});try{const{computedStyles:ja,...Ha}=us,Va=await fetch("/api/design/comment-variations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instruction:ls,variantCount:ws,element:Ha})}),Ga=await Va.json().catch(()=>({}));if(!Va.ok)throw new Error(typeof Ga.error=="string"?Ga.error:"Could not generate variations");const Wa=Ga.variants;if(!Array.isArray(Wa)||Wa.length!==ws)throw new Error("Invalid variation response");const Ka=Wa;if($(Za=>{const qa=Za.get(os);if(!qa)return Za;const Ja=1,Ya=Ka.length+1,Xa=typeof qa.selectedVariantIndex=="number"?Math.min(Math.max(qa.selectedVariantIndex,0),Ya-1):Ja,el=new Map(Za);return el.set(os,{...qa,styleVariants:Ka,selectedVariantIndex:Xa,variantGenerationStatus:"idle",variantGenerationError:void 0,requestedVariantCount:ws,finalizedVariant:void 0}),el}),ns==null||ns.capture("variant_directions_generate_completed",{variant_count:Ka.length}),hs){const Za=Ka.map((qa,Ja)=>({index:Ja+1,label:qa.label,changeSpec:qa.changeSpec??""})).filter(qa=>qa.changeSpec.trim().length>0);Za.length>0&&hs({commentId:os,sessionId:crypto.randomUUID(),instruction:ls,elementContext:us,variants:Za})}}catch(ja){const Ha=ja instanceof Error?ja.message:"Could not generate variations";$(Va=>{const Ga=Va.get(os);if(!Ga)return Va;const Wa=new Map(Va);return Wa.set(os,{...Ga,variantGenerationStatus:void 0,variantGenerationError:void 0,requestedVariantCount:void 0,styleVariants:void 0,selectedVariantIndex:void 0,finalizedVariant:void 0}),Wa}),ns==null||ns.capture("variant_directions_generate_failed",{error_message:Ha})}},[ns,$])}},parseSSELine=$=>{if(!$.startsWith("data: "))return null;try{return JSON.parse($.slice(6))}catch{return null}},useVariantCodeGeneration=()=>{const $=useSetAtom(commentsAtom),ns=useSetAppliedVariantDiff(),ss=useStore(),os=usePostHog();return{startCodeGeneration:reactExports.useCallback(async({commentId:us,sessionId:ps,instruction:hs,elementContext:ws,variants:ja})=>{var Wa,Ka;$(Za=>{const qa=Za.get(us);if(!(qa!=null&&qa.styleVariants))return Za;const Ja=new Map(Za),Ya=new Set(ja.map(Xa=>Xa.index));return Ja.set(us,{...qa,variantSessionId:ps,styleVariants:qa.styleVariants.map((Xa,el)=>Ya.has(el+1)?{...Xa,codeStatus:"pending"}:Xa)}),Ja}),os==null||os.capture("variant_code_gen_started",{variant_count:ja.length,instruction_length:hs.length});let Ha=0,Va=0;const Ga=new AbortController;registerVariantGeneration(us,Ga);try{const Za=ss.get(appliedVariantDiffAtom),{computedStyles:qa,...Ja}=ws,Ya=await fetch("/api/design/generate-variant-code",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:ps,instruction:hs,element:Ja,variants:ja,currentAppliedDiff:Za==null?void 0:Za.diff}),signal:Ga.signal});if(!Ya.ok||!Ya.body){os==null||os.capture("variant_code_gen_failed",{variant_count:ja.length,status:Ya.status,reason:Ya.body?"non_ok_response":"missing_body"});return}const Xa=Ya.body.getReader(),el=new TextDecoder;let nl="";for(;;){const{done:rl,value:sl}=await Xa.read();if(rl)break;nl+=el.decode(sl,{stream:!0});const il=nl.split(`
|
|
348
|
-
`);nl=il.pop()??"";for(const al of il){const cl=parseSSELine(al.trim());if(cl!=null&&cl.type){if(cl.type==="variant_completed"){const ml=cl.variantIndex,vl=cl.diff;Ha+=1,os==null||os.capture("variant_code_gen_variant_ready",{variant_index:ml,variant_count:ja.length}),$(El=>{const pl=El.get(us);if(!(pl!=null&&pl.styleVariants))return El;const Al=new Map(El),ll=[...pl.styleVariants],dl=ml-1;return ll[dl]&&(ll[dl]={...ll[dl],codeStatus:"ready",codeDiff:vl}),Al.set(us,{...pl,styleVariants:ll}),Al});const yl=ss.get(activeCarouselCommentIdAtom),wl=ss.get(appliedVariantDiffAtom);yl===us&&!wl&&((Wa=ss.get(commentsAtom).get(us))==null?void 0:Wa.selectedVariantIndex)===ml&&!((Ka=ss.get(commentsAtom).get(us))!=null&&Ka.finalizedVariant)&&(ns({commentId:us,variantIndex:ml,diff:vl}),fetch("/api/design/apply-variant-diff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({diff:vl,reverse:!1})}).then(El=>{El.ok||ns(null)}).catch(()=>{ns(null)}))}else if(cl.type==="variant_error"){const ml=cl.variantIndex,vl=cl.error;Va+=1,os==null||os.capture("variant_code_gen_variant_failed",{variant_index:ml,variant_count:ja.length,error_message:vl}),$(yl=>{const wl=yl.get(us);if(!(wl!=null&&wl.styleVariants))return yl;const El=new Map(yl),pl=[...wl.styleVariants],Al=ml-1;return pl[Al]&&(pl[Al]={...pl[Al],codeStatus:"error",codeError:vl}),El.set(us,{...wl,styleVariants:pl}),El})}}}}os==null||os.capture("variant_code_gen_completed",{variant_count:ja.length,success_count:Ha,error_count:Va})}catch(Za){const qa=Za instanceof DOMException&&Za.name==="AbortError",Ja=Za instanceof Error?Za.message:"Direction code generation failed";os==null||os.capture("variant_code_gen_failed",{variant_count:ja.length,reason:qa?"aborted":"exception",error_message:Ja}),$(Ya=>{const Xa=Ya.get(us);if(!(Xa!=null&&Xa.styleVariants))return Ya;const el=new Map(Ya);return el.set(us,{...Xa,styleVariants:Xa.styleVariants.map(nl=>({...nl,codeStatus:void 0,codeDiff:void 0}))}),el})}finally{unregisterVariantGeneration(us)}},[os,$,ns,ss])}};var util;(function($){$.assertEqual=ls=>{};function ns(ls){}$.assertIs=ns;function ss(ls){throw new Error}$.assertNever=ss,$.arrayToEnum=ls=>{const us={};for(const ps of ls)us[ps]=ps;return us},$.getValidEnumValues=ls=>{const us=$.objectKeys(ls).filter(hs=>typeof ls[ls[hs]]!="number"),ps={};for(const hs of us)ps[hs]=ls[hs];return $.objectValues(ps)},$.objectValues=ls=>$.objectKeys(ls).map(function(us){return ls[us]}),$.objectKeys=typeof Object.keys=="function"?ls=>Object.keys(ls):ls=>{const us=[];for(const ps in ls)Object.prototype.hasOwnProperty.call(ls,ps)&&us.push(ps);return us},$.find=(ls,us)=>{for(const ps of ls)if(us(ps))return ps},$.isInteger=typeof Number.isInteger=="function"?ls=>Number.isInteger(ls):ls=>typeof ls=="number"&&Number.isFinite(ls)&&Math.floor(ls)===ls;function os(ls,us=" | "){return ls.map(ps=>typeof ps=="string"?`'${ps}'`:ps).join(us)}$.joinValues=os,$.jsonStringifyReplacer=(ls,us)=>typeof us=="bigint"?us.toString():us})(util||(util={}));var objectUtil;(function($){$.mergeShapes=(ns,ss)=>({...ns,...ss})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=$=>{switch(typeof $){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN($)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray($)?ZodParsedType.array:$===null?ZodParsedType.null:$.then&&typeof $.then=="function"&&$.catch&&typeof $.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&$ instanceof Map?ZodParsedType.map:typeof Set<"u"&&$ instanceof Set?ZodParsedType.set:typeof Date<"u"&&$ instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(ns){super(),this.issues=[],this.addIssue=os=>{this.issues=[...this.issues,os]},this.addIssues=(os=[])=>{this.issues=[...this.issues,...os]};const ss=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,ss):this.__proto__=ss,this.name="ZodError",this.issues=ns}format(ns){const ss=ns||function(us){return us.message},os={_errors:[]},ls=us=>{for(const ps of us.issues)if(ps.code==="invalid_union")ps.unionErrors.map(ls);else if(ps.code==="invalid_return_type")ls(ps.returnTypeError);else if(ps.code==="invalid_arguments")ls(ps.argumentsError);else if(ps.path.length===0)os._errors.push(ss(ps));else{let hs=os,ws=0;for(;ws<ps.path.length;){const ja=ps.path[ws];ws===ps.path.length-1?(hs[ja]=hs[ja]||{_errors:[]},hs[ja]._errors.push(ss(ps))):hs[ja]=hs[ja]||{_errors:[]},hs=hs[ja],ws++}}};return ls(this),os}static assert(ns){if(!(ns instanceof ZodError))throw new Error(`Not a ZodError: ${ns}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(ns=ss=>ss.message){const ss={},os=[];for(const ls of this.issues)if(ls.path.length>0){const us=ls.path[0];ss[us]=ss[us]||[],ss[us].push(ns(ls))}else os.push(ns(ls));return{formErrors:os,fieldErrors:ss}}get formErrors(){return this.flatten()}}ZodError.create=$=>new ZodError($);const errorMap=($,ns)=>{let ss;switch($.code){case ZodIssueCode.invalid_type:$.received===ZodParsedType.undefined?ss="Required":ss=`Expected ${$.expected}, received ${$.received}`;break;case ZodIssueCode.invalid_literal:ss=`Invalid literal value, expected ${JSON.stringify($.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:ss=`Unrecognized key(s) in object: ${util.joinValues($.keys,", ")}`;break;case ZodIssueCode.invalid_union:ss="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:ss=`Invalid discriminator value. Expected ${util.joinValues($.options)}`;break;case ZodIssueCode.invalid_enum_value:ss=`Invalid enum value. Expected ${util.joinValues($.options)}, received '${$.received}'`;break;case ZodIssueCode.invalid_arguments:ss="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:ss="Invalid function return type";break;case ZodIssueCode.invalid_date:ss="Invalid date";break;case ZodIssueCode.invalid_string:typeof $.validation=="object"?"includes"in $.validation?(ss=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position=="number"&&(ss=`${ss} at one or more positions greater than or equal to ${$.validation.position}`)):"startsWith"in $.validation?ss=`Invalid input: must start with "${$.validation.startsWith}"`:"endsWith"in $.validation?ss=`Invalid input: must end with "${$.validation.endsWith}"`:util.assertNever($.validation):$.validation!=="regex"?ss=`Invalid ${$.validation}`:ss="Invalid";break;case ZodIssueCode.too_small:$.type==="array"?ss=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`:$.type==="string"?ss=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`:$.type==="number"?ss=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`:$.type==="bigint"?ss=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`:$.type==="date"?ss=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`:ss="Invalid input";break;case ZodIssueCode.too_big:$.type==="array"?ss=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`:$.type==="string"?ss=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`:$.type==="number"?ss=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`:$.type==="bigint"?ss=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`:$.type==="date"?ss=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`:ss="Invalid input";break;case ZodIssueCode.custom:ss="Invalid input";break;case ZodIssueCode.invalid_intersection_types:ss="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:ss=`Number must be a multiple of ${$.multipleOf}`;break;case ZodIssueCode.not_finite:ss="Number must be finite";break;default:ss=ns.defaultError,util.assertNever($)}return{message:ss}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=$=>{const{data:ns,path:ss,errorMaps:os,issueData:ls}=$,us=[...ss,...ls.path||[]],ps={...ls,path:us};if(ls.message!==void 0)return{...ls,path:us,message:ls.message};let hs="";const ws=os.filter(ja=>!!ja).slice().reverse();for(const ja of ws)hs=ja(ps,{data:ns,defaultError:hs}).message;return{...ls,path:us,message:hs}};function addIssueToContext($,ns){const ss=getErrorMap(),os=makeIssue({issueData:ns,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,ss,ss===errorMap?void 0:errorMap].filter(ls=>!!ls)});$.common.issues.push(os)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(ns,ss){const os=[];for(const ls of ss){if(ls.status==="aborted")return INVALID;ls.status==="dirty"&&ns.dirty(),os.push(ls.value)}return{status:ns.value,value:os}}static async mergeObjectAsync(ns,ss){const os=[];for(const ls of ss){const us=await ls.key,ps=await ls.value;os.push({key:us,value:ps})}return ParseStatus.mergeObjectSync(ns,os)}static mergeObjectSync(ns,ss){const os={};for(const ls of ss){const{key:us,value:ps}=ls;if(us.status==="aborted"||ps.status==="aborted")return INVALID;us.status==="dirty"&&ns.dirty(),ps.status==="dirty"&&ns.dirty(),us.value!=="__proto__"&&(typeof ps.value<"u"||ls.alwaysSet)&&(os[us.value]=ps.value)}return{status:ns.value,value:os}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=$=>({status:"dirty",value:$}),OK=$=>({status:"valid",value:$}),isAborted=$=>$.status==="aborted",isDirty=$=>$.status==="dirty",isValid=$=>$.status==="valid",isAsync=$=>typeof Promise<"u"&&$ instanceof Promise;var errorUtil;(function($){$.errToObj=ns=>typeof ns=="string"?{message:ns}:ns||{},$.toString=ns=>typeof ns=="string"?ns:ns==null?void 0:ns.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(ns,ss,os,ls){this._cachedPath=[],this.parent=ns,this.data=ss,this._path=os,this._key=ls}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=($,ns)=>{if(isValid(ns))return{success:!0,data:ns.value};if(!$.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const ss=new ZodError($.common.issues);return this._error=ss,this._error}}};function processCreateParams($){if(!$)return{};const{errorMap:ns,invalid_type_error:ss,required_error:os,description:ls}=$;if(ns&&(ss||os))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return ns?{errorMap:ns,description:ls}:{errorMap:(ps,hs)=>{const{message:ws}=$;return ps.code==="invalid_enum_value"?{message:ws??hs.defaultError}:typeof hs.data>"u"?{message:ws??os??hs.defaultError}:ps.code!=="invalid_type"?{message:hs.defaultError}:{message:ws??ss??hs.defaultError}},description:ls}}class ZodType{get description(){return this._def.description}_getType(ns){return getParsedType(ns.data)}_getOrReturnCtx(ns,ss){return ss||{common:ns.parent.common,data:ns.data,parsedType:getParsedType(ns.data),schemaErrorMap:this._def.errorMap,path:ns.path,parent:ns.parent}}_processInputParams(ns){return{status:new ParseStatus,ctx:{common:ns.parent.common,data:ns.data,parsedType:getParsedType(ns.data),schemaErrorMap:this._def.errorMap,path:ns.path,parent:ns.parent}}}_parseSync(ns){const ss=this._parse(ns);if(isAsync(ss))throw new Error("Synchronous parse encountered promise.");return ss}_parseAsync(ns){const ss=this._parse(ns);return Promise.resolve(ss)}parse(ns,ss){const os=this.safeParse(ns,ss);if(os.success)return os.data;throw os.error}safeParse(ns,ss){const os={common:{issues:[],async:(ss==null?void 0:ss.async)??!1,contextualErrorMap:ss==null?void 0:ss.errorMap},path:(ss==null?void 0:ss.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:ns,parsedType:getParsedType(ns)},ls=this._parseSync({data:ns,path:os.path,parent:os});return handleResult(os,ls)}"~validate"(ns){var os,ls;const ss={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:ns,parsedType:getParsedType(ns)};if(!this["~standard"].async)try{const us=this._parseSync({data:ns,path:[],parent:ss});return isValid(us)?{value:us.value}:{issues:ss.common.issues}}catch(us){(ls=(os=us==null?void 0:us.message)==null?void 0:os.toLowerCase())!=null&&ls.includes("encountered")&&(this["~standard"].async=!0),ss.common={issues:[],async:!0}}return this._parseAsync({data:ns,path:[],parent:ss}).then(us=>isValid(us)?{value:us.value}:{issues:ss.common.issues})}async parseAsync(ns,ss){const os=await this.safeParseAsync(ns,ss);if(os.success)return os.data;throw os.error}async safeParseAsync(ns,ss){const os={common:{issues:[],contextualErrorMap:ss==null?void 0:ss.errorMap,async:!0},path:(ss==null?void 0:ss.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:ns,parsedType:getParsedType(ns)},ls=this._parse({data:ns,path:os.path,parent:os}),us=await(isAsync(ls)?ls:Promise.resolve(ls));return handleResult(os,us)}refine(ns,ss){const os=ls=>typeof ss=="string"||typeof ss>"u"?{message:ss}:typeof ss=="function"?ss(ls):ss;return this._refinement((ls,us)=>{const ps=ns(ls),hs=()=>us.addIssue({code:ZodIssueCode.custom,...os(ls)});return typeof Promise<"u"&&ps instanceof Promise?ps.then(ws=>ws?!0:(hs(),!1)):ps?!0:(hs(),!1)})}refinement(ns,ss){return this._refinement((os,ls)=>ns(os)?!0:(ls.addIssue(typeof ss=="function"?ss(os,ls):ss),!1))}_refinement(ns){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:ns}})}superRefine(ns){return this._refinement(ns)}constructor(ns){this.spa=this.safeParseAsync,this._def=ns,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:ss=>this["~validate"](ss)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(ns){return ZodUnion.create([this,ns],this._def)}and(ns){return ZodIntersection.create(this,ns,this._def)}transform(ns){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:ns}})}default(ns){const ss=typeof ns=="function"?ns:()=>ns;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:ss,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(ns){const ss=typeof ns=="function"?ns:()=>ns;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:ss,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(ns){const ss=this.constructor;return new ss({...this._def,description:ns})}pipe(ns){return ZodPipeline.create(this,ns)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource($){let ns="[0-5]\\d";$.precision?ns=`${ns}\\.\\d{${$.precision}}`:$.precision==null&&(ns=`${ns}(\\.\\d+)?`);const ss=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${ns})${ss}`}function timeRegex($){return new RegExp(`^${timeRegexSource($)}$`)}function datetimeRegex($){let ns=`${dateRegexSource}T${timeRegexSource($)}`;const ss=[];return ss.push($.local?"Z?":"Z"),$.offset&&ss.push("([+-]\\d{2}:?\\d{2})"),ns=`${ns}(${ss.join("|")})`,new RegExp(`^${ns}$`)}function isValidIP($,ns){return!!((ns==="v4"||!ns)&&ipv4Regex.test($)||(ns==="v6"||!ns)&&ipv6Regex.test($))}function isValidJWT($,ns){if(!jwtRegex.test($))return!1;try{const[ss]=$.split(".");if(!ss)return!1;const os=ss.replace(/-/g,"+").replace(/_/g,"/").padEnd(ss.length+(4-ss.length%4)%4,"="),ls=JSON.parse(atob(os));return!(typeof ls!="object"||ls===null||"typ"in ls&&(ls==null?void 0:ls.typ)!=="JWT"||!ls.alg||ns&&ls.alg!==ns)}catch{return!1}}function isValidCidr($,ns){return!!((ns==="v4"||!ns)&&ipv4CidrRegex.test($)||(ns==="v6"||!ns)&&ipv6CidrRegex.test($))}class ZodString extends ZodType{_parse(ns){if(this._def.coerce&&(ns.data=String(ns.data)),this._getType(ns)!==ZodParsedType.string){const us=this._getOrReturnCtx(ns);return addIssueToContext(us,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:us.parsedType}),INVALID}const os=new ParseStatus;let ls;for(const us of this._def.checks)if(us.kind==="min")ns.data.length<us.value&&(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.too_small,minimum:us.value,type:"string",inclusive:!0,exact:!1,message:us.message}),os.dirty());else if(us.kind==="max")ns.data.length>us.value&&(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.too_big,maximum:us.value,type:"string",inclusive:!0,exact:!1,message:us.message}),os.dirty());else if(us.kind==="length"){const ps=ns.data.length>us.value,hs=ns.data.length<us.value;(ps||hs)&&(ls=this._getOrReturnCtx(ns,ls),ps?addIssueToContext(ls,{code:ZodIssueCode.too_big,maximum:us.value,type:"string",inclusive:!0,exact:!0,message:us.message}):hs&&addIssueToContext(ls,{code:ZodIssueCode.too_small,minimum:us.value,type:"string",inclusive:!0,exact:!0,message:us.message}),os.dirty())}else if(us.kind==="email")emailRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"email",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"emoji",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="uuid")uuidRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"uuid",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="nanoid")nanoidRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="cuid")cuidRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"cuid",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="cuid2")cuid2Regex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="ulid")ulidRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"ulid",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="url")try{new URL(ns.data)}catch{ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"url",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()}else us.kind==="regex"?(us.regex.lastIndex=0,us.regex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"regex",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty())):us.kind==="trim"?ns.data=ns.data.trim():us.kind==="includes"?ns.data.includes(us.value,us.position)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:{includes:us.value,position:us.position},message:us.message}),os.dirty()):us.kind==="toLowerCase"?ns.data=ns.data.toLowerCase():us.kind==="toUpperCase"?ns.data=ns.data.toUpperCase():us.kind==="startsWith"?ns.data.startsWith(us.value)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:{startsWith:us.value},message:us.message}),os.dirty()):us.kind==="endsWith"?ns.data.endsWith(us.value)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:{endsWith:us.value},message:us.message}),os.dirty()):us.kind==="datetime"?datetimeRegex(us).test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:"datetime",message:us.message}),os.dirty()):us.kind==="date"?dateRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:"date",message:us.message}),os.dirty()):us.kind==="time"?timeRegex(us).test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:"time",message:us.message}),os.dirty()):us.kind==="duration"?durationRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"duration",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="ip"?isValidIP(ns.data,us.version)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"ip",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="jwt"?isValidJWT(ns.data,us.alg)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"jwt",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="cidr"?isValidCidr(ns.data,us.version)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"cidr",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="base64"?base64Regex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"base64",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="base64url"?base64urlRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"base64url",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):util.assertNever(us);return{status:os.value,value:ns.data}}_regex(ns,ss,os){return this.refinement(ls=>ns.test(ls),{validation:ss,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(os)})}_addCheck(ns){return new ZodString({...this._def,checks:[...this._def.checks,ns]})}email(ns){return this._addCheck({kind:"email",...errorUtil.errToObj(ns)})}url(ns){return this._addCheck({kind:"url",...errorUtil.errToObj(ns)})}emoji(ns){return this._addCheck({kind:"emoji",...errorUtil.errToObj(ns)})}uuid(ns){return this._addCheck({kind:"uuid",...errorUtil.errToObj(ns)})}nanoid(ns){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(ns)})}cuid(ns){return this._addCheck({kind:"cuid",...errorUtil.errToObj(ns)})}cuid2(ns){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(ns)})}ulid(ns){return this._addCheck({kind:"ulid",...errorUtil.errToObj(ns)})}base64(ns){return this._addCheck({kind:"base64",...errorUtil.errToObj(ns)})}base64url(ns){return this._addCheck({kind:"base64url",...errorUtil.errToObj(ns)})}jwt(ns){return this._addCheck({kind:"jwt",...errorUtil.errToObj(ns)})}ip(ns){return this._addCheck({kind:"ip",...errorUtil.errToObj(ns)})}cidr(ns){return this._addCheck({kind:"cidr",...errorUtil.errToObj(ns)})}datetime(ns){return typeof ns=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:ns}):this._addCheck({kind:"datetime",precision:typeof(ns==null?void 0:ns.precision)>"u"?null:ns==null?void 0:ns.precision,offset:(ns==null?void 0:ns.offset)??!1,local:(ns==null?void 0:ns.local)??!1,...errorUtil.errToObj(ns==null?void 0:ns.message)})}date(ns){return this._addCheck({kind:"date",message:ns})}time(ns){return typeof ns=="string"?this._addCheck({kind:"time",precision:null,message:ns}):this._addCheck({kind:"time",precision:typeof(ns==null?void 0:ns.precision)>"u"?null:ns==null?void 0:ns.precision,...errorUtil.errToObj(ns==null?void 0:ns.message)})}duration(ns){return this._addCheck({kind:"duration",...errorUtil.errToObj(ns)})}regex(ns,ss){return this._addCheck({kind:"regex",regex:ns,...errorUtil.errToObj(ss)})}includes(ns,ss){return this._addCheck({kind:"includes",value:ns,position:ss==null?void 0:ss.position,...errorUtil.errToObj(ss==null?void 0:ss.message)})}startsWith(ns,ss){return this._addCheck({kind:"startsWith",value:ns,...errorUtil.errToObj(ss)})}endsWith(ns,ss){return this._addCheck({kind:"endsWith",value:ns,...errorUtil.errToObj(ss)})}min(ns,ss){return this._addCheck({kind:"min",value:ns,...errorUtil.errToObj(ss)})}max(ns,ss){return this._addCheck({kind:"max",value:ns,...errorUtil.errToObj(ss)})}length(ns,ss){return this._addCheck({kind:"length",value:ns,...errorUtil.errToObj(ss)})}nonempty(ns){return this.min(1,errorUtil.errToObj(ns))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(ns=>ns.kind==="datetime")}get isDate(){return!!this._def.checks.find(ns=>ns.kind==="date")}get isTime(){return!!this._def.checks.find(ns=>ns.kind==="time")}get isDuration(){return!!this._def.checks.find(ns=>ns.kind==="duration")}get isEmail(){return!!this._def.checks.find(ns=>ns.kind==="email")}get isURL(){return!!this._def.checks.find(ns=>ns.kind==="url")}get isEmoji(){return!!this._def.checks.find(ns=>ns.kind==="emoji")}get isUUID(){return!!this._def.checks.find(ns=>ns.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(ns=>ns.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(ns=>ns.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(ns=>ns.kind==="cuid2")}get isULID(){return!!this._def.checks.find(ns=>ns.kind==="ulid")}get isIP(){return!!this._def.checks.find(ns=>ns.kind==="ip")}get isCIDR(){return!!this._def.checks.find(ns=>ns.kind==="cidr")}get isBase64(){return!!this._def.checks.find(ns=>ns.kind==="base64")}get isBase64url(){return!!this._def.checks.find(ns=>ns.kind==="base64url")}get minLength(){let ns=null;for(const ss of this._def.checks)ss.kind==="min"&&(ns===null||ss.value>ns)&&(ns=ss.value);return ns}get maxLength(){let ns=null;for(const ss of this._def.checks)ss.kind==="max"&&(ns===null||ss.value<ns)&&(ns=ss.value);return ns}}ZodString.create=$=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:($==null?void 0:$.coerce)??!1,...processCreateParams($)});function floatSafeRemainder($,ns){const ss=($.toString().split(".")[1]||"").length,os=(ns.toString().split(".")[1]||"").length,ls=ss>os?ss:os,us=Number.parseInt($.toFixed(ls).replace(".","")),ps=Number.parseInt(ns.toFixed(ls).replace(".",""));return us%ps/10**ls}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(ns){if(this._def.coerce&&(ns.data=Number(ns.data)),this._getType(ns)!==ZodParsedType.number){const us=this._getOrReturnCtx(ns);return addIssueToContext(us,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:us.parsedType}),INVALID}let os;const ls=new ParseStatus;for(const us of this._def.checks)us.kind==="int"?util.isInteger(ns.data)||(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:us.message}),ls.dirty()):us.kind==="min"?(us.inclusive?ns.data<us.value:ns.data<=us.value)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.too_small,minimum:us.value,type:"number",inclusive:us.inclusive,exact:!1,message:us.message}),ls.dirty()):us.kind==="max"?(us.inclusive?ns.data>us.value:ns.data>=us.value)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.too_big,maximum:us.value,type:"number",inclusive:us.inclusive,exact:!1,message:us.message}),ls.dirty()):us.kind==="multipleOf"?floatSafeRemainder(ns.data,us.value)!==0&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.not_multiple_of,multipleOf:us.value,message:us.message}),ls.dirty()):us.kind==="finite"?Number.isFinite(ns.data)||(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.not_finite,message:us.message}),ls.dirty()):util.assertNever(us);return{status:ls.value,value:ns.data}}gte(ns,ss){return this.setLimit("min",ns,!0,errorUtil.toString(ss))}gt(ns,ss){return this.setLimit("min",ns,!1,errorUtil.toString(ss))}lte(ns,ss){return this.setLimit("max",ns,!0,errorUtil.toString(ss))}lt(ns,ss){return this.setLimit("max",ns,!1,errorUtil.toString(ss))}setLimit(ns,ss,os,ls){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:ns,value:ss,inclusive:os,message:errorUtil.toString(ls)}]})}_addCheck(ns){return new ZodNumber({...this._def,checks:[...this._def.checks,ns]})}int(ns){return this._addCheck({kind:"int",message:errorUtil.toString(ns)})}positive(ns){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(ns)})}negative(ns){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(ns)})}nonpositive(ns){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(ns)})}nonnegative(ns){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(ns)})}multipleOf(ns,ss){return this._addCheck({kind:"multipleOf",value:ns,message:errorUtil.toString(ss)})}finite(ns){return this._addCheck({kind:"finite",message:errorUtil.toString(ns)})}safe(ns){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(ns)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(ns)})}get minValue(){let ns=null;for(const ss of this._def.checks)ss.kind==="min"&&(ns===null||ss.value>ns)&&(ns=ss.value);return ns}get maxValue(){let ns=null;for(const ss of this._def.checks)ss.kind==="max"&&(ns===null||ss.value<ns)&&(ns=ss.value);return ns}get isInt(){return!!this._def.checks.find(ns=>ns.kind==="int"||ns.kind==="multipleOf"&&util.isInteger(ns.value))}get isFinite(){let ns=null,ss=null;for(const os of this._def.checks){if(os.kind==="finite"||os.kind==="int"||os.kind==="multipleOf")return!0;os.kind==="min"?(ss===null||os.value>ss)&&(ss=os.value):os.kind==="max"&&(ns===null||os.value<ns)&&(ns=os.value)}return Number.isFinite(ss)&&Number.isFinite(ns)}}ZodNumber.create=$=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:($==null?void 0:$.coerce)||!1,...processCreateParams($)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(ns){if(this._def.coerce)try{ns.data=BigInt(ns.data)}catch{return this._getInvalidInput(ns)}if(this._getType(ns)!==ZodParsedType.bigint)return this._getInvalidInput(ns);let os;const ls=new ParseStatus;for(const us of this._def.checks)us.kind==="min"?(us.inclusive?ns.data<us.value:ns.data<=us.value)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.too_small,type:"bigint",minimum:us.value,inclusive:us.inclusive,message:us.message}),ls.dirty()):us.kind==="max"?(us.inclusive?ns.data>us.value:ns.data>=us.value)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.too_big,type:"bigint",maximum:us.value,inclusive:us.inclusive,message:us.message}),ls.dirty()):us.kind==="multipleOf"?ns.data%us.value!==BigInt(0)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.not_multiple_of,multipleOf:us.value,message:us.message}),ls.dirty()):util.assertNever(us);return{status:ls.value,value:ns.data}}_getInvalidInput(ns){const ss=this._getOrReturnCtx(ns);return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ss.parsedType}),INVALID}gte(ns,ss){return this.setLimit("min",ns,!0,errorUtil.toString(ss))}gt(ns,ss){return this.setLimit("min",ns,!1,errorUtil.toString(ss))}lte(ns,ss){return this.setLimit("max",ns,!0,errorUtil.toString(ss))}lt(ns,ss){return this.setLimit("max",ns,!1,errorUtil.toString(ss))}setLimit(ns,ss,os,ls){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:ns,value:ss,inclusive:os,message:errorUtil.toString(ls)}]})}_addCheck(ns){return new ZodBigInt({...this._def,checks:[...this._def.checks,ns]})}positive(ns){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(ns)})}negative(ns){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(ns)})}nonpositive(ns){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(ns)})}nonnegative(ns){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(ns)})}multipleOf(ns,ss){return this._addCheck({kind:"multipleOf",value:ns,message:errorUtil.toString(ss)})}get minValue(){let ns=null;for(const ss of this._def.checks)ss.kind==="min"&&(ns===null||ss.value>ns)&&(ns=ss.value);return ns}get maxValue(){let ns=null;for(const ss of this._def.checks)ss.kind==="max"&&(ns===null||ss.value<ns)&&(ns=ss.value);return ns}}ZodBigInt.create=$=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:($==null?void 0:$.coerce)??!1,...processCreateParams($)});class ZodBoolean extends ZodType{_parse(ns){if(this._def.coerce&&(ns.data=!!ns.data),this._getType(ns)!==ZodParsedType.boolean){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodBoolean.create=$=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:($==null?void 0:$.coerce)||!1,...processCreateParams($)});class ZodDate extends ZodType{_parse(ns){if(this._def.coerce&&(ns.data=new Date(ns.data)),this._getType(ns)!==ZodParsedType.date){const us=this._getOrReturnCtx(ns);return addIssueToContext(us,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:us.parsedType}),INVALID}if(Number.isNaN(ns.data.getTime())){const us=this._getOrReturnCtx(ns);return addIssueToContext(us,{code:ZodIssueCode.invalid_date}),INVALID}const os=new ParseStatus;let ls;for(const us of this._def.checks)us.kind==="min"?ns.data.getTime()<us.value&&(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.too_small,message:us.message,inclusive:!0,exact:!1,minimum:us.value,type:"date"}),os.dirty()):us.kind==="max"?ns.data.getTime()>us.value&&(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.too_big,message:us.message,inclusive:!0,exact:!1,maximum:us.value,type:"date"}),os.dirty()):util.assertNever(us);return{status:os.value,value:new Date(ns.data.getTime())}}_addCheck(ns){return new ZodDate({...this._def,checks:[...this._def.checks,ns]})}min(ns,ss){return this._addCheck({kind:"min",value:ns.getTime(),message:errorUtil.toString(ss)})}max(ns,ss){return this._addCheck({kind:"max",value:ns.getTime(),message:errorUtil.toString(ss)})}get minDate(){let ns=null;for(const ss of this._def.checks)ss.kind==="min"&&(ns===null||ss.value>ns)&&(ns=ss.value);return ns!=null?new Date(ns):null}get maxDate(){let ns=null;for(const ss of this._def.checks)ss.kind==="max"&&(ns===null||ss.value<ns)&&(ns=ss.value);return ns!=null?new Date(ns):null}}ZodDate.create=$=>new ZodDate({checks:[],coerce:($==null?void 0:$.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams($)});class ZodSymbol extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.symbol){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodSymbol.create=$=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams($)});class ZodUndefined extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.undefined){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodUndefined.create=$=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams($)});class ZodNull extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.null){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodNull.create=$=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams($)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(ns){return OK(ns.data)}}ZodAny.create=$=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams($)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(ns){return OK(ns.data)}}ZodUnknown.create=$=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams($)});class ZodNever extends ZodType{_parse(ns){const ss=this._getOrReturnCtx(ns);return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ss.parsedType}),INVALID}}ZodNever.create=$=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams($)});class ZodVoid extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.undefined){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodVoid.create=$=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams($)});class ZodArray extends ZodType{_parse(ns){const{ctx:ss,status:os}=this._processInputParams(ns),ls=this._def;if(ss.parsedType!==ZodParsedType.array)return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ss.parsedType}),INVALID;if(ls.exactLength!==null){const ps=ss.data.length>ls.exactLength.value,hs=ss.data.length<ls.exactLength.value;(ps||hs)&&(addIssueToContext(ss,{code:ps?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:hs?ls.exactLength.value:void 0,maximum:ps?ls.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:ls.exactLength.message}),os.dirty())}if(ls.minLength!==null&&ss.data.length<ls.minLength.value&&(addIssueToContext(ss,{code:ZodIssueCode.too_small,minimum:ls.minLength.value,type:"array",inclusive:!0,exact:!1,message:ls.minLength.message}),os.dirty()),ls.maxLength!==null&&ss.data.length>ls.maxLength.value&&(addIssueToContext(ss,{code:ZodIssueCode.too_big,maximum:ls.maxLength.value,type:"array",inclusive:!0,exact:!1,message:ls.maxLength.message}),os.dirty()),ss.common.async)return Promise.all([...ss.data].map((ps,hs)=>ls.type._parseAsync(new ParseInputLazyPath(ss,ps,ss.path,hs)))).then(ps=>ParseStatus.mergeArray(os,ps));const us=[...ss.data].map((ps,hs)=>ls.type._parseSync(new ParseInputLazyPath(ss,ps,ss.path,hs)));return ParseStatus.mergeArray(os,us)}get element(){return this._def.type}min(ns,ss){return new ZodArray({...this._def,minLength:{value:ns,message:errorUtil.toString(ss)}})}max(ns,ss){return new ZodArray({...this._def,maxLength:{value:ns,message:errorUtil.toString(ss)}})}length(ns,ss){return new ZodArray({...this._def,exactLength:{value:ns,message:errorUtil.toString(ss)}})}nonempty(ns){return this.min(1,ns)}}ZodArray.create=($,ns)=>new ZodArray({type:$,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(ns)});function deepPartialify($){if($ instanceof ZodObject){const ns={};for(const ss in $.shape){const os=$.shape[ss];ns[ss]=ZodOptional.create(deepPartialify(os))}return new ZodObject({...$._def,shape:()=>ns})}else return $ instanceof ZodArray?new ZodArray({...$._def,type:deepPartialify($.element)}):$ instanceof ZodOptional?ZodOptional.create(deepPartialify($.unwrap())):$ instanceof ZodNullable?ZodNullable.create(deepPartialify($.unwrap())):$ instanceof ZodTuple?ZodTuple.create($.items.map(ns=>deepPartialify(ns))):$}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const ns=this._def.shape(),ss=util.objectKeys(ns);return this._cached={shape:ns,keys:ss},this._cached}_parse(ns){if(this._getType(ns)!==ZodParsedType.object){const ja=this._getOrReturnCtx(ns);return addIssueToContext(ja,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ja.parsedType}),INVALID}const{status:os,ctx:ls}=this._processInputParams(ns),{shape:us,keys:ps}=this._getCached(),hs=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const ja in ls.data)ps.includes(ja)||hs.push(ja);const ws=[];for(const ja of ps){const Ha=us[ja],Va=ls.data[ja];ws.push({key:{status:"valid",value:ja},value:Ha._parse(new ParseInputLazyPath(ls,Va,ls.path,ja)),alwaysSet:ja in ls.data})}if(this._def.catchall instanceof ZodNever){const ja=this._def.unknownKeys;if(ja==="passthrough")for(const Ha of hs)ws.push({key:{status:"valid",value:Ha},value:{status:"valid",value:ls.data[Ha]}});else if(ja==="strict")hs.length>0&&(addIssueToContext(ls,{code:ZodIssueCode.unrecognized_keys,keys:hs}),os.dirty());else if(ja!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const ja=this._def.catchall;for(const Ha of hs){const Va=ls.data[Ha];ws.push({key:{status:"valid",value:Ha},value:ja._parse(new ParseInputLazyPath(ls,Va,ls.path,Ha)),alwaysSet:Ha in ls.data})}}return ls.common.async?Promise.resolve().then(async()=>{const ja=[];for(const Ha of ws){const Va=await Ha.key,Ga=await Ha.value;ja.push({key:Va,value:Ga,alwaysSet:Ha.alwaysSet})}return ja}).then(ja=>ParseStatus.mergeObjectSync(os,ja)):ParseStatus.mergeObjectSync(os,ws)}get shape(){return this._def.shape()}strict(ns){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...ns!==void 0?{errorMap:(ss,os)=>{var us,ps;const ls=((ps=(us=this._def).errorMap)==null?void 0:ps.call(us,ss,os).message)??os.defaultError;return ss.code==="unrecognized_keys"?{message:errorUtil.errToObj(ns).message??ls}:{message:ls}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(ns){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...ns})})}merge(ns){return new ZodObject({unknownKeys:ns._def.unknownKeys,catchall:ns._def.catchall,shape:()=>({...this._def.shape(),...ns._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(ns,ss){return this.augment({[ns]:ss})}catchall(ns){return new ZodObject({...this._def,catchall:ns})}pick(ns){const ss={};for(const os of util.objectKeys(ns))ns[os]&&this.shape[os]&&(ss[os]=this.shape[os]);return new ZodObject({...this._def,shape:()=>ss})}omit(ns){const ss={};for(const os of util.objectKeys(this.shape))ns[os]||(ss[os]=this.shape[os]);return new ZodObject({...this._def,shape:()=>ss})}deepPartial(){return deepPartialify(this)}partial(ns){const ss={};for(const os of util.objectKeys(this.shape)){const ls=this.shape[os];ns&&!ns[os]?ss[os]=ls:ss[os]=ls.optional()}return new ZodObject({...this._def,shape:()=>ss})}required(ns){const ss={};for(const os of util.objectKeys(this.shape))if(ns&&!ns[os])ss[os]=this.shape[os];else{let us=this.shape[os];for(;us instanceof ZodOptional;)us=us._def.innerType;ss[os]=us}return new ZodObject({...this._def,shape:()=>ss})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=($,ns)=>new ZodObject({shape:()=>$,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(ns)});ZodObject.strictCreate=($,ns)=>new ZodObject({shape:()=>$,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(ns)});ZodObject.lazycreate=($,ns)=>new ZodObject({shape:$,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(ns)});class ZodUnion extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns),os=this._def.options;function ls(us){for(const hs of us)if(hs.result.status==="valid")return hs.result;for(const hs of us)if(hs.result.status==="dirty")return ss.common.issues.push(...hs.ctx.common.issues),hs.result;const ps=us.map(hs=>new ZodError(hs.ctx.common.issues));return addIssueToContext(ss,{code:ZodIssueCode.invalid_union,unionErrors:ps}),INVALID}if(ss.common.async)return Promise.all(os.map(async us=>{const ps={...ss,common:{...ss.common,issues:[]},parent:null};return{result:await us._parseAsync({data:ss.data,path:ss.path,parent:ps}),ctx:ps}})).then(ls);{let us;const ps=[];for(const ws of os){const ja={...ss,common:{...ss.common,issues:[]},parent:null},Ha=ws._parseSync({data:ss.data,path:ss.path,parent:ja});if(Ha.status==="valid")return Ha;Ha.status==="dirty"&&!us&&(us={result:Ha,ctx:ja}),ja.common.issues.length&&ps.push(ja.common.issues)}if(us)return ss.common.issues.push(...us.ctx.common.issues),us.result;const hs=ps.map(ws=>new ZodError(ws));return addIssueToContext(ss,{code:ZodIssueCode.invalid_union,unionErrors:hs}),INVALID}}get options(){return this._def.options}}ZodUnion.create=($,ns)=>new ZodUnion({options:$,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(ns)});const getDiscriminator=$=>$ instanceof ZodLazy?getDiscriminator($.schema):$ instanceof ZodEffects?getDiscriminator($.innerType()):$ instanceof ZodLiteral?[$.value]:$ instanceof ZodEnum?$.options:$ instanceof ZodNativeEnum?util.objectValues($.enum):$ instanceof ZodDefault?getDiscriminator($._def.innerType):$ instanceof ZodUndefined?[void 0]:$ instanceof ZodNull?[null]:$ instanceof ZodOptional?[void 0,...getDiscriminator($.unwrap())]:$ instanceof ZodNullable?[null,...getDiscriminator($.unwrap())]:$ instanceof ZodBranded||$ instanceof ZodReadonly?getDiscriminator($.unwrap()):$ instanceof ZodCatch?getDiscriminator($._def.innerType):[];class ZodDiscriminatedUnion extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns);if(ss.parsedType!==ZodParsedType.object)return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ss.parsedType}),INVALID;const os=this.discriminator,ls=ss.data[os],us=this.optionsMap.get(ls);return us?ss.common.async?us._parseAsync({data:ss.data,path:ss.path,parent:ss}):us._parseSync({data:ss.data,path:ss.path,parent:ss}):(addIssueToContext(ss,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[os]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(ns,ss,os){const ls=new Map;for(const us of ss){const ps=getDiscriminator(us.shape[ns]);if(!ps.length)throw new Error(`A discriminator value for key \`${ns}\` could not be extracted from all schema options`);for(const hs of ps){if(ls.has(hs))throw new Error(`Discriminator property ${String(ns)} has duplicate value ${String(hs)}`);ls.set(hs,us)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:ns,options:ss,optionsMap:ls,...processCreateParams(os)})}}function mergeValues($,ns){const ss=getParsedType($),os=getParsedType(ns);if($===ns)return{valid:!0,data:$};if(ss===ZodParsedType.object&&os===ZodParsedType.object){const ls=util.objectKeys(ns),us=util.objectKeys($).filter(hs=>ls.indexOf(hs)!==-1),ps={...$,...ns};for(const hs of us){const ws=mergeValues($[hs],ns[hs]);if(!ws.valid)return{valid:!1};ps[hs]=ws.data}return{valid:!0,data:ps}}else if(ss===ZodParsedType.array&&os===ZodParsedType.array){if($.length!==ns.length)return{valid:!1};const ls=[];for(let us=0;us<$.length;us++){const ps=$[us],hs=ns[us],ws=mergeValues(ps,hs);if(!ws.valid)return{valid:!1};ls.push(ws.data)}return{valid:!0,data:ls}}else return ss===ZodParsedType.date&&os===ZodParsedType.date&&+$==+ns?{valid:!0,data:$}:{valid:!1}}class ZodIntersection extends ZodType{_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns),ls=(us,ps)=>{if(isAborted(us)||isAborted(ps))return INVALID;const hs=mergeValues(us.value,ps.value);return hs.valid?((isDirty(us)||isDirty(ps))&&ss.dirty(),{status:ss.value,value:hs.data}):(addIssueToContext(os,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return os.common.async?Promise.all([this._def.left._parseAsync({data:os.data,path:os.path,parent:os}),this._def.right._parseAsync({data:os.data,path:os.path,parent:os})]).then(([us,ps])=>ls(us,ps)):ls(this._def.left._parseSync({data:os.data,path:os.path,parent:os}),this._def.right._parseSync({data:os.data,path:os.path,parent:os}))}}ZodIntersection.create=($,ns,ss)=>new ZodIntersection({left:$,right:ns,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(ss)});class ZodTuple extends ZodType{_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns);if(os.parsedType!==ZodParsedType.array)return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:os.parsedType}),INVALID;if(os.data.length<this._def.items.length)return addIssueToContext(os,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&os.data.length>this._def.items.length&&(addIssueToContext(os,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ss.dirty());const us=[...os.data].map((ps,hs)=>{const ws=this._def.items[hs]||this._def.rest;return ws?ws._parse(new ParseInputLazyPath(os,ps,os.path,hs)):null}).filter(ps=>!!ps);return os.common.async?Promise.all(us).then(ps=>ParseStatus.mergeArray(ss,ps)):ParseStatus.mergeArray(ss,us)}get items(){return this._def.items}rest(ns){return new ZodTuple({...this._def,rest:ns})}}ZodTuple.create=($,ns)=>{if(!Array.isArray($))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:$,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(ns)})};class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns);if(os.parsedType!==ZodParsedType.map)return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:os.parsedType}),INVALID;const ls=this._def.keyType,us=this._def.valueType,ps=[...os.data.entries()].map(([hs,ws],ja)=>({key:ls._parse(new ParseInputLazyPath(os,hs,os.path,[ja,"key"])),value:us._parse(new ParseInputLazyPath(os,ws,os.path,[ja,"value"]))}));if(os.common.async){const hs=new Map;return Promise.resolve().then(async()=>{for(const ws of ps){const ja=await ws.key,Ha=await ws.value;if(ja.status==="aborted"||Ha.status==="aborted")return INVALID;(ja.status==="dirty"||Ha.status==="dirty")&&ss.dirty(),hs.set(ja.value,Ha.value)}return{status:ss.value,value:hs}})}else{const hs=new Map;for(const ws of ps){const ja=ws.key,Ha=ws.value;if(ja.status==="aborted"||Ha.status==="aborted")return INVALID;(ja.status==="dirty"||Ha.status==="dirty")&&ss.dirty(),hs.set(ja.value,Ha.value)}return{status:ss.value,value:hs}}}}ZodMap.create=($,ns,ss)=>new ZodMap({valueType:ns,keyType:$,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(ss)});class ZodSet extends ZodType{_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns);if(os.parsedType!==ZodParsedType.set)return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:os.parsedType}),INVALID;const ls=this._def;ls.minSize!==null&&os.data.size<ls.minSize.value&&(addIssueToContext(os,{code:ZodIssueCode.too_small,minimum:ls.minSize.value,type:"set",inclusive:!0,exact:!1,message:ls.minSize.message}),ss.dirty()),ls.maxSize!==null&&os.data.size>ls.maxSize.value&&(addIssueToContext(os,{code:ZodIssueCode.too_big,maximum:ls.maxSize.value,type:"set",inclusive:!0,exact:!1,message:ls.maxSize.message}),ss.dirty());const us=this._def.valueType;function ps(ws){const ja=new Set;for(const Ha of ws){if(Ha.status==="aborted")return INVALID;Ha.status==="dirty"&&ss.dirty(),ja.add(Ha.value)}return{status:ss.value,value:ja}}const hs=[...os.data.values()].map((ws,ja)=>us._parse(new ParseInputLazyPath(os,ws,os.path,ja)));return os.common.async?Promise.all(hs).then(ws=>ps(ws)):ps(hs)}min(ns,ss){return new ZodSet({...this._def,minSize:{value:ns,message:errorUtil.toString(ss)}})}max(ns,ss){return new ZodSet({...this._def,maxSize:{value:ns,message:errorUtil.toString(ss)}})}size(ns,ss){return this.min(ns,ss).max(ns,ss)}nonempty(ns){return this.min(1,ns)}}ZodSet.create=($,ns)=>new ZodSet({valueType:$,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(ns)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(ns){const{ctx:ss}=this._processInputParams(ns);return this._def.getter()._parse({data:ss.data,path:ss.path,parent:ss})}}ZodLazy.create=($,ns)=>new ZodLazy({getter:$,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(ns)});class ZodLiteral extends ZodType{_parse(ns){if(ns.data!==this._def.value){const ss=this._getOrReturnCtx(ns);return addIssueToContext(ss,{received:ss.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:ns.data}}get value(){return this._def.value}}ZodLiteral.create=($,ns)=>new ZodLiteral({value:$,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(ns)});function createZodEnum($,ns){return new ZodEnum({values:$,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(ns)})}class ZodEnum extends ZodType{_parse(ns){if(typeof ns.data!="string"){const ss=this._getOrReturnCtx(ns),os=this._def.values;return addIssueToContext(ss,{expected:util.joinValues(os),received:ss.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(ns.data)){const ss=this._getOrReturnCtx(ns),os=this._def.values;return addIssueToContext(ss,{received:ss.data,code:ZodIssueCode.invalid_enum_value,options:os}),INVALID}return OK(ns.data)}get options(){return this._def.values}get enum(){const ns={};for(const ss of this._def.values)ns[ss]=ss;return ns}get Values(){const ns={};for(const ss of this._def.values)ns[ss]=ss;return ns}get Enum(){const ns={};for(const ss of this._def.values)ns[ss]=ss;return ns}extract(ns,ss=this._def){return ZodEnum.create(ns,{...this._def,...ss})}exclude(ns,ss=this._def){return ZodEnum.create(this.options.filter(os=>!ns.includes(os)),{...this._def,...ss})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(ns){const ss=util.getValidEnumValues(this._def.values),os=this._getOrReturnCtx(ns);if(os.parsedType!==ZodParsedType.string&&os.parsedType!==ZodParsedType.number){const ls=util.objectValues(ss);return addIssueToContext(os,{expected:util.joinValues(ls),received:os.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(ns.data)){const ls=util.objectValues(ss);return addIssueToContext(os,{received:os.data,code:ZodIssueCode.invalid_enum_value,options:ls}),INVALID}return OK(ns.data)}get enum(){return this._def.values}}ZodNativeEnum.create=($,ns)=>new ZodNativeEnum({values:$,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(ns)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(ns){const{ctx:ss}=this._processInputParams(ns);if(ss.parsedType!==ZodParsedType.promise&&ss.common.async===!1)return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ss.parsedType}),INVALID;const os=ss.parsedType===ZodParsedType.promise?ss.data:Promise.resolve(ss.data);return OK(os.then(ls=>this._def.type.parseAsync(ls,{path:ss.path,errorMap:ss.common.contextualErrorMap})))}}ZodPromise.create=($,ns)=>new ZodPromise({type:$,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(ns)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns),ls=this._def.effect||null,us={addIssue:ps=>{addIssueToContext(os,ps),ps.fatal?ss.abort():ss.dirty()},get path(){return os.path}};if(us.addIssue=us.addIssue.bind(us),ls.type==="preprocess"){const ps=ls.transform(os.data,us);if(os.common.async)return Promise.resolve(ps).then(async hs=>{if(ss.value==="aborted")return INVALID;const ws=await this._def.schema._parseAsync({data:hs,path:os.path,parent:os});return ws.status==="aborted"?INVALID:ws.status==="dirty"||ss.value==="dirty"?DIRTY(ws.value):ws});{if(ss.value==="aborted")return INVALID;const hs=this._def.schema._parseSync({data:ps,path:os.path,parent:os});return hs.status==="aborted"?INVALID:hs.status==="dirty"||ss.value==="dirty"?DIRTY(hs.value):hs}}if(ls.type==="refinement"){const ps=hs=>{const ws=ls.refinement(hs,us);if(os.common.async)return Promise.resolve(ws);if(ws instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return hs};if(os.common.async===!1){const hs=this._def.schema._parseSync({data:os.data,path:os.path,parent:os});return hs.status==="aborted"?INVALID:(hs.status==="dirty"&&ss.dirty(),ps(hs.value),{status:ss.value,value:hs.value})}else return this._def.schema._parseAsync({data:os.data,path:os.path,parent:os}).then(hs=>hs.status==="aborted"?INVALID:(hs.status==="dirty"&&ss.dirty(),ps(hs.value).then(()=>({status:ss.value,value:hs.value}))))}if(ls.type==="transform")if(os.common.async===!1){const ps=this._def.schema._parseSync({data:os.data,path:os.path,parent:os});if(!isValid(ps))return INVALID;const hs=ls.transform(ps.value,us);if(hs instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:ss.value,value:hs}}else return this._def.schema._parseAsync({data:os.data,path:os.path,parent:os}).then(ps=>isValid(ps)?Promise.resolve(ls.transform(ps.value,us)).then(hs=>({status:ss.value,value:hs})):INVALID);util.assertNever(ls)}}ZodEffects.create=($,ns,ss)=>new ZodEffects({schema:$,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:ns,...processCreateParams(ss)});ZodEffects.createWithPreprocess=($,ns,ss)=>new ZodEffects({schema:ns,effect:{type:"preprocess",transform:$},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(ss)});class ZodOptional extends ZodType{_parse(ns){return this._getType(ns)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(ns)}unwrap(){return this._def.innerType}}ZodOptional.create=($,ns)=>new ZodOptional({innerType:$,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(ns)});class ZodNullable extends ZodType{_parse(ns){return this._getType(ns)===ZodParsedType.null?OK(null):this._def.innerType._parse(ns)}unwrap(){return this._def.innerType}}ZodNullable.create=($,ns)=>new ZodNullable({innerType:$,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(ns)});class ZodDefault extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns);let os=ss.data;return ss.parsedType===ZodParsedType.undefined&&(os=this._def.defaultValue()),this._def.innerType._parse({data:os,path:ss.path,parent:ss})}removeDefault(){return this._def.innerType}}ZodDefault.create=($,ns)=>new ZodDefault({innerType:$,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof ns.default=="function"?ns.default:()=>ns.default,...processCreateParams(ns)});class ZodCatch extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns),os={...ss,common:{...ss.common,issues:[]}},ls=this._def.innerType._parse({data:os.data,path:os.path,parent:{...os}});return isAsync(ls)?ls.then(us=>({status:"valid",value:us.status==="valid"?us.value:this._def.catchValue({get error(){return new ZodError(os.common.issues)},input:os.data})})):{status:"valid",value:ls.status==="valid"?ls.value:this._def.catchValue({get error(){return new ZodError(os.common.issues)},input:os.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=($,ns)=>new ZodCatch({innerType:$,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof ns.catch=="function"?ns.catch:()=>ns.catch,...processCreateParams(ns)});class ZodNaN extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.nan){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:os.parsedType}),INVALID}return{status:"valid",value:ns.data}}}ZodNaN.create=$=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams($)});class ZodBranded extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns),os=ss.data;return this._def.type._parse({data:os,path:ss.path,parent:ss})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns);if(os.common.async)return(async()=>{const us=await this._def.in._parseAsync({data:os.data,path:os.path,parent:os});return us.status==="aborted"?INVALID:us.status==="dirty"?(ss.dirty(),DIRTY(us.value)):this._def.out._parseAsync({data:us.value,path:os.path,parent:os})})();{const ls=this._def.in._parseSync({data:os.data,path:os.path,parent:os});return ls.status==="aborted"?INVALID:ls.status==="dirty"?(ss.dirty(),{status:"dirty",value:ls.value}):this._def.out._parseSync({data:ls.value,path:os.path,parent:os})}}static create(ns,ss){return new ZodPipeline({in:ns,out:ss,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(ns){const ss=this._def.innerType._parse(ns),os=ls=>(isValid(ls)&&(ls.value=Object.freeze(ls.value)),ls);return isAsync(ss)?ss.then(ls=>os(ls)):os(ss)}unwrap(){return this._def.innerType}}ZodReadonly.create=($,ns)=>new ZodReadonly({innerType:$,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(ns)});var ZodFirstPartyTypeKind;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,booleanType=ZodBoolean.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create;ZodUnion.create;const discriminatedUnionType=ZodDiscriminatedUnion.create;ZodIntersection.create;ZodTuple.create;const literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;var define_process_env_default$1={};const LOG_LEVEL=(define_process_env_default$1.LOG_LEVEL||"INFO").toUpperCase();log$B.setLevel(log$B.levels[LOG_LEVEL]||log$B.levels.INFO);const PRIVATE_IPV4_PATTERNS=[/^10\./,/^127\./,/^192\.168\./,/^169\.254\./,/^172\.(1[6-9]|2\d|3[0-1])\./,/^0\./,/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./],PRIVATE_IPV6_PATTERNS=[/^::1$/i,/^fe80:/i,/^f[cd][0-9a-f]{2}:/i],isIpv4MappedPrivateIpv6=$=>{const ns=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec($);if(!ns)return!1;const ss=ns[1];return PRIVATE_IPV4_PATTERNS.some(os=>os.test(ss))},LOCAL_HOSTNAME_PATTERNS=[/^localhost$/i,/\.localhost$/i,/^localhost\./i,/\.local$/i,/\.internal$/i,/\.lan$/i,/\.intranet$/i],validateInspirationUrl=$=>{const ns=$.trim();if(!ns)return{ok:!1,reason:"URL is empty."};let ss;try{ss=new URL(ns)}catch{return{ok:!1,reason:`URL is not valid: ${ns}`}}if(ss.protocol!=="http:"&&ss.protocol!=="https:")return{ok:!1,reason:`Only HTTP and HTTPS inspiration links are supported (got '${ss.protocol.replace(/:$/,"")}').`};const os=ss.hostname.toLowerCase();return os?isLocalLiteralHostname(os)?{ok:!1,reason:`URL hostname '${os}' resolves to a local or private-network target.`}:(ss.hash="",{ok:!0,url:ss,normalized:ss.toString()}):{ok:!1,reason:"URL is missing a hostname."}},isLocalLiteralHostname=$=>{const ns=$.replace(/^\[|\]$/g,"");return!!(PRIVATE_IPV4_PATTERNS.some(ss=>ss.test(ns))||PRIVATE_IPV6_PATTERNS.some(ss=>ss.test(ns))||isIpv4MappedPrivateIpv6(ns)||LOCAL_HOSTNAME_PATTERNS.some(ss=>ss.test(ns)))},projectContextExisting=objectType({kind:literalType("existing")}),DESIGN_CONTEXT_MARKDOWN_MAX_LENGTH=5e4,DESIGN_CONTEXT_SLUG_MAX_LENGTH=120,SOURCE_URL_MAX_LENGTH=2048,SOURCE_ARTIFACT_LABEL_MAX_LENGTH=80,SOURCE_ARTIFACT_CONTENT_MAX_LENGTH=8e3,SOURCE_FINDING_MAX_LENGTH=400,SOURCE_LIST_MAX_ITEMS=24,SOURCE_SCREENSHOT_MAX_ITEMS=16,sourceIntentRoleSchema=enumType(["design_source","interaction_reference","asset_source","content_reference","other"]),sourceIntentConfidenceSchema=enumType(["low","medium","high"]),sourceIntentEntrySchema=objectType({url:stringType().min(1).max(SOURCE_URL_MAX_LENGTH).optional(),imageRef:stringType().min(1).max(64).optional(),role:sourceIntentRoleSchema,confidence:sourceIntentConfidenceSchema,reason:stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)}).refine($=>!!$.url!=!!$.imageRef,{message:"sourceIntent entry must specify exactly one of `url` or `imageRef`."}),sourceIntentArtifactSchema=objectType({sources:arrayType(sourceIntentEntrySchema).min(1).max(SOURCE_LIST_MAX_ITEMS)}),designContextEntrySchema=discriminatedUnionType("kind",[objectType({kind:literalType("slug"),slug:stringType().min(1).max(DESIGN_CONTEXT_SLUG_MAX_LENGTH)}),objectType({kind:literalType("markdown"),content:stringType().min(1).max(DESIGN_CONTEXT_MARKDOWN_MAX_LENGTH),label:stringType().min(1).max(60)})]),sourceArtifactKindSchema=enumType(["urlText","siteBrief","visualBrief","screenshotNotes","motionBrief"]),sourceArtifactInputSchema=objectType({kind:sourceArtifactKindSchema,label:stringType().min(1).max(SOURCE_ARTIFACT_LABEL_MAX_LENGTH),content:stringType().min(1).max(SOURCE_ARTIFACT_CONTENT_MAX_LENGTH)}),sourceRoleSchema=enumType(["primary","inspiration","competitor"]),sourceRoleEntrySchema=objectType({url:stringType().min(1).max(SOURCE_URL_MAX_LENGTH),role:sourceRoleSchema,rationale:stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH).optional()}),sourceContextArtifactSchema=objectType({sourceFindings:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).min(1).max(SOURCE_LIST_MAX_ITEMS),sectionInventory:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).min(1).max(SOURCE_LIST_MAX_ITEMS),visualObservations:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).min(1).max(SOURCE_LIST_MAX_ITEMS),sourceRoles:arrayType(sourceRoleEntrySchema).min(1).max(SOURCE_LIST_MAX_ITEMS),qualityBar:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).min(1).max(SOURCE_LIST_MAX_ITEMS),screenshotReferences:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).max(SOURCE_SCREENSHOT_MAX_ITEMS).optional(),risks:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).max(SOURCE_LIST_MAX_ITEMS).optional()}),sourceContextInputSchema=objectType({sourceUrls:arrayType(stringType().min(1).max(SOURCE_URL_MAX_LENGTH)).max(SOURCE_LIST_MAX_ITEMS).optional(),preserveBrand:booleanType().optional(),sourceArtifacts:arrayType(sourceArtifactInputSchema).max(SOURCE_LIST_MAX_ITEMS).optional(),artifact:sourceContextArtifactSchema.optional(),sourceIntent:sourceIntentArtifactSchema.optional(),designDecision:enumType(["let_rivet_choose","go_custom"]).optional()}),executionModeSchema=enumType(["static_preview","vite_app"]),executionConfidenceSchema=enumType(["low","medium","high"]),assetPlanEntrySchema=objectType({source:stringType().min(1).max(SOURCE_URL_MAX_LENGTH),destination:stringType().min(1).max(SOURCE_URL_MAX_LENGTH),referenceAs:stringType().min(1).max(SOURCE_URL_MAX_LENGTH)}),executionCapabilityPlanSchema=objectType({mode:executionModeSchema,confidence:executionConfidenceSchema,reason:stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH),assetPlan:arrayType(assetPlanEntrySchema).max(SOURCE_LIST_MAX_ITEMS).optional(),runtimeRequirements:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).max(SOURCE_LIST_MAX_ITEMS).optional(),userQuestion:stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH).optional()}),projectContextFresh=objectType({kind:literalType("fresh"),workspacePath:stringType().min(1),workspaceRoot:stringType().min(1),framework:enumType(["vite","next","astro","remix"]).optional(),assetSourceRoot:stringType().min(1).max(SOURCE_URL_MAX_LENGTH).optional(),designContext:arrayType(designContextEntrySchema).optional(),sourceContext:sourceContextInputSchema.optional(),executionPlan:executionCapabilityPlanSchema.optional()}),projectContextSchema=discriminatedUnionType("kind",[projectContextExisting,projectContextFresh]),targetSchema=objectType({type:enumType(["element","file","route"]),ref:stringType().min(1)}),briefSchema=objectType({briefId:stringType().min(1),label:stringType().min(1).max(40).describe('≤ 4 words. Rendered as the variant card title in the UI. e.g. "Spring blur", "Linear sharp".'),body:stringType().min(1).max(200).describe(`Exactly ONE sentence, ≤ 12 words. Single evocative descriptor of the variant's direction — what makes it distinct. Rendered as the card subtitle. e.g. "Apple-style spring physics with ambient blur and soft edges". No bullets, no lists, no line breaks.`),visualReferenceUrl:stringType().url().refine($=>validateInspirationUrl($).ok,{message:"visualReferenceUrl must be an HTTP(S) URL that does not target local or private networks"}).optional().describe("Optional HTTP(S) inspiration URL. Subject to SSRF guard — must not resolve to local or private network targets.")}),VARIANT_COUNT_MIN=2,VARIANT_COUNT_MAX=8;stringType().optional(),stringType().optional(),stringType().min(1),numberType().int().min(VARIANT_COUNT_MIN).max(VARIANT_COUNT_MAX).optional(),targetSchema.optional(),projectContextSchema.optional();stringType().min(1),stringType().min(1),numberType().int().nonnegative(),stringType().optional(),arrayType(briefSchema).min(1).max(8);const browserDesignContextSchema=objectType({url:stringType().min(1).max(SOURCE_URL_MAX_LENGTH).optional(),imageRef:stringType().min(1).max(64).optional(),label:stringType().min(1).max(60),markdown:stringType().min(1).max(DESIGN_CONTEXT_MARKDOWN_MAX_LENGTH)}).refine($=>!!$.url!=!!$.imageRef,{message:"designContexts entry must specify exactly one of `url` or `imageRef`."});objectType({sourceIntent:sourceIntentArtifactSchema,sourceContext:sourceContextArtifactSchema,designContexts:arrayType(browserDesignContextSchema).max(SOURCE_LIST_MAX_ITEMS).optional(),executionPlan:executionCapabilityPlanSchema});stringType().min(1),stringType().min(1),numberType().int().nonnegative(),stringType().min(1);stringType().min(1),arrayType(stringType().min(1)).min(1).max(8).optional(),booleanType().optional(),booleanType().optional(),stringType().min(1).optional(),arrayType(objectType({briefId:stringType().min(1),bodyOverride:stringType().optional()})).min(1).max(8).optional();stringType().min(1),stringType().min(1),booleanType().optional(),booleanType().optional(),stringType().min(1).optional();enumType(["check","wait","request_work"]).optional();stringType().min(1),stringType().optional(),numberType().int().min(1).max(8).optional();enumType(["running","succeeded","failed","cancelled"]);stringType().min(1),stringType().min(1),stringType().min(1),numberType().int().nonnegative(),unknownType().optional(),objectType({code:stringType(),message:stringType()}).optional(),stringType().optional(),numberType().int().nonnegative().optional(),numberType().int().nonnegative().optional(),stringType().optional();stringType().min(1),numberType().int().min(VARIANT_COUNT_MIN).max(VARIANT_COUNT_MAX),arrayType(stringType().min(1).max(SOURCE_URL_MAX_LENGTH)).max(SOURCE_LIST_MAX_ITEMS).optional(),booleanType().optional(),arrayType(sourceArtifactInputSchema).max(SOURCE_LIST_MAX_ITEMS).optional(),booleanType().optional(),stringType().optional();stringType().min(1),stringType().optional();stringType().min(1),stringType().min(1),stringType().optional();enumType(["existing","zero_to_one"]).describe('"existing": vary an existing project at projectPath/cwd (spawns code_gen items). "zero_to_one": prompt-only fresh project; server derives destinationPath (spawns static_preview items).');const startVariantsBriefContent=briefSchema.omit({briefId:!0});stringType().min(1),numberType().int().min(VARIANT_COUNT_MIN).max(VARIANT_COUNT_MAX).optional(),targetSchema.optional(),arrayType(startVariantsBriefContent).min(VARIANT_COUNT_MIN).max(VARIANT_COUNT_MAX).optional().describe("One brief per variant. `briefs.length` sets the variant count (3-5); do NOT also pass `count`. Each brief MUST describe a distinct direction — never copy the user prompt verbatim into a body."),enumType(["vite"]).optional(),stringType().optional(),stringType().optional(),arrayType(designContextEntrySchema).optional(),sourceContextInputSchema.optional(),stringType().optional();const variantHistoryStatusSchema=enumType(["completed","committed","rejected","cancelled"]);stringType().optional(),numberType().int().min(1).max(500).optional(),variantHistoryStatusSchema.optional();stringType().optional(),stringType().min(1),stringType().min(1),booleanType().optional();const DEFAULT_VARIANT_COUNT$1=3,PATTERNS=[/\bvariants?\s*[:=]\s*(\d+)(?!\.\d)\b/i,/\b(\d+)(?!\.\d)\s*variants?\b/i,/\bvariants?\s+(\d+)(?!\.\d)\b/i],clamp=$=>$<VARIANT_COUNT_MIN?VARIANT_COUNT_MIN:$>VARIANT_COUNT_MAX?VARIANT_COUNT_MAX:$,parseVariantCount=$=>{if(!$)return DEFAULT_VARIANT_COUNT$1;for(const ns of PATTERNS){const ss=ns.exec($);if(!ss)continue;const os=ss[1];if(!/^\d+$/.test(os))continue;const ls=Number.parseInt(os,10);if(!(!Number.isInteger(ls)||ls<=0))return clamp(ls)}return DEFAULT_VARIANT_COUNT$1},POPOVER_OFFSET_Y=8,POPOVER_W=320,VIEWPORT_PAD=8,DEFAULT_VARIANT_COUNT=3,OPTIMISTIC_GENERATING_TIMEOUT_MS=15e3,IFRAME_ABOVE_THRESHOLD_PCT=.65,CommentPopover=({elementContext:$,target:ns=BASE_TARGET,pin:ss,dragBox:os,position:ls,onClose:us,existingCommentId:ps,isMCPSession:hs=!1,onInputChange:ws,shake:ja})=>{var oc,fc;const Ha=usePostHog(),Va=useAnimationControls(),[Ga,Wa]=useAtom(commentsAtom),Ka=useAtomValue(iframeRefAtom),qa=useAtomValue(featureFlagsAtom).variants.isEnabled,Ja=useSetAtom(activeCarouselCommentIdAtom),Ya=useSetAtom(modeAtom),Xa=useSetAtom(panelOpenAtom),el=useSetAtom(variantsPanelOpenAtom),nl=useSetAtom(variantsPanelOptimisticGeneratingAtom),rl=useStore(),{generateVariantsForComment:sl}=useCommentVariantGeneration(),{sendVariantRequestComment:il}=useChangeSender(),{startCodeGeneration:al}=useVariantCodeGeneration(),ml=useAtomValue(agentVariantsSnapshotAtom).active===!0,vl=useAtomValue(globalChangeTrackerAtom),yl=ps?Ga.get(ps):void 0,wl=(yl==null?void 0:yl.instruction)??"",[El,pl]=reactExports.useState(wl),[Al,ll]=reactExports.useState((yl==null?void 0:yl.images)??[]),[dl,fl]=reactExports.useState((yl==null?void 0:yl.references)??[]),[ul,bl]=reactExports.useState(!1),hl=reactExports.useRef(null),Sl=reactExports.useRef(null),kl=reactExports.useRef(null);reactExports.useEffect(()=>{const Xl=setTimeout(()=>{const ec=hl.current;ec&&(ec.focus(),ec.selectionStart=ec.selectionEnd=ec.value.length)},150);return()=>clearTimeout(Xl)},[]);const Pl=reactExports.useCallback(()=>{kl.current&&(clearTimeout(kl.current),kl.current=null)},[]);reactExports.useEffect(()=>()=>{Pl()},[Pl]);const Ol=reactExports.useRef(ja);reactExports.useEffect(()=>{ja!==Ol.current&&Va.start({x:[0,-5,5,-4,4,-2,2,0],y:[0,1.5,-1.5,1,-1,.5,-.5,0],transition:{duration:.45,ease:"easeInOut"}})},[ja,Va]);const Tl=El.trim()!==wl.trim()&&El.trim()!==""||Al.length!==(((oc=yl==null?void 0:yl.images)==null?void 0:oc.length)??0)||dl.length!==(((fc=yl==null?void 0:yl.references)==null?void 0:fc.length)??0),Il=ps?Tl:El.trim()!=="",zl=reactExports.useCallback(Xl=>{fl(Xl),ws==null||ws(El.trim()!==""||Al.length>0||Xl.length>0)},[El,Al.length,ws]),Nl=reactExports.useCallback(Xl=>{zl(dl.filter(ec=>!(ec.sessionId===Xl.sessionId&&ec.variantId===Xl.variantId)))},[dl,zl]),Bl=reactExports.useCallback(Xl=>{us(Xl)},[us]),Zl=reactExports.useCallback(Xl=>{Xl.style.height="auto",Xl.style.height=`${Xl.scrollHeight}px`},[]),Gl=reactExports.useCallback(Xl=>{compressImage(Xl).then(ec=>{ll(Ac=>[...Ac,ec])}).catch(()=>{console.warn("[CommentPopover] Failed to process image:",Xl.name)})},[]),ql=reactExports.useCallback(Xl=>{ll(ec=>[...ec,Xl]),ws==null||ws(!0)},[ws]),{isDragOver:cc,dropHandlers:gc}=useImageDrop(ql),pc=Xl=>{const ec=Xl.target.files;if(!ec)return;let Ac=!1;for(const Sc of Array.from(ec))Sc.type.startsWith("image/")&&(Gl(Sc),Ac=!0);Sl.current&&(Sl.current.value=""),Ac&&(ws==null||ws(!0))},Jl=Xl=>{var Ac;const ec=(Ac=Xl.clipboardData)==null?void 0:Ac.items;if(ec){for(const Sc of Array.from(ec))if(Sc.type.startsWith("image/")){Xl.preventDefault();const Cc=Sc.getAsFile();Cc&&(Gl(Cc),ws==null||ws(!0))}}},bc=Xl=>{const ec=Al.filter((Ac,Sc)=>Sc!==Xl);ll(ec),ws==null||ws(El.trim()!==""||ec.length>0)},Hl=reactExports.useCallback(async Xl=>{var Zc,pu;const ec=El.trim();if(!ec)return;const Ac=(Xl==null?void 0:Xl.forceGenerateVariants)===!0&&!hs,Sc=Ac?{styleVariants:void 0,selectedVariantIndex:void 0,finalizedVariant:void 0,variantGenerationStatus:"generating",variantGenerationError:void 0,requestedVariantCount:DEFAULT_VARIANT_COUNT}:{};if(Ac&&ps){cancelVariantGeneration(ps);const Xc=rl.get(appliedVariantDiffAtom);Xc&&Xc.commentId===ps&&(await revertVariantDiff(Xc.diff),rl.set(appliedVariantDiffAtom,null));const hu=(pu=(Zc=Ga.get(ps))==null?void 0:Zc.finalizedVariant)==null?void 0:pu.codeDiff;hu&&await revertVariantDiff(hu)}let Cc;if(ps)Cc=ps,Wa(Xc=>{const hu=Xc.get(ps);if(!hu)return Xc;const Gu=new Map(Xc);return Gu.set(ps,{...hu,instruction:ec,images:Al.length>0?Al:void 0,references:dl.length>0?dl:void 0,variantRequest:void 0,...Sc}),Gu}),Ha==null||Ha.capture("comment_edited",{instruction_length:ec.length,image_count:Al.length,reference_count:dl.length,has_variants:Ac});else{const Xc=crypto.randomUUID();Cc=Xc;const hu={id:Xc,target:ns,elementContext:$,pin:ss,dragBox:os,instruction:ec,images:Al.length>0?Al:void 0,references:dl.length>0?dl:void 0,...Sc,status:"pending"};Wa(Gu=>{const Rc=new Map(Gu);return Rc.set(Xc,hu),Rc}),Ha==null||Ha.capture("comment_added",{instruction_length:ec.length,image_count:Al.length,reference_count:dl.length,has_variants:Ac})}Bl({preserveSelection:!0}),Ac&&(Ja(Cc),sl({commentId:Cc,instruction:ec,elementContext:$,requestedVariantCount:DEFAULT_VARIANT_COUNT,onVariantsReady:Xc=>void al(Xc)}))},[El,Al,dl,ps,$,ns,ss,os,Ga,Wa,Ha,hs,sl,al,Bl,Ja,rl]),Ql=reactExports.useCallback(async()=>{const Xl=El.trim();if(!Xl)return;const ec=parseVariantCount(El),Ac=ps??crypto.randomUUID();if(ps)Wa(Cc=>{const Zc=Cc.get(ps);if(!Zc)return Cc;const pu=new Map(Cc);return pu.set(ps,{...Zc,instruction:Xl,images:void 0,references:dl.length>0?dl:void 0,variantRequest:{count:ec}}),pu}),Ha==null||Ha.capture("comment_edited",{instruction_length:Xl.length,image_count:0,reference_count:dl.length,has_variants:!1});else{const Cc={id:Ac,target:ns,elementContext:$,pin:ss,dragBox:os,instruction:Xl,references:dl.length>0?dl:void 0,variantRequest:{count:ec},status:"pending"};Wa(Zc=>{const pu=new Map(Zc);return pu.set(Ac,Cc),pu}),Ha==null||Ha.capture("comment_added",{instruction_length:Xl.length,image_count:0,reference_count:dl.length,has_variants:!1})}Ha==null||Ha.capture("comment_variant_trigger_started",{source:"mcp",requestedCount:ec}),Pl(),nl(!0),kl.current=setTimeout(()=>{kl.current=null,nl(!1)},OPTIMISTIC_GENERATING_TIMEOUT_MS),el(!0),Xa(!0),Ya("view"),Bl({preserveSelection:!0});const Sc=await il(Ac);Sc.success||(Pl(),nl(!1),toast.error(Sc.error||"Failed to queue direction request"))},[El,dl,ps,$,ns,ss,os,Wa,Ha,Bl,Ya,Xa,el,nl,il,Pl]),Yl=Hl,ac=reactExports.useCallback(async()=>{var Xl;if(ps){cancelVariantGeneration(ps);const ec=(Ka==null?void 0:Ka.current)??null;ec&&restoreCommentPreviewBaselines(ec,Ga.values());const Ac=rl.get(appliedVariantDiffAtom);Ac&&Ac.commentId===ps&&(await revertVariantDiff(Ac.diff),rl.set(appliedVariantDiffAtom,null));const Sc=Ga.get(ps),Cc=(Xl=Sc==null?void 0:Sc.finalizedVariant)==null?void 0:Xl.codeDiff;Cc&&await revertVariantDiff(Cc),Wa(Zc=>{const pu=new Map(Zc);return pu.delete(ps),pu}),Ha==null||Ha.capture("comment_deleted")}Bl()},[ps,Ga,Ka,Wa,Bl,Ha,rl]),lc=reactExports.useCallback(Xl=>{Xl.key==="Enter"&&(Xl.metaKey||Xl.ctrlKey)&&(Xl.preventDefault(),Xl.nativeEvent.stopImmediatePropagation(),Yl()),Xl.key==="Escape"&&(Xl.nativeEvent.stopImmediatePropagation(),Bl({preserveSelection:!0}))},[Yl,Bl]),Dl=window.innerHeight,Ll=ls.y/Dl>IFRAME_ABOVE_THRESHOLD_PCT,Kl=ps?"Save":"Add",nc=(()=>{if(El.trim()==="")return"empty_instruction";if(Al.length>0)return"images_attached";if(ml)return"active_session";if(vl.getStyleChanges().length>0||vl.getTextChanges().length>0)return"mixed_batch";const ec=Array.from(Ga.values()).filter(Cc=>Cc.status==="pending"&&Cc.id!==ps);return ec.some(Cc=>!!Cc.variantRequest)?"duplicate_variant_request":ec.some(Cc=>!Cc.variantRequest)?"mixed_batch":null})(),_l=parseVariantCount(El),uc=(()=>{switch(nc){case"empty_instruction":return"Add an instruction to generate directions.";case"images_attached":return"Remove attached images — image context is not supported for directions yet.";case"mixed_batch":return"Directions must be sent on their own — clear other pending changes first.";case"duplicate_variant_request":return"A direction request is already pending — send or cancel it first.";case"active_session":return"A directions session is already running — finish or cancel it first.";default:return`Generate ${_l} design directions for the selected element. You'll preview and pick one.`}})();return jsxRuntimeExports.jsx("div",{className:"fixed z-comment-preview cursor-auto",style:{top:Ll?ls.y-POPOVER_OFFSET_Y:ls.y+POPOVER_OFFSET_Y,left:Math.max(VIEWPORT_PAD,Math.min(ls.x-POPOVER_W/2,window.innerWidth-POPOVER_W-VIEWPORT_PAD)),transform:Ll?"translateY(-100%)":void 0},onClick:Xl=>Xl.stopPropagation(),children:jsxRuntimeExports.jsx(motion.div,{animate:Va,children:jsxRuntimeExports.jsxs(motion.div,{className:"relative flex w-80 flex-col gap-2 rounded-xl bg-main p-4 shadow-2xl",style:{transformOrigin:"center 24px"},initial:{scale:.82,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.82,opacity:0,transition:{duration:.1,ease:[.55,0,1,.45]}},transition:{type:"spring",stiffness:500,damping:28,mass:.8},...gc,children:[cc?jsxRuntimeExports.jsx("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-xl border-2 border-dashed border-primary bg-primary/10",children:jsxRuntimeExports.jsx("span",{className:"text-sm font-medium text-content",children:"Drop image here"})}):null,dl.length>0?jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:dl.map(Xl=>jsxRuntimeExports.jsx(CommentReferenceChip,{reference:Xl,onRemove:()=>Nl(Xl)},`${Xl.sessionId}:${Xl.variantId}`))}):null,jsxRuntimeExports.jsx("textarea",{ref:Xl=>{hl.current=Xl,Xl&&Zl(Xl)},value:El,onChange:Xl=>{const ec=Xl.target.value;pl(Xl.target.value),Zl(Xl.target),ws==null||ws(ec.trim()!==""||Al.length>0)},onKeyDown:lc,onPaste:Jl,placeholder:"What should change?",rows:3,style:{maxHeight:"9rem",overflowY:"auto"},className:"w-full resize-none rounded-lg border border-divider bg-main-light p-3 text-sm text-content outline-none transition-colors duration-100 placeholder:text-content-subtle focus:border-primary focus:ring-1 focus:ring-primary/30"}),Al.length>0?jsxRuntimeExports.jsx("div",{className:"max-h-40 overflow-y-auto rounded",children:jsxRuntimeExports.jsx("div",{className:`grid gap-1.5 ${Al.length===1?"grid-cols-1":"grid-cols-2"}`,children:Al.map((Xl,ec)=>jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("img",{src:Xl,alt:`Reference ${ec+1}`,className:`w-full rounded border border-divider object-cover ${Al.length===1?"max-h-32":"aspect-[4/3]"}`}),jsxRuntimeExports.jsx("button",{onClick:()=>bc(ec),className:"absolute right-1 top-1 rounded-full bg-red-500/80 p-0.5 text-white backdrop-blur-sm hover:bg-red-600",children:jsxRuntimeExports.jsx(n$1,{className:"h-2.5 w-2.5",weight:"bold"})})]},ec))})}):null,jsxRuntimeExports.jsx("input",{ref:Sl,type:"file",accept:"image/*",multiple:!0,onChange:pc,className:"hidden"}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[ps?jsxRuntimeExports.jsx("button",{type:"button",onClick:ac,className:"p-1 text-content-subtle transition-colors hover:text-accent-error",title:"Delete comment",children:jsxRuntimeExports.jsx(n$2,{className:"h-4 w-4",weight:"bold"})}):null,jsxRuntimeExports.jsx(Tooltip,{label:"Attach",children:jsxRuntimeExports.jsx("button",{type:"button","aria-label":"Attach reference image",onClick:()=>{var Xl;return(Xl=Sl.current)==null?void 0:Xl.click()},className:"p-1 text-content-subtle transition-colors hover:text-content",children:jsxRuntimeExports.jsx(I,{className:"h-4 w-4",weight:"bold"})})}),jsxRuntimeExports.jsx(Tooltip,{label:"Reference a direction",children:jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("button",{type:"button","aria-label":"Reference a direction","aria-haspopup":"listbox","aria-expanded":ul,onClick:()=>bl(Xl=>!Xl),className:`p-1 transition-colors ${ul||dl.length>0?"text-content":"text-content-subtle hover:text-content"}`,children:jsxRuntimeExports.jsx(n$9,{className:"h-4 w-4",weight:"bold"})}),ul?jsxRuntimeExports.jsx("div",{className:"absolute bottom-full left-0 z-20 mb-2",children:jsxRuntimeExports.jsx(CommentReferencePicker,{attached:dl,commentTarget:ns,onChange:zl,onClose:()=>bl(!1)})}):null]})}),!hs&&qa?jsxRuntimeExports.jsx(Tooltip,{label:"Vary",children:jsxRuntimeExports.jsx("button",{type:"button","aria-label":"Generate 3 directions",onClick:()=>Yl({forceGenerateVariants:!0}),disabled:!Il,className:"p-1 text-content-subtle transition-colors hover:text-content disabled:opacity-50",children:jsxRuntimeExports.jsx(n$8,{className:"h-4 w-4",weight:"bold"})})}):null,hs?jsxRuntimeExports.jsx(Tooltip,{label:uc,children:jsxRuntimeExports.jsx("button",{type:"button","aria-label":"Generate directions","data-testid":"mcp-variant-trigger",onClick:()=>void Ql(),disabled:nc!==null,className:"p-1 text-content-subtle transition-colors hover:text-content disabled:opacity-50",children:jsxRuntimeExports.jsx(n$8,{className:"h-4 w-4",weight:"bold"})})}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>Bl(),className:"px-2 py-1.5 text-sm text-content-muted transition-colors hover:text-content",children:"Cancel"}),jsxRuntimeExports.jsx("button",{onClick:()=>Yl(),disabled:!Il,className:"rounded-full bg-primary px-5 py-1.5 text-sm font-medium text-white transition-colors hover:bg-primary-hover disabled:opacity-50",children:Kl})]})]})]})})})},log$6=createLogger("PreviewSurface"),PreviewSurface=({target:$,src:ns,framework:ss,mode:os,isUpstreamReady:ls,remountKey:us})=>{const ps=previewTargetKey($),hs=useSetAtom(registerSurfaceIframeAtom),ws=useSetAtom(registerSurfaceAdapterAtom),ja=useSetAtom(selectedElementTargetAtom),Ha=useAtomValue(commentsAtom),Va=useSetAtom(editingCommentIdAtom),Ga=useSetAtom(activeCarouselCommentIdAtom),Wa=useAtomValue(isMCPSessionAtom),Ka=useAtomValue(variantsPanelOpenAtom),Za=useSetAtom(isCommentDraftDirtyAtom),[qa,Ja]=useAtom(commentShakeAtom),Ya=useAtomValue(panelClickVersionAtom),[Xa,el]=reactExports.useState(null),nl=useStore(),[rl,sl]=useAtom(commentDraftAtom),il=reactExports.useCallback(()=>nl.get(isCommentDraftDirtyAtom),[nl]),al=rl&&previewTargetsEqual(rl.target,$)?rl:null,cl=reactExports.useRef(null),{enterEditMode:ml}=useInlineTextEdit({iframeRef:cl}),vl=useAtomValue(featureFlagsAtom);useElementResize({iframeRef:cl,enabled:vl.resize.isEnabled,surfaceId:ps});const yl=reactExports.useCallback(Nl=>Za(Nl),[Za]),wl=reactExports.useCallback((Nl,Bl,Zl)=>{if(il()){Ja(Gl=>Gl+1);return}yl(!1),Va(null),Ga(null),ja($),sl({key:crypto.randomUUID(),target:$,elementContext:Nl,pin:Bl,dragBox:Zl})},[il,Ja,yl,Va,Ga,ja,sl,$]),El=reactExports.useCallback(()=>{if(il()){Ja(Nl=>Nl+1);return}sl(null),Va(null),Ga(null),yl(!1)},[il,Ja,sl,yl,Va,Ga]),pl=reactExports.useCallback((Nl,Bl,Zl)=>{ml(Nl,Bl,Zl)},[ml]),{setupIframe:Al,clearSelectionState:ll,iframeRef:dl}=useIframeSelection({surfaceId:ps,target:$,mode:os,isBoxModelVisible:!0,onTextEdit:pl,onCommentClick:wl,onCommentSelectionClear:El}),fl=reactExports.useRef(Ya);reactExports.useEffect(()=>{Ya!==fl.current&&(fl.current=Ya,os!=="edit"&&(il()||(sl(null),Va(null),Ga(null),yl(!1),ll())))},[Ya,os,il,ll,sl,yl,Va,Ga]);const ul=reactExports.useCallback(Nl=>{sl(null),Va(null),Ga(null),yl(!1),Nl!=null&&Nl.preserveSelection||ll()},[ll,sl,yl,Va,Ga]),bl=reactExports.useCallback(()=>ul({preserveSelection:!0}),[ul]),{startCodeGeneration:hl}=useVariantCodeGeneration(),Sl=reactExports.useCallback(Nl=>{const Bl=Ha.get(Nl);if(!Bl)return;yl(!1);const Zl=Bl.styleVariants&&Bl.styleVariants.length>0;if(Va(Nl),Ga(Zl?Nl:null),ja($),sl({key:crypto.randomUUID(),target:$,elementContext:Bl.elementContext,pin:Bl.pin,dragBox:Bl.dragBox,existingCommentId:Nl}),Bl.variantGenerationStatus!=="generating"&&!Bl.finalizedVariant&&Bl.styleVariants&&!hasVariantGeneration(Nl)){const Gl=Bl.styleVariants.map((ql,cc)=>({v:ql,index:cc+1})).filter(({v:ql})=>ql.changeSpec&&!ql.codeDiff&&!ql.codeStatus);Gl.length>0&&hl({commentId:Nl,sessionId:crypto.randomUUID(),instruction:Bl.instruction,elementContext:Bl.elementContext,variants:Gl.map(({v:ql,index:cc})=>({index:cc,label:ql.label,changeSpec:ql.changeSpec}))})}},[Ha,yl,Va,Ga,ja,sl,$,hl]),kl=reactExports.useCallback((Nl,Bl,Zl=!1)=>{const Gl=dl.current;if(!Gl)return null;const ql=Gl.contentDocument??null;if(!ql)return null;const cc=resolveElementFromContext(ql,Nl);if(!cc)return null;const gc=Gl.getBoundingClientRect(),pc=cc.getBoundingClientRect(),Jl={top:gc.top+pc.top,bottom:gc.top+pc.bottom},bc=Zl&&carouselPillIsBelow(Jl);let Hl=gc.top+pc.top+Bl.elementYPct*pc.height;return Zl&&(Hl=bc?gc.top+pc.bottom+CAROUSEL_BAR_GAP+CAROUSEL_BAR_HEIGHT:gc.top+pc.top-CAROUSEL_BAR_GAP-CAROUSEL_BAR_HEIGHT),{x:gc.left+pc.left+Bl.elementXPct*pc.width,y:Hl}},[dl]),[,Pl]=reactExports.useState(0),Ol=reactExports.useCallback(()=>Pl(Nl=>Nl+1),[]);reactExports.useEffect(()=>{const Nl=dl.current;if(!al||!Nl)return;const Bl=Nl.contentDocument;Bl&&Bl.addEventListener("scroll",Ol,!0);const Zl=new ResizeObserver(Ol);return Zl.observe(Nl),Nl.addEventListener("load",Ol),()=>{Bl&&Bl.removeEventListener("scroll",Ol,!0),Zl.disconnect(),Nl.removeEventListener("load",Ol)}},[al,dl,Ol]);const Tl=al!=null&&al.existingCommentId?(()=>{var Bl;const Nl=Ha.get(al.existingCommentId);return!!((Bl=Nl==null?void 0:Nl.styleVariants)!=null&&Bl.length&&!Nl.finalizedVariant)})():!1,Il=al?kl(al.elementContext,al.pin,Tl):null;reactExports.useEffect(()=>{if(ss!=="static"&&!ls){Xa&&(el(null),ws({surfaceId:ps,adapter:null}));return}if(dl.current&&!Xa){const Nl=ss==="static";console.log(`[PreviewSurface] Creating ${Nl?"Static":""}IframeDisplayAdapter`);const Bl=os==="edit"?"edit":"view",Zl=Nl?new StaticIframeAdapter(dl.current,{mode:Bl,isBoxModelVisible:!0}):new IframeDisplayAdapter(dl.current,{mode:Bl,isBoxModelVisible:!0});Zl.initialize(),el(Zl),ws({surfaceId:ps,adapter:Zl})}},[Xa,ss,ls,os,dl,ws,ps]);const zl=reactExports.useCallback(Nl=>{Nl&&(Al(Nl),cl.current=Nl)},[Al]);return reactExports.useEffect(()=>(hs({surfaceId:ps,ref:dl}),()=>{hs({surfaceId:ps,ref:null}),ws({surfaceId:ps,adapter:null})}),[hs,ws,ps,dl]),reactExports.useEffect(()=>{os!=="comment"&&(il()||(sl(null),Va(null),Ga(null),os==="view"&&ll()))},[os,il,ll,sl,Va,Ga]),jsxRuntimeExports.jsxs("div",{className:"relative h-full w-full",children:[jsxRuntimeExports.jsx("iframe",{ref:zl,src:ns,className:"h-full w-full border-none",title:"Project Preview",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-modals",onLoad:()=>{Na==null||Na.capture("preview_iframe_loaded",{framework:ss,src:ns})},onError:()=>{Na==null||Na.capture("preview_iframe_load_failed",{framework:ss,src:ns}),log$6.warn("Preview iframe failed to load",{framework:ss,src:ns})}},us),ls&&!Ka?jsxRuntimeExports.jsx(CommentMarkerLayer,{onEditComment:Sl,target:$,iframeRef:dl}):null,$.kind==="base"&&ls&&!Wa&&!Ka?jsxRuntimeExports.jsx(CommentCarouselLayer,{onCommentClose:bl}):null,(al==null?void 0:al.dragBox)&&!al.existingCommentId&&dl.current&&(()=>{const Nl=dl.current,Bl=Nl.getBoundingClientRect(),Zl=Nl.contentDocument;if(!Zl)return null;const Gl=resolveElementFromContext(Zl,al.elementContext);if(!Gl)return null;const ql=Gl.getBoundingClientRect(),{leftPct:cc,topPct:gc,widthPct:pc,heightPct:Jl}=al.dragBox;return jsxRuntimeExports.jsx("div",{"data-comment-drag-box":"true",style:{position:"fixed",pointerEvents:"none",zIndex:45,border:"1px dashed var(--color-primary, #FF3300)",background:"rgba(255, 51, 0, 0.08)",borderRadius:2,boxSizing:"border-box",left:Bl.left+ql.left+cc*ql.width,top:Bl.top+ql.top+gc*ql.height,width:pc*ql.width,height:Jl*ql.height}})})(),al&&Il&&!al.existingCommentId&&jsxRuntimeExports.jsx(CommentMarker,{comment:{id:"draft",elementContext:al.elementContext,pin:al.pin,instruction:"",status:"pending"},index:Ha.size,position:Il,onDismiss:()=>{},onEdit:()=>{}}),reactDomExports.createPortal(jsxRuntimeExports.jsx(AnimatePresence,{children:al&&Il?jsxRuntimeExports.jsx(CommentPopover,{elementContext:al.elementContext,target:$,pin:al.pin,dragBox:al.dragBox,position:Il,onClose:ul,existingCommentId:al.existingCommentId,isMCPSession:Wa,onInputChange:Nl=>{yl(Nl)},shake:qa},al.key):null}),document.body)]})},IframePreview=({isInteractionDisabled:$=!1,framework:ns,userPort:ss,activeDemoSessionId:os=null,holdPreviewNavigation:ls=!1})=>{const us=useAtomValue(modeAtom),ps=useAtomValue(iframeRemountKeyAtom),hs=useAtomValue(iframePreviewOverrideUrlAtom),ws=useAtomValue(agentVariantsSnapshotAtom),ja=useAtomValue(variantPreviewPreferDevServerAtom),Ha=useSetAtom(variantPreviewPreferDevServerAtom),Va=ws.active&&ws.projectContext.kind==="fresh";reactExports.useEffect(()=>{ws.active||Ha(!1)},[ws.active,Ha]);const Ga=reactExports.useMemo(()=>{var cl;if(ja||hs||!ws.active)return null;const{stage:sl,variants:il}=ws;if(sl!=="ready"&&sl!=="degraded")return null;const al=il.find(ml=>{var vl;return ml.status==="succeeded"&&((vl=ml.preview)==null?void 0:vl.kind)==="static_artifact"});return((cl=al==null?void 0:al.preview)==null?void 0:cl.kind)==="static_artifact"?al.preview.url:null},[hs,ja,ws]),Wa=hs??Ga,Ka=Wa!==null||Va&&!ja,{isUpstreamReady:Za,iframeRemountKey:qa,initialProbeComplete:Ja}=usePreviewUpstreamHealth(ns,{rerunProbeImmediatelyOnVersion:ps,skip:Ka}),Ya=!!Wa||Za,Xa=`${qa}:${ps}`,el=os?`/try/${encodeURIComponent(os)}`:"",nl=ns==="static"?`${el}/static/`:`${el}/`,rl=Wa??(ls||!Ya?"about:blank":nl);return jsxRuntimeExports.jsxs("div",{className:"relative h-full w-full",children:[!Ya&&Ja?jsxRuntimeExports.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-main/90 px-6",children:jsxRuntimeExports.jsx("div",{role:"alert","aria-live":"polite",className:"flex max-w-sm flex-col items-center gap-5 text-center",children:Va?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-semibold text-content",children:"Directions will appear here"}),jsxRuntimeExports.jsx("p",{className:"text-base leading-relaxed text-content-muted",children:"Select one from the panel to preview it."})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-semibold text-content",children:"Preview isn't connected"}),jsxRuntimeExports.jsx("p",{className:"text-base leading-relaxed text-content-muted",children:"The connection between Rivet and your project is offline. Try restarting Rivet, then click reload below."}),jsxRuntimeExports.jsx("button",{onClick:()=>window.location.reload(),className:"rounded-md bg-primary px-10 py-2.5 text-sm font-medium text-white transition-colors hover:bg-primary-hover",children:"Reload"})]})})}):null,jsxRuntimeExports.jsx(PreviewSurface,{target:BASE_TARGET,src:rl,framework:ns,mode:$?"view":us,isUpstreamReady:Ya,remountKey:Xa})]})},Progress=({message:$,isLoading:ns=!0})=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-content",children:[ns?jsxRuntimeExports.jsx(s$6,{className:"h-4 w-4 shrink-0 animate-spin text-primary",weight:"bold"}):null,jsxRuntimeExports.jsx("span",{className:"whitespace-pre-wrap font-sans",children:$})]});function SecondaryVariantIframe({side:$,sessionId:ns,variantId:ss,url:os,label:ls,isFallback:us=!1}){const ps=useSetAtom(variantSplitViewAtom),hs=useAtomValue(modeAtom),ws=reactExports.useCallback(()=>{if(us){ps(null);return}ps(Ha=>{if(!Ha)return null;const Va={...Ha};return delete Va[$],Va.left||Va.right?Va:null})},[ps,$,us]),ja=reactExports.useMemo(()=>({kind:"variant",sessionId:ns,variantId:ss}),[ns,ss]);return jsxRuntimeExports.jsxs("div",{className:"variant-split-secondary","data-cy":"variant-split-pane","data-variant-id":ss,children:[jsxRuntimeExports.jsxs("div",{className:"variant-split-secondary-toolbar",children:[jsxRuntimeExports.jsx("span",{className:"variant-split-secondary-label",title:ls,children:ls}),jsxRuntimeExports.jsx("button",{type:"button",className:"variant-split-secondary-close",onClick:ws,"aria-label":"Exit split view",children:jsxRuntimeExports.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",focusable:"false",children:jsxRuntimeExports.jsx("path",{d:"M2.5 2.5 L9.5 9.5 M9.5 2.5 L2.5 9.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})})]}),jsxRuntimeExports.jsx("div",{className:"variant-split-secondary-body relative min-h-0 flex-1",children:jsxRuntimeExports.jsx(PreviewSurface,{target:ja,src:os,framework:"static",mode:hs,isUpstreamReady:!0})})]})}const GHOST_WIDTH=220,GHOST_HEIGHT=64;function VariantDragGhost(){const $=useAtomValue(draggedVariantAtom),ns=useAtomValue(draggedVariantPointerAtom),ss=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!$||!ns||!ss.current)return;const os=ns.x-GHOST_WIDTH/2,ls=ns.y-22;ss.current.style.transform=`translate3d(${os}px, ${ls}px, 0)`},[$,ns]),$?jsxRuntimeExports.jsx("div",{ref:ss,"aria-hidden":"true",className:"variant-drag-ghost",style:{width:GHOST_WIDTH,height:GHOST_HEIGHT},children:jsxRuntimeExports.jsx("div",{className:"variant-drag-ghost-row",children:jsxRuntimeExports.jsx("div",{className:"variant-drag-ghost-title",children:$.label})})}):null}function VariantSplitDropZones(){const $=useAtomValue(draggedVariantAtom),ns=useAtomValue(draggedVariantPointerAtom),ss=useSetAtom(draggedVariantAtom),os=useSetAtom(variantSplitViewAtom),ls=reactExports.useRef(null),[us,ps]=reactExports.useState(null),[hs,ws]=reactExports.useState("hidden");reactExports.useEffect(()=>{if(!$){ws("hidden"),ps(null);return}const Va=requestAnimationFrame(()=>ws("visible"));return()=>cancelAnimationFrame(Va)},[$]);const ja=reactExports.useCallback((Va,Ga)=>{const Wa=ls.current;if(!Wa)return null;const Ka=Wa.getBoundingClientRect();return Va<Ka.left||Va>Ka.right||Ga<Ka.top||Ga>Ka.bottom?null:Va<(Ka.left+Ka.right)/2?"left":"right"},[]);if(reactExports.useEffect(()=>{if(!$||!ns)return;const Va=ja(ns.x,ns.y);ps(Ga=>Ga===Va?Ga:Va)},[$,ns,ja]),reactExports.useEffect(()=>{if(!$)return;const Va=Ga=>{const Wa=ja(Ga.clientX,Ga.clientY);if(Wa&&$.url){const Ka={sessionId:$.sessionId,variantId:$.variantId,label:$.label,url:$.url};os(Za=>({...Za??{},[Wa]:Ka})),ws("exiting"),window.setTimeout(()=>ss(null),220)}else ws("exiting"),window.setTimeout(()=>ss(null),220)};return window.addEventListener("pointerup",Va),window.addEventListener("pointercancel",Va),()=>{window.removeEventListener("pointerup",Va),window.removeEventListener("pointercancel",Va)}},[$,ja,ss,os]),!$)return null;const Ha=["variant-drop-zones",hs==="visible"&&"is-visible",hs==="exiting"&&"is-exiting"].filter(Boolean).join(" ");return jsxRuntimeExports.jsxs("div",{ref:ls,className:Ha,"aria-hidden":"true",children:[jsxRuntimeExports.jsx(Zone,{side:"left",hovered:us==="left",canDrop:!!$.url,label:$.label}),jsxRuntimeExports.jsx(Zone,{side:"right",hovered:us==="right",canDrop:!!$.url,label:$.label})]})}function Zone({side:$,hovered:ns,canDrop:ss,label:os}){return jsxRuntimeExports.jsxs("div",{className:["variant-drop-zone",`is-${$}`,ns&&"is-hover",!ss&&"is-disabled"].filter(Boolean).join(" "),children:[jsxRuntimeExports.jsxs("div",{className:"variant-drop-zone-inner",children:[jsxRuntimeExports.jsx("div",{className:`variant-drop-zone-icon is-${$}`}),jsxRuntimeExports.jsx("div",{className:"variant-drop-zone-caption",children:ss?`Add ${$} split`:"Split unavailable for this direction"})]}),jsxRuntimeExports.jsx("div",{className:"variant-drop-zone-preview","aria-hidden":"true",children:jsxRuntimeExports.jsx("div",{className:"variant-drop-zone-preview-label",children:os})}),jsxRuntimeExports.jsx("div",{className:"variant-drop-zone-border"})]})}const PreviewFrame=({isLoading:$=!1,isInteractionDisabled:ns=!1,activeDemoSessionId:ss=null,holdHostedTryoutPreviewNavigation:os=!1})=>{const{config:ls,fetchConfig:us,isLoading:ps,error:hs}=useServerConfig();return reactExports.useEffect(()=>{us().catch(ws=>{Na==null||Na.capture("preview_config_load_failed",{message:ws instanceof Error?ws.message:"unknown_error"})})},[us]),ps?os?jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 w-full flex-1 bg-main","aria-busy":"true"}):jsxRuntimeExports.jsx("div",{className:"flex h-full w-full items-center justify-center bg-main px-6",children:jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:jsxRuntimeExports.jsx(Progress,{message:"Loading..."})})}):hs||!ls?jsxRuntimeExports.jsx("div",{className:"flex h-full w-full items-center justify-center bg-main px-6",children:jsxRuntimeExports.jsxs("div",{className:"max-w-md rounded-lg border border-divider bg-main-light p-4 text-center shadow-lg",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-content",children:"We couldn't load your app preview."}),jsxRuntimeExports.jsx("p",{className:"text-content-subtle mt-2 text-sm",children:hs||"Missing preview configuration from the server."}),jsxRuntimeExports.jsx("p",{className:"text-content-subtle mt-2 text-sm",children:"If this keeps happening, restart your Rivet session and try again."}),jsxRuntimeExports.jsx("button",{type:"button",className:"mt-4 rounded-md border border-divider px-3 py-1.5 text-xs text-content hover:bg-main/80",onClick:()=>{Na==null||Na.capture("preview_config_retry_clicked"),us().catch(ws=>{Na==null||Na.capture("preview_config_load_failed",{message:ws instanceof Error?ws.message:"unknown_error"})})},children:"Retry preview"})]})}):jsxRuntimeExports.jsx(PreviewFrameInner,{isLoading:$,isInteractionDisabled:ns,framework:ls.framework,userPort:ls.userPort,activeDemoSessionId:ss,holdHostedTryoutPreviewNavigation:os})};function PreviewFrameInner($){const ns=useAtomValue(variantSplitViewAtom),ss=useAtomValue(draggedVariantAtom),os=useAtomValue(modeAtom),ls=useSetAtom(changeModeAtom),us=useAtomValue(agentVariantsSnapshotAtom),ps=ns==null?void 0:ns.left,hs=ns==null?void 0:ns.right,ws=reactExports.useMemo(()=>{var Ya,Xa;if(!us.active||us.projectContext.kind!=="fresh"||!(!!ps!=!!hs))return;const qa=(Ya=ps??hs)==null?void 0:Ya.variantId,Ja=us.variants.find(el=>{var nl;return el.status==="succeeded"&&((nl=el.preview)==null?void 0:nl.kind)==="static_artifact"&&el.workItemId!==qa});if(((Xa=Ja==null?void 0:Ja.preview)==null?void 0:Xa.kind)==="static_artifact")return{sessionId:us.sessionId,variantId:Ja.workItemId,label:Ja.label,url:Ja.preview.url}},[us,ps,hs]),ja=ps??(hs?ws:void 0),Ha=hs??(ps?ws:void 0),Va=!ps&&!!ja,Ga=!hs&&!!Ha,Wa=!!(ja||Ha),Ka=jsxRuntimeExports.jsx(IframePreview,{isInteractionDisabled:$.isInteractionDisabled,framework:$.framework,userPort:$.userPort,activeDemoSessionId:$.activeDemoSessionId,holdPreviewNavigation:$.holdHostedTryoutPreviewNavigation});return jsxRuntimeExports.jsxs("div",{className:`variant-preview-region relative flex h-full min-h-0 w-full flex-1 flex-col ${ss?"is-dragging":""} ${Wa?"is-split":""}`,children:[$.isInteractionDisabled?null:jsxRuntimeExports.jsx(CommandBar,{mode:os,onModeChange:ls,isLoading:$.isLoading}),jsxRuntimeExports.jsxs("div",{className:"variant-preview-row flex h-full min-h-0 w-full flex-1",children:[ja&&jsxRuntimeExports.jsx(SecondaryVariantIframe,{side:"left",sessionId:ja.sessionId,variantId:ja.variantId,url:ja.url,label:ja.label,isFallback:Va},`left-${ja.sessionId}:${ja.variantId}`),!(ja&&Ha)&&jsxRuntimeExports.jsx("div",{className:"variant-preview-primary flex h-full min-h-0 flex-1 flex-col",children:Ka}),Ha&&jsxRuntimeExports.jsx(SecondaryVariantIframe,{side:"right",sessionId:Ha.sessionId,variantId:Ha.variantId,url:Ha.url,label:Ha.label,isFallback:Ga},`right-${Ha.sessionId}:${Ha.variantId}`)]}),jsxRuntimeExports.jsx("div",{className:"variant-preview-atmosphere","aria-hidden":"true"}),jsxRuntimeExports.jsx(VariantSplitDropZones,{}),jsxRuntimeExports.jsx(VariantDragGhost,{})]})}const log$5=createLogger("SupportTicketModal"),MESSAGE_MAX_LENGTH=5e3,DEFAULT_TICKET_TYPE="feedback",extractValidationMessage=$=>{var os;if(!$)return null;const ns=(os=$.formErrors)==null?void 0:os[0];if(ns)return ns;const ss=$.fieldErrors??{};for(const ls of Object.values(ss)){const us=ls==null?void 0:ls[0];if(us)return us}return null},parseSupportTicketError=async $=>{let ns;try{ns=await $.json()}catch{ns=void 0}if($.status===400){if(typeof(ns==null?void 0:ns.details)=="string"&&ns.details.trim())return ns.details;if(typeof(ns==null?void 0:ns.details)=="object"&&ns.details!==null){const ss=extractValidationMessage(ns.details);if(ss)return ss}return"Please check your feedback and try again."}return $.status>=500?typeof(ns==null?void 0:ns.details)=="string"&&ns.details.trim()?ns.details:"Could not send feedback right now. Please try again later.":typeof(ns==null?void 0:ns.error)=="string"&&ns.error.trim()?ns.error:`HTTP ${$.status}`},SupportTicketModal=({isOpen:$,onClose:ns,contactEmail:ss})=>{const os=usePostHog(),[ls,us]=reactExports.useState(""),[ps,hs]=reactExports.useState(!1),ws=reactExports.useCallback(()=>{us("")},[]),ja=reactExports.useCallback(()=>{ps||(ws(),ns())},[ps,ns,ws]),Ha=reactExports.useCallback(async()=>{const Ka=ls.trim();if(!(!Ka||ps)){hs(!0);try{const Za=typeof(os==null?void 0:os.get_session_id)=="function"?os.get_session_id():void 0,qa=typeof(os==null?void 0:os.get_distinct_id)=="function"?os.get_distinct_id():void 0,Ja=ss==null?void 0:ss.trim(),Ya=await fetch("/api/support/tickets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:DEFAULT_TICKET_TYPE,message:Ka,contactEmail:Ja||void 0,metadata:{posthogSessionId:Za??void 0,posthogDistinctId:qa??void 0,appVersion:"0.9.8",appEnvironment:"production",pageUrl:window.location.href,userAgent:navigator.userAgent,submittedAt:new Date().toISOString()}})});if(!Ya.ok){const Xa=await parseSupportTicketError(Ya);throw new Error(Xa)}os==null||os.capture("support_ticket_submitted",{ticket_type:DEFAULT_TICKET_TYPE,has_posthog_session_id:!!Za}),toast.success("Feedback sent",{description:"Thanks for sharing this."}),ws(),ns()}catch(Za){const qa=Za instanceof Error?Za.message:"Failed to send message";os==null||os.capture("support_ticket_submit_failed",{ticket_type:DEFAULT_TICKET_TYPE,error:qa}),log$5.error("Failed to submit support ticket:",qa),toast.error("Could not send feedback",{description:qa})}finally{hs(!1)}}},[ss,ps,ls,ns,os,ws]),Va=reactExports.useCallback(Ka=>{Ka.key==="Enter"&&(Ka.metaKey||Ka.ctrlKey)&&(Ka.preventDefault(),Ha())},[Ha]),Ga=MESSAGE_MAX_LENGTH-ls.length,Wa=ps||ls.trim().length===0;return jsxRuntimeExports.jsx(Root$1,{open:$,onOpenChange:Ka=>!Ka&&ja(),children:jsxRuntimeExports.jsxs(Portal,{children:[jsxRuntimeExports.jsx(Overlay,{className:"fixed inset-0 z-max bg-black/40"}),jsxRuntimeExports.jsx(Content$1,{className:"fixed left-1/2 top-1/2 z-max w-[480px] -translate-x-1/2 -translate-y-1/2 rounded-lg border border-divider bg-main p-6 shadow-xl outline-none",children:jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(Title,{className:"text-lg font-semibold text-content",children:"Send feedback"}),jsxRuntimeExports.jsx(Close,{asChild:!0,children:jsxRuntimeExports.jsx("button",{className:"rounded p-1 text-content-subtle transition-colors hover:text-content",disabled:ps,children:jsxRuntimeExports.jsx(n$1,{className:"h-4 w-4",weight:"bold"})})})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-content-subtle",children:"Tell us what happened or what we can improve."}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("label",{htmlFor:"support-ticket-message",className:"text-xs font-medium text-content-muted",children:"Your feedback"}),jsxRuntimeExports.jsx("textarea",{id:"support-ticket-message",value:ls,onChange:Ka=>us(Ka.target.value),onKeyDown:Va,maxLength:MESSAGE_MAX_LENGTH,rows:7,disabled:ps,placeholder:"What happened?",className:"w-full resize-none rounded-md border border-divider bg-main-input px-3 py-2 text-sm text-content outline-none placeholder:text-content-subtle disabled:opacity-50"}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between text-xs text-content-subtle",children:[jsxRuntimeExports.jsx("span",{children:"Context details are included automatically."}),jsxRuntimeExports.jsx("span",{children:Ga})]})]}),jsxRuntimeExports.jsx("button",{onClick:Ha,disabled:Wa,className:"flex w-full items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-xs text-white transition-colors hover:bg-primary-hover disabled:opacity-50",children:ps?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(s$6,{className:"h-4 w-4 animate-spin",weight:"bold"}),jsxRuntimeExports.jsx("span",{children:"Sending..."})]}):jsxRuntimeExports.jsx("span",{children:"Send feedback"})})]})})]})})},rivetWordmark="data:image/svg+xml,%3csvg%20width='94'%20height='24'%20viewBox='0%200%2094%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M-0.000156164%2023.832V7.704H5.11184L6.47984%208.424C7.58384%207.704%209.04784%207.344%2010.8718%207.344C12.0718%207.344%2013.1278%207.476%2014.0398%207.74C14.9518%207.98%2015.6838%208.244%2016.2358%208.532C16.8118%208.82%2017.1718%209.024%2017.3158%209.144L15.5158%2013.824C15.2758%2013.656%2014.8198%2013.428%2014.1478%2013.14C13.4998%2012.852%2012.7318%2012.588%2011.8438%2012.348C10.9558%2012.084%2010.0198%2011.952%209.03584%2011.952H8.63984C7.96784%2011.952%207.45184%2012.072%207.09184%2012.312C6.73184%2012.528%206.55184%2013.02%206.55184%2013.788V23.832H-0.000156164ZM23.464%206.156C21.04%206.156%2019.828%205.124%2019.828%203.06C19.828%201.908%2020.128%201.116%2020.728%200.684C21.352%200.227999%2022.264%20-1.43051e-06%2023.464%20-1.43051e-06C24.736%20-1.43051e-06%2025.66%200.227999%2026.236%200.684C26.836%201.116%2027.136%201.908%2027.136%203.06C27.136%205.124%2025.912%206.156%2023.464%206.156ZM20.152%2023.832V7.704H26.704V23.832H20.152ZM37.4767%2023.832L29.6647%207.704H36.9007L40.3207%2016.524L41.2567%2019.116H41.6167L42.5527%2016.524L46.0087%207.704H53.1727L52.5967%209.9L45.4327%2023.832H37.4767ZM61.1953%2023.832C59.6113%2023.832%2058.3873%2023.604%2057.5233%2023.148C56.6833%2022.692%2056.1073%2022.068%2055.7953%2021.276C55.4833%2020.46%2055.3273%2019.524%2055.3273%2018.468V13.032C55.3273%2012.072%2055.4833%2011.196%2055.7953%2010.404C56.1313%209.588%2056.7193%208.94%2057.5593%208.46C58.3993%207.956%2059.6113%207.704%2061.1953%207.704H68.6473C70.5193%207.704%2071.9473%207.932%2072.9313%208.388C73.9393%208.82%2074.6233%209.444%2074.9833%2010.26C75.3673%2011.052%2075.5593%2011.976%2075.5593%2013.032V17.64H69.2593C67.0993%2017.64%2065.4553%2017.592%2064.3273%2017.496C63.2233%2017.4%2062.4433%2017.34%2061.9873%2017.316V17.856C61.9633%2018.816%2062.5393%2019.296%2063.7153%2019.296H64.8313C66.7513%2019.296%2068.5273%2019.26%2070.1593%2019.188C71.7913%2019.092%2073.0033%2019.008%2073.7953%2018.936L75.9553%2022.356C75.9553%2022.596%2075.7513%2022.824%2075.3433%2023.04C74.9353%2023.256%2074.2153%2023.448%2073.1833%2023.616C72.1753%2023.76%2070.7353%2023.832%2068.8633%2023.832H61.1953ZM61.9873%2014.184H68.8993V13.68C68.8993%2013.2%2068.8513%2012.864%2068.7553%2012.672C68.6833%2012.48%2068.4313%2012.36%2067.9993%2012.312C67.5673%2012.264%2066.8353%2012.24%2065.8033%2012.24H63.7153C62.5633%2012.24%2061.9873%2012.72%2061.9873%2013.68V14.184ZM85.8224%2023.832C83.9984%2023.832%2082.7504%2023.448%2082.0784%2022.68C81.4064%2021.912%2081.0704%2020.76%2081.0704%2019.224V12.24H78.1184V7.704H79.6304C80.0384%207.704%2080.3624%207.632%2080.6024%207.488C80.8664%207.32%2081.0344%207.032%2081.1064%206.624L81.7904%202.772H87.6944V7.704H93.7064V12.24H87.6944V17.82C87.6944%2018.42%2087.8384%2018.816%2088.1264%2019.008C88.4144%2019.2%2088.8464%2019.296%2089.4224%2019.296H93.0224L93.7424%2023.472C93.2384%2023.544%2092.4704%2023.628%2091.4384%2023.724C90.4064%2023.796%2089.2784%2023.832%2088.0544%2023.832H85.8224Z'%20fill='%23FF3300'/%3e%3c/svg%3e",AuthScreenView=({isSigningIn:$,onStartSignIn:ns,errorMessage:ss=null,isDesktopShell:os=!1,displayMode:ls="full"})=>{const us=ls==="modal";return jsxRuntimeExports.jsxs("div",{className:us?"glass-panel relative w-full max-w-sm rounded-2xl border border-white/10 px-8 py-14 font-main text-white shadow-2xl":"relative flex min-h-screen flex-col items-center justify-center overflow-hidden bg-[#1c1c20] font-main text-white",children:[os&&!us?jsxRuntimeExports.jsx("div",{className:"fixed left-0 right-0 top-0 z-10 h-8",style:{WebkitAppRegion:"drag"}}):null,jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center gap-10",children:[jsxRuntimeExports.jsx("img",{src:rivetWordmark,alt:"Rivet",className:"h-8 w-auto object-contain"}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("h1",{className:"mb-2 text-xl font-medium text-content",children:"Welcome to Rivet"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-content-muted",children:"Sign in to get started"})]}),jsxRuntimeExports.jsx("button",{onClick:ns,disabled:$,className:"glass-panel active-push flex items-center gap-3 rounded-xl px-8 py-3.5 text-sm font-medium transition-all hover:bg-white/10 disabled:opacity-50",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"}),jsxRuntimeExports.jsx("span",{children:"Signing in..."})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("img",{src:"https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg",alt:"Google",className:"h-5 w-5 brightness-110"}),jsxRuntimeExports.jsx("span",{children:"Sign in with Google"})]})}),ss?jsxRuntimeExports.jsx("p",{className:"text-center text-xs text-red-200",children:ss}):null]})]})},log$4=createLogger("useConfig"),useConfig=()=>{const $=useAtomValue(featureFlagsAtom),ns=useSetAtom(featureFlagsAtom),ss=useSetAtom(isMCPSessionAtom),os=useSetAtom(mcpEditorAtom),ls=useSetAtom(agentModeAvailableAtom),us=useSetAtom(featureFlagsLoadedAtom),ps=reactExports.useCallback(Va=>{ls(Va.agentModeAvailable),ns(Va.featureFlags??DEFAULT_FEATURE_FLAGS),us(!0),Va.isMCPSession&&ss(!0),Va.mcpEditor&&os(Va.mcpEditor)},[ls,ns,us,ss,os]),hs=useQuery({queryKey:["rivet-config"],queryFn:async()=>{const Va=await fetch("/api/config");if(!Va.ok)throw new Error(`Failed to fetch config: ${Va.statusText}`);return await Va.json()},staleTime:3e4}),{refetch:ws}=hs;reactExports.useEffect(()=>{hs.data&&(ps(hs.data),log$4.info("Config loaded:",hs.data))},[hs.data,ps]),reactExports.useEffect(()=>{hs.error&&(us(!0),log$4.warn("Failed to load config:",hs.error instanceof Error?hs.error.message:"Failed to load config"))},[hs.error,us]);const ja=reactExports.useCallback(async()=>{const Va=await ws();return Va.data?Va.data:(us(!0),null)},[ws,us]);let Ha=null;return hs.error instanceof Error?Ha=hs.error.message:hs.error&&(Ha="Failed to load config"),{config:hs.data??null,featureFlags:$,loading:hs.isPending,error:Ha,refetchConfig:ja}};var define_process_env_default={};const DEFAULT_PROXY_URL="https://rivet-proxy.onrender.com";var Mx;const envProxyUrl=(Mx=define_process_env_default.RIVET_PROXY_URL)==null?void 0:Mx.trim(),PROXY_URL=envProxyUrl&&envProxyUrl.length>0?envProxyUrl:DEFAULT_PROXY_URL,DEFAULT_GATEWAY_URL="https://rivet-core-production.up.railway.app";var Fx;const envGatewayUrl=(Fx=define_process_env_default.RIVET_GATEWAY_URL)==null?void 0:Fx.trim();envGatewayUrl&&envGatewayUrl.length>0;const DEFAULT_POSTHOG_HOST="https://us.i.posthog.com";var Dx;const envPosthogHost=(Dx=define_process_env_default.RIVET_POSTHOG_HOST)==null?void 0:Dx.trim();envPosthogHost&&envPosthogHost.length>0;const log$3=createLogger("useOAuthCallback"),useOAuthCallback=()=>{const[$,ns]=reactExports.useState({isProcessing:!1,isComplete:!1,error:null});return reactExports.useEffect(()=>{const ss=new AbortController;let os=!1;return(async()=>{var hs,ws;const us=window.location.hash,ps=window.location.search;if(!(!us||!us.includes("access_token"))&&!os){ns({isProcessing:!0,isComplete:!1,error:null});try{log$3.info("Processing OAuth callback...");const ja=new URLSearchParams(us.substring(1)),Ha=ja.get("access_token"),Va=ja.get("refresh_token"),Wa=new URLSearchParams(ps).get("session");if(!Ha)throw new Error("No access token found in URL");if(!Wa)throw new Error("No session ID found in URL");log$3.info(`Completing OAuth with session: ${Wa}`);const Ka=await fetch(`${PROXY_URL}/api/auth/google/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:Wa,accessToken:Ha,refreshToken:Va}),signal:ss.signal}),Za=await Ka.json();if(!Ka.ok||!Za.success)throw new Error(Za.error||Za.message||"Failed to complete authentication");if(log$3.info("OAuth authentication completed successfully"),os)return;if((hs=Za.user)!=null&&hs.email&&Na.identify(Za.user.email,{email:Za.user.email}),(ws=Za.user)!=null&&ws.email&&Ha)try{const Ja=await fetch("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:Za.user.email,token:Ha,refreshToken:Va}),signal:ss.signal});Ja.ok||log$3.warn(`Local auth store returned ${Ja.status}`)}catch(Ja){if(os)return;log$3.warn("Failed to store auth locally:",Ja)}if(os)return;const qa=window.location.pathname;window.history.replaceState({},document.title,qa),ns({isProcessing:!1,isComplete:!0,error:null})}catch(ja){if(os)return;const Ha=ja instanceof Error?ja.message:"Unknown error occurred";log$3.warn("OAuth callback error:",ja),ns({isProcessing:!1,isComplete:!1,error:Ha})}}})(),()=>{os=!0,ss.abort()}},[]),$},log$2=createLogger("useAgentVariantsSession"),useAgentVariantsSession=()=>{const $=useSetAtom(agentVariantsSnapshotAtom),ns=useSetAtom(variantsPanelOpenAtom),ss=useSetAtom(panelOpenAtom),os=useSetAtom(modeAtom),ls=useSetAtom(variantsPanelOptimisticGeneratingAtom),us=useSetAtom(pruneVariantTargetsAtom),ps=useStore(),hs=reactExports.useRef(null);reactExports.useEffect(()=>{const ws=new EventSource("/api/variants/events");return ws.onmessage=ja=>{try{const Ha=JSON.parse(ja.data),Va=hs.current;Ha.active?(ls(!1),Ha.sessionId!==hs.current&&(hs.current=Ha.sessionId,ns(!0),ss(!0),os("view"))):(hs.current!==null&&ns(!1),hs.current=null,ls(!1)),$(Ha);const Ga=!Ha.active&&Va!==null,Wa=Ha.active&&Ha.sessionId!==Va;if(Ga||Wa){const Ka=new Set;if(Ha.active)for(const qa of Ha.variants)Ka.add(previewTargetKey({kind:"variant",sessionId:Ha.sessionId,variantId:qa.workItemId}));const Za=ps.get(variantSplitViewAtom);for(const qa of[Za==null?void 0:Za.left,Za==null?void 0:Za.right])qa&&Ka.add(previewTargetKey({kind:"variant",sessionId:qa.sessionId,variantId:qa.variantId}));us(Ka)}}catch(Ha){log$2.warn("failed to parse SSE event payload",Ha)}},ws.onerror=ja=>{log$2.warn("SSE error (auto-reconnects)",ja),ls(!1)},()=>{ws.close()}},[$,ns,ss,os,ls,us,ps])},log$1=createLogger("useTokenEditor"),useTokenEditor=()=>{const[$,ns]=reactExports.useState(null),[ss,os]=reactExports.useState(null),[ls,us]=reactExports.useState(new Map),[ps,hs]=reactExports.useState(!0),[ws,ja]=reactExports.useState(!1),[Ha,Va]=reactExports.useState(null),Ga=reactExports.useCallback(async()=>{hs(!0),Va(null);try{const qa=await fetch("/api/tokens");if(!qa.ok)throw new Error(`Failed to fetch tokens: ${qa.statusText}`);const Ja=await qa.json();ns(Ja.registry),os(Ja.framework),log$1.info(`Loaded ${Ja.framework} tokens`)}catch(qa){const Ja=qa instanceof Error?qa.message:"Unknown error";Va(Ja),log$1.warn("Failed to fetch tokens:",qa)}finally{hs(!1)}},[]);reactExports.useEffect(()=>{Ga()},[Ga]);const Wa=reactExports.useCallback((qa,Ja,Ya,Xa)=>{const el=`${qa}.${Ja}`;us(nl=>{const rl=new Map(nl);return Xa===Ya?rl.delete(el):rl.set(el,{category:qa,path:Ja,originalValue:Ya,newValue:Xa}),rl})},[]),Ka=reactExports.useCallback(async()=>{if(ls.size===0)return!0;ja(!0),Va(null);const qa=Array.from(ls.values());let Ja=!0;for(const Ya of qa)try{log$1.info(`Saving ${Ya.category}.${Ya.path} = "${Ya.newValue}"`);const el=await(await fetch("/api/tokens/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:Ya.category,path:Ya.path,value:Ya.newValue})})).json();if(!el.success)throw new Error(el.error||"Update failed");log$1.info(`Successfully saved ${Ya.category}.${Ya.path}`)}catch(Xa){const el=Xa instanceof Error?Xa.message:"Unknown error";Va(`Failed to update ${Ya.category}.${Ya.path}: ${el}`),log$1.warn(`Failed to save ${Ya.category}.${Ya.path}:`,Xa),Ja=!1;break}return Ja&&(us(new Map),await Ga()),ja(!1),Ja},[ls,Ga]),Za=reactExports.useCallback(()=>{us(new Map),log$1.info("Reverted all pending changes")},[]);return{tokens:$,framework:ss,pendingChanges:ls,isLoading:ps,isSaving:ws,error:Ha,updateToken:Wa,saveChanges:Ka,revertChanges:Za,refetch:Ga}};var ENTRY_FOCUS="rovingFocusGroup.onEntryFocus",EVENT_OPTIONS={bubbles:!1,cancelable:!0},GROUP_NAME="RovingFocusGroup",[Collection,useCollection,createCollectionScope]=createCollection(GROUP_NAME),[createRovingFocusGroupContext,createRovingFocusGroupScope]=createContextScope(GROUP_NAME,[createCollectionScope]),[RovingFocusProvider,useRovingFocusContext]=createRovingFocusGroupContext(GROUP_NAME),RovingFocusGroup=reactExports.forwardRef(($,ns)=>jsxRuntimeExports.jsx(Collection.Provider,{scope:$.__scopeRovingFocusGroup,children:jsxRuntimeExports.jsx(Collection.Slot,{scope:$.__scopeRovingFocusGroup,children:jsxRuntimeExports.jsx(RovingFocusGroupImpl,{...$,ref:ns})})}));RovingFocusGroup.displayName=GROUP_NAME;var RovingFocusGroupImpl=reactExports.forwardRef(($,ns)=>{const{__scopeRovingFocusGroup:ss,orientation:os,loop:ls=!1,dir:us,currentTabStopId:ps,defaultCurrentTabStopId:hs,onCurrentTabStopIdChange:ws,onEntryFocus:ja,preventScrollOnEntryFocus:Ha=!1,...Va}=$,Ga=reactExports.useRef(null),Wa=useComposedRefs(ns,Ga),Ka=useDirection(us),[Za,qa]=useControllableState({prop:ps,defaultProp:hs??null,onChange:ws,caller:GROUP_NAME}),[Ja,Ya]=reactExports.useState(!1),Xa=useCallbackRef$1(ja),el=useCollection(ss),nl=reactExports.useRef(!1),[rl,sl]=reactExports.useState(0);return reactExports.useEffect(()=>{const il=Ga.current;if(il)return il.addEventListener(ENTRY_FOCUS,Xa),()=>il.removeEventListener(ENTRY_FOCUS,Xa)},[Xa]),jsxRuntimeExports.jsx(RovingFocusProvider,{scope:ss,orientation:os,dir:Ka,loop:ls,currentTabStopId:Za,onItemFocus:reactExports.useCallback(il=>qa(il),[qa]),onItemShiftTab:reactExports.useCallback(()=>Ya(!0),[]),onFocusableItemAdd:reactExports.useCallback(()=>sl(il=>il+1),[]),onFocusableItemRemove:reactExports.useCallback(()=>sl(il=>il-1),[]),children:jsxRuntimeExports.jsx(Primitive.div,{tabIndex:Ja||rl===0?-1:0,"data-orientation":os,...Va,ref:Wa,style:{outline:"none",...$.style},onMouseDown:composeEventHandlers($.onMouseDown,()=>{nl.current=!0}),onFocus:composeEventHandlers($.onFocus,il=>{const al=!nl.current;if(il.target===il.currentTarget&&al&&!Ja){const cl=new CustomEvent(ENTRY_FOCUS,EVENT_OPTIONS);if(il.currentTarget.dispatchEvent(cl),!cl.defaultPrevented){const ml=el().filter(pl=>pl.focusable),vl=ml.find(pl=>pl.active),yl=ml.find(pl=>pl.id===Za),El=[vl,yl,...ml].filter(Boolean).map(pl=>pl.ref.current);focusFirst(El,Ha)}}nl.current=!1}),onBlur:composeEventHandlers($.onBlur,()=>Ya(!1))})})}),ITEM_NAME="RovingFocusGroupItem",RovingFocusGroupItem=reactExports.forwardRef(($,ns)=>{const{__scopeRovingFocusGroup:ss,focusable:os=!0,active:ls=!1,tabStopId:us,children:ps,...hs}=$,ws=useId(),ja=us||ws,Ha=useRovingFocusContext(ITEM_NAME,ss),Va=Ha.currentTabStopId===ja,Ga=useCollection(ss),{onFocusableItemAdd:Wa,onFocusableItemRemove:Ka,currentTabStopId:Za}=Ha;return reactExports.useEffect(()=>{if(os)return Wa(),()=>Ka()},[os,Wa,Ka]),jsxRuntimeExports.jsx(Collection.ItemSlot,{scope:ss,id:ja,focusable:os,active:ls,children:jsxRuntimeExports.jsx(Primitive.span,{tabIndex:Va?0:-1,"data-orientation":Ha.orientation,...hs,ref:ns,onMouseDown:composeEventHandlers($.onMouseDown,qa=>{os?Ha.onItemFocus(ja):qa.preventDefault()}),onFocus:composeEventHandlers($.onFocus,()=>Ha.onItemFocus(ja)),onKeyDown:composeEventHandlers($.onKeyDown,qa=>{if(qa.key==="Tab"&&qa.shiftKey){Ha.onItemShiftTab();return}if(qa.target!==qa.currentTarget)return;const Ja=getFocusIntent(qa,Ha.orientation,Ha.dir);if(Ja!==void 0){if(qa.metaKey||qa.ctrlKey||qa.altKey||qa.shiftKey)return;qa.preventDefault();let Xa=Ga().filter(el=>el.focusable).map(el=>el.ref.current);if(Ja==="last")Xa.reverse();else if(Ja==="prev"||Ja==="next"){Ja==="prev"&&Xa.reverse();const el=Xa.indexOf(qa.currentTarget);Xa=Ha.loop?wrapArray(Xa,el+1):Xa.slice(el+1)}setTimeout(()=>focusFirst(Xa))}}),children:typeof ps=="function"?ps({isCurrentTabStop:Va,hasTabStop:Za!=null}):ps})})});RovingFocusGroupItem.displayName=ITEM_NAME;var MAP_KEY_TO_FOCUS_INTENT={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function getDirectionAwareKey($,ns){return ns!=="rtl"?$:$==="ArrowLeft"?"ArrowRight":$==="ArrowRight"?"ArrowLeft":$}function getFocusIntent($,ns,ss){const os=getDirectionAwareKey($.key,ss);if(!(ns==="vertical"&&["ArrowLeft","ArrowRight"].includes(os))&&!(ns==="horizontal"&&["ArrowUp","ArrowDown"].includes(os)))return MAP_KEY_TO_FOCUS_INTENT[os]}function focusFirst($,ns=!1){const ss=document.activeElement;for(const os of $)if(os===ss||(os.focus({preventScroll:ns}),document.activeElement!==ss))return}function wrapArray($,ns){return $.map((ss,os)=>$[(ns+os)%$.length])}var Root=RovingFocusGroup,Item=RovingFocusGroupItem,TABS_NAME="Tabs",[createTabsContext]=createContextScope(TABS_NAME,[createRovingFocusGroupScope]),useRovingFocusGroupScope=createRovingFocusGroupScope(),[TabsProvider,useTabsContext]=createTabsContext(TABS_NAME),Tabs=reactExports.forwardRef(($,ns)=>{const{__scopeTabs:ss,value:os,onValueChange:ls,defaultValue:us,orientation:ps="horizontal",dir:hs,activationMode:ws="automatic",...ja}=$,Ha=useDirection(hs),[Va,Ga]=useControllableState({prop:os,onChange:ls,defaultProp:us??"",caller:TABS_NAME});return jsxRuntimeExports.jsx(TabsProvider,{scope:ss,baseId:useId(),value:Va,onValueChange:Ga,orientation:ps,dir:Ha,activationMode:ws,children:jsxRuntimeExports.jsx(Primitive.div,{dir:Ha,"data-orientation":ps,...ja,ref:ns})})});Tabs.displayName=TABS_NAME;var TAB_LIST_NAME="TabsList",TabsList=reactExports.forwardRef(($,ns)=>{const{__scopeTabs:ss,loop:os=!0,...ls}=$,us=useTabsContext(TAB_LIST_NAME,ss),ps=useRovingFocusGroupScope(ss);return jsxRuntimeExports.jsx(Root,{asChild:!0,...ps,orientation:us.orientation,dir:us.dir,loop:os,children:jsxRuntimeExports.jsx(Primitive.div,{role:"tablist","aria-orientation":us.orientation,...ls,ref:ns})})});TabsList.displayName=TAB_LIST_NAME;var TRIGGER_NAME="TabsTrigger",TabsTrigger=reactExports.forwardRef(($,ns)=>{const{__scopeTabs:ss,value:os,disabled:ls=!1,...us}=$,ps=useTabsContext(TRIGGER_NAME,ss),hs=useRovingFocusGroupScope(ss),ws=makeTriggerId(ps.baseId,os),ja=makeContentId(ps.baseId,os),Ha=os===ps.value;return jsxRuntimeExports.jsx(Item,{asChild:!0,...hs,focusable:!ls,active:Ha,children:jsxRuntimeExports.jsx(Primitive.button,{type:"button",role:"tab","aria-selected":Ha,"aria-controls":ja,"data-state":Ha?"active":"inactive","data-disabled":ls?"":void 0,disabled:ls,id:ws,...us,ref:ns,onMouseDown:composeEventHandlers($.onMouseDown,Va=>{!ls&&Va.button===0&&Va.ctrlKey===!1?ps.onValueChange(os):Va.preventDefault()}),onKeyDown:composeEventHandlers($.onKeyDown,Va=>{[" ","Enter"].includes(Va.key)&&ps.onValueChange(os)}),onFocus:composeEventHandlers($.onFocus,()=>{const Va=ps.activationMode!=="manual";!Ha&&!ls&&Va&&ps.onValueChange(os)})})})});TabsTrigger.displayName=TRIGGER_NAME;var CONTENT_NAME="TabsContent",TabsContent=reactExports.forwardRef(($,ns)=>{const{__scopeTabs:ss,value:os,forceMount:ls,children:us,...ps}=$,hs=useTabsContext(CONTENT_NAME,ss),ws=makeTriggerId(hs.baseId,os),ja=makeContentId(hs.baseId,os),Ha=os===hs.value,Va=reactExports.useRef(Ha);return reactExports.useEffect(()=>{const Ga=requestAnimationFrame(()=>Va.current=!1);return()=>cancelAnimationFrame(Ga)},[]),jsxRuntimeExports.jsx(Presence,{present:ls||Ha,children:({present:Ga})=>jsxRuntimeExports.jsx(Primitive.div,{"data-state":Ha?"active":"inactive","data-orientation":hs.orientation,role:"tabpanel","aria-labelledby":ws,hidden:!Ga,id:ja,tabIndex:0,...ps,ref:ns,style:{...$.style,animationDuration:Va.current?"0s":void 0},children:Ga&&us})})});TabsContent.displayName=CONTENT_NAME;function makeTriggerId($,ns){return`${$}-trigger-${ns}`}function makeContentId($,ns){return`${$}-content-${ns}`}var Root2=Tabs,List=TabsList,Trigger=TabsTrigger,Content=TabsContent;const ColorSwatchGrid=({tokens:$,pendingChanges:ns,category:ss,onUpdateToken:os,highlightToken:ls})=>{const[us,ps]=reactExports.useState(null),[hs,ws]=reactExports.useState(""),ja=reactExports.useRef(null);if(reactExports.useEffect(()=>{ls&&ja.current&&setTimeout(()=>{var Za;(Za=ja.current)==null||Za.scrollIntoView({behavior:"smooth",block:"center"})},100)},[ls]),!$||Object.keys($).length===0)return jsxRuntimeExports.jsx("div",{className:"flex items-center justify-center py-12 text-sm text-gray-500",children:"No tokens defined for this category"});const Ha=(Za,qa)=>{const Ja=`${ss}.${Za}`,Ya=ns.get(Ja);return Ya?Ya.newValue:qa},Va=Za=>{if(Za.includes("var(")||Za.includes("--"))return{textClass:"text-white",mutedClass:"text-white/70"};let qa=0,Ja=0,Ya=0,Xa=!1;if(Za.startsWith("#")){const sl=Za.slice(1);sl.length===3?(qa=parseInt(sl[0]+sl[0],16),Ja=parseInt(sl[1]+sl[1],16),Ya=parseInt(sl[2]+sl[2],16),Xa=!0):sl.length>=6&&(qa=parseInt(sl.slice(0,2),16),Ja=parseInt(sl.slice(2,4),16),Ya=parseInt(sl.slice(4,6),16),Xa=!0)}const el=Za.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(el&&(qa=parseInt(el[1],10),Ja=parseInt(el[2],10),Ya=parseInt(el[3],10),Xa=!0),!Xa){const sl=Za.match(/rgba?\(\s*(\d+)\s+(\d+)\s+(\d+)/);sl&&(qa=parseInt(sl[1],10),Ja=parseInt(sl[2],10),Ya=parseInt(sl[3],10),Xa=!0)}if(!Xa){const sl=Za.match(/hsla?\(\s*(\d+)\s*,\s*(\d+)%?\s*,\s*(\d+)%?/);if(sl){const il=hslValuesToRgb(parseInt(sl[1],10),parseInt(sl[2],10),parseInt(sl[3],10));qa=il.r,Ja=il.g,Ya=il.b,Xa=!0}}if(!Xa){const sl=Za.match(/hsla?\(\s*(\d+)\s+(\d+)%?\s+(\d+)%?/);if(sl){const il=hslValuesToRgb(parseInt(sl[1],10),parseInt(sl[2],10),parseInt(sl[3],10));qa=il.r,Ja=il.g,Ya=il.b,Xa=!0}}if(!Xa){const sl=Za.match(/oklch\(\s*([\d.]+)(%?)/);if(sl){const il=parseFloat(sl[1]),cl=(sl[2]==="%"?il/100:il)>.5;return{textClass:cl?"text-gray-900":"text-white",mutedClass:cl?"text-gray-600":"text-white/70"}}}if(!Xa)return{textClass:"text-white",mutedClass:"text-white/70"};const rl=calculateLuminance(qa,Ja,Ya)>.5;return{textClass:rl?"text-gray-900":"text-white",mutedClass:rl?"text-gray-600":"text-white/70"}},Ga=(Za,qa,Ja,Ya)=>{const Xa=Ha(qa,Ja),el=us===qa,nl=el&&hs?hs:Xa,rl=qa.replace(/\./g,"-"),sl=ls===rl||ls===Za,il=nl.includes("rgba")||nl.startsWith("#")&&nl.length===9||/oklch\(/.test(nl)&&nl.includes("/"),{textClass:al}=Va(nl),cl=wl=>{ws(wl)},ml=wl=>{os(ss,qa,Ja,wl),ps(null),ws("")},vl=wl=>{wl?(ps(qa),ws(Xa)):(hs&&hs!==Xa&&os(ss,qa,Ja,hs),ps(null),ws(""))},yl=Ya?"h-44":"h-52";return jsxRuntimeExports.jsxs(Root2$3,{open:el,onOpenChange:vl,children:[jsxRuntimeExports.jsx(Trigger$4,{asChild:!0,children:jsxRuntimeExports.jsxs("div",{ref:sl?ja:null,className:`group relative flex ${yl} cursor-pointer flex-col justify-between overflow-hidden rounded-lg border border-white/10 p-4 transition-all ${sl?"animate-token-highlight":""}`,children:[jsxRuntimeExports.jsxs("div",{className:"absolute inset-0",children:[il&&jsxRuntimeExports.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`
|
|
348
|
+
`);nl=il.pop()??"";for(const al of il){const cl=parseSSELine(al.trim());if(cl!=null&&cl.type){if(cl.type==="variant_completed"){const ml=cl.variantIndex,vl=cl.diff;Ha+=1,os==null||os.capture("variant_code_gen_variant_ready",{variant_index:ml,variant_count:ja.length}),$(El=>{const pl=El.get(us);if(!(pl!=null&&pl.styleVariants))return El;const Al=new Map(El),ll=[...pl.styleVariants],dl=ml-1;return ll[dl]&&(ll[dl]={...ll[dl],codeStatus:"ready",codeDiff:vl}),Al.set(us,{...pl,styleVariants:ll}),Al});const yl=ss.get(activeCarouselCommentIdAtom),wl=ss.get(appliedVariantDiffAtom);yl===us&&!wl&&((Wa=ss.get(commentsAtom).get(us))==null?void 0:Wa.selectedVariantIndex)===ml&&!((Ka=ss.get(commentsAtom).get(us))!=null&&Ka.finalizedVariant)&&(ns({commentId:us,variantIndex:ml,diff:vl}),fetch("/api/design/apply-variant-diff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({diff:vl,reverse:!1})}).then(El=>{El.ok||ns(null)}).catch(()=>{ns(null)}))}else if(cl.type==="variant_error"){const ml=cl.variantIndex,vl=cl.error;Va+=1,os==null||os.capture("variant_code_gen_variant_failed",{variant_index:ml,variant_count:ja.length,error_message:vl}),$(yl=>{const wl=yl.get(us);if(!(wl!=null&&wl.styleVariants))return yl;const El=new Map(yl),pl=[...wl.styleVariants],Al=ml-1;return pl[Al]&&(pl[Al]={...pl[Al],codeStatus:"error",codeError:vl}),El.set(us,{...wl,styleVariants:pl}),El})}}}}os==null||os.capture("variant_code_gen_completed",{variant_count:ja.length,success_count:Ha,error_count:Va})}catch(Za){const qa=Za instanceof DOMException&&Za.name==="AbortError",Ja=Za instanceof Error?Za.message:"Direction code generation failed";os==null||os.capture("variant_code_gen_failed",{variant_count:ja.length,reason:qa?"aborted":"exception",error_message:Ja}),$(Ya=>{const Xa=Ya.get(us);if(!(Xa!=null&&Xa.styleVariants))return Ya;const el=new Map(Ya);return el.set(us,{...Xa,styleVariants:Xa.styleVariants.map(nl=>({...nl,codeStatus:void 0,codeDiff:void 0}))}),el})}finally{unregisterVariantGeneration(us)}},[os,$,ns,ss])}};var util;(function($){$.assertEqual=ls=>{};function ns(ls){}$.assertIs=ns;function ss(ls){throw new Error}$.assertNever=ss,$.arrayToEnum=ls=>{const us={};for(const ps of ls)us[ps]=ps;return us},$.getValidEnumValues=ls=>{const us=$.objectKeys(ls).filter(hs=>typeof ls[ls[hs]]!="number"),ps={};for(const hs of us)ps[hs]=ls[hs];return $.objectValues(ps)},$.objectValues=ls=>$.objectKeys(ls).map(function(us){return ls[us]}),$.objectKeys=typeof Object.keys=="function"?ls=>Object.keys(ls):ls=>{const us=[];for(const ps in ls)Object.prototype.hasOwnProperty.call(ls,ps)&&us.push(ps);return us},$.find=(ls,us)=>{for(const ps of ls)if(us(ps))return ps},$.isInteger=typeof Number.isInteger=="function"?ls=>Number.isInteger(ls):ls=>typeof ls=="number"&&Number.isFinite(ls)&&Math.floor(ls)===ls;function os(ls,us=" | "){return ls.map(ps=>typeof ps=="string"?`'${ps}'`:ps).join(us)}$.joinValues=os,$.jsonStringifyReplacer=(ls,us)=>typeof us=="bigint"?us.toString():us})(util||(util={}));var objectUtil;(function($){$.mergeShapes=(ns,ss)=>({...ns,...ss})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=$=>{switch(typeof $){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN($)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray($)?ZodParsedType.array:$===null?ZodParsedType.null:$.then&&typeof $.then=="function"&&$.catch&&typeof $.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&$ instanceof Map?ZodParsedType.map:typeof Set<"u"&&$ instanceof Set?ZodParsedType.set:typeof Date<"u"&&$ instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(ns){super(),this.issues=[],this.addIssue=os=>{this.issues=[...this.issues,os]},this.addIssues=(os=[])=>{this.issues=[...this.issues,...os]};const ss=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,ss):this.__proto__=ss,this.name="ZodError",this.issues=ns}format(ns){const ss=ns||function(us){return us.message},os={_errors:[]},ls=us=>{for(const ps of us.issues)if(ps.code==="invalid_union")ps.unionErrors.map(ls);else if(ps.code==="invalid_return_type")ls(ps.returnTypeError);else if(ps.code==="invalid_arguments")ls(ps.argumentsError);else if(ps.path.length===0)os._errors.push(ss(ps));else{let hs=os,ws=0;for(;ws<ps.path.length;){const ja=ps.path[ws];ws===ps.path.length-1?(hs[ja]=hs[ja]||{_errors:[]},hs[ja]._errors.push(ss(ps))):hs[ja]=hs[ja]||{_errors:[]},hs=hs[ja],ws++}}};return ls(this),os}static assert(ns){if(!(ns instanceof ZodError))throw new Error(`Not a ZodError: ${ns}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(ns=ss=>ss.message){const ss={},os=[];for(const ls of this.issues)if(ls.path.length>0){const us=ls.path[0];ss[us]=ss[us]||[],ss[us].push(ns(ls))}else os.push(ns(ls));return{formErrors:os,fieldErrors:ss}}get formErrors(){return this.flatten()}}ZodError.create=$=>new ZodError($);const errorMap=($,ns)=>{let ss;switch($.code){case ZodIssueCode.invalid_type:$.received===ZodParsedType.undefined?ss="Required":ss=`Expected ${$.expected}, received ${$.received}`;break;case ZodIssueCode.invalid_literal:ss=`Invalid literal value, expected ${JSON.stringify($.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:ss=`Unrecognized key(s) in object: ${util.joinValues($.keys,", ")}`;break;case ZodIssueCode.invalid_union:ss="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:ss=`Invalid discriminator value. Expected ${util.joinValues($.options)}`;break;case ZodIssueCode.invalid_enum_value:ss=`Invalid enum value. Expected ${util.joinValues($.options)}, received '${$.received}'`;break;case ZodIssueCode.invalid_arguments:ss="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:ss="Invalid function return type";break;case ZodIssueCode.invalid_date:ss="Invalid date";break;case ZodIssueCode.invalid_string:typeof $.validation=="object"?"includes"in $.validation?(ss=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position=="number"&&(ss=`${ss} at one or more positions greater than or equal to ${$.validation.position}`)):"startsWith"in $.validation?ss=`Invalid input: must start with "${$.validation.startsWith}"`:"endsWith"in $.validation?ss=`Invalid input: must end with "${$.validation.endsWith}"`:util.assertNever($.validation):$.validation!=="regex"?ss=`Invalid ${$.validation}`:ss="Invalid";break;case ZodIssueCode.too_small:$.type==="array"?ss=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`:$.type==="string"?ss=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`:$.type==="number"?ss=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`:$.type==="bigint"?ss=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`:$.type==="date"?ss=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`:ss="Invalid input";break;case ZodIssueCode.too_big:$.type==="array"?ss=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`:$.type==="string"?ss=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`:$.type==="number"?ss=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`:$.type==="bigint"?ss=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`:$.type==="date"?ss=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`:ss="Invalid input";break;case ZodIssueCode.custom:ss="Invalid input";break;case ZodIssueCode.invalid_intersection_types:ss="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:ss=`Number must be a multiple of ${$.multipleOf}`;break;case ZodIssueCode.not_finite:ss="Number must be finite";break;default:ss=ns.defaultError,util.assertNever($)}return{message:ss}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=$=>{const{data:ns,path:ss,errorMaps:os,issueData:ls}=$,us=[...ss,...ls.path||[]],ps={...ls,path:us};if(ls.message!==void 0)return{...ls,path:us,message:ls.message};let hs="";const ws=os.filter(ja=>!!ja).slice().reverse();for(const ja of ws)hs=ja(ps,{data:ns,defaultError:hs}).message;return{...ls,path:us,message:hs}};function addIssueToContext($,ns){const ss=getErrorMap(),os=makeIssue({issueData:ns,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,ss,ss===errorMap?void 0:errorMap].filter(ls=>!!ls)});$.common.issues.push(os)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(ns,ss){const os=[];for(const ls of ss){if(ls.status==="aborted")return INVALID;ls.status==="dirty"&&ns.dirty(),os.push(ls.value)}return{status:ns.value,value:os}}static async mergeObjectAsync(ns,ss){const os=[];for(const ls of ss){const us=await ls.key,ps=await ls.value;os.push({key:us,value:ps})}return ParseStatus.mergeObjectSync(ns,os)}static mergeObjectSync(ns,ss){const os={};for(const ls of ss){const{key:us,value:ps}=ls;if(us.status==="aborted"||ps.status==="aborted")return INVALID;us.status==="dirty"&&ns.dirty(),ps.status==="dirty"&&ns.dirty(),us.value!=="__proto__"&&(typeof ps.value<"u"||ls.alwaysSet)&&(os[us.value]=ps.value)}return{status:ns.value,value:os}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=$=>({status:"dirty",value:$}),OK=$=>({status:"valid",value:$}),isAborted=$=>$.status==="aborted",isDirty=$=>$.status==="dirty",isValid=$=>$.status==="valid",isAsync=$=>typeof Promise<"u"&&$ instanceof Promise;var errorUtil;(function($){$.errToObj=ns=>typeof ns=="string"?{message:ns}:ns||{},$.toString=ns=>typeof ns=="string"?ns:ns==null?void 0:ns.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(ns,ss,os,ls){this._cachedPath=[],this.parent=ns,this.data=ss,this._path=os,this._key=ls}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=($,ns)=>{if(isValid(ns))return{success:!0,data:ns.value};if(!$.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const ss=new ZodError($.common.issues);return this._error=ss,this._error}}};function processCreateParams($){if(!$)return{};const{errorMap:ns,invalid_type_error:ss,required_error:os,description:ls}=$;if(ns&&(ss||os))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return ns?{errorMap:ns,description:ls}:{errorMap:(ps,hs)=>{const{message:ws}=$;return ps.code==="invalid_enum_value"?{message:ws??hs.defaultError}:typeof hs.data>"u"?{message:ws??os??hs.defaultError}:ps.code!=="invalid_type"?{message:hs.defaultError}:{message:ws??ss??hs.defaultError}},description:ls}}class ZodType{get description(){return this._def.description}_getType(ns){return getParsedType(ns.data)}_getOrReturnCtx(ns,ss){return ss||{common:ns.parent.common,data:ns.data,parsedType:getParsedType(ns.data),schemaErrorMap:this._def.errorMap,path:ns.path,parent:ns.parent}}_processInputParams(ns){return{status:new ParseStatus,ctx:{common:ns.parent.common,data:ns.data,parsedType:getParsedType(ns.data),schemaErrorMap:this._def.errorMap,path:ns.path,parent:ns.parent}}}_parseSync(ns){const ss=this._parse(ns);if(isAsync(ss))throw new Error("Synchronous parse encountered promise.");return ss}_parseAsync(ns){const ss=this._parse(ns);return Promise.resolve(ss)}parse(ns,ss){const os=this.safeParse(ns,ss);if(os.success)return os.data;throw os.error}safeParse(ns,ss){const os={common:{issues:[],async:(ss==null?void 0:ss.async)??!1,contextualErrorMap:ss==null?void 0:ss.errorMap},path:(ss==null?void 0:ss.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:ns,parsedType:getParsedType(ns)},ls=this._parseSync({data:ns,path:os.path,parent:os});return handleResult(os,ls)}"~validate"(ns){var os,ls;const ss={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:ns,parsedType:getParsedType(ns)};if(!this["~standard"].async)try{const us=this._parseSync({data:ns,path:[],parent:ss});return isValid(us)?{value:us.value}:{issues:ss.common.issues}}catch(us){(ls=(os=us==null?void 0:us.message)==null?void 0:os.toLowerCase())!=null&&ls.includes("encountered")&&(this["~standard"].async=!0),ss.common={issues:[],async:!0}}return this._parseAsync({data:ns,path:[],parent:ss}).then(us=>isValid(us)?{value:us.value}:{issues:ss.common.issues})}async parseAsync(ns,ss){const os=await this.safeParseAsync(ns,ss);if(os.success)return os.data;throw os.error}async safeParseAsync(ns,ss){const os={common:{issues:[],contextualErrorMap:ss==null?void 0:ss.errorMap,async:!0},path:(ss==null?void 0:ss.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:ns,parsedType:getParsedType(ns)},ls=this._parse({data:ns,path:os.path,parent:os}),us=await(isAsync(ls)?ls:Promise.resolve(ls));return handleResult(os,us)}refine(ns,ss){const os=ls=>typeof ss=="string"||typeof ss>"u"?{message:ss}:typeof ss=="function"?ss(ls):ss;return this._refinement((ls,us)=>{const ps=ns(ls),hs=()=>us.addIssue({code:ZodIssueCode.custom,...os(ls)});return typeof Promise<"u"&&ps instanceof Promise?ps.then(ws=>ws?!0:(hs(),!1)):ps?!0:(hs(),!1)})}refinement(ns,ss){return this._refinement((os,ls)=>ns(os)?!0:(ls.addIssue(typeof ss=="function"?ss(os,ls):ss),!1))}_refinement(ns){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:ns}})}superRefine(ns){return this._refinement(ns)}constructor(ns){this.spa=this.safeParseAsync,this._def=ns,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:ss=>this["~validate"](ss)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(ns){return ZodUnion.create([this,ns],this._def)}and(ns){return ZodIntersection.create(this,ns,this._def)}transform(ns){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:ns}})}default(ns){const ss=typeof ns=="function"?ns:()=>ns;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:ss,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(ns){const ss=typeof ns=="function"?ns:()=>ns;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:ss,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(ns){const ss=this.constructor;return new ss({...this._def,description:ns})}pipe(ns){return ZodPipeline.create(this,ns)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource($){let ns="[0-5]\\d";$.precision?ns=`${ns}\\.\\d{${$.precision}}`:$.precision==null&&(ns=`${ns}(\\.\\d+)?`);const ss=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${ns})${ss}`}function timeRegex($){return new RegExp(`^${timeRegexSource($)}$`)}function datetimeRegex($){let ns=`${dateRegexSource}T${timeRegexSource($)}`;const ss=[];return ss.push($.local?"Z?":"Z"),$.offset&&ss.push("([+-]\\d{2}:?\\d{2})"),ns=`${ns}(${ss.join("|")})`,new RegExp(`^${ns}$`)}function isValidIP($,ns){return!!((ns==="v4"||!ns)&&ipv4Regex.test($)||(ns==="v6"||!ns)&&ipv6Regex.test($))}function isValidJWT($,ns){if(!jwtRegex.test($))return!1;try{const[ss]=$.split(".");if(!ss)return!1;const os=ss.replace(/-/g,"+").replace(/_/g,"/").padEnd(ss.length+(4-ss.length%4)%4,"="),ls=JSON.parse(atob(os));return!(typeof ls!="object"||ls===null||"typ"in ls&&(ls==null?void 0:ls.typ)!=="JWT"||!ls.alg||ns&&ls.alg!==ns)}catch{return!1}}function isValidCidr($,ns){return!!((ns==="v4"||!ns)&&ipv4CidrRegex.test($)||(ns==="v6"||!ns)&&ipv6CidrRegex.test($))}class ZodString extends ZodType{_parse(ns){if(this._def.coerce&&(ns.data=String(ns.data)),this._getType(ns)!==ZodParsedType.string){const us=this._getOrReturnCtx(ns);return addIssueToContext(us,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:us.parsedType}),INVALID}const os=new ParseStatus;let ls;for(const us of this._def.checks)if(us.kind==="min")ns.data.length<us.value&&(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.too_small,minimum:us.value,type:"string",inclusive:!0,exact:!1,message:us.message}),os.dirty());else if(us.kind==="max")ns.data.length>us.value&&(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.too_big,maximum:us.value,type:"string",inclusive:!0,exact:!1,message:us.message}),os.dirty());else if(us.kind==="length"){const ps=ns.data.length>us.value,hs=ns.data.length<us.value;(ps||hs)&&(ls=this._getOrReturnCtx(ns,ls),ps?addIssueToContext(ls,{code:ZodIssueCode.too_big,maximum:us.value,type:"string",inclusive:!0,exact:!0,message:us.message}):hs&&addIssueToContext(ls,{code:ZodIssueCode.too_small,minimum:us.value,type:"string",inclusive:!0,exact:!0,message:us.message}),os.dirty())}else if(us.kind==="email")emailRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"email",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"emoji",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="uuid")uuidRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"uuid",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="nanoid")nanoidRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="cuid")cuidRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"cuid",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="cuid2")cuid2Regex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="ulid")ulidRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"ulid",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty());else if(us.kind==="url")try{new URL(ns.data)}catch{ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"url",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()}else us.kind==="regex"?(us.regex.lastIndex=0,us.regex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"regex",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty())):us.kind==="trim"?ns.data=ns.data.trim():us.kind==="includes"?ns.data.includes(us.value,us.position)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:{includes:us.value,position:us.position},message:us.message}),os.dirty()):us.kind==="toLowerCase"?ns.data=ns.data.toLowerCase():us.kind==="toUpperCase"?ns.data=ns.data.toUpperCase():us.kind==="startsWith"?ns.data.startsWith(us.value)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:{startsWith:us.value},message:us.message}),os.dirty()):us.kind==="endsWith"?ns.data.endsWith(us.value)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:{endsWith:us.value},message:us.message}),os.dirty()):us.kind==="datetime"?datetimeRegex(us).test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:"datetime",message:us.message}),os.dirty()):us.kind==="date"?dateRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:"date",message:us.message}),os.dirty()):us.kind==="time"?timeRegex(us).test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.invalid_string,validation:"time",message:us.message}),os.dirty()):us.kind==="duration"?durationRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"duration",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="ip"?isValidIP(ns.data,us.version)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"ip",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="jwt"?isValidJWT(ns.data,us.alg)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"jwt",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="cidr"?isValidCidr(ns.data,us.version)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"cidr",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="base64"?base64Regex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"base64",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):us.kind==="base64url"?base64urlRegex.test(ns.data)||(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{validation:"base64url",code:ZodIssueCode.invalid_string,message:us.message}),os.dirty()):util.assertNever(us);return{status:os.value,value:ns.data}}_regex(ns,ss,os){return this.refinement(ls=>ns.test(ls),{validation:ss,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(os)})}_addCheck(ns){return new ZodString({...this._def,checks:[...this._def.checks,ns]})}email(ns){return this._addCheck({kind:"email",...errorUtil.errToObj(ns)})}url(ns){return this._addCheck({kind:"url",...errorUtil.errToObj(ns)})}emoji(ns){return this._addCheck({kind:"emoji",...errorUtil.errToObj(ns)})}uuid(ns){return this._addCheck({kind:"uuid",...errorUtil.errToObj(ns)})}nanoid(ns){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(ns)})}cuid(ns){return this._addCheck({kind:"cuid",...errorUtil.errToObj(ns)})}cuid2(ns){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(ns)})}ulid(ns){return this._addCheck({kind:"ulid",...errorUtil.errToObj(ns)})}base64(ns){return this._addCheck({kind:"base64",...errorUtil.errToObj(ns)})}base64url(ns){return this._addCheck({kind:"base64url",...errorUtil.errToObj(ns)})}jwt(ns){return this._addCheck({kind:"jwt",...errorUtil.errToObj(ns)})}ip(ns){return this._addCheck({kind:"ip",...errorUtil.errToObj(ns)})}cidr(ns){return this._addCheck({kind:"cidr",...errorUtil.errToObj(ns)})}datetime(ns){return typeof ns=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:ns}):this._addCheck({kind:"datetime",precision:typeof(ns==null?void 0:ns.precision)>"u"?null:ns==null?void 0:ns.precision,offset:(ns==null?void 0:ns.offset)??!1,local:(ns==null?void 0:ns.local)??!1,...errorUtil.errToObj(ns==null?void 0:ns.message)})}date(ns){return this._addCheck({kind:"date",message:ns})}time(ns){return typeof ns=="string"?this._addCheck({kind:"time",precision:null,message:ns}):this._addCheck({kind:"time",precision:typeof(ns==null?void 0:ns.precision)>"u"?null:ns==null?void 0:ns.precision,...errorUtil.errToObj(ns==null?void 0:ns.message)})}duration(ns){return this._addCheck({kind:"duration",...errorUtil.errToObj(ns)})}regex(ns,ss){return this._addCheck({kind:"regex",regex:ns,...errorUtil.errToObj(ss)})}includes(ns,ss){return this._addCheck({kind:"includes",value:ns,position:ss==null?void 0:ss.position,...errorUtil.errToObj(ss==null?void 0:ss.message)})}startsWith(ns,ss){return this._addCheck({kind:"startsWith",value:ns,...errorUtil.errToObj(ss)})}endsWith(ns,ss){return this._addCheck({kind:"endsWith",value:ns,...errorUtil.errToObj(ss)})}min(ns,ss){return this._addCheck({kind:"min",value:ns,...errorUtil.errToObj(ss)})}max(ns,ss){return this._addCheck({kind:"max",value:ns,...errorUtil.errToObj(ss)})}length(ns,ss){return this._addCheck({kind:"length",value:ns,...errorUtil.errToObj(ss)})}nonempty(ns){return this.min(1,errorUtil.errToObj(ns))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(ns=>ns.kind==="datetime")}get isDate(){return!!this._def.checks.find(ns=>ns.kind==="date")}get isTime(){return!!this._def.checks.find(ns=>ns.kind==="time")}get isDuration(){return!!this._def.checks.find(ns=>ns.kind==="duration")}get isEmail(){return!!this._def.checks.find(ns=>ns.kind==="email")}get isURL(){return!!this._def.checks.find(ns=>ns.kind==="url")}get isEmoji(){return!!this._def.checks.find(ns=>ns.kind==="emoji")}get isUUID(){return!!this._def.checks.find(ns=>ns.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(ns=>ns.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(ns=>ns.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(ns=>ns.kind==="cuid2")}get isULID(){return!!this._def.checks.find(ns=>ns.kind==="ulid")}get isIP(){return!!this._def.checks.find(ns=>ns.kind==="ip")}get isCIDR(){return!!this._def.checks.find(ns=>ns.kind==="cidr")}get isBase64(){return!!this._def.checks.find(ns=>ns.kind==="base64")}get isBase64url(){return!!this._def.checks.find(ns=>ns.kind==="base64url")}get minLength(){let ns=null;for(const ss of this._def.checks)ss.kind==="min"&&(ns===null||ss.value>ns)&&(ns=ss.value);return ns}get maxLength(){let ns=null;for(const ss of this._def.checks)ss.kind==="max"&&(ns===null||ss.value<ns)&&(ns=ss.value);return ns}}ZodString.create=$=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:($==null?void 0:$.coerce)??!1,...processCreateParams($)});function floatSafeRemainder($,ns){const ss=($.toString().split(".")[1]||"").length,os=(ns.toString().split(".")[1]||"").length,ls=ss>os?ss:os,us=Number.parseInt($.toFixed(ls).replace(".","")),ps=Number.parseInt(ns.toFixed(ls).replace(".",""));return us%ps/10**ls}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(ns){if(this._def.coerce&&(ns.data=Number(ns.data)),this._getType(ns)!==ZodParsedType.number){const us=this._getOrReturnCtx(ns);return addIssueToContext(us,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:us.parsedType}),INVALID}let os;const ls=new ParseStatus;for(const us of this._def.checks)us.kind==="int"?util.isInteger(ns.data)||(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:us.message}),ls.dirty()):us.kind==="min"?(us.inclusive?ns.data<us.value:ns.data<=us.value)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.too_small,minimum:us.value,type:"number",inclusive:us.inclusive,exact:!1,message:us.message}),ls.dirty()):us.kind==="max"?(us.inclusive?ns.data>us.value:ns.data>=us.value)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.too_big,maximum:us.value,type:"number",inclusive:us.inclusive,exact:!1,message:us.message}),ls.dirty()):us.kind==="multipleOf"?floatSafeRemainder(ns.data,us.value)!==0&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.not_multiple_of,multipleOf:us.value,message:us.message}),ls.dirty()):us.kind==="finite"?Number.isFinite(ns.data)||(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.not_finite,message:us.message}),ls.dirty()):util.assertNever(us);return{status:ls.value,value:ns.data}}gte(ns,ss){return this.setLimit("min",ns,!0,errorUtil.toString(ss))}gt(ns,ss){return this.setLimit("min",ns,!1,errorUtil.toString(ss))}lte(ns,ss){return this.setLimit("max",ns,!0,errorUtil.toString(ss))}lt(ns,ss){return this.setLimit("max",ns,!1,errorUtil.toString(ss))}setLimit(ns,ss,os,ls){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:ns,value:ss,inclusive:os,message:errorUtil.toString(ls)}]})}_addCheck(ns){return new ZodNumber({...this._def,checks:[...this._def.checks,ns]})}int(ns){return this._addCheck({kind:"int",message:errorUtil.toString(ns)})}positive(ns){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(ns)})}negative(ns){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(ns)})}nonpositive(ns){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(ns)})}nonnegative(ns){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(ns)})}multipleOf(ns,ss){return this._addCheck({kind:"multipleOf",value:ns,message:errorUtil.toString(ss)})}finite(ns){return this._addCheck({kind:"finite",message:errorUtil.toString(ns)})}safe(ns){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(ns)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(ns)})}get minValue(){let ns=null;for(const ss of this._def.checks)ss.kind==="min"&&(ns===null||ss.value>ns)&&(ns=ss.value);return ns}get maxValue(){let ns=null;for(const ss of this._def.checks)ss.kind==="max"&&(ns===null||ss.value<ns)&&(ns=ss.value);return ns}get isInt(){return!!this._def.checks.find(ns=>ns.kind==="int"||ns.kind==="multipleOf"&&util.isInteger(ns.value))}get isFinite(){let ns=null,ss=null;for(const os of this._def.checks){if(os.kind==="finite"||os.kind==="int"||os.kind==="multipleOf")return!0;os.kind==="min"?(ss===null||os.value>ss)&&(ss=os.value):os.kind==="max"&&(ns===null||os.value<ns)&&(ns=os.value)}return Number.isFinite(ss)&&Number.isFinite(ns)}}ZodNumber.create=$=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:($==null?void 0:$.coerce)||!1,...processCreateParams($)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(ns){if(this._def.coerce)try{ns.data=BigInt(ns.data)}catch{return this._getInvalidInput(ns)}if(this._getType(ns)!==ZodParsedType.bigint)return this._getInvalidInput(ns);let os;const ls=new ParseStatus;for(const us of this._def.checks)us.kind==="min"?(us.inclusive?ns.data<us.value:ns.data<=us.value)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.too_small,type:"bigint",minimum:us.value,inclusive:us.inclusive,message:us.message}),ls.dirty()):us.kind==="max"?(us.inclusive?ns.data>us.value:ns.data>=us.value)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.too_big,type:"bigint",maximum:us.value,inclusive:us.inclusive,message:us.message}),ls.dirty()):us.kind==="multipleOf"?ns.data%us.value!==BigInt(0)&&(os=this._getOrReturnCtx(ns,os),addIssueToContext(os,{code:ZodIssueCode.not_multiple_of,multipleOf:us.value,message:us.message}),ls.dirty()):util.assertNever(us);return{status:ls.value,value:ns.data}}_getInvalidInput(ns){const ss=this._getOrReturnCtx(ns);return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ss.parsedType}),INVALID}gte(ns,ss){return this.setLimit("min",ns,!0,errorUtil.toString(ss))}gt(ns,ss){return this.setLimit("min",ns,!1,errorUtil.toString(ss))}lte(ns,ss){return this.setLimit("max",ns,!0,errorUtil.toString(ss))}lt(ns,ss){return this.setLimit("max",ns,!1,errorUtil.toString(ss))}setLimit(ns,ss,os,ls){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:ns,value:ss,inclusive:os,message:errorUtil.toString(ls)}]})}_addCheck(ns){return new ZodBigInt({...this._def,checks:[...this._def.checks,ns]})}positive(ns){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(ns)})}negative(ns){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(ns)})}nonpositive(ns){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(ns)})}nonnegative(ns){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(ns)})}multipleOf(ns,ss){return this._addCheck({kind:"multipleOf",value:ns,message:errorUtil.toString(ss)})}get minValue(){let ns=null;for(const ss of this._def.checks)ss.kind==="min"&&(ns===null||ss.value>ns)&&(ns=ss.value);return ns}get maxValue(){let ns=null;for(const ss of this._def.checks)ss.kind==="max"&&(ns===null||ss.value<ns)&&(ns=ss.value);return ns}}ZodBigInt.create=$=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:($==null?void 0:$.coerce)??!1,...processCreateParams($)});class ZodBoolean extends ZodType{_parse(ns){if(this._def.coerce&&(ns.data=!!ns.data),this._getType(ns)!==ZodParsedType.boolean){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodBoolean.create=$=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:($==null?void 0:$.coerce)||!1,...processCreateParams($)});class ZodDate extends ZodType{_parse(ns){if(this._def.coerce&&(ns.data=new Date(ns.data)),this._getType(ns)!==ZodParsedType.date){const us=this._getOrReturnCtx(ns);return addIssueToContext(us,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:us.parsedType}),INVALID}if(Number.isNaN(ns.data.getTime())){const us=this._getOrReturnCtx(ns);return addIssueToContext(us,{code:ZodIssueCode.invalid_date}),INVALID}const os=new ParseStatus;let ls;for(const us of this._def.checks)us.kind==="min"?ns.data.getTime()<us.value&&(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.too_small,message:us.message,inclusive:!0,exact:!1,minimum:us.value,type:"date"}),os.dirty()):us.kind==="max"?ns.data.getTime()>us.value&&(ls=this._getOrReturnCtx(ns,ls),addIssueToContext(ls,{code:ZodIssueCode.too_big,message:us.message,inclusive:!0,exact:!1,maximum:us.value,type:"date"}),os.dirty()):util.assertNever(us);return{status:os.value,value:new Date(ns.data.getTime())}}_addCheck(ns){return new ZodDate({...this._def,checks:[...this._def.checks,ns]})}min(ns,ss){return this._addCheck({kind:"min",value:ns.getTime(),message:errorUtil.toString(ss)})}max(ns,ss){return this._addCheck({kind:"max",value:ns.getTime(),message:errorUtil.toString(ss)})}get minDate(){let ns=null;for(const ss of this._def.checks)ss.kind==="min"&&(ns===null||ss.value>ns)&&(ns=ss.value);return ns!=null?new Date(ns):null}get maxDate(){let ns=null;for(const ss of this._def.checks)ss.kind==="max"&&(ns===null||ss.value<ns)&&(ns=ss.value);return ns!=null?new Date(ns):null}}ZodDate.create=$=>new ZodDate({checks:[],coerce:($==null?void 0:$.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams($)});class ZodSymbol extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.symbol){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodSymbol.create=$=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams($)});class ZodUndefined extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.undefined){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodUndefined.create=$=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams($)});class ZodNull extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.null){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodNull.create=$=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams($)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(ns){return OK(ns.data)}}ZodAny.create=$=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams($)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(ns){return OK(ns.data)}}ZodUnknown.create=$=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams($)});class ZodNever extends ZodType{_parse(ns){const ss=this._getOrReturnCtx(ns);return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ss.parsedType}),INVALID}}ZodNever.create=$=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams($)});class ZodVoid extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.undefined){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:os.parsedType}),INVALID}return OK(ns.data)}}ZodVoid.create=$=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams($)});class ZodArray extends ZodType{_parse(ns){const{ctx:ss,status:os}=this._processInputParams(ns),ls=this._def;if(ss.parsedType!==ZodParsedType.array)return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ss.parsedType}),INVALID;if(ls.exactLength!==null){const ps=ss.data.length>ls.exactLength.value,hs=ss.data.length<ls.exactLength.value;(ps||hs)&&(addIssueToContext(ss,{code:ps?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:hs?ls.exactLength.value:void 0,maximum:ps?ls.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:ls.exactLength.message}),os.dirty())}if(ls.minLength!==null&&ss.data.length<ls.minLength.value&&(addIssueToContext(ss,{code:ZodIssueCode.too_small,minimum:ls.minLength.value,type:"array",inclusive:!0,exact:!1,message:ls.minLength.message}),os.dirty()),ls.maxLength!==null&&ss.data.length>ls.maxLength.value&&(addIssueToContext(ss,{code:ZodIssueCode.too_big,maximum:ls.maxLength.value,type:"array",inclusive:!0,exact:!1,message:ls.maxLength.message}),os.dirty()),ss.common.async)return Promise.all([...ss.data].map((ps,hs)=>ls.type._parseAsync(new ParseInputLazyPath(ss,ps,ss.path,hs)))).then(ps=>ParseStatus.mergeArray(os,ps));const us=[...ss.data].map((ps,hs)=>ls.type._parseSync(new ParseInputLazyPath(ss,ps,ss.path,hs)));return ParseStatus.mergeArray(os,us)}get element(){return this._def.type}min(ns,ss){return new ZodArray({...this._def,minLength:{value:ns,message:errorUtil.toString(ss)}})}max(ns,ss){return new ZodArray({...this._def,maxLength:{value:ns,message:errorUtil.toString(ss)}})}length(ns,ss){return new ZodArray({...this._def,exactLength:{value:ns,message:errorUtil.toString(ss)}})}nonempty(ns){return this.min(1,ns)}}ZodArray.create=($,ns)=>new ZodArray({type:$,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(ns)});function deepPartialify($){if($ instanceof ZodObject){const ns={};for(const ss in $.shape){const os=$.shape[ss];ns[ss]=ZodOptional.create(deepPartialify(os))}return new ZodObject({...$._def,shape:()=>ns})}else return $ instanceof ZodArray?new ZodArray({...$._def,type:deepPartialify($.element)}):$ instanceof ZodOptional?ZodOptional.create(deepPartialify($.unwrap())):$ instanceof ZodNullable?ZodNullable.create(deepPartialify($.unwrap())):$ instanceof ZodTuple?ZodTuple.create($.items.map(ns=>deepPartialify(ns))):$}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const ns=this._def.shape(),ss=util.objectKeys(ns);return this._cached={shape:ns,keys:ss},this._cached}_parse(ns){if(this._getType(ns)!==ZodParsedType.object){const ja=this._getOrReturnCtx(ns);return addIssueToContext(ja,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ja.parsedType}),INVALID}const{status:os,ctx:ls}=this._processInputParams(ns),{shape:us,keys:ps}=this._getCached(),hs=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const ja in ls.data)ps.includes(ja)||hs.push(ja);const ws=[];for(const ja of ps){const Ha=us[ja],Va=ls.data[ja];ws.push({key:{status:"valid",value:ja},value:Ha._parse(new ParseInputLazyPath(ls,Va,ls.path,ja)),alwaysSet:ja in ls.data})}if(this._def.catchall instanceof ZodNever){const ja=this._def.unknownKeys;if(ja==="passthrough")for(const Ha of hs)ws.push({key:{status:"valid",value:Ha},value:{status:"valid",value:ls.data[Ha]}});else if(ja==="strict")hs.length>0&&(addIssueToContext(ls,{code:ZodIssueCode.unrecognized_keys,keys:hs}),os.dirty());else if(ja!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const ja=this._def.catchall;for(const Ha of hs){const Va=ls.data[Ha];ws.push({key:{status:"valid",value:Ha},value:ja._parse(new ParseInputLazyPath(ls,Va,ls.path,Ha)),alwaysSet:Ha in ls.data})}}return ls.common.async?Promise.resolve().then(async()=>{const ja=[];for(const Ha of ws){const Va=await Ha.key,Ga=await Ha.value;ja.push({key:Va,value:Ga,alwaysSet:Ha.alwaysSet})}return ja}).then(ja=>ParseStatus.mergeObjectSync(os,ja)):ParseStatus.mergeObjectSync(os,ws)}get shape(){return this._def.shape()}strict(ns){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...ns!==void 0?{errorMap:(ss,os)=>{var us,ps;const ls=((ps=(us=this._def).errorMap)==null?void 0:ps.call(us,ss,os).message)??os.defaultError;return ss.code==="unrecognized_keys"?{message:errorUtil.errToObj(ns).message??ls}:{message:ls}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(ns){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...ns})})}merge(ns){return new ZodObject({unknownKeys:ns._def.unknownKeys,catchall:ns._def.catchall,shape:()=>({...this._def.shape(),...ns._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(ns,ss){return this.augment({[ns]:ss})}catchall(ns){return new ZodObject({...this._def,catchall:ns})}pick(ns){const ss={};for(const os of util.objectKeys(ns))ns[os]&&this.shape[os]&&(ss[os]=this.shape[os]);return new ZodObject({...this._def,shape:()=>ss})}omit(ns){const ss={};for(const os of util.objectKeys(this.shape))ns[os]||(ss[os]=this.shape[os]);return new ZodObject({...this._def,shape:()=>ss})}deepPartial(){return deepPartialify(this)}partial(ns){const ss={};for(const os of util.objectKeys(this.shape)){const ls=this.shape[os];ns&&!ns[os]?ss[os]=ls:ss[os]=ls.optional()}return new ZodObject({...this._def,shape:()=>ss})}required(ns){const ss={};for(const os of util.objectKeys(this.shape))if(ns&&!ns[os])ss[os]=this.shape[os];else{let us=this.shape[os];for(;us instanceof ZodOptional;)us=us._def.innerType;ss[os]=us}return new ZodObject({...this._def,shape:()=>ss})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=($,ns)=>new ZodObject({shape:()=>$,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(ns)});ZodObject.strictCreate=($,ns)=>new ZodObject({shape:()=>$,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(ns)});ZodObject.lazycreate=($,ns)=>new ZodObject({shape:$,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(ns)});class ZodUnion extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns),os=this._def.options;function ls(us){for(const hs of us)if(hs.result.status==="valid")return hs.result;for(const hs of us)if(hs.result.status==="dirty")return ss.common.issues.push(...hs.ctx.common.issues),hs.result;const ps=us.map(hs=>new ZodError(hs.ctx.common.issues));return addIssueToContext(ss,{code:ZodIssueCode.invalid_union,unionErrors:ps}),INVALID}if(ss.common.async)return Promise.all(os.map(async us=>{const ps={...ss,common:{...ss.common,issues:[]},parent:null};return{result:await us._parseAsync({data:ss.data,path:ss.path,parent:ps}),ctx:ps}})).then(ls);{let us;const ps=[];for(const ws of os){const ja={...ss,common:{...ss.common,issues:[]},parent:null},Ha=ws._parseSync({data:ss.data,path:ss.path,parent:ja});if(Ha.status==="valid")return Ha;Ha.status==="dirty"&&!us&&(us={result:Ha,ctx:ja}),ja.common.issues.length&&ps.push(ja.common.issues)}if(us)return ss.common.issues.push(...us.ctx.common.issues),us.result;const hs=ps.map(ws=>new ZodError(ws));return addIssueToContext(ss,{code:ZodIssueCode.invalid_union,unionErrors:hs}),INVALID}}get options(){return this._def.options}}ZodUnion.create=($,ns)=>new ZodUnion({options:$,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(ns)});const getDiscriminator=$=>$ instanceof ZodLazy?getDiscriminator($.schema):$ instanceof ZodEffects?getDiscriminator($.innerType()):$ instanceof ZodLiteral?[$.value]:$ instanceof ZodEnum?$.options:$ instanceof ZodNativeEnum?util.objectValues($.enum):$ instanceof ZodDefault?getDiscriminator($._def.innerType):$ instanceof ZodUndefined?[void 0]:$ instanceof ZodNull?[null]:$ instanceof ZodOptional?[void 0,...getDiscriminator($.unwrap())]:$ instanceof ZodNullable?[null,...getDiscriminator($.unwrap())]:$ instanceof ZodBranded||$ instanceof ZodReadonly?getDiscriminator($.unwrap()):$ instanceof ZodCatch?getDiscriminator($._def.innerType):[];class ZodDiscriminatedUnion extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns);if(ss.parsedType!==ZodParsedType.object)return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ss.parsedType}),INVALID;const os=this.discriminator,ls=ss.data[os],us=this.optionsMap.get(ls);return us?ss.common.async?us._parseAsync({data:ss.data,path:ss.path,parent:ss}):us._parseSync({data:ss.data,path:ss.path,parent:ss}):(addIssueToContext(ss,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[os]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(ns,ss,os){const ls=new Map;for(const us of ss){const ps=getDiscriminator(us.shape[ns]);if(!ps.length)throw new Error(`A discriminator value for key \`${ns}\` could not be extracted from all schema options`);for(const hs of ps){if(ls.has(hs))throw new Error(`Discriminator property ${String(ns)} has duplicate value ${String(hs)}`);ls.set(hs,us)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:ns,options:ss,optionsMap:ls,...processCreateParams(os)})}}function mergeValues($,ns){const ss=getParsedType($),os=getParsedType(ns);if($===ns)return{valid:!0,data:$};if(ss===ZodParsedType.object&&os===ZodParsedType.object){const ls=util.objectKeys(ns),us=util.objectKeys($).filter(hs=>ls.indexOf(hs)!==-1),ps={...$,...ns};for(const hs of us){const ws=mergeValues($[hs],ns[hs]);if(!ws.valid)return{valid:!1};ps[hs]=ws.data}return{valid:!0,data:ps}}else if(ss===ZodParsedType.array&&os===ZodParsedType.array){if($.length!==ns.length)return{valid:!1};const ls=[];for(let us=0;us<$.length;us++){const ps=$[us],hs=ns[us],ws=mergeValues(ps,hs);if(!ws.valid)return{valid:!1};ls.push(ws.data)}return{valid:!0,data:ls}}else return ss===ZodParsedType.date&&os===ZodParsedType.date&&+$==+ns?{valid:!0,data:$}:{valid:!1}}class ZodIntersection extends ZodType{_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns),ls=(us,ps)=>{if(isAborted(us)||isAborted(ps))return INVALID;const hs=mergeValues(us.value,ps.value);return hs.valid?((isDirty(us)||isDirty(ps))&&ss.dirty(),{status:ss.value,value:hs.data}):(addIssueToContext(os,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return os.common.async?Promise.all([this._def.left._parseAsync({data:os.data,path:os.path,parent:os}),this._def.right._parseAsync({data:os.data,path:os.path,parent:os})]).then(([us,ps])=>ls(us,ps)):ls(this._def.left._parseSync({data:os.data,path:os.path,parent:os}),this._def.right._parseSync({data:os.data,path:os.path,parent:os}))}}ZodIntersection.create=($,ns,ss)=>new ZodIntersection({left:$,right:ns,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(ss)});class ZodTuple extends ZodType{_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns);if(os.parsedType!==ZodParsedType.array)return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:os.parsedType}),INVALID;if(os.data.length<this._def.items.length)return addIssueToContext(os,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&os.data.length>this._def.items.length&&(addIssueToContext(os,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ss.dirty());const us=[...os.data].map((ps,hs)=>{const ws=this._def.items[hs]||this._def.rest;return ws?ws._parse(new ParseInputLazyPath(os,ps,os.path,hs)):null}).filter(ps=>!!ps);return os.common.async?Promise.all(us).then(ps=>ParseStatus.mergeArray(ss,ps)):ParseStatus.mergeArray(ss,us)}get items(){return this._def.items}rest(ns){return new ZodTuple({...this._def,rest:ns})}}ZodTuple.create=($,ns)=>{if(!Array.isArray($))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:$,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(ns)})};class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns);if(os.parsedType!==ZodParsedType.map)return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:os.parsedType}),INVALID;const ls=this._def.keyType,us=this._def.valueType,ps=[...os.data.entries()].map(([hs,ws],ja)=>({key:ls._parse(new ParseInputLazyPath(os,hs,os.path,[ja,"key"])),value:us._parse(new ParseInputLazyPath(os,ws,os.path,[ja,"value"]))}));if(os.common.async){const hs=new Map;return Promise.resolve().then(async()=>{for(const ws of ps){const ja=await ws.key,Ha=await ws.value;if(ja.status==="aborted"||Ha.status==="aborted")return INVALID;(ja.status==="dirty"||Ha.status==="dirty")&&ss.dirty(),hs.set(ja.value,Ha.value)}return{status:ss.value,value:hs}})}else{const hs=new Map;for(const ws of ps){const ja=ws.key,Ha=ws.value;if(ja.status==="aborted"||Ha.status==="aborted")return INVALID;(ja.status==="dirty"||Ha.status==="dirty")&&ss.dirty(),hs.set(ja.value,Ha.value)}return{status:ss.value,value:hs}}}}ZodMap.create=($,ns,ss)=>new ZodMap({valueType:ns,keyType:$,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(ss)});class ZodSet extends ZodType{_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns);if(os.parsedType!==ZodParsedType.set)return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:os.parsedType}),INVALID;const ls=this._def;ls.minSize!==null&&os.data.size<ls.minSize.value&&(addIssueToContext(os,{code:ZodIssueCode.too_small,minimum:ls.minSize.value,type:"set",inclusive:!0,exact:!1,message:ls.minSize.message}),ss.dirty()),ls.maxSize!==null&&os.data.size>ls.maxSize.value&&(addIssueToContext(os,{code:ZodIssueCode.too_big,maximum:ls.maxSize.value,type:"set",inclusive:!0,exact:!1,message:ls.maxSize.message}),ss.dirty());const us=this._def.valueType;function ps(ws){const ja=new Set;for(const Ha of ws){if(Ha.status==="aborted")return INVALID;Ha.status==="dirty"&&ss.dirty(),ja.add(Ha.value)}return{status:ss.value,value:ja}}const hs=[...os.data.values()].map((ws,ja)=>us._parse(new ParseInputLazyPath(os,ws,os.path,ja)));return os.common.async?Promise.all(hs).then(ws=>ps(ws)):ps(hs)}min(ns,ss){return new ZodSet({...this._def,minSize:{value:ns,message:errorUtil.toString(ss)}})}max(ns,ss){return new ZodSet({...this._def,maxSize:{value:ns,message:errorUtil.toString(ss)}})}size(ns,ss){return this.min(ns,ss).max(ns,ss)}nonempty(ns){return this.min(1,ns)}}ZodSet.create=($,ns)=>new ZodSet({valueType:$,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(ns)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(ns){const{ctx:ss}=this._processInputParams(ns);return this._def.getter()._parse({data:ss.data,path:ss.path,parent:ss})}}ZodLazy.create=($,ns)=>new ZodLazy({getter:$,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(ns)});class ZodLiteral extends ZodType{_parse(ns){if(ns.data!==this._def.value){const ss=this._getOrReturnCtx(ns);return addIssueToContext(ss,{received:ss.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:ns.data}}get value(){return this._def.value}}ZodLiteral.create=($,ns)=>new ZodLiteral({value:$,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(ns)});function createZodEnum($,ns){return new ZodEnum({values:$,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(ns)})}class ZodEnum extends ZodType{_parse(ns){if(typeof ns.data!="string"){const ss=this._getOrReturnCtx(ns),os=this._def.values;return addIssueToContext(ss,{expected:util.joinValues(os),received:ss.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(ns.data)){const ss=this._getOrReturnCtx(ns),os=this._def.values;return addIssueToContext(ss,{received:ss.data,code:ZodIssueCode.invalid_enum_value,options:os}),INVALID}return OK(ns.data)}get options(){return this._def.values}get enum(){const ns={};for(const ss of this._def.values)ns[ss]=ss;return ns}get Values(){const ns={};for(const ss of this._def.values)ns[ss]=ss;return ns}get Enum(){const ns={};for(const ss of this._def.values)ns[ss]=ss;return ns}extract(ns,ss=this._def){return ZodEnum.create(ns,{...this._def,...ss})}exclude(ns,ss=this._def){return ZodEnum.create(this.options.filter(os=>!ns.includes(os)),{...this._def,...ss})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(ns){const ss=util.getValidEnumValues(this._def.values),os=this._getOrReturnCtx(ns);if(os.parsedType!==ZodParsedType.string&&os.parsedType!==ZodParsedType.number){const ls=util.objectValues(ss);return addIssueToContext(os,{expected:util.joinValues(ls),received:os.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(ns.data)){const ls=util.objectValues(ss);return addIssueToContext(os,{received:os.data,code:ZodIssueCode.invalid_enum_value,options:ls}),INVALID}return OK(ns.data)}get enum(){return this._def.values}}ZodNativeEnum.create=($,ns)=>new ZodNativeEnum({values:$,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(ns)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(ns){const{ctx:ss}=this._processInputParams(ns);if(ss.parsedType!==ZodParsedType.promise&&ss.common.async===!1)return addIssueToContext(ss,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ss.parsedType}),INVALID;const os=ss.parsedType===ZodParsedType.promise?ss.data:Promise.resolve(ss.data);return OK(os.then(ls=>this._def.type.parseAsync(ls,{path:ss.path,errorMap:ss.common.contextualErrorMap})))}}ZodPromise.create=($,ns)=>new ZodPromise({type:$,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(ns)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns),ls=this._def.effect||null,us={addIssue:ps=>{addIssueToContext(os,ps),ps.fatal?ss.abort():ss.dirty()},get path(){return os.path}};if(us.addIssue=us.addIssue.bind(us),ls.type==="preprocess"){const ps=ls.transform(os.data,us);if(os.common.async)return Promise.resolve(ps).then(async hs=>{if(ss.value==="aborted")return INVALID;const ws=await this._def.schema._parseAsync({data:hs,path:os.path,parent:os});return ws.status==="aborted"?INVALID:ws.status==="dirty"||ss.value==="dirty"?DIRTY(ws.value):ws});{if(ss.value==="aborted")return INVALID;const hs=this._def.schema._parseSync({data:ps,path:os.path,parent:os});return hs.status==="aborted"?INVALID:hs.status==="dirty"||ss.value==="dirty"?DIRTY(hs.value):hs}}if(ls.type==="refinement"){const ps=hs=>{const ws=ls.refinement(hs,us);if(os.common.async)return Promise.resolve(ws);if(ws instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return hs};if(os.common.async===!1){const hs=this._def.schema._parseSync({data:os.data,path:os.path,parent:os});return hs.status==="aborted"?INVALID:(hs.status==="dirty"&&ss.dirty(),ps(hs.value),{status:ss.value,value:hs.value})}else return this._def.schema._parseAsync({data:os.data,path:os.path,parent:os}).then(hs=>hs.status==="aborted"?INVALID:(hs.status==="dirty"&&ss.dirty(),ps(hs.value).then(()=>({status:ss.value,value:hs.value}))))}if(ls.type==="transform")if(os.common.async===!1){const ps=this._def.schema._parseSync({data:os.data,path:os.path,parent:os});if(!isValid(ps))return INVALID;const hs=ls.transform(ps.value,us);if(hs instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:ss.value,value:hs}}else return this._def.schema._parseAsync({data:os.data,path:os.path,parent:os}).then(ps=>isValid(ps)?Promise.resolve(ls.transform(ps.value,us)).then(hs=>({status:ss.value,value:hs})):INVALID);util.assertNever(ls)}}ZodEffects.create=($,ns,ss)=>new ZodEffects({schema:$,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:ns,...processCreateParams(ss)});ZodEffects.createWithPreprocess=($,ns,ss)=>new ZodEffects({schema:ns,effect:{type:"preprocess",transform:$},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(ss)});class ZodOptional extends ZodType{_parse(ns){return this._getType(ns)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(ns)}unwrap(){return this._def.innerType}}ZodOptional.create=($,ns)=>new ZodOptional({innerType:$,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(ns)});class ZodNullable extends ZodType{_parse(ns){return this._getType(ns)===ZodParsedType.null?OK(null):this._def.innerType._parse(ns)}unwrap(){return this._def.innerType}}ZodNullable.create=($,ns)=>new ZodNullable({innerType:$,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(ns)});class ZodDefault extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns);let os=ss.data;return ss.parsedType===ZodParsedType.undefined&&(os=this._def.defaultValue()),this._def.innerType._parse({data:os,path:ss.path,parent:ss})}removeDefault(){return this._def.innerType}}ZodDefault.create=($,ns)=>new ZodDefault({innerType:$,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof ns.default=="function"?ns.default:()=>ns.default,...processCreateParams(ns)});class ZodCatch extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns),os={...ss,common:{...ss.common,issues:[]}},ls=this._def.innerType._parse({data:os.data,path:os.path,parent:{...os}});return isAsync(ls)?ls.then(us=>({status:"valid",value:us.status==="valid"?us.value:this._def.catchValue({get error(){return new ZodError(os.common.issues)},input:os.data})})):{status:"valid",value:ls.status==="valid"?ls.value:this._def.catchValue({get error(){return new ZodError(os.common.issues)},input:os.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=($,ns)=>new ZodCatch({innerType:$,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof ns.catch=="function"?ns.catch:()=>ns.catch,...processCreateParams(ns)});class ZodNaN extends ZodType{_parse(ns){if(this._getType(ns)!==ZodParsedType.nan){const os=this._getOrReturnCtx(ns);return addIssueToContext(os,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:os.parsedType}),INVALID}return{status:"valid",value:ns.data}}}ZodNaN.create=$=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams($)});class ZodBranded extends ZodType{_parse(ns){const{ctx:ss}=this._processInputParams(ns),os=ss.data;return this._def.type._parse({data:os,path:ss.path,parent:ss})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(ns){const{status:ss,ctx:os}=this._processInputParams(ns);if(os.common.async)return(async()=>{const us=await this._def.in._parseAsync({data:os.data,path:os.path,parent:os});return us.status==="aborted"?INVALID:us.status==="dirty"?(ss.dirty(),DIRTY(us.value)):this._def.out._parseAsync({data:us.value,path:os.path,parent:os})})();{const ls=this._def.in._parseSync({data:os.data,path:os.path,parent:os});return ls.status==="aborted"?INVALID:ls.status==="dirty"?(ss.dirty(),{status:"dirty",value:ls.value}):this._def.out._parseSync({data:ls.value,path:os.path,parent:os})}}static create(ns,ss){return new ZodPipeline({in:ns,out:ss,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(ns){const ss=this._def.innerType._parse(ns),os=ls=>(isValid(ls)&&(ls.value=Object.freeze(ls.value)),ls);return isAsync(ss)?ss.then(ls=>os(ls)):os(ss)}unwrap(){return this._def.innerType}}ZodReadonly.create=($,ns)=>new ZodReadonly({innerType:$,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(ns)});var ZodFirstPartyTypeKind;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,booleanType=ZodBoolean.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create;ZodUnion.create;const discriminatedUnionType=ZodDiscriminatedUnion.create;ZodIntersection.create;ZodTuple.create;const literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;var define_process_env_default$1={};const LOG_LEVEL=(define_process_env_default$1.LOG_LEVEL||"INFO").toUpperCase();log$B.setLevel(log$B.levels[LOG_LEVEL]||log$B.levels.INFO);const PRIVATE_IPV4_PATTERNS=[/^10\./,/^127\./,/^192\.168\./,/^169\.254\./,/^172\.(1[6-9]|2\d|3[0-1])\./,/^0\./,/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./],PRIVATE_IPV6_PATTERNS=[/^::1$/i,/^fe80:/i,/^f[cd][0-9a-f]{2}:/i],isIpv4MappedPrivateIpv6=$=>{const ns=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec($);if(!ns)return!1;const ss=ns[1];return PRIVATE_IPV4_PATTERNS.some(os=>os.test(ss))},LOCAL_HOSTNAME_PATTERNS=[/^localhost$/i,/\.localhost$/i,/^localhost\./i,/\.local$/i,/\.internal$/i,/\.lan$/i,/\.intranet$/i],validateInspirationUrl=$=>{const ns=$.trim();if(!ns)return{ok:!1,reason:"URL is empty."};let ss;try{ss=new URL(ns)}catch{return{ok:!1,reason:`URL is not valid: ${ns}`}}if(ss.protocol!=="http:"&&ss.protocol!=="https:")return{ok:!1,reason:`Only HTTP and HTTPS inspiration links are supported (got '${ss.protocol.replace(/:$/,"")}').`};const os=ss.hostname.toLowerCase();return os?isLocalLiteralHostname(os)?{ok:!1,reason:`URL hostname '${os}' resolves to a local or private-network target.`}:(ss.hash="",{ok:!0,url:ss,normalized:ss.toString()}):{ok:!1,reason:"URL is missing a hostname."}},isLocalLiteralHostname=$=>{const ns=$.replace(/^\[|\]$/g,"");return!!(PRIVATE_IPV4_PATTERNS.some(ss=>ss.test(ns))||PRIVATE_IPV6_PATTERNS.some(ss=>ss.test(ns))||isIpv4MappedPrivateIpv6(ns)||LOCAL_HOSTNAME_PATTERNS.some(ss=>ss.test(ns)))},projectContextExisting=objectType({kind:literalType("existing")}),DESIGN_CONTEXT_MARKDOWN_MAX_LENGTH=5e4,DESIGN_CONTEXT_SLUG_MAX_LENGTH=120,SOURCE_URL_MAX_LENGTH=2048,SOURCE_ARTIFACT_LABEL_MAX_LENGTH=80,SOURCE_ARTIFACT_CONTENT_MAX_LENGTH=8e3,SOURCE_FINDING_MAX_LENGTH=400,SOURCE_LIST_MAX_ITEMS=24,SOURCE_SCREENSHOT_MAX_ITEMS=16,sourceIntentRoleSchema=enumType(["design_source","interaction_reference","asset_source","content_reference","other"]),sourceIntentConfidenceSchema=enumType(["low","medium","high"]),sourceIntentEntrySchema=objectType({url:stringType().min(1).max(SOURCE_URL_MAX_LENGTH).optional(),imageRef:stringType().min(1).max(64).optional(),role:sourceIntentRoleSchema,confidence:sourceIntentConfidenceSchema,reason:stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)}).refine($=>!!$.url!=!!$.imageRef,{message:"sourceIntent entry must specify exactly one of `url` or `imageRef`."}),sourceIntentArtifactSchema=objectType({sources:arrayType(sourceIntentEntrySchema).min(1).max(SOURCE_LIST_MAX_ITEMS)}),designContextEntrySchema=discriminatedUnionType("kind",[objectType({kind:literalType("slug"),slug:stringType().min(1).max(DESIGN_CONTEXT_SLUG_MAX_LENGTH)}),objectType({kind:literalType("markdown"),content:stringType().min(1).max(DESIGN_CONTEXT_MARKDOWN_MAX_LENGTH),label:stringType().min(1).max(60)})]),sourceArtifactKindSchema=enumType(["urlText","siteBrief","visualBrief","screenshotNotes","motionBrief"]),sourceArtifactInputSchema=objectType({kind:sourceArtifactKindSchema,label:stringType().min(1).max(SOURCE_ARTIFACT_LABEL_MAX_LENGTH),content:stringType().min(1).max(SOURCE_ARTIFACT_CONTENT_MAX_LENGTH)}),sourceRoleSchema=enumType(["primary","inspiration","competitor"]),sourceRoleEntrySchema=objectType({url:stringType().min(1).max(SOURCE_URL_MAX_LENGTH),role:sourceRoleSchema,rationale:stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH).optional()}),sourceContextArtifactSchema=objectType({sourceFindings:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).min(1).max(SOURCE_LIST_MAX_ITEMS),sectionInventory:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).min(1).max(SOURCE_LIST_MAX_ITEMS),visualObservations:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).min(1).max(SOURCE_LIST_MAX_ITEMS),sourceRoles:arrayType(sourceRoleEntrySchema).min(1).max(SOURCE_LIST_MAX_ITEMS),qualityBar:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).min(1).max(SOURCE_LIST_MAX_ITEMS),screenshotReferences:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).max(SOURCE_SCREENSHOT_MAX_ITEMS).optional(),risks:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).max(SOURCE_LIST_MAX_ITEMS).optional()}),sourceContextInputSchema=objectType({sourceUrls:arrayType(stringType().min(1).max(SOURCE_URL_MAX_LENGTH)).max(SOURCE_LIST_MAX_ITEMS).optional(),preserveBrand:booleanType().optional(),sourceArtifacts:arrayType(sourceArtifactInputSchema).max(SOURCE_LIST_MAX_ITEMS).optional(),artifact:sourceContextArtifactSchema.optional(),sourceIntent:sourceIntentArtifactSchema.optional(),designDecision:enumType(["let_rivet_choose","go_custom"]).optional()}),executionModeSchema=enumType(["static_preview","vite_app"]),executionConfidenceSchema=enumType(["low","medium","high"]),assetPlanEntrySchema=objectType({source:stringType().min(1).max(SOURCE_URL_MAX_LENGTH),destination:stringType().min(1).max(SOURCE_URL_MAX_LENGTH),referenceAs:stringType().min(1).max(SOURCE_URL_MAX_LENGTH)}),executionCapabilityPlanSchema=objectType({mode:executionModeSchema,confidence:executionConfidenceSchema,reason:stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH),assetPlan:arrayType(assetPlanEntrySchema).max(SOURCE_LIST_MAX_ITEMS).optional(),runtimeRequirements:arrayType(stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH)).max(SOURCE_LIST_MAX_ITEMS).optional(),userQuestion:stringType().min(1).max(SOURCE_FINDING_MAX_LENGTH).optional()}),projectContextFresh=objectType({kind:literalType("fresh"),workspacePath:stringType().min(1),workspaceRoot:stringType().min(1),framework:enumType(["vite","next","astro","remix"]).optional(),assetSourceRoot:stringType().min(1).max(SOURCE_URL_MAX_LENGTH).optional(),designContext:arrayType(designContextEntrySchema).optional(),sourceContext:sourceContextInputSchema.optional(),executionPlan:executionCapabilityPlanSchema.optional()}),projectContextSchema=discriminatedUnionType("kind",[projectContextExisting,projectContextFresh]),targetSchema=objectType({type:enumType(["element","file","route"]),ref:stringType().min(1)}),briefSchema=objectType({briefId:stringType().min(1),label:stringType().min(1).max(40).describe('≤ 4 words. Rendered as the variant card title in the UI. e.g. "Spring blur", "Linear sharp".'),body:stringType().min(1).max(200).describe(`Exactly ONE sentence, ≤ 12 words. Single evocative descriptor of the variant's direction — what makes it distinct. Rendered as the card subtitle. e.g. "Apple-style spring physics with ambient blur and soft edges". No bullets, no lists, no line breaks.`),visualReferenceUrl:stringType().url().refine($=>validateInspirationUrl($).ok,{message:"visualReferenceUrl must be an HTTP(S) URL that does not target local or private networks"}).optional().describe("Optional HTTP(S) inspiration URL. Subject to SSRF guard — must not resolve to local or private network targets.")}),VARIANT_COUNT_MIN=2,VARIANT_COUNT_MAX=8;stringType().optional(),stringType().optional(),stringType().min(1),numberType().int().min(VARIANT_COUNT_MIN).max(VARIANT_COUNT_MAX).optional(),targetSchema.optional(),projectContextSchema.optional();stringType().min(1),stringType().min(1),numberType().int().nonnegative(),stringType().optional(),arrayType(briefSchema).min(1).max(8);const browserDesignContextSchema=objectType({url:stringType().min(1).max(SOURCE_URL_MAX_LENGTH).optional(),imageRef:stringType().min(1).max(64).optional(),label:stringType().min(1).max(60),markdown:stringType().min(1).max(DESIGN_CONTEXT_MARKDOWN_MAX_LENGTH)}).refine($=>!!$.url!=!!$.imageRef,{message:"designContexts entry must specify exactly one of `url` or `imageRef`."});objectType({sourceIntent:sourceIntentArtifactSchema,sourceContext:sourceContextArtifactSchema,designContexts:arrayType(browserDesignContextSchema).max(SOURCE_LIST_MAX_ITEMS).optional(),executionPlan:executionCapabilityPlanSchema});stringType().min(1),stringType().min(1),numberType().int().nonnegative(),stringType().min(1);stringType().min(1),arrayType(stringType().min(1)).min(1).max(8).optional(),booleanType().optional(),booleanType().optional(),stringType().min(1).optional(),arrayType(objectType({briefId:stringType().min(1),bodyOverride:stringType().optional()})).min(1).max(8).optional();stringType().min(1),stringType().min(1),booleanType().optional(),booleanType().optional(),stringType().min(1).optional();enumType(["check","wait","request_work"]).optional();stringType().min(1),stringType().optional(),numberType().int().min(1).max(8).optional();enumType(["running","succeeded","failed","cancelled"]);stringType().min(1),stringType().min(1),stringType().min(1),numberType().int().nonnegative(),unknownType().optional(),objectType({code:stringType(),message:stringType()}).optional(),stringType().optional(),numberType().int().nonnegative().optional(),numberType().int().nonnegative().optional(),stringType().optional();stringType().min(1),numberType().int().min(VARIANT_COUNT_MIN).max(VARIANT_COUNT_MAX),arrayType(stringType().min(1).max(SOURCE_URL_MAX_LENGTH)).max(SOURCE_LIST_MAX_ITEMS).optional(),booleanType().optional(),arrayType(sourceArtifactInputSchema).max(SOURCE_LIST_MAX_ITEMS).optional(),booleanType().optional(),stringType().optional();stringType().min(1),stringType().optional();stringType().min(1),stringType().min(1),stringType().optional();enumType(["existing","zero_to_one"]).describe('"existing": vary an existing project at projectPath/cwd (spawns code_gen items). "zero_to_one": prompt-only fresh project; server derives destinationPath (spawns static_preview items).');const startVariantsBriefContent=briefSchema.omit({briefId:!0});stringType().min(1),numberType().int().min(VARIANT_COUNT_MIN).max(VARIANT_COUNT_MAX).optional(),targetSchema.optional(),arrayType(startVariantsBriefContent).min(VARIANT_COUNT_MIN).max(VARIANT_COUNT_MAX).optional().describe("One brief per variant. `briefs.length` sets the variant count (3-5); do NOT also pass `count`. Each brief MUST describe a distinct direction — never copy the user prompt verbatim into a body."),enumType(["vite"]).optional(),stringType().optional(),stringType().optional(),arrayType(designContextEntrySchema).optional(),sourceContextInputSchema.optional(),stringType().optional();const variantHistoryStatusSchema=enumType(["completed","committed","rejected","cancelled"]);stringType().optional(),numberType().int().min(1).max(500).optional(),variantHistoryStatusSchema.optional();stringType().optional(),stringType().min(1),stringType().min(1),booleanType().optional();const DEFAULT_VARIANT_COUNT$1=3,PATTERNS=[/\bvariants?\s*[:=]\s*(\d+)(?!\.\d)\b/i,/\b(\d+)(?!\.\d)\s*variants?\b/i,/\bvariants?\s+(\d+)(?!\.\d)\b/i],clamp=$=>$<VARIANT_COUNT_MIN?VARIANT_COUNT_MIN:$>VARIANT_COUNT_MAX?VARIANT_COUNT_MAX:$,parseVariantCount=$=>{if(!$)return DEFAULT_VARIANT_COUNT$1;for(const ns of PATTERNS){const ss=ns.exec($);if(!ss)continue;const os=ss[1];if(!/^\d+$/.test(os))continue;const ls=Number.parseInt(os,10);if(!(!Number.isInteger(ls)||ls<=0))return clamp(ls)}return DEFAULT_VARIANT_COUNT$1},POPOVER_OFFSET_Y=8,POPOVER_W=320,VIEWPORT_PAD=8,DEFAULT_VARIANT_COUNT=3,OPTIMISTIC_GENERATING_TIMEOUT_MS=15e3,IFRAME_ABOVE_THRESHOLD_PCT=.65,CommentPopover=({elementContext:$,target:ns=BASE_TARGET,pin:ss,dragBox:os,position:ls,onClose:us,existingCommentId:ps,isMCPSession:hs=!1,onInputChange:ws,shake:ja})=>{var oc,fc;const Ha=usePostHog(),Va=useAnimationControls(),[Ga,Wa]=useAtom(commentsAtom),Ka=useAtomValue(iframeRefAtom),qa=useAtomValue(featureFlagsAtom).variants.isEnabled,Ja=useSetAtom(activeCarouselCommentIdAtom),Ya=useSetAtom(modeAtom),Xa=useSetAtom(panelOpenAtom),el=useSetAtom(variantsPanelOpenAtom),nl=useSetAtom(variantsPanelOptimisticGeneratingAtom),rl=useStore(),{generateVariantsForComment:sl}=useCommentVariantGeneration(),{sendVariantRequestComment:il}=useChangeSender(),{startCodeGeneration:al}=useVariantCodeGeneration(),ml=useAtomValue(agentVariantsSnapshotAtom).active===!0,vl=useAtomValue(globalChangeTrackerAtom),yl=ps?Ga.get(ps):void 0,wl=(yl==null?void 0:yl.instruction)??"",[El,pl]=reactExports.useState(wl),[Al,ll]=reactExports.useState((yl==null?void 0:yl.images)??[]),[dl,fl]=reactExports.useState((yl==null?void 0:yl.references)??[]),[ul,bl]=reactExports.useState(!1),hl=reactExports.useRef(null),Sl=reactExports.useRef(null),kl=reactExports.useRef(null);reactExports.useEffect(()=>{const Xl=setTimeout(()=>{const ec=hl.current;ec&&(ec.focus(),ec.selectionStart=ec.selectionEnd=ec.value.length)},150);return()=>clearTimeout(Xl)},[]);const Pl=reactExports.useCallback(()=>{kl.current&&(clearTimeout(kl.current),kl.current=null)},[]);reactExports.useEffect(()=>()=>{Pl()},[Pl]);const Ol=reactExports.useRef(ja);reactExports.useEffect(()=>{ja!==Ol.current&&Va.start({x:[0,-5,5,-4,4,-2,2,0],y:[0,1.5,-1.5,1,-1,.5,-.5,0],transition:{duration:.45,ease:"easeInOut"}})},[ja,Va]);const Tl=El.trim()!==wl.trim()&&El.trim()!==""||Al.length!==(((oc=yl==null?void 0:yl.images)==null?void 0:oc.length)??0)||dl.length!==(((fc=yl==null?void 0:yl.references)==null?void 0:fc.length)??0),Il=ps?Tl:El.trim()!=="",zl=reactExports.useCallback(Xl=>{fl(Xl),ws==null||ws(El.trim()!==""||Al.length>0||Xl.length>0)},[El,Al.length,ws]),Nl=reactExports.useCallback(Xl=>{zl(dl.filter(ec=>!(ec.sessionId===Xl.sessionId&&ec.variantId===Xl.variantId)))},[dl,zl]),Bl=reactExports.useCallback(Xl=>{us(Xl)},[us]),Zl=reactExports.useCallback(Xl=>{Xl.style.height="auto",Xl.style.height=`${Xl.scrollHeight}px`},[]),Gl=reactExports.useCallback(Xl=>{compressImage(Xl).then(ec=>{ll(Ac=>[...Ac,ec])}).catch(()=>{console.warn("[CommentPopover] Failed to process image:",Xl.name)})},[]),ql=reactExports.useCallback(Xl=>{ll(ec=>[...ec,Xl]),ws==null||ws(!0)},[ws]),{isDragOver:cc,dropHandlers:gc}=useImageDrop(ql),pc=Xl=>{const ec=Xl.target.files;if(!ec)return;let Ac=!1;for(const Sc of Array.from(ec))Sc.type.startsWith("image/")&&(Gl(Sc),Ac=!0);Sl.current&&(Sl.current.value=""),Ac&&(ws==null||ws(!0))},Jl=Xl=>{var Ac;const ec=(Ac=Xl.clipboardData)==null?void 0:Ac.items;if(ec){for(const Sc of Array.from(ec))if(Sc.type.startsWith("image/")){Xl.preventDefault();const Cc=Sc.getAsFile();Cc&&(Gl(Cc),ws==null||ws(!0))}}},bc=Xl=>{const ec=Al.filter((Ac,Sc)=>Sc!==Xl);ll(ec),ws==null||ws(El.trim()!==""||ec.length>0)},Hl=reactExports.useCallback(async Xl=>{var Zc,pu;const ec=El.trim();if(!ec)return;const Ac=(Xl==null?void 0:Xl.forceGenerateVariants)===!0&&!hs,Sc=Ac?{styleVariants:void 0,selectedVariantIndex:void 0,finalizedVariant:void 0,variantGenerationStatus:"generating",variantGenerationError:void 0,requestedVariantCount:DEFAULT_VARIANT_COUNT}:{};if(Ac&&ps){cancelVariantGeneration(ps);const Xc=rl.get(appliedVariantDiffAtom);Xc&&Xc.commentId===ps&&(await revertVariantDiff(Xc.diff),rl.set(appliedVariantDiffAtom,null));const hu=(pu=(Zc=Ga.get(ps))==null?void 0:Zc.finalizedVariant)==null?void 0:pu.codeDiff;hu&&await revertVariantDiff(hu)}let Cc;if(ps)Cc=ps,Wa(Xc=>{const hu=Xc.get(ps);if(!hu)return Xc;const Gu=new Map(Xc);return Gu.set(ps,{...hu,instruction:ec,images:Al.length>0?Al:void 0,references:dl.length>0?dl:void 0,variantRequest:void 0,...Sc}),Gu}),Ha==null||Ha.capture("comment_edited",{instruction_length:ec.length,image_count:Al.length,reference_count:dl.length,has_variants:Ac});else{const Xc=crypto.randomUUID();Cc=Xc;const hu={id:Xc,target:ns,elementContext:$,pin:ss,dragBox:os,instruction:ec,images:Al.length>0?Al:void 0,references:dl.length>0?dl:void 0,...Sc,status:"pending"};Wa(Gu=>{const Rc=new Map(Gu);return Rc.set(Xc,hu),Rc}),Ha==null||Ha.capture("comment_added",{instruction_length:ec.length,image_count:Al.length,reference_count:dl.length,has_variants:Ac})}Bl({preserveSelection:!0}),Ac&&(Ja(Cc),sl({commentId:Cc,instruction:ec,elementContext:$,requestedVariantCount:DEFAULT_VARIANT_COUNT,onVariantsReady:Xc=>void al(Xc)}))},[El,Al,dl,ps,$,ns,ss,os,Ga,Wa,Ha,hs,sl,al,Bl,Ja,rl]),Ql=reactExports.useCallback(async()=>{const Xl=El.trim();if(!Xl)return;const ec=parseVariantCount(El),Ac=ps??crypto.randomUUID();if(ps)Wa(Cc=>{const Zc=Cc.get(ps);if(!Zc)return Cc;const pu=new Map(Cc);return pu.set(ps,{...Zc,instruction:Xl,images:void 0,references:dl.length>0?dl:void 0,variantRequest:{count:ec}}),pu}),Ha==null||Ha.capture("comment_edited",{instruction_length:Xl.length,image_count:0,reference_count:dl.length,has_variants:!1});else{const Cc={id:Ac,target:ns,elementContext:$,pin:ss,dragBox:os,instruction:Xl,references:dl.length>0?dl:void 0,variantRequest:{count:ec},status:"pending"};Wa(Zc=>{const pu=new Map(Zc);return pu.set(Ac,Cc),pu}),Ha==null||Ha.capture("comment_added",{instruction_length:Xl.length,image_count:0,reference_count:dl.length,has_variants:!1})}Ha==null||Ha.capture("comment_variant_trigger_started",{source:"mcp",requestedCount:ec}),Pl(),nl(!0),kl.current=setTimeout(()=>{kl.current=null,nl(!1)},OPTIMISTIC_GENERATING_TIMEOUT_MS),el(!0),Xa(!0),Ya("view"),Bl({preserveSelection:!0});const Sc=await il(Ac);Sc.success||(Pl(),nl(!1),toast.error(Sc.error||"Failed to queue direction request"))},[El,dl,ps,$,ns,ss,os,Wa,Ha,Bl,Ya,Xa,el,nl,il,Pl]),Yl=Hl,ac=reactExports.useCallback(async()=>{var Xl;if(ps){cancelVariantGeneration(ps);const ec=(Ka==null?void 0:Ka.current)??null;ec&&restoreCommentPreviewBaselines(ec,Ga.values());const Ac=rl.get(appliedVariantDiffAtom);Ac&&Ac.commentId===ps&&(await revertVariantDiff(Ac.diff),rl.set(appliedVariantDiffAtom,null));const Sc=Ga.get(ps),Cc=(Xl=Sc==null?void 0:Sc.finalizedVariant)==null?void 0:Xl.codeDiff;Cc&&await revertVariantDiff(Cc),Wa(Zc=>{const pu=new Map(Zc);return pu.delete(ps),pu}),Ha==null||Ha.capture("comment_deleted")}Bl()},[ps,Ga,Ka,Wa,Bl,Ha,rl]),lc=reactExports.useCallback(Xl=>{Xl.key==="Enter"&&(Xl.metaKey||Xl.ctrlKey)&&(Xl.preventDefault(),Xl.nativeEvent.stopImmediatePropagation(),Yl()),Xl.key==="Escape"&&(Xl.nativeEvent.stopImmediatePropagation(),Bl({preserveSelection:!0}))},[Yl,Bl]),Dl=window.innerHeight,Ll=ls.y/Dl>IFRAME_ABOVE_THRESHOLD_PCT,Kl=ps?"Save":"Add",nc=(()=>{if(El.trim()==="")return"empty_instruction";if(Al.length>0)return"images_attached";if(ml)return"active_session";if(vl.getStyleChanges().length>0||vl.getTextChanges().length>0)return"mixed_batch";const ec=Array.from(Ga.values()).filter(Cc=>Cc.status==="pending"&&Cc.id!==ps);return ec.some(Cc=>!!Cc.variantRequest)?"duplicate_variant_request":ec.some(Cc=>!Cc.variantRequest)?"mixed_batch":null})(),_l=parseVariantCount(El),uc=(()=>{switch(nc){case"empty_instruction":return"Add an instruction to generate directions.";case"images_attached":return"Remove attached images — image context is not supported for directions yet.";case"mixed_batch":return"Directions must be sent on their own — clear other pending changes first.";case"duplicate_variant_request":return"A direction request is already pending — send or cancel it first.";case"active_session":return"A directions session is already running — finish or cancel it first.";default:return`Generate ${_l} design directions for the selected element. You'll preview and pick one.`}})();return jsxRuntimeExports.jsx("div",{className:"fixed z-comment-preview cursor-auto",style:{top:Ll?ls.y-POPOVER_OFFSET_Y:ls.y+POPOVER_OFFSET_Y,left:Math.max(VIEWPORT_PAD,Math.min(ls.x-POPOVER_W/2,window.innerWidth-POPOVER_W-VIEWPORT_PAD)),transform:Ll?"translateY(-100%)":void 0},onClick:Xl=>Xl.stopPropagation(),children:jsxRuntimeExports.jsx(motion.div,{animate:Va,children:jsxRuntimeExports.jsxs(motion.div,{className:"relative flex w-80 flex-col gap-2 rounded-xl bg-main p-4 shadow-2xl",style:{transformOrigin:"center 24px"},initial:{scale:.82,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.82,opacity:0,transition:{duration:.1,ease:[.55,0,1,.45]}},transition:{type:"spring",stiffness:500,damping:28,mass:.8},...gc,children:[cc?jsxRuntimeExports.jsx("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-xl border-2 border-dashed border-primary bg-primary/10",children:jsxRuntimeExports.jsx("span",{className:"text-sm font-medium text-content",children:"Drop image here"})}):null,dl.length>0?jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:dl.map(Xl=>jsxRuntimeExports.jsx(CommentReferenceChip,{reference:Xl,onRemove:()=>Nl(Xl)},`${Xl.sessionId}:${Xl.variantId}`))}):null,jsxRuntimeExports.jsx("textarea",{ref:Xl=>{hl.current=Xl,Xl&&Zl(Xl)},value:El,onChange:Xl=>{const ec=Xl.target.value;pl(Xl.target.value),Zl(Xl.target),ws==null||ws(ec.trim()!==""||Al.length>0)},onKeyDown:lc,onPaste:Jl,placeholder:"What should change?",rows:3,style:{maxHeight:"9rem",overflowY:"auto"},className:"w-full resize-none rounded-lg border border-divider bg-main-light p-3 text-sm text-content outline-none transition-colors duration-100 placeholder:text-content-subtle focus:border-primary focus:ring-1 focus:ring-primary/30"}),Al.length>0?jsxRuntimeExports.jsx("div",{className:"max-h-40 overflow-y-auto rounded",children:jsxRuntimeExports.jsx("div",{className:`grid gap-1.5 ${Al.length===1?"grid-cols-1":"grid-cols-2"}`,children:Al.map((Xl,ec)=>jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("img",{src:Xl,alt:`Reference ${ec+1}`,className:`w-full rounded border border-divider object-cover ${Al.length===1?"max-h-32":"aspect-[4/3]"}`}),jsxRuntimeExports.jsx("button",{onClick:()=>bc(ec),className:"absolute right-1 top-1 rounded-full bg-red-500/80 p-0.5 text-white backdrop-blur-sm hover:bg-red-600",children:jsxRuntimeExports.jsx(n$1,{className:"h-2.5 w-2.5",weight:"bold"})})]},ec))})}):null,jsxRuntimeExports.jsx("input",{ref:Sl,type:"file",accept:"image/*",multiple:!0,onChange:pc,className:"hidden"}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[ps?jsxRuntimeExports.jsx("button",{type:"button",onClick:ac,className:"p-1 text-content-subtle transition-colors hover:text-accent-error",title:"Delete comment",children:jsxRuntimeExports.jsx(n$2,{className:"h-4 w-4",weight:"bold"})}):null,jsxRuntimeExports.jsx(Tooltip,{label:"Attach",children:jsxRuntimeExports.jsx("button",{type:"button","aria-label":"Attach reference image",onClick:()=>{var Xl;return(Xl=Sl.current)==null?void 0:Xl.click()},className:"p-1 text-content-subtle transition-colors hover:text-content",children:jsxRuntimeExports.jsx(I,{className:"h-4 w-4",weight:"bold"})})}),jsxRuntimeExports.jsx(Tooltip,{label:"Reference a direction",children:jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("button",{type:"button","aria-label":"Reference a direction","aria-haspopup":"listbox","aria-expanded":ul,onClick:()=>bl(Xl=>!Xl),className:`p-1 transition-colors ${ul||dl.length>0?"text-content":"text-content-subtle hover:text-content"}`,children:jsxRuntimeExports.jsx(n$9,{className:"h-4 w-4",weight:"bold"})}),ul?jsxRuntimeExports.jsx("div",{className:"absolute bottom-full left-0 z-20 mb-2",children:jsxRuntimeExports.jsx(CommentReferencePicker,{attached:dl,commentTarget:ns,onChange:zl,onClose:()=>bl(!1)})}):null]})}),!hs&&qa?jsxRuntimeExports.jsx(Tooltip,{label:"Vary",children:jsxRuntimeExports.jsx("button",{type:"button","aria-label":"Generate 3 directions",onClick:()=>Yl({forceGenerateVariants:!0}),disabled:!Il,className:"p-1 text-content-subtle transition-colors hover:text-content disabled:opacity-50",children:jsxRuntimeExports.jsx(n$8,{className:"h-4 w-4",weight:"bold"})})}):null,hs?jsxRuntimeExports.jsx(Tooltip,{label:uc,children:jsxRuntimeExports.jsx("button",{type:"button","aria-label":"Generate directions","data-testid":"mcp-variant-trigger",onClick:()=>void Ql(),disabled:nc!==null,className:"p-1 text-content-subtle transition-colors hover:text-content disabled:opacity-50",children:jsxRuntimeExports.jsx(n$8,{className:"h-4 w-4",weight:"bold"})})}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>Bl(),className:"px-2 py-1.5 text-sm text-content-muted transition-colors hover:text-content",children:"Cancel"}),jsxRuntimeExports.jsx("button",{onClick:()=>Yl(),disabled:!Il,className:"rounded-full bg-primary px-5 py-1.5 text-sm font-medium text-white transition-colors hover:bg-primary-hover disabled:opacity-50",children:Kl})]})]})]})})})},log$6=createLogger("PreviewSurface"),PreviewSurface=({target:$,src:ns,framework:ss,mode:os,isUpstreamReady:ls,remountKey:us})=>{const ps=previewTargetKey($),hs=useSetAtom(registerSurfaceIframeAtom),ws=useSetAtom(registerSurfaceAdapterAtom),ja=useSetAtom(selectedElementTargetAtom),Ha=useAtomValue(commentsAtom),Va=useSetAtom(editingCommentIdAtom),Ga=useSetAtom(activeCarouselCommentIdAtom),Wa=useAtomValue(isMCPSessionAtom),Ka=useAtomValue(variantsPanelOpenAtom),Za=useSetAtom(isCommentDraftDirtyAtom),[qa,Ja]=useAtom(commentShakeAtom),Ya=useAtomValue(panelClickVersionAtom),[Xa,el]=reactExports.useState(null),nl=useStore(),[rl,sl]=useAtom(commentDraftAtom),il=reactExports.useCallback(()=>nl.get(isCommentDraftDirtyAtom),[nl]),al=rl&&previewTargetsEqual(rl.target,$)?rl:null,cl=reactExports.useRef(null),{enterEditMode:ml}=useInlineTextEdit({iframeRef:cl}),vl=useAtomValue(featureFlagsAtom);useElementResize({iframeRef:cl,enabled:vl.resize.isEnabled,surfaceId:ps});const yl=reactExports.useCallback(Nl=>Za(Nl),[Za]),wl=reactExports.useCallback((Nl,Bl,Zl)=>{if(il()){Ja(Gl=>Gl+1);return}yl(!1),Va(null),Ga(null),ja($),sl({key:crypto.randomUUID(),target:$,elementContext:Nl,pin:Bl,dragBox:Zl})},[il,Ja,yl,Va,Ga,ja,sl,$]),El=reactExports.useCallback(()=>{if(il()){Ja(Nl=>Nl+1);return}sl(null),Va(null),Ga(null),yl(!1)},[il,Ja,sl,yl,Va,Ga]),pl=reactExports.useCallback((Nl,Bl,Zl)=>{ml(Nl,Bl,Zl)},[ml]),{setupIframe:Al,clearSelectionState:ll,iframeRef:dl}=useIframeSelection({surfaceId:ps,target:$,mode:os,isBoxModelVisible:!0,onTextEdit:pl,onCommentClick:wl,onCommentSelectionClear:El}),fl=reactExports.useRef(Ya);reactExports.useEffect(()=>{Ya!==fl.current&&(fl.current=Ya,os!=="edit"&&(il()||(sl(null),Va(null),Ga(null),yl(!1),ll())))},[Ya,os,il,ll,sl,yl,Va,Ga]);const ul=reactExports.useCallback(Nl=>{sl(null),Va(null),Ga(null),yl(!1),Nl!=null&&Nl.preserveSelection||ll()},[ll,sl,yl,Va,Ga]),bl=reactExports.useCallback(()=>ul({preserveSelection:!0}),[ul]),{startCodeGeneration:hl}=useVariantCodeGeneration(),Sl=reactExports.useCallback(Nl=>{const Bl=Ha.get(Nl);if(!Bl)return;yl(!1);const Zl=Bl.styleVariants&&Bl.styleVariants.length>0;if(Va(Nl),Ga(Zl?Nl:null),ja($),sl({key:crypto.randomUUID(),target:$,elementContext:Bl.elementContext,pin:Bl.pin,dragBox:Bl.dragBox,existingCommentId:Nl}),Bl.variantGenerationStatus!=="generating"&&!Bl.finalizedVariant&&Bl.styleVariants&&!hasVariantGeneration(Nl)){const Gl=Bl.styleVariants.map((ql,cc)=>({v:ql,index:cc+1})).filter(({v:ql})=>ql.changeSpec&&!ql.codeDiff&&!ql.codeStatus);Gl.length>0&&hl({commentId:Nl,sessionId:crypto.randomUUID(),instruction:Bl.instruction,elementContext:Bl.elementContext,variants:Gl.map(({v:ql,index:cc})=>({index:cc,label:ql.label,changeSpec:ql.changeSpec}))})}},[Ha,yl,Va,Ga,ja,sl,$,hl]),kl=reactExports.useCallback((Nl,Bl,Zl=!1)=>{const Gl=dl.current;if(!Gl)return null;const ql=Gl.contentDocument??null;if(!ql)return null;const cc=resolveElementFromContext(ql,Nl);if(!cc)return null;const gc=Gl.getBoundingClientRect(),pc=cc.getBoundingClientRect(),Jl={top:gc.top+pc.top,bottom:gc.top+pc.bottom},bc=Zl&&carouselPillIsBelow(Jl);let Hl=gc.top+pc.top+Bl.elementYPct*pc.height;return Zl&&(Hl=bc?gc.top+pc.bottom+CAROUSEL_BAR_GAP+CAROUSEL_BAR_HEIGHT:gc.top+pc.top-CAROUSEL_BAR_GAP-CAROUSEL_BAR_HEIGHT),{x:gc.left+pc.left+Bl.elementXPct*pc.width,y:Hl}},[dl]),[,Pl]=reactExports.useState(0),Ol=reactExports.useCallback(()=>Pl(Nl=>Nl+1),[]);reactExports.useEffect(()=>{const Nl=dl.current;if(!al||!Nl)return;const Bl=Nl.contentDocument;Bl&&Bl.addEventListener("scroll",Ol,!0);const Zl=new ResizeObserver(Ol);return Zl.observe(Nl),Nl.addEventListener("load",Ol),()=>{Bl&&Bl.removeEventListener("scroll",Ol,!0),Zl.disconnect(),Nl.removeEventListener("load",Ol)}},[al,dl,Ol]);const Tl=al!=null&&al.existingCommentId?(()=>{var Bl;const Nl=Ha.get(al.existingCommentId);return!!((Bl=Nl==null?void 0:Nl.styleVariants)!=null&&Bl.length&&!Nl.finalizedVariant)})():!1,Il=al?kl(al.elementContext,al.pin,Tl):null;reactExports.useEffect(()=>{if(ss!=="static"&&!ls){Xa&&(el(null),ws({surfaceId:ps,adapter:null}));return}if(dl.current&&!Xa){const Nl=ss==="static";console.log(`[PreviewSurface] Creating ${Nl?"Static":""}IframeDisplayAdapter`);const Bl=os==="edit"?"edit":"view",Zl=Nl?new StaticIframeAdapter(dl.current,{mode:Bl,isBoxModelVisible:!0}):new IframeDisplayAdapter(dl.current,{mode:Bl,isBoxModelVisible:!0});Zl.initialize(),el(Zl),ws({surfaceId:ps,adapter:Zl})}},[Xa,ss,ls,os,dl,ws,ps]);const zl=reactExports.useCallback(Nl=>{Nl&&(Al(Nl),cl.current=Nl)},[Al]);return reactExports.useEffect(()=>(hs({surfaceId:ps,ref:dl}),()=>{hs({surfaceId:ps,ref:null}),ws({surfaceId:ps,adapter:null})}),[hs,ws,ps,dl]),reactExports.useEffect(()=>{os!=="comment"&&(il()||(sl(null),Va(null),Ga(null),os==="view"&&ll()))},[os,il,ll,sl,Va,Ga]),jsxRuntimeExports.jsxs("div",{className:"relative h-full w-full",children:[jsxRuntimeExports.jsx("iframe",{ref:zl,src:ns,className:"h-full w-full border-none",title:"Project Preview",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-modals",onLoad:()=>{Na==null||Na.capture("preview_iframe_loaded",{framework:ss,src:ns})},onError:()=>{Na==null||Na.capture("preview_iframe_load_failed",{framework:ss,src:ns}),log$6.warn("Preview iframe failed to load",{framework:ss,src:ns})}},us),ls&&!Ka?jsxRuntimeExports.jsx(CommentMarkerLayer,{onEditComment:Sl,target:$,iframeRef:dl}):null,$.kind==="base"&&ls&&!Wa&&!Ka?jsxRuntimeExports.jsx(CommentCarouselLayer,{onCommentClose:bl}):null,(al==null?void 0:al.dragBox)&&!al.existingCommentId&&dl.current&&(()=>{const Nl=dl.current,Bl=Nl.getBoundingClientRect(),Zl=Nl.contentDocument;if(!Zl)return null;const Gl=resolveElementFromContext(Zl,al.elementContext);if(!Gl)return null;const ql=Gl.getBoundingClientRect(),{leftPct:cc,topPct:gc,widthPct:pc,heightPct:Jl}=al.dragBox;return jsxRuntimeExports.jsx("div",{"data-comment-drag-box":"true",style:{position:"fixed",pointerEvents:"none",zIndex:45,border:"1px dashed var(--color-primary, #FF3300)",background:"rgba(255, 51, 0, 0.08)",borderRadius:2,boxSizing:"border-box",left:Bl.left+ql.left+cc*ql.width,top:Bl.top+ql.top+gc*ql.height,width:pc*ql.width,height:Jl*ql.height}})})(),al&&Il&&!al.existingCommentId&&jsxRuntimeExports.jsx(CommentMarker,{comment:{id:"draft",elementContext:al.elementContext,pin:al.pin,instruction:"",status:"pending"},index:Ha.size,position:Il,onDismiss:()=>{},onEdit:()=>{}}),reactDomExports.createPortal(jsxRuntimeExports.jsx(AnimatePresence,{children:al&&Il?jsxRuntimeExports.jsx(CommentPopover,{elementContext:al.elementContext,target:$,pin:al.pin,dragBox:al.dragBox,position:Il,onClose:ul,existingCommentId:al.existingCommentId,isMCPSession:Wa,onInputChange:Nl=>{yl(Nl)},shake:qa},al.key):null}),document.body)]})},IframePreview=({isInteractionDisabled:$=!1,framework:ns,userPort:ss,activeDemoSessionId:os=null,holdPreviewNavigation:ls=!1})=>{const us=useAtomValue(modeAtom),ps=useAtomValue(iframeRemountKeyAtom),hs=useAtomValue(iframePreviewOverrideUrlAtom),ws=useAtomValue(agentVariantsSnapshotAtom),ja=useAtomValue(variantPreviewPreferDevServerAtom),Ha=useSetAtom(variantPreviewPreferDevServerAtom),Va=ws.active&&ws.projectContext.kind==="fresh";reactExports.useEffect(()=>{ws.active||Ha(!1)},[ws.active,Ha]);const Ga=reactExports.useMemo(()=>{var cl;if(ja||hs||!ws.active)return null;const{stage:sl,variants:il}=ws;if(sl!=="ready"&&sl!=="degraded")return null;const al=il.find(ml=>{var vl;return ml.status==="succeeded"&&((vl=ml.preview)==null?void 0:vl.kind)==="static_artifact"});return((cl=al==null?void 0:al.preview)==null?void 0:cl.kind)==="static_artifact"?al.preview.url:null},[hs,ja,ws]),Wa=hs??Ga,Ka=Wa!==null||Va&&!ja,{isUpstreamReady:Za,iframeRemountKey:qa,initialProbeComplete:Ja}=usePreviewUpstreamHealth(ns,{rerunProbeImmediatelyOnVersion:ps,skip:Ka}),Ya=!!Wa||Za,Xa=`${qa}:${ps}`,el=os?`/try/${encodeURIComponent(os)}`:"",nl=ns==="static"?`${el}/static/`:`${el}/`,rl=Wa??(ls||!Ya?"about:blank":nl);return jsxRuntimeExports.jsxs("div",{className:"relative h-full w-full",children:[!Ya&&Ja?jsxRuntimeExports.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-main/90 px-6",children:jsxRuntimeExports.jsx("div",{role:"alert","aria-live":"polite",className:"flex max-w-sm flex-col items-center gap-5 text-center",children:Va?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-semibold text-content",children:"Directions will appear here"}),jsxRuntimeExports.jsx("p",{className:"text-base leading-relaxed text-content-muted",children:"Select one from the panel to preview it."})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-semibold text-content",children:"Preview isn't connected"}),jsxRuntimeExports.jsx("p",{className:"text-base leading-relaxed text-content-muted",children:"The connection between Rivet and your project is offline. Try restarting Rivet, then click reload below."}),jsxRuntimeExports.jsx("button",{onClick:()=>window.location.reload(),className:"rounded-md bg-primary px-10 py-2.5 text-sm font-medium text-white transition-colors hover:bg-primary-hover",children:"Reload"})]})})}):null,jsxRuntimeExports.jsx(PreviewSurface,{target:BASE_TARGET,src:rl,framework:ns,mode:$?"view":us,isUpstreamReady:Ya,remountKey:Xa})]})},Progress=({message:$,isLoading:ns=!0})=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-content",children:[ns?jsxRuntimeExports.jsx(s$6,{className:"h-4 w-4 shrink-0 animate-spin text-primary",weight:"bold"}):null,jsxRuntimeExports.jsx("span",{className:"whitespace-pre-wrap font-sans",children:$})]});function SecondaryVariantIframe({side:$,sessionId:ns,variantId:ss,url:os,label:ls,isFallback:us=!1}){const ps=useSetAtom(variantSplitViewAtom),hs=useAtomValue(modeAtom),ws=reactExports.useCallback(()=>{if(us){ps(null);return}ps(Ha=>{if(!Ha)return null;const Va={...Ha};return delete Va[$],Va.left||Va.right?Va:null})},[ps,$,us]),ja=reactExports.useMemo(()=>({kind:"variant",sessionId:ns,variantId:ss}),[ns,ss]);return jsxRuntimeExports.jsxs("div",{className:"variant-split-secondary","data-cy":"variant-split-pane","data-variant-id":ss,children:[jsxRuntimeExports.jsxs("div",{className:"variant-split-secondary-toolbar",children:[jsxRuntimeExports.jsx("span",{className:"variant-split-secondary-label",title:ls,children:ls}),jsxRuntimeExports.jsx("button",{type:"button",className:"variant-split-secondary-close",onClick:ws,"aria-label":"Exit split view",children:jsxRuntimeExports.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",focusable:"false",children:jsxRuntimeExports.jsx("path",{d:"M2.5 2.5 L9.5 9.5 M9.5 2.5 L2.5 9.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})})]}),jsxRuntimeExports.jsx("div",{className:"variant-split-secondary-body relative min-h-0 flex-1",children:jsxRuntimeExports.jsx(PreviewSurface,{target:ja,src:os,framework:"static",mode:hs,isUpstreamReady:!0})})]})}const GHOST_WIDTH=220,GHOST_HEIGHT=64;function VariantDragGhost(){const $=useAtomValue(draggedVariantAtom),ns=useAtomValue(draggedVariantPointerAtom),ss=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!$||!ns||!ss.current)return;const os=ns.x-GHOST_WIDTH/2,ls=ns.y-22;ss.current.style.transform=`translate3d(${os}px, ${ls}px, 0)`},[$,ns]),$?jsxRuntimeExports.jsx("div",{ref:ss,"aria-hidden":"true",className:"variant-drag-ghost",style:{width:GHOST_WIDTH,height:GHOST_HEIGHT},children:jsxRuntimeExports.jsx("div",{className:"variant-drag-ghost-row",children:jsxRuntimeExports.jsx("div",{className:"variant-drag-ghost-title",children:$.label})})}):null}function VariantSplitDropZones(){const $=useAtomValue(draggedVariantAtom),ns=useAtomValue(draggedVariantPointerAtom),ss=useSetAtom(draggedVariantAtom),os=useSetAtom(variantSplitViewAtom),ls=reactExports.useRef(null),[us,ps]=reactExports.useState(null),[hs,ws]=reactExports.useState("hidden");reactExports.useEffect(()=>{if(!$){ws("hidden"),ps(null);return}const Va=requestAnimationFrame(()=>ws("visible"));return()=>cancelAnimationFrame(Va)},[$]);const ja=reactExports.useCallback((Va,Ga)=>{const Wa=ls.current;if(!Wa)return null;const Ka=Wa.getBoundingClientRect();return Va<Ka.left||Va>Ka.right||Ga<Ka.top||Ga>Ka.bottom?null:Va<(Ka.left+Ka.right)/2?"left":"right"},[]);if(reactExports.useEffect(()=>{if(!$||!ns)return;const Va=ja(ns.x,ns.y);ps(Ga=>Ga===Va?Ga:Va)},[$,ns,ja]),reactExports.useEffect(()=>{if(!$)return;const Va=Ga=>{const Wa=ja(Ga.clientX,Ga.clientY);if(Wa&&$.url){const Ka={sessionId:$.sessionId,variantId:$.variantId,label:$.label,url:$.url};os(Za=>({...Za??{},[Wa]:Ka})),ws("exiting"),window.setTimeout(()=>ss(null),220)}else ws("exiting"),window.setTimeout(()=>ss(null),220)};return window.addEventListener("pointerup",Va),window.addEventListener("pointercancel",Va),()=>{window.removeEventListener("pointerup",Va),window.removeEventListener("pointercancel",Va)}},[$,ja,ss,os]),!$)return null;const Ha=["variant-drop-zones",hs==="visible"&&"is-visible",hs==="exiting"&&"is-exiting"].filter(Boolean).join(" ");return jsxRuntimeExports.jsxs("div",{ref:ls,className:Ha,"aria-hidden":"true",children:[jsxRuntimeExports.jsx(Zone,{side:"left",hovered:us==="left",canDrop:!!$.url,label:$.label}),jsxRuntimeExports.jsx(Zone,{side:"right",hovered:us==="right",canDrop:!!$.url,label:$.label})]})}function Zone({side:$,hovered:ns,canDrop:ss,label:os}){return jsxRuntimeExports.jsxs("div",{className:["variant-drop-zone",`is-${$}`,ns&&"is-hover",!ss&&"is-disabled"].filter(Boolean).join(" "),children:[jsxRuntimeExports.jsxs("div",{className:"variant-drop-zone-inner",children:[jsxRuntimeExports.jsx("div",{className:`variant-drop-zone-icon is-${$}`}),jsxRuntimeExports.jsx("div",{className:"variant-drop-zone-caption",children:ss?`Add ${$} split`:"Split unavailable for this direction"})]}),jsxRuntimeExports.jsx("div",{className:"variant-drop-zone-preview","aria-hidden":"true",children:jsxRuntimeExports.jsx("div",{className:"variant-drop-zone-preview-label",children:os})}),jsxRuntimeExports.jsx("div",{className:"variant-drop-zone-border"})]})}const PreviewFrame=({isLoading:$=!1,isInteractionDisabled:ns=!1,activeDemoSessionId:ss=null,holdHostedTryoutPreviewNavigation:os=!1})=>{const{config:ls,fetchConfig:us,isLoading:ps,error:hs}=useServerConfig();return reactExports.useEffect(()=>{us().catch(ws=>{Na==null||Na.capture("preview_config_load_failed",{message:ws instanceof Error?ws.message:"unknown_error"})})},[us]),ps?os?jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 w-full flex-1 bg-main","aria-busy":"true"}):jsxRuntimeExports.jsx("div",{className:"flex h-full w-full items-center justify-center bg-main px-6",children:jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:jsxRuntimeExports.jsx(Progress,{message:"Loading..."})})}):hs||!ls?jsxRuntimeExports.jsx("div",{className:"flex h-full w-full items-center justify-center bg-main px-6",children:jsxRuntimeExports.jsxs("div",{className:"max-w-md rounded-lg border border-divider bg-main-light p-4 text-center shadow-lg",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-content",children:"We couldn't load your app preview."}),jsxRuntimeExports.jsx("p",{className:"text-content-subtle mt-2 text-sm",children:hs||"Missing preview configuration from the server."}),jsxRuntimeExports.jsx("p",{className:"text-content-subtle mt-2 text-sm",children:"If this keeps happening, restart your Rivet session and try again."}),jsxRuntimeExports.jsx("button",{type:"button",className:"mt-4 rounded-md border border-divider px-3 py-1.5 text-xs text-content hover:bg-main/80",onClick:()=>{Na==null||Na.capture("preview_config_retry_clicked"),us().catch(ws=>{Na==null||Na.capture("preview_config_load_failed",{message:ws instanceof Error?ws.message:"unknown_error"})})},children:"Retry preview"})]})}):jsxRuntimeExports.jsx(PreviewFrameInner,{isLoading:$,isInteractionDisabled:ns,framework:ls.framework,userPort:ls.userPort,activeDemoSessionId:ss,holdHostedTryoutPreviewNavigation:os})};function PreviewFrameInner($){const ns=useAtomValue(variantSplitViewAtom),ss=useAtomValue(draggedVariantAtom),os=useAtomValue(modeAtom),ls=useSetAtom(changeModeAtom),us=useAtomValue(agentVariantsSnapshotAtom),ps=ns==null?void 0:ns.left,hs=ns==null?void 0:ns.right,ws=reactExports.useMemo(()=>{var Ya,Xa;if(!us.active||us.projectContext.kind!=="fresh"||!(!!ps!=!!hs))return;const qa=(Ya=ps??hs)==null?void 0:Ya.variantId,Ja=us.variants.find(el=>{var nl;return el.status==="succeeded"&&((nl=el.preview)==null?void 0:nl.kind)==="static_artifact"&&el.workItemId!==qa});if(((Xa=Ja==null?void 0:Ja.preview)==null?void 0:Xa.kind)==="static_artifact")return{sessionId:us.sessionId,variantId:Ja.workItemId,label:Ja.label,url:Ja.preview.url}},[us,ps,hs]),ja=ps??(hs?ws:void 0),Ha=hs??(ps?ws:void 0),Va=!ps&&!!ja,Ga=!hs&&!!Ha,Wa=!!(ja||Ha),Ka=jsxRuntimeExports.jsx(IframePreview,{isInteractionDisabled:$.isInteractionDisabled,framework:$.framework,userPort:$.userPort,activeDemoSessionId:$.activeDemoSessionId,holdPreviewNavigation:$.holdHostedTryoutPreviewNavigation});return jsxRuntimeExports.jsxs("div",{className:`variant-preview-region relative flex h-full min-h-0 w-full flex-1 flex-col ${ss?"is-dragging":""} ${Wa?"is-split":""}`,children:[$.isInteractionDisabled?null:jsxRuntimeExports.jsx(CommandBar,{mode:os,onModeChange:ls,isLoading:$.isLoading}),jsxRuntimeExports.jsxs("div",{className:"variant-preview-row flex h-full min-h-0 w-full flex-1",children:[ja&&jsxRuntimeExports.jsx(SecondaryVariantIframe,{side:"left",sessionId:ja.sessionId,variantId:ja.variantId,url:ja.url,label:ja.label,isFallback:Va},`left-${ja.sessionId}:${ja.variantId}`),!(ja&&Ha)&&jsxRuntimeExports.jsx("div",{className:"variant-preview-primary flex h-full min-h-0 flex-1 flex-col",children:Ka}),Ha&&jsxRuntimeExports.jsx(SecondaryVariantIframe,{side:"right",sessionId:Ha.sessionId,variantId:Ha.variantId,url:Ha.url,label:Ha.label,isFallback:Ga},`right-${Ha.sessionId}:${Ha.variantId}`)]}),jsxRuntimeExports.jsx("div",{className:"variant-preview-atmosphere","aria-hidden":"true"}),jsxRuntimeExports.jsx(VariantSplitDropZones,{}),jsxRuntimeExports.jsx(VariantDragGhost,{})]})}const log$5=createLogger("SupportTicketModal"),MESSAGE_MAX_LENGTH=5e3,DEFAULT_TICKET_TYPE="feedback",extractValidationMessage=$=>{var os;if(!$)return null;const ns=(os=$.formErrors)==null?void 0:os[0];if(ns)return ns;const ss=$.fieldErrors??{};for(const ls of Object.values(ss)){const us=ls==null?void 0:ls[0];if(us)return us}return null},parseSupportTicketError=async $=>{let ns;try{ns=await $.json()}catch{ns=void 0}if($.status===400){if(typeof(ns==null?void 0:ns.details)=="string"&&ns.details.trim())return ns.details;if(typeof(ns==null?void 0:ns.details)=="object"&&ns.details!==null){const ss=extractValidationMessage(ns.details);if(ss)return ss}return"Please check your feedback and try again."}return $.status>=500?typeof(ns==null?void 0:ns.details)=="string"&&ns.details.trim()?ns.details:"Could not send feedback right now. Please try again later.":typeof(ns==null?void 0:ns.error)=="string"&&ns.error.trim()?ns.error:`HTTP ${$.status}`},SupportTicketModal=({isOpen:$,onClose:ns,contactEmail:ss})=>{const os=usePostHog(),[ls,us]=reactExports.useState(""),[ps,hs]=reactExports.useState(!1),ws=reactExports.useCallback(()=>{us("")},[]),ja=reactExports.useCallback(()=>{ps||(ws(),ns())},[ps,ns,ws]),Ha=reactExports.useCallback(async()=>{const Ka=ls.trim();if(!(!Ka||ps)){hs(!0);try{const Za=typeof(os==null?void 0:os.get_session_id)=="function"?os.get_session_id():void 0,qa=typeof(os==null?void 0:os.get_distinct_id)=="function"?os.get_distinct_id():void 0,Ja=ss==null?void 0:ss.trim(),Ya=await fetch("/api/support/tickets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:DEFAULT_TICKET_TYPE,message:Ka,contactEmail:Ja||void 0,metadata:{posthogSessionId:Za??void 0,posthogDistinctId:qa??void 0,appVersion:"0.9.9",appEnvironment:"production",pageUrl:window.location.href,userAgent:navigator.userAgent,submittedAt:new Date().toISOString()}})});if(!Ya.ok){const Xa=await parseSupportTicketError(Ya);throw new Error(Xa)}os==null||os.capture("support_ticket_submitted",{ticket_type:DEFAULT_TICKET_TYPE,has_posthog_session_id:!!Za}),toast.success("Feedback sent",{description:"Thanks for sharing this."}),ws(),ns()}catch(Za){const qa=Za instanceof Error?Za.message:"Failed to send message";os==null||os.capture("support_ticket_submit_failed",{ticket_type:DEFAULT_TICKET_TYPE,error:qa}),log$5.error("Failed to submit support ticket:",qa),toast.error("Could not send feedback",{description:qa})}finally{hs(!1)}}},[ss,ps,ls,ns,os,ws]),Va=reactExports.useCallback(Ka=>{Ka.key==="Enter"&&(Ka.metaKey||Ka.ctrlKey)&&(Ka.preventDefault(),Ha())},[Ha]),Ga=MESSAGE_MAX_LENGTH-ls.length,Wa=ps||ls.trim().length===0;return jsxRuntimeExports.jsx(Root$1,{open:$,onOpenChange:Ka=>!Ka&&ja(),children:jsxRuntimeExports.jsxs(Portal,{children:[jsxRuntimeExports.jsx(Overlay,{className:"fixed inset-0 z-max bg-black/40"}),jsxRuntimeExports.jsx(Content$1,{className:"fixed left-1/2 top-1/2 z-max w-[480px] -translate-x-1/2 -translate-y-1/2 rounded-lg border border-divider bg-main p-6 shadow-xl outline-none",children:jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(Title,{className:"text-lg font-semibold text-content",children:"Send feedback"}),jsxRuntimeExports.jsx(Close,{asChild:!0,children:jsxRuntimeExports.jsx("button",{className:"rounded p-1 text-content-subtle transition-colors hover:text-content",disabled:ps,children:jsxRuntimeExports.jsx(n$1,{className:"h-4 w-4",weight:"bold"})})})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-content-subtle",children:"Tell us what happened or what we can improve."}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("label",{htmlFor:"support-ticket-message",className:"text-xs font-medium text-content-muted",children:"Your feedback"}),jsxRuntimeExports.jsx("textarea",{id:"support-ticket-message",value:ls,onChange:Ka=>us(Ka.target.value),onKeyDown:Va,maxLength:MESSAGE_MAX_LENGTH,rows:7,disabled:ps,placeholder:"What happened?",className:"w-full resize-none rounded-md border border-divider bg-main-input px-3 py-2 text-sm text-content outline-none placeholder:text-content-subtle disabled:opacity-50"}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between text-xs text-content-subtle",children:[jsxRuntimeExports.jsx("span",{children:"Context details are included automatically."}),jsxRuntimeExports.jsx("span",{children:Ga})]})]}),jsxRuntimeExports.jsx("button",{onClick:Ha,disabled:Wa,className:"flex w-full items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-xs text-white transition-colors hover:bg-primary-hover disabled:opacity-50",children:ps?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(s$6,{className:"h-4 w-4 animate-spin",weight:"bold"}),jsxRuntimeExports.jsx("span",{children:"Sending..."})]}):jsxRuntimeExports.jsx("span",{children:"Send feedback"})})]})})]})})},rivetWordmark="data:image/svg+xml,%3csvg%20width='94'%20height='24'%20viewBox='0%200%2094%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M-0.000156164%2023.832V7.704H5.11184L6.47984%208.424C7.58384%207.704%209.04784%207.344%2010.8718%207.344C12.0718%207.344%2013.1278%207.476%2014.0398%207.74C14.9518%207.98%2015.6838%208.244%2016.2358%208.532C16.8118%208.82%2017.1718%209.024%2017.3158%209.144L15.5158%2013.824C15.2758%2013.656%2014.8198%2013.428%2014.1478%2013.14C13.4998%2012.852%2012.7318%2012.588%2011.8438%2012.348C10.9558%2012.084%2010.0198%2011.952%209.03584%2011.952H8.63984C7.96784%2011.952%207.45184%2012.072%207.09184%2012.312C6.73184%2012.528%206.55184%2013.02%206.55184%2013.788V23.832H-0.000156164ZM23.464%206.156C21.04%206.156%2019.828%205.124%2019.828%203.06C19.828%201.908%2020.128%201.116%2020.728%200.684C21.352%200.227999%2022.264%20-1.43051e-06%2023.464%20-1.43051e-06C24.736%20-1.43051e-06%2025.66%200.227999%2026.236%200.684C26.836%201.116%2027.136%201.908%2027.136%203.06C27.136%205.124%2025.912%206.156%2023.464%206.156ZM20.152%2023.832V7.704H26.704V23.832H20.152ZM37.4767%2023.832L29.6647%207.704H36.9007L40.3207%2016.524L41.2567%2019.116H41.6167L42.5527%2016.524L46.0087%207.704H53.1727L52.5967%209.9L45.4327%2023.832H37.4767ZM61.1953%2023.832C59.6113%2023.832%2058.3873%2023.604%2057.5233%2023.148C56.6833%2022.692%2056.1073%2022.068%2055.7953%2021.276C55.4833%2020.46%2055.3273%2019.524%2055.3273%2018.468V13.032C55.3273%2012.072%2055.4833%2011.196%2055.7953%2010.404C56.1313%209.588%2056.7193%208.94%2057.5593%208.46C58.3993%207.956%2059.6113%207.704%2061.1953%207.704H68.6473C70.5193%207.704%2071.9473%207.932%2072.9313%208.388C73.9393%208.82%2074.6233%209.444%2074.9833%2010.26C75.3673%2011.052%2075.5593%2011.976%2075.5593%2013.032V17.64H69.2593C67.0993%2017.64%2065.4553%2017.592%2064.3273%2017.496C63.2233%2017.4%2062.4433%2017.34%2061.9873%2017.316V17.856C61.9633%2018.816%2062.5393%2019.296%2063.7153%2019.296H64.8313C66.7513%2019.296%2068.5273%2019.26%2070.1593%2019.188C71.7913%2019.092%2073.0033%2019.008%2073.7953%2018.936L75.9553%2022.356C75.9553%2022.596%2075.7513%2022.824%2075.3433%2023.04C74.9353%2023.256%2074.2153%2023.448%2073.1833%2023.616C72.1753%2023.76%2070.7353%2023.832%2068.8633%2023.832H61.1953ZM61.9873%2014.184H68.8993V13.68C68.8993%2013.2%2068.8513%2012.864%2068.7553%2012.672C68.6833%2012.48%2068.4313%2012.36%2067.9993%2012.312C67.5673%2012.264%2066.8353%2012.24%2065.8033%2012.24H63.7153C62.5633%2012.24%2061.9873%2012.72%2061.9873%2013.68V14.184ZM85.8224%2023.832C83.9984%2023.832%2082.7504%2023.448%2082.0784%2022.68C81.4064%2021.912%2081.0704%2020.76%2081.0704%2019.224V12.24H78.1184V7.704H79.6304C80.0384%207.704%2080.3624%207.632%2080.6024%207.488C80.8664%207.32%2081.0344%207.032%2081.1064%206.624L81.7904%202.772H87.6944V7.704H93.7064V12.24H87.6944V17.82C87.6944%2018.42%2087.8384%2018.816%2088.1264%2019.008C88.4144%2019.2%2088.8464%2019.296%2089.4224%2019.296H93.0224L93.7424%2023.472C93.2384%2023.544%2092.4704%2023.628%2091.4384%2023.724C90.4064%2023.796%2089.2784%2023.832%2088.0544%2023.832H85.8224Z'%20fill='%23FF3300'/%3e%3c/svg%3e",AuthScreenView=({isSigningIn:$,onStartSignIn:ns,errorMessage:ss=null,isDesktopShell:os=!1,displayMode:ls="full"})=>{const us=ls==="modal";return jsxRuntimeExports.jsxs("div",{className:us?"glass-panel relative w-full max-w-sm rounded-2xl border border-white/10 px-8 py-14 font-main text-white shadow-2xl":"relative flex min-h-screen flex-col items-center justify-center overflow-hidden bg-[#1c1c20] font-main text-white",children:[os&&!us?jsxRuntimeExports.jsx("div",{className:"fixed left-0 right-0 top-0 z-10 h-8",style:{WebkitAppRegion:"drag"}}):null,jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center gap-10",children:[jsxRuntimeExports.jsx("img",{src:rivetWordmark,alt:"Rivet",className:"h-8 w-auto object-contain"}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("h1",{className:"mb-2 text-xl font-medium text-content",children:"Welcome to Rivet"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-content-muted",children:"Sign in to get started"})]}),jsxRuntimeExports.jsx("button",{onClick:ns,disabled:$,className:"glass-panel active-push flex items-center gap-3 rounded-xl px-8 py-3.5 text-sm font-medium transition-all hover:bg-white/10 disabled:opacity-50",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"}),jsxRuntimeExports.jsx("span",{children:"Signing in..."})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("img",{src:"https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg",alt:"Google",className:"h-5 w-5 brightness-110"}),jsxRuntimeExports.jsx("span",{children:"Sign in with Google"})]})}),ss?jsxRuntimeExports.jsx("p",{className:"text-center text-xs text-red-200",children:ss}):null]})]})},log$4=createLogger("useConfig"),useConfig=()=>{const $=useAtomValue(featureFlagsAtom),ns=useSetAtom(featureFlagsAtom),ss=useSetAtom(isMCPSessionAtom),os=useSetAtom(mcpEditorAtom),ls=useSetAtom(agentModeAvailableAtom),us=useSetAtom(featureFlagsLoadedAtom),ps=reactExports.useCallback(Va=>{ls(Va.agentModeAvailable),ns(Va.featureFlags??DEFAULT_FEATURE_FLAGS),us(!0),Va.isMCPSession&&ss(!0),Va.mcpEditor&&os(Va.mcpEditor)},[ls,ns,us,ss,os]),hs=useQuery({queryKey:["rivet-config"],queryFn:async()=>{const Va=await fetch("/api/config");if(!Va.ok)throw new Error(`Failed to fetch config: ${Va.statusText}`);return await Va.json()},staleTime:3e4}),{refetch:ws}=hs;reactExports.useEffect(()=>{hs.data&&(ps(hs.data),log$4.info("Config loaded:",hs.data))},[hs.data,ps]),reactExports.useEffect(()=>{hs.error&&(us(!0),log$4.warn("Failed to load config:",hs.error instanceof Error?hs.error.message:"Failed to load config"))},[hs.error,us]);const ja=reactExports.useCallback(async()=>{const Va=await ws();return Va.data?Va.data:(us(!0),null)},[ws,us]);let Ha=null;return hs.error instanceof Error?Ha=hs.error.message:hs.error&&(Ha="Failed to load config"),{config:hs.data??null,featureFlags:$,loading:hs.isPending,error:Ha,refetchConfig:ja}};var define_process_env_default={};const DEFAULT_PROXY_URL="https://rivet-proxy.onrender.com";var Mx;const envProxyUrl=(Mx=define_process_env_default.RIVET_PROXY_URL)==null?void 0:Mx.trim(),PROXY_URL=envProxyUrl&&envProxyUrl.length>0?envProxyUrl:DEFAULT_PROXY_URL,DEFAULT_GATEWAY_URL="https://rivet-core-production.up.railway.app";var Fx;const envGatewayUrl=(Fx=define_process_env_default.RIVET_GATEWAY_URL)==null?void 0:Fx.trim();envGatewayUrl&&envGatewayUrl.length>0;const DEFAULT_POSTHOG_HOST="https://us.i.posthog.com";var Dx;const envPosthogHost=(Dx=define_process_env_default.RIVET_POSTHOG_HOST)==null?void 0:Dx.trim();envPosthogHost&&envPosthogHost.length>0;const log$3=createLogger("useOAuthCallback"),useOAuthCallback=()=>{const[$,ns]=reactExports.useState({isProcessing:!1,isComplete:!1,error:null});return reactExports.useEffect(()=>{const ss=new AbortController;let os=!1;return(async()=>{var hs,ws;const us=window.location.hash,ps=window.location.search;if(!(!us||!us.includes("access_token"))&&!os){ns({isProcessing:!0,isComplete:!1,error:null});try{log$3.info("Processing OAuth callback...");const ja=new URLSearchParams(us.substring(1)),Ha=ja.get("access_token"),Va=ja.get("refresh_token"),Wa=new URLSearchParams(ps).get("session");if(!Ha)throw new Error("No access token found in URL");if(!Wa)throw new Error("No session ID found in URL");log$3.info(`Completing OAuth with session: ${Wa}`);const Ka=await fetch(`${PROXY_URL}/api/auth/google/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:Wa,accessToken:Ha,refreshToken:Va}),signal:ss.signal}),Za=await Ka.json();if(!Ka.ok||!Za.success)throw new Error(Za.error||Za.message||"Failed to complete authentication");if(log$3.info("OAuth authentication completed successfully"),os)return;if((hs=Za.user)!=null&&hs.email&&Na.identify(Za.user.email,{email:Za.user.email}),(ws=Za.user)!=null&&ws.email&&Ha)try{const Ja=await fetch("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:Za.user.email,token:Ha,refreshToken:Va}),signal:ss.signal});Ja.ok||log$3.warn(`Local auth store returned ${Ja.status}`)}catch(Ja){if(os)return;log$3.warn("Failed to store auth locally:",Ja)}if(os)return;const qa=window.location.pathname;window.history.replaceState({},document.title,qa),ns({isProcessing:!1,isComplete:!0,error:null})}catch(ja){if(os)return;const Ha=ja instanceof Error?ja.message:"Unknown error occurred";log$3.warn("OAuth callback error:",ja),ns({isProcessing:!1,isComplete:!1,error:Ha})}}})(),()=>{os=!0,ss.abort()}},[]),$},log$2=createLogger("useAgentVariantsSession"),useAgentVariantsSession=()=>{const $=useSetAtom(agentVariantsSnapshotAtom),ns=useSetAtom(variantsPanelOpenAtom),ss=useSetAtom(panelOpenAtom),os=useSetAtom(modeAtom),ls=useSetAtom(variantsPanelOptimisticGeneratingAtom),us=useSetAtom(pruneVariantTargetsAtom),ps=useStore(),hs=reactExports.useRef(null);reactExports.useEffect(()=>{const ws=new EventSource("/api/variants/events");return ws.onmessage=ja=>{try{const Ha=JSON.parse(ja.data),Va=hs.current;Ha.active?(ls(!1),Ha.sessionId!==hs.current&&(hs.current=Ha.sessionId,ns(!0),ss(!0),os("view"))):(hs.current!==null&&ns(!1),hs.current=null,ls(!1)),$(Ha);const Ga=!Ha.active&&Va!==null,Wa=Ha.active&&Ha.sessionId!==Va;if(Ga||Wa){const Ka=new Set;if(Ha.active)for(const qa of Ha.variants)Ka.add(previewTargetKey({kind:"variant",sessionId:Ha.sessionId,variantId:qa.workItemId}));const Za=ps.get(variantSplitViewAtom);for(const qa of[Za==null?void 0:Za.left,Za==null?void 0:Za.right])qa&&Ka.add(previewTargetKey({kind:"variant",sessionId:qa.sessionId,variantId:qa.variantId}));us(Ka)}}catch(Ha){log$2.warn("failed to parse SSE event payload",Ha)}},ws.onerror=ja=>{log$2.warn("SSE error (auto-reconnects)",ja),ls(!1)},()=>{ws.close()}},[$,ns,ss,os,ls,us,ps])},log$1=createLogger("useTokenEditor"),useTokenEditor=()=>{const[$,ns]=reactExports.useState(null),[ss,os]=reactExports.useState(null),[ls,us]=reactExports.useState(new Map),[ps,hs]=reactExports.useState(!0),[ws,ja]=reactExports.useState(!1),[Ha,Va]=reactExports.useState(null),Ga=reactExports.useCallback(async()=>{hs(!0),Va(null);try{const qa=await fetch("/api/tokens");if(!qa.ok)throw new Error(`Failed to fetch tokens: ${qa.statusText}`);const Ja=await qa.json();ns(Ja.registry),os(Ja.framework),log$1.info(`Loaded ${Ja.framework} tokens`)}catch(qa){const Ja=qa instanceof Error?qa.message:"Unknown error";Va(Ja),log$1.warn("Failed to fetch tokens:",qa)}finally{hs(!1)}},[]);reactExports.useEffect(()=>{Ga()},[Ga]);const Wa=reactExports.useCallback((qa,Ja,Ya,Xa)=>{const el=`${qa}.${Ja}`;us(nl=>{const rl=new Map(nl);return Xa===Ya?rl.delete(el):rl.set(el,{category:qa,path:Ja,originalValue:Ya,newValue:Xa}),rl})},[]),Ka=reactExports.useCallback(async()=>{if(ls.size===0)return!0;ja(!0),Va(null);const qa=Array.from(ls.values());let Ja=!0;for(const Ya of qa)try{log$1.info(`Saving ${Ya.category}.${Ya.path} = "${Ya.newValue}"`);const el=await(await fetch("/api/tokens/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:Ya.category,path:Ya.path,value:Ya.newValue})})).json();if(!el.success)throw new Error(el.error||"Update failed");log$1.info(`Successfully saved ${Ya.category}.${Ya.path}`)}catch(Xa){const el=Xa instanceof Error?Xa.message:"Unknown error";Va(`Failed to update ${Ya.category}.${Ya.path}: ${el}`),log$1.warn(`Failed to save ${Ya.category}.${Ya.path}:`,Xa),Ja=!1;break}return Ja&&(us(new Map),await Ga()),ja(!1),Ja},[ls,Ga]),Za=reactExports.useCallback(()=>{us(new Map),log$1.info("Reverted all pending changes")},[]);return{tokens:$,framework:ss,pendingChanges:ls,isLoading:ps,isSaving:ws,error:Ha,updateToken:Wa,saveChanges:Ka,revertChanges:Za,refetch:Ga}};var ENTRY_FOCUS="rovingFocusGroup.onEntryFocus",EVENT_OPTIONS={bubbles:!1,cancelable:!0},GROUP_NAME="RovingFocusGroup",[Collection,useCollection,createCollectionScope]=createCollection(GROUP_NAME),[createRovingFocusGroupContext,createRovingFocusGroupScope]=createContextScope(GROUP_NAME,[createCollectionScope]),[RovingFocusProvider,useRovingFocusContext]=createRovingFocusGroupContext(GROUP_NAME),RovingFocusGroup=reactExports.forwardRef(($,ns)=>jsxRuntimeExports.jsx(Collection.Provider,{scope:$.__scopeRovingFocusGroup,children:jsxRuntimeExports.jsx(Collection.Slot,{scope:$.__scopeRovingFocusGroup,children:jsxRuntimeExports.jsx(RovingFocusGroupImpl,{...$,ref:ns})})}));RovingFocusGroup.displayName=GROUP_NAME;var RovingFocusGroupImpl=reactExports.forwardRef(($,ns)=>{const{__scopeRovingFocusGroup:ss,orientation:os,loop:ls=!1,dir:us,currentTabStopId:ps,defaultCurrentTabStopId:hs,onCurrentTabStopIdChange:ws,onEntryFocus:ja,preventScrollOnEntryFocus:Ha=!1,...Va}=$,Ga=reactExports.useRef(null),Wa=useComposedRefs(ns,Ga),Ka=useDirection(us),[Za,qa]=useControllableState({prop:ps,defaultProp:hs??null,onChange:ws,caller:GROUP_NAME}),[Ja,Ya]=reactExports.useState(!1),Xa=useCallbackRef$1(ja),el=useCollection(ss),nl=reactExports.useRef(!1),[rl,sl]=reactExports.useState(0);return reactExports.useEffect(()=>{const il=Ga.current;if(il)return il.addEventListener(ENTRY_FOCUS,Xa),()=>il.removeEventListener(ENTRY_FOCUS,Xa)},[Xa]),jsxRuntimeExports.jsx(RovingFocusProvider,{scope:ss,orientation:os,dir:Ka,loop:ls,currentTabStopId:Za,onItemFocus:reactExports.useCallback(il=>qa(il),[qa]),onItemShiftTab:reactExports.useCallback(()=>Ya(!0),[]),onFocusableItemAdd:reactExports.useCallback(()=>sl(il=>il+1),[]),onFocusableItemRemove:reactExports.useCallback(()=>sl(il=>il-1),[]),children:jsxRuntimeExports.jsx(Primitive.div,{tabIndex:Ja||rl===0?-1:0,"data-orientation":os,...Va,ref:Wa,style:{outline:"none",...$.style},onMouseDown:composeEventHandlers($.onMouseDown,()=>{nl.current=!0}),onFocus:composeEventHandlers($.onFocus,il=>{const al=!nl.current;if(il.target===il.currentTarget&&al&&!Ja){const cl=new CustomEvent(ENTRY_FOCUS,EVENT_OPTIONS);if(il.currentTarget.dispatchEvent(cl),!cl.defaultPrevented){const ml=el().filter(pl=>pl.focusable),vl=ml.find(pl=>pl.active),yl=ml.find(pl=>pl.id===Za),El=[vl,yl,...ml].filter(Boolean).map(pl=>pl.ref.current);focusFirst(El,Ha)}}nl.current=!1}),onBlur:composeEventHandlers($.onBlur,()=>Ya(!1))})})}),ITEM_NAME="RovingFocusGroupItem",RovingFocusGroupItem=reactExports.forwardRef(($,ns)=>{const{__scopeRovingFocusGroup:ss,focusable:os=!0,active:ls=!1,tabStopId:us,children:ps,...hs}=$,ws=useId(),ja=us||ws,Ha=useRovingFocusContext(ITEM_NAME,ss),Va=Ha.currentTabStopId===ja,Ga=useCollection(ss),{onFocusableItemAdd:Wa,onFocusableItemRemove:Ka,currentTabStopId:Za}=Ha;return reactExports.useEffect(()=>{if(os)return Wa(),()=>Ka()},[os,Wa,Ka]),jsxRuntimeExports.jsx(Collection.ItemSlot,{scope:ss,id:ja,focusable:os,active:ls,children:jsxRuntimeExports.jsx(Primitive.span,{tabIndex:Va?0:-1,"data-orientation":Ha.orientation,...hs,ref:ns,onMouseDown:composeEventHandlers($.onMouseDown,qa=>{os?Ha.onItemFocus(ja):qa.preventDefault()}),onFocus:composeEventHandlers($.onFocus,()=>Ha.onItemFocus(ja)),onKeyDown:composeEventHandlers($.onKeyDown,qa=>{if(qa.key==="Tab"&&qa.shiftKey){Ha.onItemShiftTab();return}if(qa.target!==qa.currentTarget)return;const Ja=getFocusIntent(qa,Ha.orientation,Ha.dir);if(Ja!==void 0){if(qa.metaKey||qa.ctrlKey||qa.altKey||qa.shiftKey)return;qa.preventDefault();let Xa=Ga().filter(el=>el.focusable).map(el=>el.ref.current);if(Ja==="last")Xa.reverse();else if(Ja==="prev"||Ja==="next"){Ja==="prev"&&Xa.reverse();const el=Xa.indexOf(qa.currentTarget);Xa=Ha.loop?wrapArray(Xa,el+1):Xa.slice(el+1)}setTimeout(()=>focusFirst(Xa))}}),children:typeof ps=="function"?ps({isCurrentTabStop:Va,hasTabStop:Za!=null}):ps})})});RovingFocusGroupItem.displayName=ITEM_NAME;var MAP_KEY_TO_FOCUS_INTENT={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function getDirectionAwareKey($,ns){return ns!=="rtl"?$:$==="ArrowLeft"?"ArrowRight":$==="ArrowRight"?"ArrowLeft":$}function getFocusIntent($,ns,ss){const os=getDirectionAwareKey($.key,ss);if(!(ns==="vertical"&&["ArrowLeft","ArrowRight"].includes(os))&&!(ns==="horizontal"&&["ArrowUp","ArrowDown"].includes(os)))return MAP_KEY_TO_FOCUS_INTENT[os]}function focusFirst($,ns=!1){const ss=document.activeElement;for(const os of $)if(os===ss||(os.focus({preventScroll:ns}),document.activeElement!==ss))return}function wrapArray($,ns){return $.map((ss,os)=>$[(ns+os)%$.length])}var Root=RovingFocusGroup,Item=RovingFocusGroupItem,TABS_NAME="Tabs",[createTabsContext]=createContextScope(TABS_NAME,[createRovingFocusGroupScope]),useRovingFocusGroupScope=createRovingFocusGroupScope(),[TabsProvider,useTabsContext]=createTabsContext(TABS_NAME),Tabs=reactExports.forwardRef(($,ns)=>{const{__scopeTabs:ss,value:os,onValueChange:ls,defaultValue:us,orientation:ps="horizontal",dir:hs,activationMode:ws="automatic",...ja}=$,Ha=useDirection(hs),[Va,Ga]=useControllableState({prop:os,onChange:ls,defaultProp:us??"",caller:TABS_NAME});return jsxRuntimeExports.jsx(TabsProvider,{scope:ss,baseId:useId(),value:Va,onValueChange:Ga,orientation:ps,dir:Ha,activationMode:ws,children:jsxRuntimeExports.jsx(Primitive.div,{dir:Ha,"data-orientation":ps,...ja,ref:ns})})});Tabs.displayName=TABS_NAME;var TAB_LIST_NAME="TabsList",TabsList=reactExports.forwardRef(($,ns)=>{const{__scopeTabs:ss,loop:os=!0,...ls}=$,us=useTabsContext(TAB_LIST_NAME,ss),ps=useRovingFocusGroupScope(ss);return jsxRuntimeExports.jsx(Root,{asChild:!0,...ps,orientation:us.orientation,dir:us.dir,loop:os,children:jsxRuntimeExports.jsx(Primitive.div,{role:"tablist","aria-orientation":us.orientation,...ls,ref:ns})})});TabsList.displayName=TAB_LIST_NAME;var TRIGGER_NAME="TabsTrigger",TabsTrigger=reactExports.forwardRef(($,ns)=>{const{__scopeTabs:ss,value:os,disabled:ls=!1,...us}=$,ps=useTabsContext(TRIGGER_NAME,ss),hs=useRovingFocusGroupScope(ss),ws=makeTriggerId(ps.baseId,os),ja=makeContentId(ps.baseId,os),Ha=os===ps.value;return jsxRuntimeExports.jsx(Item,{asChild:!0,...hs,focusable:!ls,active:Ha,children:jsxRuntimeExports.jsx(Primitive.button,{type:"button",role:"tab","aria-selected":Ha,"aria-controls":ja,"data-state":Ha?"active":"inactive","data-disabled":ls?"":void 0,disabled:ls,id:ws,...us,ref:ns,onMouseDown:composeEventHandlers($.onMouseDown,Va=>{!ls&&Va.button===0&&Va.ctrlKey===!1?ps.onValueChange(os):Va.preventDefault()}),onKeyDown:composeEventHandlers($.onKeyDown,Va=>{[" ","Enter"].includes(Va.key)&&ps.onValueChange(os)}),onFocus:composeEventHandlers($.onFocus,()=>{const Va=ps.activationMode!=="manual";!Ha&&!ls&&Va&&ps.onValueChange(os)})})})});TabsTrigger.displayName=TRIGGER_NAME;var CONTENT_NAME="TabsContent",TabsContent=reactExports.forwardRef(($,ns)=>{const{__scopeTabs:ss,value:os,forceMount:ls,children:us,...ps}=$,hs=useTabsContext(CONTENT_NAME,ss),ws=makeTriggerId(hs.baseId,os),ja=makeContentId(hs.baseId,os),Ha=os===hs.value,Va=reactExports.useRef(Ha);return reactExports.useEffect(()=>{const Ga=requestAnimationFrame(()=>Va.current=!1);return()=>cancelAnimationFrame(Ga)},[]),jsxRuntimeExports.jsx(Presence,{present:ls||Ha,children:({present:Ga})=>jsxRuntimeExports.jsx(Primitive.div,{"data-state":Ha?"active":"inactive","data-orientation":hs.orientation,role:"tabpanel","aria-labelledby":ws,hidden:!Ga,id:ja,tabIndex:0,...ps,ref:ns,style:{...$.style,animationDuration:Va.current?"0s":void 0},children:Ga&&us})})});TabsContent.displayName=CONTENT_NAME;function makeTriggerId($,ns){return`${$}-trigger-${ns}`}function makeContentId($,ns){return`${$}-content-${ns}`}var Root2=Tabs,List=TabsList,Trigger=TabsTrigger,Content=TabsContent;const ColorSwatchGrid=({tokens:$,pendingChanges:ns,category:ss,onUpdateToken:os,highlightToken:ls})=>{const[us,ps]=reactExports.useState(null),[hs,ws]=reactExports.useState(""),ja=reactExports.useRef(null);if(reactExports.useEffect(()=>{ls&&ja.current&&setTimeout(()=>{var Za;(Za=ja.current)==null||Za.scrollIntoView({behavior:"smooth",block:"center"})},100)},[ls]),!$||Object.keys($).length===0)return jsxRuntimeExports.jsx("div",{className:"flex items-center justify-center py-12 text-sm text-gray-500",children:"No tokens defined for this category"});const Ha=(Za,qa)=>{const Ja=`${ss}.${Za}`,Ya=ns.get(Ja);return Ya?Ya.newValue:qa},Va=Za=>{if(Za.includes("var(")||Za.includes("--"))return{textClass:"text-white",mutedClass:"text-white/70"};let qa=0,Ja=0,Ya=0,Xa=!1;if(Za.startsWith("#")){const sl=Za.slice(1);sl.length===3?(qa=parseInt(sl[0]+sl[0],16),Ja=parseInt(sl[1]+sl[1],16),Ya=parseInt(sl[2]+sl[2],16),Xa=!0):sl.length>=6&&(qa=parseInt(sl.slice(0,2),16),Ja=parseInt(sl.slice(2,4),16),Ya=parseInt(sl.slice(4,6),16),Xa=!0)}const el=Za.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(el&&(qa=parseInt(el[1],10),Ja=parseInt(el[2],10),Ya=parseInt(el[3],10),Xa=!0),!Xa){const sl=Za.match(/rgba?\(\s*(\d+)\s+(\d+)\s+(\d+)/);sl&&(qa=parseInt(sl[1],10),Ja=parseInt(sl[2],10),Ya=parseInt(sl[3],10),Xa=!0)}if(!Xa){const sl=Za.match(/hsla?\(\s*(\d+)\s*,\s*(\d+)%?\s*,\s*(\d+)%?/);if(sl){const il=hslValuesToRgb(parseInt(sl[1],10),parseInt(sl[2],10),parseInt(sl[3],10));qa=il.r,Ja=il.g,Ya=il.b,Xa=!0}}if(!Xa){const sl=Za.match(/hsla?\(\s*(\d+)\s+(\d+)%?\s+(\d+)%?/);if(sl){const il=hslValuesToRgb(parseInt(sl[1],10),parseInt(sl[2],10),parseInt(sl[3],10));qa=il.r,Ja=il.g,Ya=il.b,Xa=!0}}if(!Xa){const sl=Za.match(/oklch\(\s*([\d.]+)(%?)/);if(sl){const il=parseFloat(sl[1]),cl=(sl[2]==="%"?il/100:il)>.5;return{textClass:cl?"text-gray-900":"text-white",mutedClass:cl?"text-gray-600":"text-white/70"}}}if(!Xa)return{textClass:"text-white",mutedClass:"text-white/70"};const rl=calculateLuminance(qa,Ja,Ya)>.5;return{textClass:rl?"text-gray-900":"text-white",mutedClass:rl?"text-gray-600":"text-white/70"}},Ga=(Za,qa,Ja,Ya)=>{const Xa=Ha(qa,Ja),el=us===qa,nl=el&&hs?hs:Xa,rl=qa.replace(/\./g,"-"),sl=ls===rl||ls===Za,il=nl.includes("rgba")||nl.startsWith("#")&&nl.length===9||/oklch\(/.test(nl)&&nl.includes("/"),{textClass:al}=Va(nl),cl=wl=>{ws(wl)},ml=wl=>{os(ss,qa,Ja,wl),ps(null),ws("")},vl=wl=>{wl?(ps(qa),ws(Xa)):(hs&&hs!==Xa&&os(ss,qa,Ja,hs),ps(null),ws(""))},yl=Ya?"h-44":"h-52";return jsxRuntimeExports.jsxs(Root2$3,{open:el,onOpenChange:vl,children:[jsxRuntimeExports.jsx(Trigger$4,{asChild:!0,children:jsxRuntimeExports.jsxs("div",{ref:sl?ja:null,className:`group relative flex ${yl} cursor-pointer flex-col justify-between overflow-hidden rounded-lg border border-white/10 p-4 transition-all ${sl?"animate-token-highlight":""}`,children:[jsxRuntimeExports.jsxs("div",{className:"absolute inset-0",children:[il&&jsxRuntimeExports.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`
|
|
349
349
|
linear-gradient(45deg, #e5e5e5 25%, transparent 25%),
|
|
350
350
|
linear-gradient(-45deg, #e5e5e5 25%, transparent 25%),
|
|
351
351
|
linear-gradient(45deg, transparent 75%, #e5e5e5 75%),
|
|
@@ -379,4 +379,4 @@ For more information, see https://radix-ui.com/primitives/docs/components/${ns.d
|
|
|
379
379
|
<body>
|
|
380
380
|
<div class="panel">${OAUTH_POPUP_LOADING_TITLE}</div>
|
|
381
381
|
</body>
|
|
382
|
-
</html>`,DEMO_SESSION_CAPACITY_MESSAGE="Too many people are trying Rivet right now. Please try again in a few minutes.",DEFAULT_DEMO_SESSION_ERROR_MESSAGE="Failed to start an isolated demo session.",resolveDemoSessionErrorMessage=async $=>{if($.status===429)return DEMO_SESSION_CAPACITY_MESSAGE;try{const ns=await $.json();if(ns.error)return ns.error;if(ns.message)return ns.message}catch{}return DEFAULT_DEMO_SESSION_ERROR_MESSAGE},MainEditor=({contactEmail:$,projectPath:ns,activeDemoSessionId:ss=null,showLoginGate:os=!1,onStartLogin:ls,isStartingLogin:us=!1,loginError:ps=null,fullPageHostedLoginProgressMessage:hs=null,holdHostedTryoutPreviewNavigation:ws=!1,hostedTryoutPreviewHoldMessage:ja=null,deferInspectorUntilPreviewReady:Ha=!1})=>{const[Va,Ga]=useAtom(selectedElementAtom),Wa=useSetAtom(designTokensAtom),Ka=useSetAtom(elementScreenshotAtom),Za=useSetAtom(changeModeAtom),[qa,Ja]=useAtom(chatMessagesAtom),Ya=useAtomValue(modeAtom),[Xa,el]=useAtom(panelOpenAtom),[nl,rl]=useAtom(variantsPanelOpenAtom),sl=useAtomValue(agentVariantsSnapshotAtom),[il,al]=reactExports.useState(!1),[cl,ml]=useAtom(commentsAtom),vl=useAtomValue(isCommentDraftDirtyAtom),yl=useSetAtom(commentShakeAtom),wl=useSetAtom(panelClickVersionAtom),El=useOAuthCallback();useAgentVariantsSession();const pl=El.isProcessing?"Completing authentication...":hs,Al=pl!==null,ll=reactExports.useRef((Va==null?void 0:Va.xpath)??null),dl=reactExports.useRef(!1),fl=reactExports.useRef(!1),ul=useSetAtom(projectPathAtom),bl=useSetAppliedVariantDiff();reactExports.useEffect(()=>{ul(ns??null)},[ns,ul]),reactExports.useEffect(()=>{if(!ns||dl.current)return;dl.current=!0;const kl=deserializeComments(ns);kl.size>0&&(fl.current=!0,ml(kl));const Pl=restoreAppliedDiff(ns);Pl&&bl(Pl)},[ns,ml,bl]),reactExports.useEffect(()=>{if(!(!ns||!dl.current)){if(fl.current){fl.current=!1;return}serializeComments(cl,ns)}},[cl,ns]),reactExports.useEffect(()=>{(async()=>{try{const Pl=await fetch("/api/tokens");if(Pl.ok){const Ol=await Pl.json();Wa(Ol),Ol.framework&&log.info(`Loaded ${Ol.framework} design tokens`)}}catch(Pl){log.error("Failed to fetch design tokens:",Pl)}})()},[Wa]);const hl=()=>{hideAllSurfaceOverlays(),Ga(null),Ka(null)};reactExports.useEffect(()=>{os&&(Za("view"),hideAllSurfaceOverlays(),Ga(null),Ka(null),document.body.style.cursor="auto")},[os,Za,Ka,Ga]);const Sl=reactExports.useMemo(()=>[{key:"Escape",allowInTextField:!0,handler:kl=>{const Pl=kl.target,Ol=Pl.tagName.toLowerCase();if(!((Ol==="input"||Ol==="textarea"||Ol==="select"||Pl.getAttribute("contenteditable")==="true")&&Ya!=="comment")){if(Pl.closest("[data-radix-popper-content-wrapper]")){log.debug("Escape key pressed inside popover - letting Radix handle it");return}if(vl){log.debug("Escape key pressed with dirty draft comment - blocking close"),yl(Il=>Il+1);return}if(nl){log.debug("Escape key pressed in variants mode - hiding panel"),rl(!1),el(!1);return}log.debug("Escape key pressed - switching to view mode"),Za("view"),hl()}},description:"Close inspector"},{key:"c",metaKey:!1,ctrlKey:!1,handler:()=>{log.debug("C key pressed - switching to comment mode"),Za("comment")},description:"Switch to comment mode"},{key:"d",metaKey:!1,ctrlKey:!1,handler:()=>{log.debug("D key pressed - switching to design mode"),Za("edit")},description:"Switch to design mode"},{key:"v",metaKey:!1,ctrlKey:!1,handler:()=>{nl||(log.debug("V key pressed - opening variants panel"),rl(!0),el(!0),Za("view"),Na.capture("variants_panel.opened",{source:"keyboard_shortcut",hasActiveSession:sl.active}))},description:"Open variants panel"},{key:"p",metaKey:!1,ctrlKey:!1,handler:()=>{log.debug("P key pressed - toggling panel"),Xa?el(!1):(el(!0),Ya==="view"&&!nl&&Za("comment"))},description:"Toggle panel"}],[Ya,vl,Za,yl,nl,rl,Xa,el,sl]);return useKeyboardShortcuts({shortcuts:Sl}),reactExports.useEffect(()=>{const kl=()=>{requestOverlayReposition("window_resize")};return window.addEventListener("resize",kl),()=>window.removeEventListener("resize",kl)},[]),reactExports.useEffect(()=>{const kl=(Va==null?void 0:Va.xpath)??null,Pl=ll.current;kl&&kl!==Pl&&(ll.current=kl)},[Va==null?void 0:Va.xpath]),reactExports.useEffect(()=>{Ya==="view"&&!nl&&el(!1)},[Ya,el,nl]),jsxRuntimeExports.jsxs(motion.div,{className:"relative flex h-screen overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,ease:"easeOut"},"data-cy":"rivet-app",children:[Al?jsxRuntimeExports.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:jsxRuntimeExports.jsx(Progress,{message:pl})})}):null,os&&!Al?jsxRuntimeExports.jsx("div",{className:"absolute inset-0 z-40 flex items-center justify-center bg-black/45 backdrop-blur-[2px]",children:jsxRuntimeExports.jsx(AuthScreenView,{isSigningIn:us,onStartSignIn:()=>{ls==null||ls()},errorMessage:ps,displayMode:"modal"})}):null,jsxRuntimeExports.jsxs("div",{className:`relative flex min-w-0 flex-1 flex-col ${os?"pointer-events-none select-none":""}`,children:[jsxRuntimeExports.jsx(PreviewFrame,{holdHostedTryoutPreviewNavigation:ws,isInteractionDisabled:os,activeDemoSessionId:ss}),ws&&ja?jsxRuntimeExports.jsx("div",{className:"absolute inset-0 z-30 flex items-center justify-center bg-main",children:jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-divider bg-main-light p-6 shadow-lg",children:jsxRuntimeExports.jsx(Progress,{message:ja})})}):null]}),os?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Ha?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(motion.div,{className:"h-full flex-shrink-0",animate:{width:Xa?"auto":0,opacity:Xa?1:0},transition:{ease:[.19,1,.22,1],duration:.45},style:{overflow:"hidden",willChange:"width"},onClickCapture:()=>wl(kl=>kl+1),children:jsxRuntimeExports.jsx(ElementInspector,{chatMessages:qa,setChatMessages:Ja,onClose:()=>el(!1)})}),jsxRuntimeExports.jsx(AnimatePresence,{children:!Xa&&jsxRuntimeExports.jsx(Tooltip,{label:"Open chat",side:"left",children:jsxRuntimeExports.jsx(motion.button,{initial:{opacity:0,x:8},animate:{opacity:1,x:0},exit:{opacity:0,x:8},transition:{duration:.15},onClick:()=>el(!0),className:"absolute right-0 top-4 z-50 rounded-l-lg border border-r-0 border-primary/30 bg-main p-2 text-content shadow-lg transition-colors",children:jsxRuntimeExports.jsx(c$3,{className:"h-4 w-4",weight:"bold"})})})})]}),jsxRuntimeExports.jsxs("button",{onClick:()=>al(!0),title:"Support and feedback",className:"absolute bottom-4 left-4 z-50 inline-flex items-center gap-1.5 rounded-md border border-primary/30 bg-main px-3 py-2 text-xs font-medium text-content transition-colors hover:bg-main-hover",children:[jsxRuntimeExports.jsx(s$7,{className:"h-3.5 w-3.5",weight:"bold"}),jsxRuntimeExports.jsx("span",{children:"Support"})]}),jsxRuntimeExports.jsx(SupportTicketModal,{isOpen:il,onClose:()=>al(!1),contactEmail:$})]}),jsxRuntimeExports.jsx(Toaster,{duration:5e3,richColors:!0,toastOptions:{style:{maxHeight:"150px",overflow:"hidden"}}})]})},App=()=>{const[$,ns]=reactExports.useState(window.location.hash),[ss,os]=reactExports.useState(0),{config:ls,refetchConfig:us,loading:ps,error:hs}=useConfig(),ws=useSetAtom(isCommentDraftDirtyAtom),[ja,Ha]=reactExports.useState(!1),[Va,Ga]=reactExports.useState(null),[Wa,Ka]=reactExports.useState(!1),[Za,qa]=reactExports.useState(!1),[Ja,Ya]=reactExports.useState(null),[Xa,el]=reactExports.useState(!1),nl=reactExports.useRef(!1),rl=reactExports.useRef(!1),sl=tryExtractDemoSessionId(window.location.pathname),il=(ls==null?void 0:ls.activeDemoSessionId)??null,al=sl??Ja??il,cl=reactExports.useMemo(()=>getHostedDemoPreviewSessionId(ls==null?void 0:ls.demoMode,ls==null?void 0:ls.agentModeAvailable,al),[ls==null?void 0:ls.demoMode,ls==null?void 0:ls.agentModeAvailable,al]),ml=reactExports.useMemo(()=>getNeedsHostedSessionBootstrap({configLoading:ps,hasConfig:ls!==null,demoMode:ls==null?void 0:ls.demoMode,agentModeAvailable:ls==null?void 0:ls.agentModeAvailable,pathnameDemoSessionId:sl,activeDemoSessionId:Ja,configuredDemoSessionId:il}),[ls,ps,sl,Ja,il]);reactExports.useLayoutEffect(()=>{if(!ml){el(!1);return}el(!0)},[ml]);const vl=Xa,yl=reactExports.useMemo(()=>getHostedTryoutPreviewHoldMessage(vl),[vl]),wl=(ls==null?void 0:ls.demoMode)===!0&&vl,El=reactExports.useRef(null);El.current=al;const pl=reactExports.useCallback(async()=>{if(!nl.current)return;Ya(null);const Sl=await us();if((Sl==null?void 0:Sl.demoMode)===!0&&Sl.agentModeAvailable!==!0){qa(!1);return}(Sl==null?void 0:Sl.demoMode)===!0&&qa(!0)},[us]);reactExports.useEffect(()=>{if((ls==null?void 0:ls.demoMode)===!0)return subscribeHostedDemoAuthRecovery(()=>{pl()})},[ls==null?void 0:ls.demoMode,pl]),reactExports.useEffect(()=>{if(nl.current=(ls==null?void 0:ls.demoMode)===!0,(ls==null?void 0:ls.demoMode)!==!0)return;const Sl=window.fetch.bind(window);return installHostedDemoFetch401Interceptor({nativeFetch:Sl,pageOrigin:window.location.origin,getShouldIntercept:()=>nl.current})},[ls==null?void 0:ls.demoMode]),reactExports.useEffect(()=>{(ls==null?void 0:ls.agentModeAvailable)===!0&&qa(!1)},[ls==null?void 0:ls.agentModeAvailable]);const Al=reactExports.useCallback(async Sl=>{const kl=El.current;if(!(Sl!=null&&Sl.forceRefresh)&&kl)return kl;if(rl.current)return"";rl.current=!0;try{const Pl=await fetch("/api/demo/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!Pl.ok){const Tl=await resolveDemoSessionErrorMessage(Pl);throw new Error(Tl)}const Ol=await Pl.json();if(!Ol.sessionId)throw new Error("Demo session response missing session id.");return Ya(Ol.sessionId),Ol.sessionId}finally{rl.current=!1}},[]);reactExports.useEffect(()=>{il&&Ya(il)},[il]),reactExports.useEffect(()=>{ls!=null&&ls.email&&Na.identify(ls.email,{email:ls.email})},[ls==null?void 0:ls.email]),reactExports.useEffect(()=>{if(!ls)return;const Sl=!!ls.demoMode,kl=Sl?al:null;Na.register({source:Sl?"tryout":"core",demo_mode:Sl,...kl?{demo_session_id:kl}:{}})},[ls,al]);const ll=reactExports.useCallback(async()=>{var kl;Ha(!0),Ga(null);let Sl=null;try{if(Sl=window.open("","_blank"),!Sl)throw new Error("Pop-up blocked. Please allow pop-ups and try again.");try{Sl.document.open(),Sl.document.write(OAUTH_POPUP_LOADING_HTML),Sl.document.close()}catch(Tl){log.warn("Failed to render loading state in auth popup:",Tl)}const Pl=await fetch(`${PROXY_URL}/api/auth/google/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"desktop"})}),Ol=await Pl.json();if(!Pl.ok||!Ol.success||!Ol.authUrl||!Ol.sessionId)throw new Error(Ol.error||Ol.message||"Failed to start Google login");if(Sl.closed)throw new Error("Sign-in window was closed before Google login started.");Sl.location.href=Ol.authUrl;for(let Tl=0;Tl<OAUTH_MAX_POLL_ATTEMPTS;Tl+=1){if(Sl.closed)throw new Error("Sign-in window was closed before authentication completed.");const zl=await(await fetch(`${PROXY_URL}/api/auth/google/token?session=${Ol.sessionId}`)).json();if(zl.success&&zl.token&&((kl=zl.user)!=null&&kl.email)){if(!(await fetch("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:zl.user.email,token:zl.token,refreshToken:zl.refreshToken})})).ok)throw new Error("Signed in, but failed to store session locally.");if(Sl.close(),(ls==null?void 0:ls.demoMode)===!0){await Al({forceRefresh:!0}),window.location.reload();return}window.location.reload();return}if(zl.error&&zl.error!=="Pending")throw new Error(zl.error||"Google login failed");await new Promise(Nl=>setTimeout(Nl,OAUTH_POLL_INTERVAL_MS))}throw new Error("Authentication timed out. Please try again.")}catch(Pl){Sl&&!Sl.closed&&Sl.close();const Ol=Pl instanceof Error?Pl.message:"Failed to start login flow";log.warn("Hosted login failed:",Ol),Ga(Ol),Ha(!1)}},[ls==null?void 0:ls.demoMode,Al]),dl=(ls==null?void 0:ls.demoMode)===!0&&((ls==null?void 0:ls.agentModeAvailable)!==!0||Za||ja),fl=reactExports.useCallback(async()=>{Ka(!0);try{await us()}finally{Ka(!1)}},[us]);if(reactExports.useEffect(()=>{if(!ml)return;let Sl=!1;return Al({forceRefresh:!0}).catch(kl=>{const Pl=kl instanceof Error?kl.message:DEFAULT_DEMO_SESSION_ERROR_MESSAGE;log.warn("Hosted session bootstrap failed:",Pl),Ga(Pl),toast.error(Pl)}).finally(()=>{Sl||el(!1)}),()=>{Sl=!0}},[ml,Al]),reactExports.useEffect(()=>{const Sl=()=>{const kl=window.location.hash;ws(!1),ns(Pl=>(Pl.startsWith("#tokens")&&!kl.startsWith("#tokens")&&os(Ol=>Ol+1),kl))};return window.addEventListener("hashchange",Sl),()=>window.removeEventListener("hashchange",Sl)},[ws]),$.startsWith("#tokens"))return jsxRuntimeExports.jsx(TokenEditor,{});const ul={pathname:window.location.pathname,configLoading:ps,hasConfig:ls!==null,isRetryingConfig:Wa},bl=shouldShowHostedPreConfigLoading(ul),hl=shouldShowHostedPreConfigError(ul);if(bl)return jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center bg-main",children:jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:jsxRuntimeExports.jsx(Progress,{message:"Loading..."})})});if(hl){const Sl=hs||"Could not load Rivet configuration.";return jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center bg-main px-6",children:jsxRuntimeExports.jsxs("div",{className:"w-full max-w-md rounded-lg border border-divider bg-main p-6 text-center shadow-lg",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-content",children:"We could not start Rivet yet."}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-xs text-content-dim",children:Sl}),jsxRuntimeExports.jsx("button",{type:"button",className:"mt-4 rounded-md border border-divider px-3 py-1.5 text-xs text-content hover:bg-main/80",onClick:()=>{fl()},children:"Retry"})]})})}return jsxRuntimeExports.jsx(MainEditor,{contactEmail:ls==null?void 0:ls.email,projectPath:ls==null?void 0:ls.projectPath,activeDemoSessionId:cl,showLoginGate:dl,onStartLogin:ll,isStartingLogin:ja,loginError:Va,fullPageHostedLoginProgressMessage:(ls==null?void 0:ls.demoMode)===!0&&ja?"Completing sign-in...":null,holdHostedTryoutPreviewNavigation:vl,hostedTryoutPreviewHoldMessage:yl,deferInspectorUntilPreviewReady:wl},ss)},POSTHOG_PUBLIC_API_KEY="phc_Ntj9tXHbS64XgYxlTfhglRmFivFsfm0AERph4ZlnNH",queryClient=new QueryClient,ErrorFallback=()=>jsxRuntimeExports.jsx("div",{style:{display:"flex",height:"100vh",alignItems:"center",justifyContent:"center"},children:jsxRuntimeExports.jsx("p",{style:{fontSize:"14px",color:"#6b7280"},children:"Something went wrong. Please reload the page."})});ReactDOM$1.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(React.StrictMode,{children:jsxRuntimeExports.jsx(PostHogProvider,{apiKey:POSTHOG_PUBLIC_API_KEY,options:{api_host:"https://us.i.posthog.com",ui_host:"https://us.posthog.com",person_profiles:"always",capture_exceptions:!0,autocapture:!0,capture_pageview:!0,capture_performance:!0,persistence:"localStorage",session_recording:{maskAllInputs:!1,maskInputOptions:{password:!0},maskTextSelector:null},mask_all_text:!1,mask_all_element_attributes:!1,loaded:$=>{$.register({source:"core",rivet_version:"0.9.8",env:"production"})}},children:jsxRuntimeExports.jsx(PostHogErrorBoundary,{fallback:jsxRuntimeExports.jsx(ErrorFallback,{}),children:jsxRuntimeExports.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports.jsx(App,{})})})})}));
|
|
382
|
+
</html>`,DEMO_SESSION_CAPACITY_MESSAGE="Too many people are trying Rivet right now. Please try again in a few minutes.",DEFAULT_DEMO_SESSION_ERROR_MESSAGE="Failed to start an isolated demo session.",resolveDemoSessionErrorMessage=async $=>{if($.status===429)return DEMO_SESSION_CAPACITY_MESSAGE;try{const ns=await $.json();if(ns.error)return ns.error;if(ns.message)return ns.message}catch{}return DEFAULT_DEMO_SESSION_ERROR_MESSAGE},MainEditor=({contactEmail:$,projectPath:ns,activeDemoSessionId:ss=null,showLoginGate:os=!1,onStartLogin:ls,isStartingLogin:us=!1,loginError:ps=null,fullPageHostedLoginProgressMessage:hs=null,holdHostedTryoutPreviewNavigation:ws=!1,hostedTryoutPreviewHoldMessage:ja=null,deferInspectorUntilPreviewReady:Ha=!1})=>{const[Va,Ga]=useAtom(selectedElementAtom),Wa=useSetAtom(designTokensAtom),Ka=useSetAtom(elementScreenshotAtom),Za=useSetAtom(changeModeAtom),[qa,Ja]=useAtom(chatMessagesAtom),Ya=useAtomValue(modeAtom),[Xa,el]=useAtom(panelOpenAtom),[nl,rl]=useAtom(variantsPanelOpenAtom),sl=useAtomValue(agentVariantsSnapshotAtom),[il,al]=reactExports.useState(!1),[cl,ml]=useAtom(commentsAtom),vl=useAtomValue(isCommentDraftDirtyAtom),yl=useSetAtom(commentShakeAtom),wl=useSetAtom(panelClickVersionAtom),El=useOAuthCallback();useAgentVariantsSession();const pl=El.isProcessing?"Completing authentication...":hs,Al=pl!==null,ll=reactExports.useRef((Va==null?void 0:Va.xpath)??null),dl=reactExports.useRef(!1),fl=reactExports.useRef(!1),ul=useSetAtom(projectPathAtom),bl=useSetAppliedVariantDiff();reactExports.useEffect(()=>{ul(ns??null)},[ns,ul]),reactExports.useEffect(()=>{if(!ns||dl.current)return;dl.current=!0;const kl=deserializeComments(ns);kl.size>0&&(fl.current=!0,ml(kl));const Pl=restoreAppliedDiff(ns);Pl&&bl(Pl)},[ns,ml,bl]),reactExports.useEffect(()=>{if(!(!ns||!dl.current)){if(fl.current){fl.current=!1;return}serializeComments(cl,ns)}},[cl,ns]),reactExports.useEffect(()=>{(async()=>{try{const Pl=await fetch("/api/tokens");if(Pl.ok){const Ol=await Pl.json();Wa(Ol),Ol.framework&&log.info(`Loaded ${Ol.framework} design tokens`)}}catch(Pl){log.error("Failed to fetch design tokens:",Pl)}})()},[Wa]);const hl=()=>{hideAllSurfaceOverlays(),Ga(null),Ka(null)};reactExports.useEffect(()=>{os&&(Za("view"),hideAllSurfaceOverlays(),Ga(null),Ka(null),document.body.style.cursor="auto")},[os,Za,Ka,Ga]);const Sl=reactExports.useMemo(()=>[{key:"Escape",allowInTextField:!0,handler:kl=>{const Pl=kl.target,Ol=Pl.tagName.toLowerCase();if(!((Ol==="input"||Ol==="textarea"||Ol==="select"||Pl.getAttribute("contenteditable")==="true")&&Ya!=="comment")){if(Pl.closest("[data-radix-popper-content-wrapper]")){log.debug("Escape key pressed inside popover - letting Radix handle it");return}if(vl){log.debug("Escape key pressed with dirty draft comment - blocking close"),yl(Il=>Il+1);return}if(nl){log.debug("Escape key pressed in variants mode - hiding panel"),rl(!1),el(!1);return}log.debug("Escape key pressed - switching to view mode"),Za("view"),hl()}},description:"Close inspector"},{key:"c",metaKey:!1,ctrlKey:!1,handler:()=>{log.debug("C key pressed - switching to comment mode"),Za("comment")},description:"Switch to comment mode"},{key:"d",metaKey:!1,ctrlKey:!1,handler:()=>{log.debug("D key pressed - switching to design mode"),Za("edit")},description:"Switch to design mode"},{key:"v",metaKey:!1,ctrlKey:!1,handler:()=>{nl||(log.debug("V key pressed - opening variants panel"),rl(!0),el(!0),Za("view"),Na.capture("variants_panel.opened",{source:"keyboard_shortcut",hasActiveSession:sl.active}))},description:"Open variants panel"},{key:"p",metaKey:!1,ctrlKey:!1,handler:()=>{log.debug("P key pressed - toggling panel"),Xa?el(!1):(el(!0),Ya==="view"&&!nl&&Za("comment"))},description:"Toggle panel"}],[Ya,vl,Za,yl,nl,rl,Xa,el,sl]);return useKeyboardShortcuts({shortcuts:Sl}),reactExports.useEffect(()=>{const kl=()=>{requestOverlayReposition("window_resize")};return window.addEventListener("resize",kl),()=>window.removeEventListener("resize",kl)},[]),reactExports.useEffect(()=>{const kl=(Va==null?void 0:Va.xpath)??null,Pl=ll.current;kl&&kl!==Pl&&(ll.current=kl)},[Va==null?void 0:Va.xpath]),reactExports.useEffect(()=>{Ya==="view"&&!nl&&el(!1)},[Ya,el,nl]),jsxRuntimeExports.jsxs(motion.div,{className:"relative flex h-screen overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,ease:"easeOut"},"data-cy":"rivet-app",children:[Al?jsxRuntimeExports.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/50",children:jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:jsxRuntimeExports.jsx(Progress,{message:pl})})}):null,os&&!Al?jsxRuntimeExports.jsx("div",{className:"absolute inset-0 z-40 flex items-center justify-center bg-black/45 backdrop-blur-[2px]",children:jsxRuntimeExports.jsx(AuthScreenView,{isSigningIn:us,onStartSignIn:()=>{ls==null||ls()},errorMessage:ps,displayMode:"modal"})}):null,jsxRuntimeExports.jsxs("div",{className:`relative flex min-w-0 flex-1 flex-col ${os?"pointer-events-none select-none":""}`,children:[jsxRuntimeExports.jsx(PreviewFrame,{holdHostedTryoutPreviewNavigation:ws,isInteractionDisabled:os,activeDemoSessionId:ss}),ws&&ja?jsxRuntimeExports.jsx("div",{className:"absolute inset-0 z-30 flex items-center justify-center bg-main",children:jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-divider bg-main-light p-6 shadow-lg",children:jsxRuntimeExports.jsx(Progress,{message:ja})})}):null]}),os?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Ha?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(motion.div,{className:"h-full flex-shrink-0",animate:{width:Xa?"auto":0,opacity:Xa?1:0},transition:{ease:[.19,1,.22,1],duration:.45},style:{overflow:"hidden",willChange:"width"},onClickCapture:()=>wl(kl=>kl+1),children:jsxRuntimeExports.jsx(ElementInspector,{chatMessages:qa,setChatMessages:Ja,onClose:()=>el(!1)})}),jsxRuntimeExports.jsx(AnimatePresence,{children:!Xa&&jsxRuntimeExports.jsx(Tooltip,{label:"Open chat",side:"left",children:jsxRuntimeExports.jsx(motion.button,{initial:{opacity:0,x:8},animate:{opacity:1,x:0},exit:{opacity:0,x:8},transition:{duration:.15},onClick:()=>el(!0),className:"absolute right-0 top-4 z-50 rounded-l-lg border border-r-0 border-primary/30 bg-main p-2 text-content shadow-lg transition-colors",children:jsxRuntimeExports.jsx(c$3,{className:"h-4 w-4",weight:"bold"})})})})]}),jsxRuntimeExports.jsxs("button",{onClick:()=>al(!0),title:"Support and feedback",className:"absolute bottom-4 left-4 z-50 inline-flex items-center gap-1.5 rounded-md border border-primary/30 bg-main px-3 py-2 text-xs font-medium text-content transition-colors hover:bg-main-hover",children:[jsxRuntimeExports.jsx(s$7,{className:"h-3.5 w-3.5",weight:"bold"}),jsxRuntimeExports.jsx("span",{children:"Support"})]}),jsxRuntimeExports.jsx(SupportTicketModal,{isOpen:il,onClose:()=>al(!1),contactEmail:$})]}),jsxRuntimeExports.jsx(Toaster,{duration:5e3,richColors:!0,toastOptions:{style:{maxHeight:"150px",overflow:"hidden"}}})]})},App=()=>{const[$,ns]=reactExports.useState(window.location.hash),[ss,os]=reactExports.useState(0),{config:ls,refetchConfig:us,loading:ps,error:hs}=useConfig(),ws=useSetAtom(isCommentDraftDirtyAtom),[ja,Ha]=reactExports.useState(!1),[Va,Ga]=reactExports.useState(null),[Wa,Ka]=reactExports.useState(!1),[Za,qa]=reactExports.useState(!1),[Ja,Ya]=reactExports.useState(null),[Xa,el]=reactExports.useState(!1),nl=reactExports.useRef(!1),rl=reactExports.useRef(!1),sl=tryExtractDemoSessionId(window.location.pathname),il=(ls==null?void 0:ls.activeDemoSessionId)??null,al=sl??Ja??il,cl=reactExports.useMemo(()=>getHostedDemoPreviewSessionId(ls==null?void 0:ls.demoMode,ls==null?void 0:ls.agentModeAvailable,al),[ls==null?void 0:ls.demoMode,ls==null?void 0:ls.agentModeAvailable,al]),ml=reactExports.useMemo(()=>getNeedsHostedSessionBootstrap({configLoading:ps,hasConfig:ls!==null,demoMode:ls==null?void 0:ls.demoMode,agentModeAvailable:ls==null?void 0:ls.agentModeAvailable,pathnameDemoSessionId:sl,activeDemoSessionId:Ja,configuredDemoSessionId:il}),[ls,ps,sl,Ja,il]);reactExports.useLayoutEffect(()=>{if(!ml){el(!1);return}el(!0)},[ml]);const vl=Xa,yl=reactExports.useMemo(()=>getHostedTryoutPreviewHoldMessage(vl),[vl]),wl=(ls==null?void 0:ls.demoMode)===!0&&vl,El=reactExports.useRef(null);El.current=al;const pl=reactExports.useCallback(async()=>{if(!nl.current)return;Ya(null);const Sl=await us();if((Sl==null?void 0:Sl.demoMode)===!0&&Sl.agentModeAvailable!==!0){qa(!1);return}(Sl==null?void 0:Sl.demoMode)===!0&&qa(!0)},[us]);reactExports.useEffect(()=>{if((ls==null?void 0:ls.demoMode)===!0)return subscribeHostedDemoAuthRecovery(()=>{pl()})},[ls==null?void 0:ls.demoMode,pl]),reactExports.useEffect(()=>{if(nl.current=(ls==null?void 0:ls.demoMode)===!0,(ls==null?void 0:ls.demoMode)!==!0)return;const Sl=window.fetch.bind(window);return installHostedDemoFetch401Interceptor({nativeFetch:Sl,pageOrigin:window.location.origin,getShouldIntercept:()=>nl.current})},[ls==null?void 0:ls.demoMode]),reactExports.useEffect(()=>{(ls==null?void 0:ls.agentModeAvailable)===!0&&qa(!1)},[ls==null?void 0:ls.agentModeAvailable]);const Al=reactExports.useCallback(async Sl=>{const kl=El.current;if(!(Sl!=null&&Sl.forceRefresh)&&kl)return kl;if(rl.current)return"";rl.current=!0;try{const Pl=await fetch("/api/demo/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!Pl.ok){const Tl=await resolveDemoSessionErrorMessage(Pl);throw new Error(Tl)}const Ol=await Pl.json();if(!Ol.sessionId)throw new Error("Demo session response missing session id.");return Ya(Ol.sessionId),Ol.sessionId}finally{rl.current=!1}},[]);reactExports.useEffect(()=>{il&&Ya(il)},[il]),reactExports.useEffect(()=>{ls!=null&&ls.email&&Na.identify(ls.email,{email:ls.email})},[ls==null?void 0:ls.email]),reactExports.useEffect(()=>{if(!ls)return;const Sl=!!ls.demoMode,kl=Sl?al:null;Na.register({source:Sl?"tryout":"core",demo_mode:Sl,...kl?{demo_session_id:kl}:{}})},[ls,al]);const ll=reactExports.useCallback(async()=>{var kl;Ha(!0),Ga(null);let Sl=null;try{if(Sl=window.open("","_blank"),!Sl)throw new Error("Pop-up blocked. Please allow pop-ups and try again.");try{Sl.document.open(),Sl.document.write(OAUTH_POPUP_LOADING_HTML),Sl.document.close()}catch(Tl){log.warn("Failed to render loading state in auth popup:",Tl)}const Pl=await fetch(`${PROXY_URL}/api/auth/google/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"desktop"})}),Ol=await Pl.json();if(!Pl.ok||!Ol.success||!Ol.authUrl||!Ol.sessionId)throw new Error(Ol.error||Ol.message||"Failed to start Google login");if(Sl.closed)throw new Error("Sign-in window was closed before Google login started.");Sl.location.href=Ol.authUrl;for(let Tl=0;Tl<OAUTH_MAX_POLL_ATTEMPTS;Tl+=1){if(Sl.closed)throw new Error("Sign-in window was closed before authentication completed.");const zl=await(await fetch(`${PROXY_URL}/api/auth/google/token?session=${Ol.sessionId}`)).json();if(zl.success&&zl.token&&((kl=zl.user)!=null&&kl.email)){if(!(await fetch("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:zl.user.email,token:zl.token,refreshToken:zl.refreshToken})})).ok)throw new Error("Signed in, but failed to store session locally.");if(Sl.close(),(ls==null?void 0:ls.demoMode)===!0){await Al({forceRefresh:!0}),window.location.reload();return}window.location.reload();return}if(zl.error&&zl.error!=="Pending")throw new Error(zl.error||"Google login failed");await new Promise(Nl=>setTimeout(Nl,OAUTH_POLL_INTERVAL_MS))}throw new Error("Authentication timed out. Please try again.")}catch(Pl){Sl&&!Sl.closed&&Sl.close();const Ol=Pl instanceof Error?Pl.message:"Failed to start login flow";log.warn("Hosted login failed:",Ol),Ga(Ol),Ha(!1)}},[ls==null?void 0:ls.demoMode,Al]),dl=(ls==null?void 0:ls.demoMode)===!0&&((ls==null?void 0:ls.agentModeAvailable)!==!0||Za||ja),fl=reactExports.useCallback(async()=>{Ka(!0);try{await us()}finally{Ka(!1)}},[us]);if(reactExports.useEffect(()=>{if(!ml)return;let Sl=!1;return Al({forceRefresh:!0}).catch(kl=>{const Pl=kl instanceof Error?kl.message:DEFAULT_DEMO_SESSION_ERROR_MESSAGE;log.warn("Hosted session bootstrap failed:",Pl),Ga(Pl),toast.error(Pl)}).finally(()=>{Sl||el(!1)}),()=>{Sl=!0}},[ml,Al]),reactExports.useEffect(()=>{const Sl=()=>{const kl=window.location.hash;ws(!1),ns(Pl=>(Pl.startsWith("#tokens")&&!kl.startsWith("#tokens")&&os(Ol=>Ol+1),kl))};return window.addEventListener("hashchange",Sl),()=>window.removeEventListener("hashchange",Sl)},[ws]),$.startsWith("#tokens"))return jsxRuntimeExports.jsx(TokenEditor,{});const ul={pathname:window.location.pathname,configLoading:ps,hasConfig:ls!==null,isRetryingConfig:Wa},bl=shouldShowHostedPreConfigLoading(ul),hl=shouldShowHostedPreConfigError(ul);if(bl)return jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center bg-main",children:jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:jsxRuntimeExports.jsx(Progress,{message:"Loading..."})})});if(hl){const Sl=hs||"Could not load Rivet configuration.";return jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center bg-main px-6",children:jsxRuntimeExports.jsxs("div",{className:"w-full max-w-md rounded-lg border border-divider bg-main p-6 text-center shadow-lg",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-content",children:"We could not start Rivet yet."}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-xs text-content-dim",children:Sl}),jsxRuntimeExports.jsx("button",{type:"button",className:"mt-4 rounded-md border border-divider px-3 py-1.5 text-xs text-content hover:bg-main/80",onClick:()=>{fl()},children:"Retry"})]})})}return jsxRuntimeExports.jsx(MainEditor,{contactEmail:ls==null?void 0:ls.email,projectPath:ls==null?void 0:ls.projectPath,activeDemoSessionId:cl,showLoginGate:dl,onStartLogin:ll,isStartingLogin:ja,loginError:Va,fullPageHostedLoginProgressMessage:(ls==null?void 0:ls.demoMode)===!0&&ja?"Completing sign-in...":null,holdHostedTryoutPreviewNavigation:vl,hostedTryoutPreviewHoldMessage:yl,deferInspectorUntilPreviewReady:wl},ss)},POSTHOG_PUBLIC_API_KEY="phc_Ntj9tXHbS64XgYxlTfhglRmFivFsfm0AERph4ZlnNH",queryClient=new QueryClient,ErrorFallback=()=>jsxRuntimeExports.jsx("div",{style:{display:"flex",height:"100vh",alignItems:"center",justifyContent:"center"},children:jsxRuntimeExports.jsx("p",{style:{fontSize:"14px",color:"#6b7280"},children:"Something went wrong. Please reload the page."})});ReactDOM$1.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(React.StrictMode,{children:jsxRuntimeExports.jsx(PostHogProvider,{apiKey:POSTHOG_PUBLIC_API_KEY,options:{api_host:"https://us.i.posthog.com",ui_host:"https://us.posthog.com",person_profiles:"always",capture_exceptions:!0,autocapture:!0,capture_pageview:!0,capture_performance:!0,persistence:"localStorage",session_recording:{maskAllInputs:!1,maskInputOptions:{password:!0},maskTextSelector:null},mask_all_text:!1,mask_all_element_attributes:!1,loaded:$=>{$.register({source:"core",rivet_version:"0.9.9",env:"production"})}},children:jsxRuntimeExports.jsx(PostHogErrorBoundary,{fallback:jsxRuntimeExports.jsx(ErrorFallback,{}),children:jsxRuntimeExports.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports.jsx(App,{})})})})}));
|
package/src/ui/dist/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>Rivet - The visual editor for design</title>
|
|
8
|
-
<script type="module" crossorigin src="/assets/main-
|
|
8
|
+
<script type="module" crossorigin src="/assets/main-DXMHtjqM.js"></script>
|
|
9
9
|
<link rel="stylesheet" crossorigin href="/assets/main-BZEruoyc.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body>
|