@howone/sdk 0.2.1 → 0.2.2

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/index.js CHANGED
@@ -1281,14 +1281,12 @@ var ERROR_CONFIG = {
1281
1281
  LOW: ["info", "debug", "trace", "notice"]
1282
1282
  },
1283
1283
  CATEGORY_KEYWORDS: {
1284
- SYNTAX: ["syntaxerror", "unexpected token", "parse error", "invalid syntax"],
1284
+ SYNTAX: ["syntaxerror", "unexpected token", "parse error", "invalid syntax", "expected", "transform failed"],
1285
1285
  NETWORK: ["fetch", "xhr", "network", "cors", "timeout", "connection"],
1286
1286
  RUNTIME: ["referenceerror", "typeerror", "rangeerror", "undefined"],
1287
1287
  SECURITY: ["csp", "xss", "csrf", "security", "unauthorized"],
1288
1288
  PERFORMANCE: ["slow", "memory", "leak", "performance", "timeout"],
1289
- DEVELOPMENT: ["vite", "hmr", "hot reload", "dev server", "webpack"],
1290
- REACT: ["react", "jsx", "component", "hook", "render"],
1291
- VITE: ["vite", "[vite]", "vite:react", "transform failed"]
1289
+ DEVELOPMENT: ["vite", "hmr", "hot reload", "dev server", "webpack", "esbuild", "plugin:vite:esbuild"]
1292
1290
  }
1293
1291
  };
1294
1292
  var GLOBAL_CONFIG = {
@@ -1629,9 +1627,13 @@ var ViteHMRDetector = class {
1629
1627
  setupHMREventListeners() {
1630
1628
  if (typeof window !== "undefined" && window.import?.meta?.hot) {
1631
1629
  const hot = window.import.meta.hot;
1632
- hot.on("vite:error", () => {
1630
+ hot.on("vite:error", (data) => {
1631
+ this.handleViteError(data);
1633
1632
  requestAnimationFrame(() => this.checkForViteErrorOverlay());
1634
1633
  });
1634
+ hot.on("vite:invalidate", (data) => {
1635
+ setTimeout(() => this.checkForCompileErrors(), 500);
1636
+ });
1635
1637
  hot.on("vite:beforeUpdate", () => {
1636
1638
  console.log("[ViteHMRDetector] HMR \u66F4\u65B0\u5F00\u59CB");
1637
1639
  });
@@ -1808,6 +1810,90 @@ File: ${errorInfo.fileText}`;
1808
1810
  }
1809
1811
  }
1810
1812
  }
1813
+ /**
1814
+ * 处理 Vite 错误事件
1815
+ */
1816
+ handleViteError(errorData) {
1817
+ try {
1818
+ const errorPayload = {
1819
+ id: `vite-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1820
+ type: "vite_hmr",
1821
+ error: {
1822
+ name: "ViteError",
1823
+ message: errorData?.message || "Vite error",
1824
+ stack: errorData?.stack || ""
1825
+ },
1826
+ source: "vite:error",
1827
+ timestamp: Date.now(),
1828
+ severity: "error",
1829
+ context: {
1830
+ viteErrorData: errorData,
1831
+ url: window.location.href,
1832
+ userAgent: navigator.userAgent
1833
+ }
1834
+ };
1835
+ if (window.__AUTO_ENGINEER_ERRORS__) {
1836
+ window.__AUTO_ENGINEER_ERRORS__.push(errorPayload);
1837
+ }
1838
+ this.sendMessage({
1839
+ type: "SYSTEM_EVENT",
1840
+ payload: errorPayload,
1841
+ timestamp: Date.now()
1842
+ });
1843
+ } catch (error) {
1844
+ console.error("[ViteHMRDetector] \u5904\u7406 Vite \u9519\u8BEF\u5931\u8D25:", error);
1845
+ }
1846
+ }
1847
+ /**
1848
+ * 检查编译错误
1849
+ */
1850
+ async checkForCompileErrors() {
1851
+ try {
1852
+ if (document.querySelector("vite-error-overlay")) {
1853
+ this.checkForViteErrorOverlay();
1854
+ return;
1855
+ }
1856
+ const response = await fetch(window.location.href, {
1857
+ method: "HEAD",
1858
+ cache: "no-cache"
1859
+ });
1860
+ if (!response.ok) {
1861
+ this.handleCompileError(`HTTP ${response.status}: ${response.statusText}`);
1862
+ }
1863
+ } catch (error) {
1864
+ this.handleCompileError(`Error: ${error.message}`);
1865
+ }
1866
+ }
1867
+ /**
1868
+ * 处理编译错误
1869
+ */
1870
+ handleCompileError(errorMessage) {
1871
+ const errorPayload = {
1872
+ id: `compile-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1873
+ type: "compile_error",
1874
+ error: {
1875
+ name: "CompileError",
1876
+ message: `Compile error: ${errorMessage}`,
1877
+ stack: ""
1878
+ },
1879
+ source: "vite:compile",
1880
+ timestamp: Date.now(),
1881
+ severity: "error",
1882
+ context: {
1883
+ url: window.location.href,
1884
+ userAgent: navigator.userAgent,
1885
+ compilationFailed: true
1886
+ }
1887
+ };
1888
+ if (window.__AUTO_ENGINEER_ERRORS__) {
1889
+ window.__AUTO_ENGINEER_ERRORS__.push(errorPayload);
1890
+ }
1891
+ this.sendMessage({
1892
+ type: "SYSTEM_EVENT",
1893
+ payload: errorPayload,
1894
+ timestamp: Date.now()
1895
+ });
1896
+ }
1811
1897
  /**
1812
1898
  * 检查当前环境是否支持 Vite HMR
1813
1899
  */
@@ -3416,12 +3502,6 @@ var ErrorTracking = class {
3416
3502
  if (ERROR_CONFIG.CATEGORY_KEYWORDS.DEVELOPMENT.some((keyword) => lowerMessage.includes(keyword))) {
3417
3503
  return "DEVELOPMENT";
3418
3504
  }
3419
- if (ERROR_CONFIG.CATEGORY_KEYWORDS.REACT.some((keyword) => lowerMessage.includes(keyword))) {
3420
- return "REACT";
3421
- }
3422
- if (ERROR_CONFIG.CATEGORY_KEYWORDS.VITE.some((keyword) => lowerMessage.includes(keyword))) {
3423
- return "VITE";
3424
- }
3425
3505
  return "UNKNOWN";
3426
3506
  }
3427
3507
  /**
@@ -5833,1708 +5913,1709 @@ var ErrorHandler = class {
5833
5913
  }
5834
5914
  };
5835
5915
 
5836
- // src/utils/iframe-navigation.ts
5837
- function getNavState() {
5838
- if (typeof window === "undefined") {
5839
- return {
5840
- navigationHistory: [],
5841
- currentHistoryIndex: -1,
5842
- initialized: false
5843
- };
5916
+ // src/components/auth/HowoneProvider.tsx
5917
+ var import_jsx_runtime7 = require("react/jsx-runtime");
5918
+ var globalErrorHandler = null;
5919
+ var initializeErrorHandler = () => {
5920
+ if (!globalErrorHandler) {
5921
+ console.log("[HowOneProvider] \u5728\u6A21\u5757\u9876\u5C42\u521D\u59CB\u5316\u9519\u8BEF\u5904\u7406\u5668...");
5922
+ globalErrorHandler = new ErrorHandler({
5923
+ enableViteHMR: true,
5924
+ enableElementSelector: true,
5925
+ enableInteractionTracking: true
5926
+ });
5927
+ globalErrorHandler.init();
5928
+ window.__ERROR_HANDLER__ = globalErrorHandler;
5929
+ console.log("[HowOneProvider] \u9519\u8BEF\u5904\u7406\u5668\u5DF2\u5728\u6A21\u5757\u9876\u5C42\u521D\u59CB\u5316\u5B8C\u6210");
5844
5930
  }
5845
- if (!window.customNavigationState) {
5846
- window.customNavigationState = {
5847
- navigationHistory: [],
5848
- currentHistoryIndex: -1,
5849
- initialized: false
5931
+ return globalErrorHandler;
5932
+ };
5933
+ initializeErrorHandler();
5934
+ var HowoneContext = (0, import_react8.createContext)(null);
5935
+ var HowOneProvider = ({
5936
+ children,
5937
+ showFloatingButton = true,
5938
+ projectId,
5939
+ defaultTheme = "system",
5940
+ themeStorageKey = "howone-theme",
5941
+ forceDefaultTheme = false,
5942
+ authUrl = "https://howone.dev/auth",
5943
+ redirectOnUnauthenticated = true
5944
+ }) => {
5945
+ const [user, setUser] = (0, import_react8.useState)(() => parseUserFromToken(getToken()));
5946
+ const [token, setTokenState] = (0, import_react8.useState)(() => getToken());
5947
+ const [hasCheckedUrlToken, setHasCheckedUrlToken] = (0, import_react8.useState)(false);
5948
+ (0, import_react8.useEffect)(() => {
5949
+ try {
5950
+ const params = new URLSearchParams(window.location.search);
5951
+ let urlToken = params.get("access_token") || params.get("token");
5952
+ if (!urlToken && window.location.hash) {
5953
+ const hashParams = new URLSearchParams(window.location.hash.slice(1));
5954
+ urlToken = hashParams.get("access_token") || hashParams.get("token");
5955
+ }
5956
+ if (urlToken) {
5957
+ console.log("[HowOneProvider] Token captured from URL, storing to localStorage...");
5958
+ setToken(urlToken);
5959
+ setTokenState(urlToken);
5960
+ setUser(parseUserFromToken(urlToken));
5961
+ params.delete("access_token");
5962
+ params.delete("token");
5963
+ params.delete("project_id");
5964
+ const newSearch = params.toString();
5965
+ const newUrl = window.location.pathname + (newSearch ? "?" + newSearch : "");
5966
+ window.history.replaceState({}, "", newUrl);
5967
+ console.log("[HowOneProvider] Token stored successfully, URL cleaned");
5968
+ }
5969
+ } catch (e) {
5970
+ console.error("[HowOneProvider] Failed to capture token from URL:", e);
5971
+ } finally {
5972
+ setHasCheckedUrlToken(true);
5973
+ }
5974
+ }, []);
5975
+ (0, import_react8.useEffect)(() => {
5976
+ if (!hasCheckedUrlToken) {
5977
+ return;
5978
+ }
5979
+ if (redirectOnUnauthenticated && !token && !user) {
5980
+ const currentUrl = new URL(window.location.href);
5981
+ if (!currentUrl.pathname.includes("/auth")) {
5982
+ console.log("[HowOneProvider] No token found, redirecting to auth page...");
5983
+ try {
5984
+ const authUrlObj = new URL(authUrl);
5985
+ const redirectUri = window.location.href;
5986
+ authUrlObj.searchParams.set("redirect_uri", redirectUri);
5987
+ if (projectId) {
5988
+ authUrlObj.searchParams.set("project_id", projectId);
5989
+ }
5990
+ console.log("[HowOneProvider] Redirecting to:", authUrlObj.toString());
5991
+ window.location.href = authUrlObj.toString();
5992
+ } catch (error) {
5993
+ console.error("[HowOneProvider] Failed to build auth URL:", error);
5994
+ window.location.href = authUrl;
5995
+ }
5996
+ }
5997
+ }
5998
+ }, [token, user, redirectOnUnauthenticated, authUrl, projectId, hasCheckedUrlToken]);
5999
+ const logout = () => {
6000
+ try {
6001
+ setToken(null);
6002
+ } catch {
6003
+ }
6004
+ setTokenState(null);
6005
+ setUser(null);
6006
+ };
6007
+ const value = {
6008
+ user,
6009
+ token,
6010
+ isAuthenticated: hasCheckedUrlToken && !!token,
6011
+ logout
6012
+ };
6013
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
6014
+ ThemeProvider,
6015
+ {
6016
+ defaultTheme,
6017
+ storageKey: themeStorageKey,
6018
+ forceDefault: forceDefaultTheme,
6019
+ children: [
6020
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ElementSelectorProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(HowoneContext.Provider, { value, children: [
6021
+ children,
6022
+ showFloatingButton && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FloatingButton, { onClick: () => window.open("https://howone.ai", "_blank") })
6023
+ ] }) }),
6024
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(GlobalToastContainer, {})
6025
+ ]
6026
+ }
6027
+ );
6028
+ };
6029
+ function useHowoneContext() {
6030
+ const ctx = (0, import_react8.useContext)(HowoneContext);
6031
+ if (!ctx) {
6032
+ const t = getToken();
6033
+ return {
6034
+ user: parseUserFromToken(t),
6035
+ token: t,
6036
+ isAuthenticated: !!t,
6037
+ logout: () => {
6038
+ try {
6039
+ setToken(null);
6040
+ } catch {
6041
+ }
6042
+ }
5850
6043
  };
5851
6044
  }
5852
- return window.customNavigationState;
6045
+ return ctx;
5853
6046
  }
5854
- function getElementSelectorState() {
5855
- if (typeof window === "undefined") {
5856
- return { active: false, callback: null };
6047
+
6048
+ // src/components/index.ts
6049
+ init_auth();
6050
+
6051
+ // src/howone/client.ts
6052
+ init_auth();
6053
+ init_config();
6054
+ var HowoneAuthClient = class {
6055
+ constructor() {
6056
+ this.listeners = /* @__PURE__ */ new Set();
6057
+ this.loading = false;
5857
6058
  }
5858
- if (!window.elementSelectorState) {
5859
- window.elementSelectorState = {
5860
- active: false,
5861
- callback: null
6059
+ emit() {
6060
+ const state = {
6061
+ user: parseUserFromToken(getToken()),
6062
+ isLoading: this.loading
5862
6063
  };
5863
- }
5864
- return window.elementSelectorState;
5865
- }
5866
- function sendNavigationState(targetWindow, targetOrigin) {
5867
- const navState = getNavState();
5868
- const canGoBack = navState.currentHistoryIndex > 0;
5869
- const canGoForward = navState.currentHistoryIndex < navState.navigationHistory.length - 1;
5870
- const state = {
5871
- type: "NAVIGATION_STATE",
5872
- payload: {
5873
- canGoBack,
5874
- canGoForward,
5875
- historyLength: navState.navigationHistory.length,
5876
- currentIndex: navState.currentHistoryIndex,
5877
- maxIndex: navState.navigationHistory.length - 1
6064
+ for (const l of this.listeners) {
6065
+ try {
6066
+ l(state);
6067
+ } catch (e) {
6068
+ void e;
6069
+ }
5878
6070
  }
5879
- };
5880
- if (targetWindow && targetOrigin) {
6071
+ }
6072
+ onAuthStateChanged(listener) {
6073
+ this.listeners.add(listener);
5881
6074
  try {
5882
- targetWindow.postMessage(state, targetOrigin);
6075
+ listener({ user: parseUserFromToken(getToken()), isLoading: this.loading });
5883
6076
  } catch (e) {
5884
- if (typeof console !== "undefined" && console.warn) {
5885
- console.warn("Failed to send navigation state:", e.message);
5886
- }
6077
+ void e;
5887
6078
  }
6079
+ return () => {
6080
+ this.listeners.delete(listener);
6081
+ };
5888
6082
  }
5889
- }
5890
- function addToNavigationHistory(url, title) {
5891
- const navState = getNavState();
5892
- if (navState.currentHistoryIndex < navState.navigationHistory.length - 1) {
5893
- navState.navigationHistory = navState.navigationHistory.slice(
5894
- 0,
5895
- navState.currentHistoryIndex + 1
5896
- );
5897
- }
5898
- const currentPage = navState.navigationHistory[navState.currentHistoryIndex];
5899
- if (currentPage && currentPage.url === url) {
5900
- return;
5901
- }
5902
- const pageInfo = {
5903
- url,
5904
- title: title || (typeof document !== "undefined" ? document.title : "") || url,
5905
- timestamp: Date.now()
5906
- };
5907
- navState.navigationHistory.push(pageInfo);
5908
- navState.currentHistoryIndex = navState.navigationHistory.length - 1;
5909
- if (typeof window !== "undefined" && window.parent && window.parent !== window) {
5910
- sendNavigationState(window.parent, "*");
5911
- }
5912
- }
5913
- function customGoBack() {
5914
- const navState = getNavState();
5915
- if (navState.currentHistoryIndex > 0) {
5916
- navState.currentHistoryIndex--;
5917
- if (typeof window !== "undefined" && window.parent && window.parent !== window) {
5918
- sendNavigationState(window.parent, "*");
5919
- }
5920
- return true;
5921
- }
5922
- return false;
5923
- }
5924
- function customGoForward() {
5925
- const navState = getNavState();
5926
- if (navState.currentHistoryIndex < navState.navigationHistory.length - 1) {
5927
- navState.currentHistoryIndex++;
5928
- if (typeof window !== "undefined" && window.parent && window.parent !== window) {
5929
- sendNavigationState(window.parent, "*");
5930
- }
5931
- return true;
5932
- }
5933
- return false;
5934
- }
5935
- function triggerElementSelection() {
5936
- if (typeof window === "undefined") return;
5937
- const event = new CustomEvent("howone:start-element-selection");
5938
- window.dispatchEvent(event);
5939
- getElementSelectorState().active = true;
5940
- }
5941
- function cancelElementSelection() {
5942
- if (typeof window === "undefined") return;
5943
- const event = new CustomEvent("howone:cancel-element-selection");
5944
- window.dispatchEvent(event);
5945
- getElementSelectorState().active = false;
5946
- }
5947
- function handlePageChange() {
5948
- if (typeof window === "undefined") return;
5949
- const currentUrl = window.location.href;
5950
- const currentTitle = document.title;
5951
- addToNavigationHistory(currentUrl, currentTitle);
5952
- }
5953
- function initIframeNavigation() {
5954
- if (typeof window === "undefined") return;
5955
- const navState = getNavState();
5956
- window.addEventListener("keydown", function(e) {
5957
- if (e.key === "Escape" && getElementSelectorState().active) {
5958
- cancelElementSelection();
5959
- }
5960
- });
5961
- window.addEventListener("message", (event) => {
6083
+ // Simple redirect-based login trigger (consumer can override)
6084
+ login() {
6085
+ const root = getEnvs().AUTH_ROOT_VALUE;
5962
6086
  try {
5963
- const { type, payload } = event.data;
5964
- switch (type) {
5965
- case "NAVIGATE_BACK":
5966
- case "GO_BACK":
5967
- customGoBack();
5968
- break;
5969
- case "NAVIGATE_FORWARD":
5970
- case "GO_FORWARD":
5971
- customGoForward();
5972
- break;
5973
- case "REQUEST_NAVIGATION_STATE":
5974
- case "CHECK_NAVIGATION_STATE":
5975
- sendNavigationState(event.source, event.origin);
5976
- break;
5977
- case "START_ELEMENT_SELECTION":
5978
- triggerElementSelection();
5979
- break;
5980
- case "ELEMENT_SELECTED":
5981
- if (event.source && event.source !== window) {
5982
- window.parent.postMessage(
5983
- {
5984
- type: "ELEMENT_SELECTED",
5985
- payload
5986
- },
5987
- "*"
5988
- );
5989
- }
5990
- break;
5991
- case "CANCEL_ELEMENT_SELECTION":
5992
- cancelElementSelection();
5993
- break;
5994
- }
5995
- } catch (e) {
5996
- }
5997
- });
5998
- window.addEventListener("popstate", () => {
5999
- setTimeout(() => {
6000
- if (window.parent && window.parent !== window) {
6001
- sendNavigationState(window.parent, "*");
6087
+ const loc = window.location.href;
6088
+ const authUrl = new URL("/auth", String(root));
6089
+ authUrl.searchParams.set("redirect_uri", String(loc));
6090
+ try {
6091
+ const cfg = (init_config(), __toCommonJS(config_exports));
6092
+ const pid = cfg.getDefaultProjectId && cfg.getDefaultProjectId();
6093
+ if (pid) authUrl.searchParams.set("project_id", String(pid));
6094
+ } catch {
6002
6095
  }
6003
- }, 50);
6004
- });
6005
- window.addEventListener("hashchange", () => {
6006
- handlePageChange();
6007
- });
6008
- window.addEventListener("load", () => {
6009
- if (!navState.initialized) {
6010
- addToNavigationHistory(window.location.href, document.title);
6011
- navState.initialized = true;
6012
- }
6013
- setTimeout(() => {
6014
- if (window.parent && window.parent !== window) {
6015
- sendNavigationState(window.parent, "*");
6096
+ try {
6097
+ if (window.top && window.top !== window) {
6098
+ window.top.location.replace(authUrl.toString());
6099
+ } else {
6100
+ window.location.replace(authUrl.toString());
6101
+ }
6102
+ } catch {
6103
+ try {
6104
+ window.location.replace(String(root));
6105
+ } catch {
6106
+ }
6016
6107
  }
6017
- }, 500);
6018
- });
6019
- if (document.readyState === "loading") {
6020
- document.addEventListener("DOMContentLoaded", () => {
6021
- if (!navState.initialized) {
6022
- addToNavigationHistory(window.location.href, document.title);
6023
- navState.initialized = true;
6108
+ } catch {
6109
+ try {
6110
+ window.location.replace(String(root));
6111
+ } catch {
6024
6112
  }
6025
- });
6026
- } else if (!navState.initialized) {
6027
- addToNavigationHistory(window.location.href, document.title);
6028
- navState.initialized = true;
6029
- }
6030
- window.iframeElementSelector = {
6031
- startSelection: function() {
6032
- triggerElementSelection();
6033
6113
  }
6114
+ }
6115
+ logout() {
6116
+ setToken(null);
6117
+ this.emit();
6118
+ }
6119
+ getUser() {
6120
+ return parseUserFromToken(getToken());
6121
+ }
6122
+ // helper to programmatically set token (e.g., after callback handling)
6123
+ setToken(token) {
6124
+ setToken(token);
6125
+ this.emit();
6126
+ }
6127
+ };
6128
+ var howone = {
6129
+ auth: new HowoneAuthClient()
6130
+ };
6131
+ var client_default = howone;
6132
+
6133
+ // src/components/ui/Loading.tsx
6134
+ var import_jsx_runtime8 = require("react/jsx-runtime");
6135
+ var Loading = ({
6136
+ size = "md",
6137
+ text = "Loading...",
6138
+ className = "",
6139
+ fullScreen = false
6140
+ }) => {
6141
+ const sizeClasses = {
6142
+ sm: "h-4 w-4",
6143
+ md: "h-8 w-8",
6144
+ lg: "h-12 w-12"
6034
6145
  };
6035
- window.iframeNavigation = {
6036
- addPage: function(url, title) {
6037
- addToNavigationHistory(
6038
- url || window.location.href,
6039
- title || document.title
6040
- );
6041
- },
6042
- getState: function() {
6043
- return {
6044
- canGoBack: navState.currentHistoryIndex > 0,
6045
- canGoForward: navState.currentHistoryIndex < navState.navigationHistory.length - 1,
6046
- historyLength: navState.navigationHistory.length,
6047
- currentIndex: navState.currentHistoryIndex,
6048
- currentPage: navState.navigationHistory[navState.currentHistoryIndex]
6049
- };
6050
- },
6051
- updateState: function() {
6052
- if (window.parent && window.parent !== window) {
6053
- sendNavigationState(window.parent, "*");
6146
+ const containerClasses = fullScreen ? "fixed inset-0 flex items-center justify-center bg-white/80 backdrop-blur-sm z-50" : "flex items-center justify-center p-4";
6147
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: `${containerClasses} ${className}`, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "text-center", children: [
6148
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
6149
+ "div",
6150
+ {
6151
+ className: `animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 mx-auto ${sizeClasses[size]}`
6054
6152
  }
6055
- }
6153
+ ),
6154
+ text && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("p", { className: "mt-2 text-sm text-gray-600", children: text })
6155
+ ] }) });
6156
+ };
6157
+ var LoadingSpinner = ({
6158
+ size = "md",
6159
+ className = ""
6160
+ }) => {
6161
+ const sizeClasses = {
6162
+ sm: "h-4 w-4",
6163
+ md: "h-8 w-8",
6164
+ lg: "h-12 w-12"
6056
6165
  };
6057
- }
6058
- var iframeNavigation = {
6059
- /**
6060
- * Initialize the navigation system
6061
- */
6062
- init: initIframeNavigation,
6063
- /**
6064
- * Add a page to navigation history
6065
- */
6066
- addPage: (url, title) => {
6067
- if (typeof window === "undefined") return;
6068
- addToNavigationHistory(
6069
- url || window.location.href,
6070
- title || (typeof document !== "undefined" ? document.title : "")
6071
- );
6072
- },
6073
- /**
6074
- * Get current navigation state
6075
- */
6076
- getState: () => {
6077
- const navState = getNavState();
6078
- return {
6079
- canGoBack: navState.currentHistoryIndex > 0,
6080
- canGoForward: navState.currentHistoryIndex < navState.navigationHistory.length - 1,
6081
- historyLength: navState.navigationHistory.length,
6082
- currentIndex: navState.currentHistoryIndex,
6083
- currentPage: navState.navigationHistory[navState.currentHistoryIndex]
6084
- };
6085
- },
6086
- /**
6087
- * Update navigation state (send to parent)
6088
- */
6089
- updateState: () => {
6090
- if (typeof window !== "undefined" && window.parent && window.parent !== window) {
6091
- sendNavigationState(window.parent, "*");
6166
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
6167
+ "div",
6168
+ {
6169
+ className: `animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 ${sizeClasses[size]} ${className}`
6092
6170
  }
6093
- },
6094
- /**
6095
- * Go back in history
6096
- */
6097
- goBack: customGoBack,
6098
- /**
6099
- * Go forward in history
6100
- */
6101
- goForward: customGoForward
6171
+ );
6102
6172
  };
6103
- var elementSelector = {
6104
- /**
6105
- * Start element selection mode
6106
- */
6107
- startSelection: triggerElementSelection,
6108
- /**
6109
- * Cancel element selection mode
6110
- */
6111
- cancel: cancelElementSelection,
6112
- /**
6113
- * Check if selector is active
6114
- */
6115
- isActive: () => getElementSelectorState().active
6173
+
6174
+ // src/components/ui/ErrorBoundary.tsx
6175
+ var import_react9 = require("react");
6176
+ var import_jsx_runtime9 = require("react/jsx-runtime");
6177
+ var ErrorBoundary = class extends import_react9.Component {
6178
+ constructor(props) {
6179
+ super(props);
6180
+ this.handleRetry = () => {
6181
+ this.setState({ hasError: false, error: void 0, errorInfo: void 0 });
6182
+ };
6183
+ this.state = { hasError: false };
6184
+ }
6185
+ static getDerivedStateFromError(error) {
6186
+ return { hasError: true, error };
6187
+ }
6188
+ componentDidCatch(error, errorInfo) {
6189
+ this.setState({
6190
+ error,
6191
+ errorInfo
6192
+ });
6193
+ this.props.onError?.(error, errorInfo);
6194
+ }
6195
+ render() {
6196
+ if (this.state.hasError) {
6197
+ if (this.props.fallback) {
6198
+ const FallbackComponent = this.props.fallback;
6199
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(FallbackComponent, { error: this.state.error, retry: this.handleRetry });
6200
+ }
6201
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "min-h-[400px] flex items-center justify-center p-4", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: "text-center max-w-md", children: [
6202
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "text-red-500 text-6xl mb-4", children: "\u26A0\uFE0F" }),
6203
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("h2", { className: "text-xl font-semibold text-gray-900 mb-2", children: "Something went wrong" }),
6204
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("p", { className: "text-gray-600 mb-4", children: "An unexpected error occurred. Please try refreshing the page." }),
6205
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
6206
+ "button",
6207
+ {
6208
+ onClick: this.handleRetry,
6209
+ className: "px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors",
6210
+ children: "Try Again"
6211
+ }
6212
+ ),
6213
+ false
6214
+ ] }) });
6215
+ }
6216
+ return this.props.children;
6217
+ }
6116
6218
  };
6219
+ var DefaultErrorFallback = ({ retry }) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "min-h-[200px] flex items-center justify-center p-4", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: "text-center", children: [
6220
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "text-red-500 text-4xl mb-2", children: "\u26A0\uFE0F" }),
6221
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("p", { className: "text-gray-600 mb-2", children: "Something went wrong" }),
6222
+ retry && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
6223
+ "button",
6224
+ {
6225
+ onClick: retry,
6226
+ className: "px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors",
6227
+ children: "Retry"
6228
+ }
6229
+ )
6230
+ ] }) });
6117
6231
 
6118
- // src/components/auth/HowoneProvider.tsx
6119
- var import_jsx_runtime7 = require("react/jsx-runtime");
6120
- var HowoneContext = (0, import_react8.createContext)(null);
6121
- var HowOneProvider = ({
6232
+ // src/components/ui/ClayxButton.tsx
6233
+ var import_jsx_runtime10 = require("react/jsx-runtime");
6234
+ var getSizeClasses = (size, isIconOnly) => {
6235
+ if (isIconOnly) {
6236
+ switch (size) {
6237
+ case "sm":
6238
+ return "h-8 w-8 min-w-8 p-0";
6239
+ case "md":
6240
+ return "h-10 w-10 min-w-10 p-0";
6241
+ case "lg":
6242
+ return "h-12 w-12 min-w-12 p-0";
6243
+ default:
6244
+ return "h-10 w-10 min-w-10 p-0";
6245
+ }
6246
+ }
6247
+ switch (size) {
6248
+ case "sm":
6249
+ return "h-8 px-3 text-sm";
6250
+ case "md":
6251
+ return "h-10 px-4 text-base";
6252
+ case "lg":
6253
+ return "h-12 px-6 text-lg";
6254
+ default:
6255
+ return "h-10 px-4 text-base";
6256
+ }
6257
+ };
6258
+ var getVariantClasses = (variant) => {
6259
+ switch (variant) {
6260
+ case "solid":
6261
+ return "bg-primary text-white hover:bg-primary/90";
6262
+ case "ghost":
6263
+ return "bg-transparent hover:bg-white/10";
6264
+ case "flat":
6265
+ return "bg-white/5 hover:bg-white/10";
6266
+ default:
6267
+ return "";
6268
+ }
6269
+ };
6270
+ var ClayxButton = ({
6271
+ isIconOnly = false,
6272
+ size = "md",
6273
+ variant = "solid",
6274
+ className = "",
6122
6275
  children,
6123
- showFloatingButton = true,
6124
- projectId,
6125
- defaultTheme = "system",
6126
- themeStorageKey = "howone-theme",
6127
- forceDefaultTheme = false,
6128
- authUrl = "https://howone.dev/auth",
6129
- redirectOnUnauthenticated = true
6276
+ disabled = false,
6277
+ ...props
6130
6278
  }) => {
6131
- const [user, setUser] = (0, import_react8.useState)(() => parseUserFromToken(getToken()));
6132
- const [token, setTokenState] = (0, import_react8.useState)(() => getToken());
6133
- const [hasCheckedUrlToken, setHasCheckedUrlToken] = (0, import_react8.useState)(false);
6134
- (0, import_react8.useEffect)(() => {
6135
- const errorHandler = new ErrorHandler({
6136
- enableViteHMR: true,
6137
- enableElementSelector: true,
6138
- enableInteractionTracking: true
6139
- // enableConsoleCapture: true,
6140
- // enableNetworkCapture: true,
6141
- // maxErrors: 100,
6142
- // maxInteractions: 50,
6143
- // debounceTime: 100,
6144
- // reportToParent: true,
6145
- // reportToConsole: true
6146
- });
6147
- errorHandler.init();
6148
- window.__ERROR_HANDLER__ = errorHandler;
6149
- initIframeNavigation();
6150
- try {
6151
- const params = new URLSearchParams(window.location.search);
6152
- let urlToken = params.get("access_token") || params.get("token");
6153
- if (!urlToken && window.location.hash) {
6154
- const hashParams = new URLSearchParams(window.location.hash.slice(1));
6155
- urlToken = hashParams.get("access_token") || hashParams.get("token");
6156
- }
6157
- if (urlToken) {
6158
- console.log("[HowOneProvider] Token captured from URL, storing to localStorage...");
6159
- setToken(urlToken);
6160
- setTokenState(urlToken);
6161
- setUser(parseUserFromToken(urlToken));
6162
- params.delete("access_token");
6163
- params.delete("token");
6164
- params.delete("project_id");
6165
- const newSearch = params.toString();
6166
- const newUrl = window.location.pathname + (newSearch ? "?" + newSearch : "");
6167
- window.history.replaceState({}, "", newUrl);
6168
- console.log("[HowOneProvider] Token stored successfully, URL cleaned");
6169
- }
6170
- } catch (e) {
6171
- console.error("[HowOneProvider] Failed to capture token from URL:", e);
6172
- } finally {
6173
- setHasCheckedUrlToken(true);
6279
+ const sizeClasses = getSizeClasses(size, isIconOnly);
6280
+ const variantClasses = getVariantClasses(variant);
6281
+ const baseClasses = `
6282
+ inline-flex items-center justify-center
6283
+ rounded-md font-medium
6284
+ transition-all duration-200
6285
+ focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-transparent
6286
+ disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none
6287
+ `.replace(/\s+/g, " ").trim();
6288
+ const combinedClasses = `${baseClasses} ${sizeClasses} ${variantClasses} ${className}`.trim();
6289
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
6290
+ "button",
6291
+ {
6292
+ className: combinedClasses,
6293
+ disabled,
6294
+ ...props,
6295
+ children
6174
6296
  }
6297
+ );
6298
+ };
6299
+
6300
+ // src/components/ui/LimitUpgradeToast.tsx
6301
+ var import_react13 = require("@iconify/react");
6302
+
6303
+ // src/components/ui/Toast/ClayxToast.tsx
6304
+ var import_react11 = __toESM(require("react"));
6305
+ var import_react_toastify2 = require("react-toastify");
6306
+ var import_react12 = require("@iconify/react");
6307
+
6308
+ // src/components/theme/ThemeToggle.tsx
6309
+ var React6 = __toESM(require("react"));
6310
+ var import_react10 = require("@iconify/react");
6311
+ var import_jsx_runtime11 = require("react/jsx-runtime");
6312
+ function ThemeToggle({ className }) {
6313
+ const { setTheme, theme } = useTheme();
6314
+ const [mounted, setMounted] = React6.useState(false);
6315
+ React6.useEffect(() => {
6316
+ setMounted(true);
6175
6317
  }, []);
6176
- (0, import_react8.useEffect)(() => {
6177
- if (!hasCheckedUrlToken) {
6178
- return;
6318
+ const handleToggle = () => {
6319
+ if (theme === "dark") {
6320
+ setTheme("light");
6321
+ } else {
6322
+ setTheme("dark");
6179
6323
  }
6180
- if (redirectOnUnauthenticated && !token && !user) {
6181
- const currentUrl = new URL(window.location.href);
6182
- if (!currentUrl.pathname.includes("/auth")) {
6183
- console.log("[HowOneProvider] No token found, redirecting to auth page...");
6184
- try {
6185
- const authUrlObj = new URL(authUrl);
6186
- const redirectUri = window.location.href;
6187
- authUrlObj.searchParams.set("redirect_uri", redirectUri);
6188
- if (projectId) {
6189
- authUrlObj.searchParams.set("project_id", projectId);
6190
- }
6191
- console.log("[HowOneProvider] Redirecting to:", authUrlObj.toString());
6192
- window.location.href = authUrlObj.toString();
6193
- } catch (error) {
6194
- console.error("[HowOneProvider] Failed to build auth URL:", error);
6195
- window.location.href = authUrl;
6324
+ };
6325
+ if (!mounted) {
6326
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
6327
+ "button",
6328
+ {
6329
+ className: `relative inline-flex h-10 w-12 items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground ${className || ""}`,
6330
+ disabled: true,
6331
+ children: [
6332
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react10.Icon, { icon: "solar:sun-bold", width: 20, height: 20 }),
6333
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "sr-only", children: "\u5207\u6362\u4E3B\u9898" })
6334
+ ]
6335
+ }
6336
+ );
6337
+ }
6338
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
6339
+ "button",
6340
+ {
6341
+ className: `inline-flex h-10 w-12 items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors ${className || ""}`,
6342
+ onClick: handleToggle,
6343
+ children: [
6344
+ theme === "light" ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react10.Icon, { icon: "solar:sun-bold", width: 20, height: 20 }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react10.Icon, { icon: "solar:moon-linear", width: 20, height: 20 }),
6345
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "sr-only", children: "\u5207\u6362\u4E3B\u9898" })
6346
+ ]
6347
+ }
6348
+ );
6349
+ }
6350
+
6351
+ // src/components/ui/Toast/ClayxToast.tsx
6352
+ var import_jsx_runtime12 = require("react/jsx-runtime");
6353
+ var TOAST_ICONS = {
6354
+ success: {
6355
+ icon: "mdi:success",
6356
+ color: "text-green-400",
6357
+ className: "text-green-400",
6358
+ // 深色主题配置
6359
+ dark: {
6360
+ bgGradient: "bg-[#14181d]",
6361
+ // 移除透明度 f2
6362
+ gradientColor: "#389726",
6363
+ borderGradient: "border-[#389726]",
6364
+ borderGradientColor: "#389726"
6365
+ },
6366
+ // 浅色主题配置
6367
+ light: {
6368
+ bgGradient: "bg-[#fafafa]",
6369
+ // 移除透明度 ff
6370
+ gradientColor: "#22c55e",
6371
+ borderGradient: "border-[#22c55e]",
6372
+ borderGradientColor: "#22c55e"
6373
+ }
6374
+ },
6375
+ error: {
6376
+ icon: "ic:outline-close",
6377
+ color: "text-red-400",
6378
+ className: "text-red-400",
6379
+ dark: {
6380
+ bgGradient: "bg-[#14181d]",
6381
+ // 移除透明度 f2
6382
+ gradientColor: "#ef4444",
6383
+ borderGradient: "border-[#ef4444]",
6384
+ borderGradientColor: "#ef4444"
6385
+ },
6386
+ light: {
6387
+ bgGradient: "bg-[#fafafa]",
6388
+ // 移除透明度 ff
6389
+ gradientColor: "#f87171",
6390
+ borderGradient: "border-[#f87171]",
6391
+ borderGradientColor: "#f87171"
6392
+ }
6393
+ },
6394
+ warning: {
6395
+ icon: "mi:warning",
6396
+ color: "text-yellow-400",
6397
+ className: "text-yellow-400",
6398
+ dark: {
6399
+ bgGradient: "bg-[#14181d]",
6400
+ // 移除透明度 f2
6401
+ gradientColor: "#facc15",
6402
+ borderGradient: "border-[#facc15]",
6403
+ borderGradientColor: "#facc15"
6404
+ },
6405
+ light: {
6406
+ bgGradient: "bg-[#fafafa]",
6407
+ // 移除透明度 ff
6408
+ gradientColor: "#f59e0b",
6409
+ borderGradient: "border-[#f59e0b]",
6410
+ borderGradientColor: "#f59e0b"
6411
+ }
6412
+ },
6413
+ info: {
6414
+ icon: "ic:outline-info",
6415
+ color: "text-blue-400",
6416
+ className: "text-blue-400",
6417
+ dark: {
6418
+ bgGradient: "bg-[#14181d]",
6419
+ // 移除透明度 f2
6420
+ gradientColor: "#60a5fa",
6421
+ borderGradient: "border-[#60a5fa]",
6422
+ borderGradientColor: "#f0f0f0"
6423
+ },
6424
+ light: {
6425
+ bgGradient: "bg-[#fafafa]",
6426
+ // 移除透明度 ff
6427
+ gradientColor: "#3b82f6",
6428
+ borderGradient: "border-[#3b82f6]",
6429
+ borderGradientColor: "#3b82f6"
6430
+ }
6431
+ },
6432
+ default: {
6433
+ icon: "ic:round-notifications",
6434
+ color: "text-gray-400",
6435
+ className: "text-gray-400",
6436
+ dark: {
6437
+ bgGradient: "bg-[#14181d]",
6438
+ // 移除透明度 f2
6439
+ gradientColor: "#9ca3af",
6440
+ borderGradient: "border-[#9ca3af]",
6441
+ borderGradientColor: "#9ca3af"
6442
+ },
6443
+ light: {
6444
+ bgGradient: "bg-[#fafafa]",
6445
+ // 移除透明度 ff
6446
+ gradientColor: "#6b7280",
6447
+ borderGradient: "border-[#6b7280]",
6448
+ borderGradientColor: "#6b7280"
6449
+ }
6450
+ }
6451
+ };
6452
+ var CloseButton = import_react11.default.memo(({ closeToast }) => {
6453
+ const { theme } = useTheme();
6454
+ const handleClick = (0, import_react11.useCallback)((e) => {
6455
+ e.preventDefault();
6456
+ e.stopPropagation();
6457
+ closeToast?.();
6458
+ }, [closeToast]);
6459
+ const getCloseButtonColor = () => {
6460
+ const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6461
+ return actualTheme === "dark" ? "#b4b4b4" : "#6b7280";
6462
+ };
6463
+ const getCloseButtonHoverColor = () => {
6464
+ const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6465
+ return actualTheme === "dark" ? "white" : "#374151";
6466
+ };
6467
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6468
+ import_react12.Icon,
6469
+ {
6470
+ icon: "vaadin:close",
6471
+ className: "flex items-center justify-center rounded-full relative z-10 flex-shrink-0 cursor-pointer \n transition-colors duration-200 drop-shadow-sm",
6472
+ onClick: handleClick,
6473
+ width: 14,
6474
+ height: 14,
6475
+ style: {
6476
+ color: getCloseButtonColor()
6477
+ },
6478
+ onMouseEnter: (e) => {
6479
+ e.currentTarget.style.color = getCloseButtonHoverColor();
6480
+ },
6481
+ onMouseLeave: (e) => {
6482
+ e.currentTarget.style.color = getCloseButtonColor();
6483
+ }
6484
+ }
6485
+ );
6486
+ });
6487
+ CloseButton.displayName = "CloseButton";
6488
+ var ToastContent = ({ type, title, message, component, closeToast }) => {
6489
+ const iconConfig = TOAST_ICONS[type];
6490
+ const { theme } = useTheme();
6491
+ const handleClose = (0, import_react11.useCallback)(() => {
6492
+ closeToast?.();
6493
+ }, [closeToast]);
6494
+ const getTextColor = () => {
6495
+ const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6496
+ return actualTheme === "dark" ? "white" : "#1f2937";
6497
+ };
6498
+ const getThemeConfig = () => {
6499
+ const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6500
+ return actualTheme === "dark" ? iconConfig.dark : iconConfig.light;
6501
+ };
6502
+ const themeConfig = getThemeConfig();
6503
+ if (component) {
6504
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: `flex items-start gap-3 !min-h-[90px] w-full backdrop-blur-md p-4 shadow-2xl relative overflow-hidden ${themeConfig.bgGradient}`, children: [
6505
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "flex-1 relative z-10", children: component }),
6506
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "relative z-10", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(CloseButton, { closeToast: handleClose }) })
6507
+ ] });
6508
+ }
6509
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: `flex items-start gap-3 !min-h-[90px] w-full backdrop-blur-md p-4 shadow-2xl relative overflow-hidden ${themeConfig.bgGradient}`, children: [
6510
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6511
+ "div",
6512
+ {
6513
+ className: "absolute left-0 top-0 w-full h-full rounded-xl",
6514
+ style: {
6515
+ background: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "#0f1419" : "#ffffff",
6516
+ zIndex: -2
6517
+ }
6518
+ }
6519
+ ),
6520
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6521
+ "div",
6522
+ {
6523
+ className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-xl",
6524
+ style: {
6525
+ background: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? `linear-gradient(135deg, ${themeConfig.gradientColor}30 0%, ${themeConfig.gradientColor}20 15%, #14181df2 30%)` : `linear-gradient(135deg, ${themeConfig.gradientColor}15 0%, ${themeConfig.gradientColor}08 15%, #fafafaff 30%)`,
6526
+ zIndex: -1
6527
+ }
6528
+ }
6529
+ ),
6530
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6531
+ "div",
6532
+ {
6533
+ className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-xl",
6534
+ style: {
6535
+ border: "2px solid transparent",
6536
+ backgroundImage: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? `linear-gradient(135deg, ${themeConfig.borderGradientColor}60 0%, ${themeConfig.borderGradientColor}40 5%, transparent 22%)` : `linear-gradient(135deg, ${themeConfig.borderGradientColor}40 0%, ${themeConfig.borderGradientColor}25 5%, transparent 22%)`,
6537
+ backgroundOrigin: "border-box",
6538
+ backgroundClip: "border-box",
6539
+ WebkitMask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6540
+ WebkitMaskComposite: "xor",
6541
+ mask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6542
+ maskComposite: "exclude"
6543
+ }
6544
+ }
6545
+ ),
6546
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "flex-shrink-0 mt-0.5 relative z-10", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: `w-7 h-7 backdrop-blur-sm rounded-full flex items-center justify-center ${theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "bg-white/10" : "bg-black/5"}`, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6547
+ import_react12.Icon,
6548
+ {
6549
+ icon: iconConfig.icon,
6550
+ width: 16,
6551
+ height: 16,
6552
+ className: iconConfig.color,
6553
+ style: {
6554
+ color: themeConfig.gradientColor
6555
+ }
6556
+ }
6557
+ ) }) }),
6558
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "flex flex-col gap-1 flex-1 relative z-10", children: [
6559
+ title && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6560
+ "div",
6561
+ {
6562
+ className: "text-[16px] font-semibold leading-tight drop-shadow-sm",
6563
+ style: {
6564
+ color: getTextColor(),
6565
+ backgroundClip: "text"
6566
+ },
6567
+ children: title
6568
+ }
6569
+ ),
6570
+ message && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6571
+ "div",
6572
+ {
6573
+ className: "text-[13px] font-normal leading-relaxed drop-shadow-sm",
6574
+ style: {
6575
+ color: getTextColor(),
6576
+ backgroundClip: "text"
6577
+ },
6578
+ children: message
6579
+ }
6580
+ )
6581
+ ] }),
6582
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "relative z-10", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(CloseButton, { closeToast: handleClose }) })
6583
+ ] });
6584
+ };
6585
+ var defaultToastOptions = {
6586
+ position: "bottom-right",
6587
+ autoClose: 3e3,
6588
+ hideProgressBar: true,
6589
+ closeOnClick: false,
6590
+ pauseOnHover: true,
6591
+ draggable: true,
6592
+ pauseOnFocusLoss: false,
6593
+ theme: "dark",
6594
+ transition: import_react_toastify2.Bounce
6595
+ };
6596
+ var createToast = (type) => {
6597
+ return (params) => {
6598
+ const { title, message, component, options } = params;
6599
+ (0, import_react_toastify2.toast)(
6600
+ ({ closeToast }) => {
6601
+ if (params.render) return params.render(closeToast);
6602
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6603
+ ToastContent,
6604
+ {
6605
+ type,
6606
+ title,
6607
+ message: message || "",
6608
+ component,
6609
+ closeToast
6610
+ }
6611
+ );
6612
+ },
6613
+ {
6614
+ ...defaultToastOptions,
6615
+ ...options,
6616
+ // 确保圆角样式不被覆盖,添加 rounded-xl 类
6617
+ className: "!p-0 !shadow-none !rounded-xl",
6618
+ style: { padding: 0, borderRadius: "0.75rem" }
6619
+ }
6620
+ );
6621
+ };
6622
+ };
6623
+ var ClayxToast = {
6624
+ success: createToast("success"),
6625
+ error: createToast("error"),
6626
+ warning: createToast("warning"),
6627
+ info: createToast("info"),
6628
+ default: createToast("default")
6629
+ };
6630
+
6631
+ // src/components/ui/LimitUpgradeToast.tsx
6632
+ var import_jsx_runtime13 = require("react/jsx-runtime");
6633
+ var LimitToastContainer = ({ message, onUpgrade, closeToast }) => {
6634
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "relative w-full max-w-[420px] overflow-hidden rounded-md bg-gradient-to-br from-[#1A1A1A] via-[#151515] to-[#1A1A1A] shadow-[0_20px_60px_rgba(168,85,247,0.2)] backdrop-blur-sm", children: [
6635
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6636
+ "div",
6637
+ {
6638
+ className: "absolute left-0 top-0 w-full h-full rounded-md",
6639
+ style: {
6640
+ background: "#0f1419",
6641
+ zIndex: -2
6642
+ }
6643
+ }
6644
+ ),
6645
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6646
+ "div",
6647
+ {
6648
+ className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-md",
6649
+ style: {
6650
+ background: `linear-gradient(135deg, rgba(168,85,247,0.3) 0%, rgba(168,85,247,0.2) 15%, #1A1A1A 30%)`,
6651
+ zIndex: -1
6652
+ }
6653
+ }
6654
+ ),
6655
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6656
+ "div",
6657
+ {
6658
+ className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-md",
6659
+ style: {
6660
+ border: "2px solid transparent",
6661
+ backgroundImage: `linear-gradient(135deg, rgba(168,85,247,0.6) 0%, rgba(168,85,247,0.4) 5%, transparent 22%)`,
6662
+ backgroundOrigin: "border-box",
6663
+ backgroundClip: "border-box",
6664
+ WebkitMask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6665
+ WebkitMaskComposite: "xor",
6666
+ mask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6667
+ maskComposite: "exclude"
6668
+ }
6669
+ }
6670
+ ),
6671
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "absolute -top-16 -right-16 h-32 w-32 rounded-full bg-gradient-to-br from-purple-500/20 via-pink-500/10 to-transparent blur-3xl animate-pulse" }),
6672
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "absolute -bottom-16 -left-16 h-32 w-32 rounded-full bg-gradient-to-tr from-blue-500/10 to-transparent blur-2xl animate-pulse", style: { animationDelay: "1s" } }),
6673
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "relative z-10 flex items-start gap-4 p-4", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "flex flex-1 flex-col gap-3", children: [
6674
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "flex items-center justify-between", children: [
6675
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "flex items-center gap-2", children: [
6676
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "text-lg font-bold bg-gradient-to-r from-white to-gray-400 bg-clip-text text-transparent", children: "Upgrade Required" }),
6677
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "px-2 py-0.5 text-xs font-bold bg-purple-500/20 text-purple-400 rounded-md border border-purple-500/30", children: "Premium" })
6678
+ ] }),
6679
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6680
+ ClayxButton,
6681
+ {
6682
+ onClick: closeToast,
6683
+ isIconOnly: true,
6684
+ size: "sm",
6685
+ className: "h-6 w-6 min-w-6 rounded-full bg-white/5 hover:bg-white/10 transition-colors",
6686
+ children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react13.Icon, { icon: "iconamoon:close", className: "w-4 h-4 text-gray-400" })
6687
+ }
6688
+ )
6689
+ ] }),
6690
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("p", { className: "text-sm text-gray-300 leading-relaxed", children: message }),
6691
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "mt-1 flex items-center gap-3", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6692
+ ClayxButton,
6693
+ {
6694
+ onClick: () => {
6695
+ onUpgrade();
6696
+ closeToast?.();
6697
+ },
6698
+ className: "flex-1 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold transition-all duration-300 hover:shadow-lg hover:shadow-purple-500/30 cursor-pointer",
6699
+ style: { cursor: "pointer" },
6700
+ children: /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("span", { className: "flex items-center gap-2", children: [
6701
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react13.Icon, { icon: "solar:rocket-2-bold", className: "w-4 h-4" }),
6702
+ "Upgrade Now"
6703
+ ] })
6196
6704
  }
6197
- }
6198
- }
6199
- }, [token, user, redirectOnUnauthenticated, authUrl, projectId, hasCheckedUrlToken]);
6200
- const logout = () => {
6201
- try {
6202
- setToken(null);
6203
- } catch {
6204
- }
6205
- setTokenState(null);
6206
- setUser(null);
6207
- };
6208
- const value = {
6209
- user,
6210
- token,
6211
- isAuthenticated: hasCheckedUrlToken && !!token,
6212
- logout
6213
- };
6214
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
6215
- ThemeProvider,
6216
- {
6217
- defaultTheme,
6218
- storageKey: themeStorageKey,
6219
- forceDefault: forceDefaultTheme,
6220
- children: [
6221
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ElementSelectorProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(HowoneContext.Provider, { value, children: [
6222
- children,
6223
- showFloatingButton && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FloatingButton, { onClick: () => window.open("https://howone.ai", "_blank") })
6224
- ] }) }),
6225
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(GlobalToastContainer, {})
6226
- ]
6227
- }
6228
- );
6705
+ ) })
6706
+ ] }) })
6707
+ ] });
6229
6708
  };
6230
- function useHowoneContext() {
6231
- const ctx = (0, import_react8.useContext)(HowoneContext);
6232
- if (!ctx) {
6233
- const t = getToken();
6234
- return {
6235
- user: parseUserFromToken(t),
6236
- token: t,
6237
- isAuthenticated: !!t,
6238
- logout: () => {
6239
- try {
6240
- setToken(null);
6241
- } catch {
6242
- }
6709
+ function showLimitUpgradeToast(message, onUpgrade) {
6710
+ ClayxToast.default({
6711
+ render: (closeToast) => /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(LimitToastContainer, { message, onUpgrade, closeToast }),
6712
+ options: {
6713
+ position: "bottom-right",
6714
+ closeOnClick: false,
6715
+ autoClose: false,
6716
+ hideProgressBar: true,
6717
+ draggable: false,
6718
+ pauseOnHover: true,
6719
+ className: "!bg-transparent !shadow-none",
6720
+ style: {
6721
+ background: "transparent",
6722
+ padding: 0,
6723
+ width: "auto",
6724
+ maxWidth: "420px"
6243
6725
  }
6244
- };
6245
- }
6246
- return ctx;
6726
+ }
6727
+ });
6247
6728
  }
6248
6729
 
6249
- // src/components/index.ts
6250
- init_auth();
6251
-
6252
- // src/howone/client.ts
6253
- init_auth();
6254
- init_config();
6255
- var HowoneAuthClient = class {
6256
- constructor() {
6257
- this.listeners = /* @__PURE__ */ new Set();
6258
- this.loading = false;
6730
+ // src/services/ai-workflow.ts
6731
+ var AIWorkflowClient = class {
6732
+ constructor(options = {}) {
6733
+ this.baseUrl = options.baseUrl?.replace(/\/+$/, "") || "";
6734
+ this.apiKey = options.apiKey;
6735
+ this.headers = { "Content-Type": "application/json", ...options.headers || {} };
6736
+ this.fetchImpl = options.fetchImpl || fetch.bind(globalThis);
6259
6737
  }
6260
- emit() {
6261
- const state = {
6262
- user: parseUserFromToken(getToken()),
6263
- isLoading: this.loading
6264
- };
6265
- for (const l of this.listeners) {
6266
- try {
6267
- l(state);
6268
- } catch (e) {
6269
- void e;
6270
- }
6738
+ buildHeaders(extra) {
6739
+ const h = { ...this.headers, ...extra || {} };
6740
+ if (this.apiKey && !h["Authorization"]) {
6741
+ h["Authorization"] = `Bearer ${this.apiKey}`;
6271
6742
  }
6743
+ return h;
6272
6744
  }
6273
- onAuthStateChanged(listener) {
6274
- this.listeners.add(listener);
6745
+ async safeJson(resp) {
6275
6746
  try {
6276
- listener({ user: parseUserFromToken(getToken()), isLoading: this.loading });
6277
- } catch (e) {
6278
- void e;
6747
+ return await resp.json();
6748
+ } catch (_e) {
6749
+ return null;
6279
6750
  }
6280
- return () => {
6281
- this.listeners.delete(listener);
6282
- };
6283
6751
  }
6284
- // Simple redirect-based login trigger (consumer can override)
6285
- login() {
6286
- const root = getEnvs().AUTH_ROOT_VALUE;
6752
+ /**
6753
+ * 按 ID 执行工作流:POST {baseUrl}/workflow/{workflowId}/execute
6754
+ * body: { input, options }
6755
+ */
6756
+ async executeWorkflow(workflowId, inputs, options) {
6757
+ if (!this.baseUrl) {
6758
+ throw new Error("AI workflow client requires a baseUrl (e.g. https://evoagentx-server.fly.dev)");
6759
+ }
6760
+ const url = `${this.baseUrl}/workflow/${workflowId}/execute`;
6287
6761
  try {
6288
- const loc = window.location.href;
6289
- const authUrl = new URL("/auth", String(root));
6290
- authUrl.searchParams.set("redirect_uri", String(loc));
6291
- try {
6292
- const cfg = (init_config(), __toCommonJS(config_exports));
6293
- const pid = cfg.getDefaultProjectId && cfg.getDefaultProjectId();
6294
- if (pid) authUrl.searchParams.set("project_id", String(pid));
6295
- } catch {
6296
- }
6297
- try {
6298
- if (window.top && window.top !== window) {
6299
- window.top.location.replace(authUrl.toString());
6300
- } else {
6301
- window.location.replace(authUrl.toString());
6302
- }
6303
- } catch {
6304
- try {
6305
- window.location.replace(String(root));
6306
- } catch {
6307
- }
6762
+ const res = await this.fetchImpl(url, {
6763
+ method: "POST",
6764
+ headers: this.buildHeaders(),
6765
+ body: JSON.stringify({ inputs, options })
6766
+ });
6767
+ const data = await this.safeJson(res);
6768
+ if (!res.ok) {
6769
+ return { success: false, error: data?.error || `HTTP ${res.status}` };
6308
6770
  }
6309
- } catch {
6310
- try {
6311
- window.location.replace(String(root));
6312
- } catch {
6771
+ if (data && data.status && data.status === 4003) {
6772
+ showLimitUpgradeToast(
6773
+ "Your credits are exhausted. Please upgrade your plan to continue generating projects.",
6774
+ () => window.open("https://clayx.ai/pricing", "_blank")
6775
+ );
6776
+ return null;
6313
6777
  }
6778
+ return data || { success: true };
6779
+ } catch (error) {
6780
+ return { success: false, error: error instanceof Error ? error.message : "Network error" };
6314
6781
  }
6315
6782
  }
6316
- logout() {
6317
- setToken(null);
6318
- this.emit();
6319
- }
6320
- getUser() {
6321
- return parseUserFromToken(getToken());
6322
- }
6323
- // helper to programmatically set token (e.g., after callback handling)
6324
- setToken(token) {
6325
- setToken(token);
6326
- this.emit();
6327
- }
6328
- };
6329
- var howone = {
6330
- auth: new HowoneAuthClient()
6331
6783
  };
6332
- var client_default = howone;
6784
+ function createAIWorkflowClient(options = {}) {
6785
+ return new AIWorkflowClient(options);
6786
+ }
6787
+ var aiWorkflow = createAIWorkflowClient({ baseUrl: "https://evoagentx-server" });
6333
6788
 
6334
- // src/components/ui/Loading.tsx
6335
- var import_jsx_runtime8 = require("react/jsx-runtime");
6336
- var Loading = ({
6337
- size = "md",
6338
- text = "Loading...",
6339
- className = "",
6340
- fullScreen = false
6341
- }) => {
6342
- const sizeClasses = {
6343
- sm: "h-4 w-4",
6344
- md: "h-8 w-8",
6345
- lg: "h-12 w-12"
6346
- };
6347
- const containerClasses = fullScreen ? "fixed inset-0 flex items-center justify-center bg-white/80 backdrop-blur-sm z-50" : "flex items-center justify-center p-4";
6348
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: `${containerClasses} ${className}`, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "text-center", children: [
6349
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
6350
- "div",
6351
- {
6352
- className: `animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 mx-auto ${sizeClasses[size]}`
6789
+ // src/services/request/index.ts
6790
+ var import_axios = __toESM(require("axios"));
6791
+ var Request = class {
6792
+ constructor(config) {
6793
+ this.abortControllers = /* @__PURE__ */ new Map();
6794
+ this.instance = import_axios.default.create({
6795
+ ...config,
6796
+ validateStatus: (status) => {
6797
+ return status >= 200 && status < 300;
6798
+ }
6799
+ });
6800
+ this.interceptors = config.interceptors;
6801
+ this.instance.interceptors.request.use(
6802
+ this.interceptors?.requestInterceptor,
6803
+ this.interceptors?.requestInterceptorCatch
6804
+ );
6805
+ this.instance.interceptors.response.use(
6806
+ this.interceptors?.responseInterceptor,
6807
+ this.interceptors?.responseInterceptorCatch
6808
+ );
6809
+ this.instance.interceptors.request.use(
6810
+ (config2) => {
6811
+ return config2;
6812
+ },
6813
+ (err) => {
6814
+ return Promise.reject(err);
6815
+ }
6816
+ );
6817
+ this.instance.interceptors.response.use(
6818
+ (res) => {
6819
+ return res.data;
6820
+ },
6821
+ (err) => {
6822
+ if (import_axios.default.isCancel(err)) {
6823
+ return Promise.reject({
6824
+ isCanceled: true,
6825
+ message: "request canceled",
6826
+ originalError: err
6827
+ });
6828
+ }
6829
+ if (err.response?.data?.error) {
6830
+ return Promise.reject(err.response.data.error);
6831
+ }
6832
+ return Promise.reject(err);
6353
6833
  }
6354
- ),
6355
- text && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("p", { className: "mt-2 text-sm text-gray-600", children: text })
6356
- ] }) });
6357
- };
6358
- var LoadingSpinner = ({
6359
- size = "md",
6360
- className = ""
6361
- }) => {
6362
- const sizeClasses = {
6363
- sm: "h-4 w-4",
6364
- md: "h-8 w-8",
6365
- lg: "h-12 w-12"
6366
- };
6367
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
6368
- "div",
6369
- {
6370
- className: `animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 ${sizeClasses[size]} ${className}`
6371
- }
6372
- );
6373
- };
6374
-
6375
- // src/components/ui/ErrorBoundary.tsx
6376
- var import_react9 = require("react");
6377
- var import_jsx_runtime9 = require("react/jsx-runtime");
6378
- var ErrorBoundary = class extends import_react9.Component {
6379
- constructor(props) {
6380
- super(props);
6381
- this.handleRetry = () => {
6382
- this.setState({ hasError: false, error: void 0, errorInfo: void 0 });
6383
- };
6384
- this.state = { hasError: false };
6834
+ );
6385
6835
  }
6386
- static getDerivedStateFromError(error) {
6387
- return { hasError: true, error };
6836
+ cancelRequest(url) {
6837
+ this.abortControllers.forEach((controller, key) => {
6838
+ if (key.includes(url)) {
6839
+ controller.abort();
6840
+ this.abortControllers.delete(key);
6841
+ }
6842
+ });
6388
6843
  }
6389
- componentDidCatch(error, errorInfo) {
6390
- this.setState({
6391
- error,
6392
- errorInfo
6844
+ cancelAllRequests() {
6845
+ this.abortControllers.forEach((controller) => {
6846
+ controller.abort();
6393
6847
  });
6394
- this.props.onError?.(error, errorInfo);
6848
+ this.abortControllers.clear();
6395
6849
  }
6396
- render() {
6397
- if (this.state.hasError) {
6398
- if (this.props.fallback) {
6399
- const FallbackComponent = this.props.fallback;
6400
- return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(FallbackComponent, { error: this.state.error, retry: this.handleRetry });
6850
+ request(config) {
6851
+ const controller = new AbortController();
6852
+ const url = config.url || "";
6853
+ const method = config.method || "GET";
6854
+ const key = `${method}:${url}`;
6855
+ this.abortControllers.set(key, controller);
6856
+ config.signal = controller.signal;
6857
+ return new Promise((resolve, reject) => {
6858
+ if (config.interceptors?.requestInterceptor) {
6859
+ config = config.interceptors.requestInterceptor(config);
6401
6860
  }
6402
- return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "min-h-[400px] flex items-center justify-center p-4", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: "text-center max-w-md", children: [
6403
- /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "text-red-500 text-6xl mb-4", children: "\u26A0\uFE0F" }),
6404
- /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("h2", { className: "text-xl font-semibold text-gray-900 mb-2", children: "Something went wrong" }),
6405
- /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("p", { className: "text-gray-600 mb-4", children: "An unexpected error occurred. Please try refreshing the page." }),
6406
- /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
6407
- "button",
6408
- {
6409
- onClick: this.handleRetry,
6410
- className: "px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors",
6411
- children: "Try Again"
6412
- }
6413
- ),
6414
- false
6415
- ] }) });
6416
- }
6417
- return this.props.children;
6861
+ this.instance.request(config).then((res) => {
6862
+ this.abortControllers.delete(key);
6863
+ if (config.interceptors?.responseInterceptor) {
6864
+ res = config.interceptors.responseInterceptor(res);
6865
+ }
6866
+ resolve(res);
6867
+ }).catch((err) => {
6868
+ this.abortControllers.delete(key);
6869
+ reject(err);
6870
+ });
6871
+ });
6418
6872
  }
6419
- };
6420
- var DefaultErrorFallback = ({ retry }) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "min-h-[200px] flex items-center justify-center p-4", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: "text-center", children: [
6421
- /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "text-red-500 text-4xl mb-2", children: "\u26A0\uFE0F" }),
6422
- /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("p", { className: "text-gray-600 mb-2", children: "Something went wrong" }),
6423
- retry && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
6424
- "button",
6425
- {
6426
- onClick: retry,
6427
- className: "px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors",
6428
- children: "Retry"
6429
- }
6430
- )
6431
- ] }) });
6432
-
6433
- // src/components/ui/ClayxButton.tsx
6434
- var import_jsx_runtime10 = require("react/jsx-runtime");
6435
- var getSizeClasses = (size, isIconOnly) => {
6436
- if (isIconOnly) {
6437
- switch (size) {
6438
- case "sm":
6439
- return "h-8 w-8 min-w-8 p-0";
6440
- case "md":
6441
- return "h-10 w-10 min-w-10 p-0";
6442
- case "lg":
6443
- return "h-12 w-12 min-w-12 p-0";
6444
- default:
6445
- return "h-10 w-10 min-w-10 p-0";
6446
- }
6873
+ get(config) {
6874
+ return this.request({ ...config, method: "GET" });
6447
6875
  }
6448
- switch (size) {
6449
- case "sm":
6450
- return "h-8 px-3 text-sm";
6451
- case "md":
6452
- return "h-10 px-4 text-base";
6453
- case "lg":
6454
- return "h-12 px-6 text-lg";
6455
- default:
6456
- return "h-10 px-4 text-base";
6876
+ post(config) {
6877
+ return this.request({ ...config, method: "POST" });
6457
6878
  }
6458
- };
6459
- var getVariantClasses = (variant) => {
6460
- switch (variant) {
6461
- case "solid":
6462
- return "bg-primary text-white hover:bg-primary/90";
6463
- case "ghost":
6464
- return "bg-transparent hover:bg-white/10";
6465
- case "flat":
6466
- return "bg-white/5 hover:bg-white/10";
6467
- default:
6468
- return "";
6879
+ delete(config) {
6880
+ return this.request({ ...config, method: "DELETE" });
6881
+ }
6882
+ put(config) {
6883
+ return this.request({ ...config, method: "PUT" });
6884
+ }
6885
+ patch(config) {
6886
+ return this.request({ ...config, method: "PATCH" });
6469
6887
  }
6470
6888
  };
6471
- var ClayxButton = ({
6472
- isIconOnly = false,
6473
- size = "md",
6474
- variant = "solid",
6475
- className = "",
6476
- children,
6477
- disabled = false,
6478
- ...props
6479
- }) => {
6480
- const sizeClasses = getSizeClasses(size, isIconOnly);
6481
- const variantClasses = getVariantClasses(variant);
6482
- const baseClasses = `
6483
- inline-flex items-center justify-center
6484
- rounded-md font-medium
6485
- transition-all duration-200
6486
- focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-transparent
6487
- disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none
6488
- `.replace(/\s+/g, " ").trim();
6489
- const combinedClasses = `${baseClasses} ${sizeClasses} ${variantClasses} ${className}`.trim();
6490
- return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
6491
- "button",
6492
- {
6493
- className: combinedClasses,
6494
- disabled,
6495
- ...props,
6496
- children
6497
- }
6498
- );
6499
- };
6500
-
6501
- // src/components/ui/LimitUpgradeToast.tsx
6502
- var import_react13 = require("@iconify/react");
6503
-
6504
- // src/components/ui/Toast/ClayxToast.tsx
6505
- var import_react11 = __toESM(require("react"));
6506
- var import_react_toastify2 = require("react-toastify");
6507
- var import_react12 = require("@iconify/react");
6889
+ var request_default = Request;
6508
6890
 
6509
- // src/components/theme/ThemeToggle.tsx
6510
- var React6 = __toESM(require("react"));
6511
- var import_react10 = require("@iconify/react");
6512
- var import_jsx_runtime11 = require("react/jsx-runtime");
6513
- function ThemeToggle({ className }) {
6514
- const { setTheme, theme } = useTheme();
6515
- const [mounted, setMounted] = React6.useState(false);
6516
- React6.useEffect(() => {
6517
- setMounted(true);
6518
- }, []);
6519
- const handleToggle = () => {
6520
- if (theme === "dark") {
6521
- setTheme("light");
6522
- } else {
6523
- setTheme("dark");
6524
- }
6525
- };
6526
- if (!mounted) {
6527
- return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
6528
- "button",
6529
- {
6530
- className: `relative inline-flex h-10 w-12 items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground ${className || ""}`,
6531
- disabled: true,
6532
- children: [
6533
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react10.Icon, { icon: "solar:sun-bold", width: 20, height: 20 }),
6534
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "sr-only", children: "\u5207\u6362\u4E3B\u9898" })
6535
- ]
6536
- }
6537
- );
6538
- }
6539
- return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
6540
- "button",
6541
- {
6542
- className: `inline-flex h-10 w-12 items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors ${className || ""}`,
6543
- onClick: handleToggle,
6544
- children: [
6545
- theme === "light" ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react10.Icon, { icon: "solar:sun-bold", width: 20, height: 20 }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react10.Icon, { icon: "solar:moon-linear", width: 20, height: 20 }),
6546
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "sr-only", children: "\u5207\u6362\u4E3B\u9898" })
6547
- ]
6891
+ // src/services/ai-workflow-axios.ts
6892
+ function createAIWorkflowClientAxios(options = {}) {
6893
+ const basePath = options.basePath ?? "/api";
6894
+ const baseUrl = (options.baseUrl || "https://evoagentx-server.fly.dev").replace(/\/+$/, "");
6895
+ const baseAPI = `${baseUrl}${basePath.startsWith("/") ? "" : "/"}${basePath}`.replace(/\/+$/, "");
6896
+ const client = options.requestInstance || new request_default({
6897
+ baseURL: baseAPI,
6898
+ timeout: options.timeout ?? 6e4,
6899
+ interceptors: {
6900
+ requestInterceptor: (config) => {
6901
+ config.headers = config.headers || {};
6902
+ if (options.apiKey && !config.headers["Authorization"]) {
6903
+ config.headers["Authorization"] = `Bearer ${options.apiKey}`;
6904
+ }
6905
+ if (options.headers) {
6906
+ config.headers = { ...config.headers || {}, ...options.headers };
6907
+ }
6908
+ return config;
6909
+ },
6910
+ requestInterceptorCatch: (err) => Promise.reject(err),
6911
+ responseInterceptor: (res) => res,
6912
+ responseInterceptorCatch: (err) => Promise.reject(err)
6548
6913
  }
6549
- );
6914
+ });
6915
+ return {
6916
+ async executeWorkflow(workflowId, inputs, opts) {
6917
+ const url = `${baseUrl}/workflow/${workflowId}/execute`;
6918
+ const data = await client.post({ url, data: { inputs, options: opts } });
6919
+ return data;
6920
+ }
6921
+ };
6550
6922
  }
6551
6923
 
6552
- // src/components/ui/Toast/ClayxToast.tsx
6553
- var import_jsx_runtime12 = require("react/jsx-runtime");
6554
- var TOAST_ICONS = {
6555
- success: {
6556
- icon: "mdi:success",
6557
- color: "text-green-400",
6558
- className: "text-green-400",
6559
- // 深色主题配置
6560
- dark: {
6561
- bgGradient: "bg-[#14181d]",
6562
- // 移除透明度 f2
6563
- gradientColor: "#389726",
6564
- borderGradient: "border-[#389726]",
6565
- borderGradientColor: "#389726"
6924
+ // src/services/artifact-types.ts
6925
+ function canAccessArtifact(a, ctx = {}) {
6926
+ if (!a) return false;
6927
+ if (a.visibility === "public") return true;
6928
+ if (a.visibility === "project") {
6929
+ if (ctx.projectId && a.projectId && ctx.projectId === a.projectId) return true;
6930
+ if (ctx.tokenScopes && ctx.tokenScopes.includes("project:read")) return true;
6931
+ return false;
6932
+ }
6933
+ if (a.visibility === "private") {
6934
+ if (ctx.userId && a.ownerId && ctx.userId === a.ownerId) return true;
6935
+ if (ctx.tokenScopes && (ctx.tokenScopes.includes("artifact:read:all") || ctx.tokenScopes.includes("admin"))) return true;
6936
+ return false;
6937
+ }
6938
+ if (a.visibility === "shared") {
6939
+ if (ctx.userId && a.sharedWith && a.sharedWith.includes(ctx.userId)) return true;
6940
+ if (ctx.tokenScopes && (ctx.tokenScopes.includes("artifact:read:all") || ctx.tokenScopes.includes("admin"))) return true;
6941
+ return false;
6942
+ }
6943
+ return false;
6944
+ }
6945
+
6946
+ // src/services/artifacts-client.ts
6947
+ function createArtifactsClient(req) {
6948
+ return {
6949
+ async create(input) {
6950
+ return await req.post({ url: "/artifacts", data: input });
6566
6951
  },
6567
- // 浅色主题配置
6568
- light: {
6569
- bgGradient: "bg-[#fafafa]",
6570
- // 移除透明度 ff
6571
- gradientColor: "#22c55e",
6572
- borderGradient: "border-[#22c55e]",
6573
- borderGradientColor: "#22c55e"
6574
- }
6575
- },
6576
- error: {
6577
- icon: "ic:outline-close",
6578
- color: "text-red-400",
6579
- className: "text-red-400",
6580
- dark: {
6581
- bgGradient: "bg-[#14181d]",
6582
- // 移除透明度 f2
6583
- gradientColor: "#ef4444",
6584
- borderGradient: "border-[#ef4444]",
6585
- borderGradientColor: "#ef4444"
6952
+ async list(query) {
6953
+ return await req.get({ url: "/artifacts", params: query });
6586
6954
  },
6587
- light: {
6588
- bgGradient: "bg-[#fafafa]",
6589
- // 移除透明度 ff
6590
- gradientColor: "#f87171",
6591
- borderGradient: "border-[#f87171]",
6592
- borderGradientColor: "#f87171"
6593
- }
6594
- },
6595
- warning: {
6596
- icon: "mi:warning",
6597
- color: "text-yellow-400",
6598
- className: "text-yellow-400",
6599
- dark: {
6600
- bgGradient: "bg-[#14181d]",
6601
- // 移除透明度 f2
6602
- gradientColor: "#facc15",
6603
- borderGradient: "border-[#facc15]",
6604
- borderGradientColor: "#facc15"
6955
+ async get(id) {
6956
+ return await req.get({ url: `/artifacts/${encodeURIComponent(id)}` });
6605
6957
  },
6606
- light: {
6607
- bgGradient: "bg-[#fafafa]",
6608
- // 移除透明度 ff
6609
- gradientColor: "#f59e0b",
6610
- borderGradient: "border-[#f59e0b]",
6611
- borderGradientColor: "#f59e0b"
6612
- }
6613
- },
6614
- info: {
6615
- icon: "ic:outline-info",
6616
- color: "text-blue-400",
6617
- className: "text-blue-400",
6618
- dark: {
6619
- bgGradient: "bg-[#14181d]",
6620
- // 移除透明度 f2
6621
- gradientColor: "#60a5fa",
6622
- borderGradient: "border-[#60a5fa]",
6623
- borderGradientColor: "#f0f0f0"
6958
+ async setVisibility(id, visibility) {
6959
+ await req.patch({ url: `/artifacts/${encodeURIComponent(id)}/visibility`, data: { visibility } });
6624
6960
  },
6625
- light: {
6626
- bgGradient: "bg-[#fafafa]",
6627
- // 移除透明度 ff
6628
- gradientColor: "#3b82f6",
6629
- borderGradient: "border-[#3b82f6]",
6630
- borderGradientColor: "#3b82f6"
6631
- }
6632
- },
6633
- default: {
6634
- icon: "ic:round-notifications",
6635
- color: "text-gray-400",
6636
- className: "text-gray-400",
6637
- dark: {
6638
- bgGradient: "bg-[#14181d]",
6639
- // 移除透明度 f2
6640
- gradientColor: "#9ca3af",
6641
- borderGradient: "border-[#9ca3af]",
6642
- borderGradientColor: "#9ca3af"
6961
+ async delete(id) {
6962
+ await req.delete({ url: `/artifacts/${encodeURIComponent(id)}` });
6643
6963
  },
6644
- light: {
6645
- bgGradient: "bg-[#fafafa]",
6646
- // 移除透明度 ff
6647
- gradientColor: "#6b7280",
6648
- borderGradient: "border-[#6b7280]",
6649
- borderGradientColor: "#6b7280"
6650
- }
6651
- }
6652
- };
6653
- var CloseButton = import_react11.default.memo(({ closeToast }) => {
6654
- const { theme } = useTheme();
6655
- const handleClick = (0, import_react11.useCallback)((e) => {
6656
- e.preventDefault();
6657
- e.stopPropagation();
6658
- closeToast?.();
6659
- }, [closeToast]);
6660
- const getCloseButtonColor = () => {
6661
- const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6662
- return actualTheme === "dark" ? "#b4b4b4" : "#6b7280";
6663
- };
6664
- const getCloseButtonHoverColor = () => {
6665
- const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6666
- return actualTheme === "dark" ? "white" : "#374151";
6667
- };
6668
- return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6669
- import_react12.Icon,
6670
- {
6671
- icon: "vaadin:close",
6672
- className: "flex items-center justify-center rounded-full relative z-10 flex-shrink-0 cursor-pointer \n transition-colors duration-200 drop-shadow-sm",
6673
- onClick: handleClick,
6674
- width: 14,
6675
- height: 14,
6676
- style: {
6677
- color: getCloseButtonColor()
6678
- },
6679
- onMouseEnter: (e) => {
6680
- e.currentTarget.style.color = getCloseButtonHoverColor();
6681
- },
6682
- onMouseLeave: (e) => {
6683
- e.currentTarget.style.color = getCloseButtonColor();
6684
- }
6964
+ // convenience local check (server is authoritative)
6965
+ canAccessLocal(a, ctx) {
6966
+ if (!a) return false;
6967
+ if (a.visibility === "public") return true;
6968
+ if (a.visibility === "project") return Boolean(ctx.projectId && a.projectId && ctx.projectId === a.projectId);
6969
+ if (a.visibility === "private") return Boolean(ctx.userId && a.ownerId && ctx.userId === a.ownerId);
6970
+ if (a.visibility === "shared") return Boolean(ctx.userId && a.sharedWith && a.sharedWith.includes(ctx.userId));
6971
+ return false;
6685
6972
  }
6686
- );
6687
- });
6688
- CloseButton.displayName = "CloseButton";
6689
- var ToastContent = ({ type, title, message, component, closeToast }) => {
6690
- const iconConfig = TOAST_ICONS[type];
6691
- const { theme } = useTheme();
6692
- const handleClose = (0, import_react11.useCallback)(() => {
6693
- closeToast?.();
6694
- }, [closeToast]);
6695
- const getTextColor = () => {
6696
- const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6697
- return actualTheme === "dark" ? "white" : "#1f2937";
6698
6973
  };
6699
- const getThemeConfig = () => {
6700
- const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6701
- return actualTheme === "dark" ? iconConfig.dark : iconConfig.light;
6702
- };
6703
- const themeConfig = getThemeConfig();
6704
- if (component) {
6705
- return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: `flex items-start gap-3 !min-h-[90px] w-full backdrop-blur-md p-4 shadow-2xl relative overflow-hidden ${themeConfig.bgGradient}`, children: [
6706
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "flex-1 relative z-10", children: component }),
6707
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "relative z-10", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(CloseButton, { closeToast: handleClose }) })
6708
- ] });
6709
- }
6710
- return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: `flex items-start gap-3 !min-h-[90px] w-full backdrop-blur-md p-4 shadow-2xl relative overflow-hidden ${themeConfig.bgGradient}`, children: [
6711
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6712
- "div",
6713
- {
6714
- className: "absolute left-0 top-0 w-full h-full rounded-xl",
6715
- style: {
6716
- background: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "#0f1419" : "#ffffff",
6717
- zIndex: -2
6718
- }
6719
- }
6720
- ),
6721
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6722
- "div",
6723
- {
6724
- className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-xl",
6725
- style: {
6726
- background: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? `linear-gradient(135deg, ${themeConfig.gradientColor}30 0%, ${themeConfig.gradientColor}20 15%, #14181df2 30%)` : `linear-gradient(135deg, ${themeConfig.gradientColor}15 0%, ${themeConfig.gradientColor}08 15%, #fafafaff 30%)`,
6727
- zIndex: -1
6728
- }
6729
- }
6730
- ),
6731
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6732
- "div",
6733
- {
6734
- className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-xl",
6735
- style: {
6736
- border: "2px solid transparent",
6737
- backgroundImage: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? `linear-gradient(135deg, ${themeConfig.borderGradientColor}60 0%, ${themeConfig.borderGradientColor}40 5%, transparent 22%)` : `linear-gradient(135deg, ${themeConfig.borderGradientColor}40 0%, ${themeConfig.borderGradientColor}25 5%, transparent 22%)`,
6738
- backgroundOrigin: "border-box",
6739
- backgroundClip: "border-box",
6740
- WebkitMask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6741
- WebkitMaskComposite: "xor",
6742
- mask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6743
- maskComposite: "exclude"
6974
+ }
6975
+
6976
+ // src/services/index.ts
6977
+ init_auth();
6978
+ init_config();
6979
+ init_config();
6980
+ init_auth();
6981
+
6982
+ // src/utils/urlSanitizer.ts
6983
+ var DEFAULT_SENSITIVE = ["token", "access_token", "auth", "auth_token"];
6984
+ function removeSensitiveParamsFromUrl(opts) {
6985
+ if (typeof window === "undefined") return;
6986
+ try {
6987
+ const { clearAll, sensitiveParams, includeHash = true, onChanged } = opts || {};
6988
+ const sens = (sensitiveParams && sensitiveParams.length > 0 ? sensitiveParams : DEFAULT_SENSITIVE).map((s) => s.toLowerCase());
6989
+ const before = window.location.href;
6990
+ const url = new URL(before);
6991
+ if (clearAll) {
6992
+ url.search = "";
6993
+ } else if (url.search) {
6994
+ let changed = false;
6995
+ for (const [k] of url.searchParams) {
6996
+ if (sens.includes(k.toLowerCase())) {
6997
+ url.searchParams.delete(k);
6998
+ changed = true;
6744
6999
  }
6745
7000
  }
6746
- ),
6747
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "flex-shrink-0 mt-0.5 relative z-10", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: `w-7 h-7 backdrop-blur-sm rounded-full flex items-center justify-center ${theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "bg-white/10" : "bg-black/5"}`, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6748
- import_react12.Icon,
6749
- {
6750
- icon: iconConfig.icon,
6751
- width: 16,
6752
- height: 16,
6753
- className: iconConfig.color,
6754
- style: {
6755
- color: themeConfig.gradientColor
6756
- }
7001
+ if (changed) {
7002
+ const qs = url.searchParams.toString();
7003
+ url.search = qs ? `?${qs}` : "";
6757
7004
  }
6758
- ) }) }),
6759
- /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("div", { className: "flex flex-col gap-1 flex-1 relative z-10", children: [
6760
- title && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6761
- "div",
6762
- {
6763
- className: "text-[16px] font-semibold leading-tight drop-shadow-sm",
6764
- style: {
6765
- color: getTextColor(),
6766
- backgroundClip: "text"
6767
- },
6768
- children: title
6769
- }
6770
- ),
6771
- message && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6772
- "div",
6773
- {
6774
- className: "text-[13px] font-normal leading-relaxed drop-shadow-sm",
6775
- style: {
6776
- color: getTextColor(),
6777
- backgroundClip: "text"
6778
- },
6779
- children: message
6780
- }
6781
- )
6782
- ] }),
6783
- /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "relative z-10", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(CloseButton, { closeToast: handleClose }) })
6784
- ] });
6785
- };
6786
- var defaultToastOptions = {
6787
- position: "bottom-right",
6788
- autoClose: 3e3,
6789
- hideProgressBar: true,
6790
- closeOnClick: false,
6791
- pauseOnHover: true,
6792
- draggable: true,
6793
- pauseOnFocusLoss: false,
6794
- theme: "dark",
6795
- transition: import_react_toastify2.Bounce
6796
- };
6797
- var createToast = (type) => {
6798
- return (params) => {
6799
- const { title, message, component, options } = params;
6800
- (0, import_react_toastify2.toast)(
6801
- ({ closeToast }) => {
6802
- if (params.render) return params.render(closeToast);
6803
- return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
6804
- ToastContent,
6805
- {
6806
- type,
6807
- title,
6808
- message: message || "",
6809
- component,
6810
- closeToast
7005
+ }
7006
+ if (includeHash && url.hash) {
7007
+ const raw = url.hash.slice(1);
7008
+ if (raw.includes("=")) {
7009
+ const hp = new URLSearchParams(raw);
7010
+ let changed = false;
7011
+ for (const [k] of hp) {
7012
+ if (clearAll || sens.includes(k.toLowerCase())) {
7013
+ hp.delete(k);
7014
+ changed = true;
6811
7015
  }
6812
- );
6813
- },
6814
- {
6815
- ...defaultToastOptions,
6816
- ...options,
6817
- // 确保圆角样式不被覆盖,添加 rounded-xl 类
6818
- className: "!p-0 !shadow-none !rounded-xl",
6819
- style: { padding: 0, borderRadius: "0.75rem" }
6820
- }
6821
- );
6822
- };
6823
- };
6824
- var ClayxToast = {
6825
- success: createToast("success"),
6826
- error: createToast("error"),
6827
- warning: createToast("warning"),
6828
- info: createToast("info"),
6829
- default: createToast("default")
6830
- };
6831
-
6832
- // src/components/ui/LimitUpgradeToast.tsx
6833
- var import_jsx_runtime13 = require("react/jsx-runtime");
6834
- var LimitToastContainer = ({ message, onUpgrade, closeToast }) => {
6835
- return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "relative w-full max-w-[420px] overflow-hidden rounded-md bg-gradient-to-br from-[#1A1A1A] via-[#151515] to-[#1A1A1A] shadow-[0_20px_60px_rgba(168,85,247,0.2)] backdrop-blur-sm", children: [
6836
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6837
- "div",
6838
- {
6839
- className: "absolute left-0 top-0 w-full h-full rounded-md",
6840
- style: {
6841
- background: "#0f1419",
6842
- zIndex: -2
6843
7016
  }
6844
- }
6845
- ),
6846
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6847
- "div",
6848
- {
6849
- className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-md",
6850
- style: {
6851
- background: `linear-gradient(135deg, rgba(168,85,247,0.3) 0%, rgba(168,85,247,0.2) 15%, #1A1A1A 30%)`,
6852
- zIndex: -1
7017
+ if (changed) {
7018
+ const hs = hp.toString();
7019
+ url.hash = hs ? `#${hs}` : "";
6853
7020
  }
6854
- }
6855
- ),
6856
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6857
- "div",
6858
- {
6859
- className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-md",
6860
- style: {
6861
- border: "2px solid transparent",
6862
- backgroundImage: `linear-gradient(135deg, rgba(168,85,247,0.6) 0%, rgba(168,85,247,0.4) 5%, transparent 22%)`,
6863
- backgroundOrigin: "border-box",
6864
- backgroundClip: "border-box",
6865
- WebkitMask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6866
- WebkitMaskComposite: "xor",
6867
- mask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6868
- maskComposite: "exclude"
7021
+ } else {
7022
+ if (!clearAll && sens.some((p) => raw.toLowerCase().startsWith(p))) {
7023
+ url.hash = "";
7024
+ } else if (clearAll) {
7025
+ url.hash = "";
6869
7026
  }
6870
7027
  }
6871
- ),
6872
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "absolute -top-16 -right-16 h-32 w-32 rounded-full bg-gradient-to-br from-purple-500/20 via-pink-500/10 to-transparent blur-3xl animate-pulse" }),
6873
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "absolute -bottom-16 -left-16 h-32 w-32 rounded-full bg-gradient-to-tr from-blue-500/10 to-transparent blur-2xl animate-pulse", style: { animationDelay: "1s" } }),
6874
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "relative z-10 flex items-start gap-4 p-4", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "flex flex-1 flex-col gap-3", children: [
6875
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "flex items-center justify-between", children: [
6876
- /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("div", { className: "flex items-center gap-2", children: [
6877
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "text-lg font-bold bg-gradient-to-r from-white to-gray-400 bg-clip-text text-transparent", children: "Upgrade Required" }),
6878
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "px-2 py-0.5 text-xs font-bold bg-purple-500/20 text-purple-400 rounded-md border border-purple-500/30", children: "Premium" })
6879
- ] }),
6880
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6881
- ClayxButton,
6882
- {
6883
- onClick: closeToast,
6884
- isIconOnly: true,
6885
- size: "sm",
6886
- className: "h-6 w-6 min-w-6 rounded-full bg-white/5 hover:bg-white/10 transition-colors",
6887
- children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react13.Icon, { icon: "iconamoon:close", className: "w-4 h-4 text-gray-400" })
6888
- }
6889
- )
6890
- ] }),
6891
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("p", { className: "text-sm text-gray-300 leading-relaxed", children: message }),
6892
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)("div", { className: "mt-1 flex items-center gap-3", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
6893
- ClayxButton,
6894
- {
6895
- onClick: () => {
6896
- onUpgrade();
6897
- closeToast?.();
6898
- },
6899
- className: "flex-1 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold transition-all duration-300 hover:shadow-lg hover:shadow-purple-500/30 cursor-pointer",
6900
- style: { cursor: "pointer" },
6901
- children: /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)("span", { className: "flex items-center gap-2", children: [
6902
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react13.Icon, { icon: "solar:rocket-2-bold", className: "w-4 h-4" }),
6903
- "Upgrade Now"
6904
- ] })
7028
+ }
7029
+ const next = url.pathname + url.search + url.hash;
7030
+ if (next !== window.location.pathname + window.location.search + window.location.hash) {
7031
+ window.history.replaceState(window.history.state, document.title, next);
7032
+ onChanged && onChanged(next);
7033
+ }
7034
+ } catch (e) {
7035
+ console.warn("[howone][urlSanitizer] failed", e);
7036
+ }
7037
+ }
7038
+
7039
+ // src/services/index.ts
7040
+ function getGlobalAvailableToken() {
7041
+ try {
7042
+ return getToken() || null;
7043
+ } catch {
7044
+ return null;
7045
+ }
7046
+ }
7047
+ function wrapRequestWithProjectPrefix(biz, projectId) {
7048
+ if (!projectId) return biz;
7049
+ const prefix = `/entities/apps/${String(projectId)}`;
7050
+ function shouldPrefix(url) {
7051
+ if (!url) return false;
7052
+ const u = String(url);
7053
+ if (u.startsWith(prefix)) return false;
7054
+ if (/^https?:\/\//.test(u) || u.startsWith("//")) return false;
7055
+ if (u.startsWith("/data")) return true;
7056
+ return false;
7057
+ }
7058
+ const wrapped = {
7059
+ instance: biz.instance,
7060
+ request: (config) => {
7061
+ try {
7062
+ if (config && typeof config.url === "string" && shouldPrefix(config.url)) {
7063
+ config = { ...config, url: `${prefix}${config.url}` };
6905
7064
  }
6906
- ) })
6907
- ] }) })
6908
- ] });
6909
- };
6910
- function showLimitUpgradeToast(message, onUpgrade) {
6911
- ClayxToast.default({
6912
- render: (closeToast) => /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(LimitToastContainer, { message, onUpgrade, closeToast }),
6913
- options: {
6914
- position: "bottom-right",
6915
- closeOnClick: false,
6916
- autoClose: false,
6917
- hideProgressBar: true,
6918
- draggable: false,
6919
- pauseOnHover: true,
6920
- className: "!bg-transparent !shadow-none",
6921
- style: {
6922
- background: "transparent",
6923
- padding: 0,
6924
- width: "auto",
6925
- maxWidth: "420px"
7065
+ } catch (_e) {
6926
7066
  }
6927
- }
6928
- });
7067
+ return biz.request(config);
7068
+ },
7069
+ get: (config) => wrapped.request({ ...config, method: "GET" }),
7070
+ post: (config) => wrapped.request({ ...config, method: "POST" }),
7071
+ put: (config) => wrapped.request({ ...config, method: "PUT" }),
7072
+ patch: (config) => wrapped.request({ ...config, method: "PATCH" }),
7073
+ delete: (config) => wrapped.request({ ...config, method: "DELETE" }),
7074
+ cancelRequest: (url) => biz.cancelRequest(url),
7075
+ cancelAllRequests: () => biz.cancelAllRequests()
7076
+ };
7077
+ return wrapped;
6929
7078
  }
6930
-
6931
- // src/services/ai-workflow.ts
6932
- var AIWorkflowClient = class {
6933
- constructor(options = {}) {
6934
- this.baseUrl = options.baseUrl?.replace(/\/+$/, "") || "";
6935
- this.apiKey = options.apiKey;
6936
- this.headers = { "Content-Type": "application/json", ...options.headers || {} };
6937
- this.fetchImpl = options.fetchImpl || fetch.bind(globalThis);
7079
+ function createClient(opts) {
7080
+ const envValue = opts.env || getGlobalEnvironment() || "prod";
7081
+ const env2 = setEnvironment(envValue);
7082
+ function makeRequestFromBase(base) {
7083
+ return new request_default({
7084
+ baseURL: base,
7085
+ timeout: 6e4,
7086
+ interceptors: {
7087
+ requestInterceptor: (config) => {
7088
+ config.headers = config.headers || {};
7089
+ if (!config.headers["Authorization"]) {
7090
+ const availableToken = getAvailableToken();
7091
+ if (availableToken) {
7092
+ config.headers["Authorization"] = `Bearer ${availableToken}`;
7093
+ }
7094
+ }
7095
+ return config;
7096
+ },
7097
+ requestInterceptorCatch: (err) => Promise.reject(err),
7098
+ responseInterceptor: (res) => {
7099
+ const data = res.data;
7100
+ if (data && data.status && data.status === 4003) {
7101
+ showLimitUpgradeToast(
7102
+ "Your credits are exhausted. Please upgrade your plan to continue generating projects.",
7103
+ () => window.open(`${getEnvs().AUTH_ROOT_VALUE}/price`, "_blank")
7104
+ );
7105
+ return res;
7106
+ }
7107
+ return res;
7108
+ },
7109
+ responseInterceptorCatch: (err) => Promise.reject(err)
7110
+ }
7111
+ });
6938
7112
  }
6939
- buildHeaders(extra) {
6940
- const h = { ...this.headers, ...extra || {} };
6941
- if (this.apiKey && !h["Authorization"]) {
6942
- h["Authorization"] = `Bearer ${this.apiKey}`;
6943
- }
6944
- return h;
7113
+ const biz = makeRequestFromBase(env2.baseUrl);
7114
+ const ai = makeRequestFromBase(env2.aiBaseUrl);
7115
+ const bizWrapped = wrapRequestWithProjectPrefix(biz, opts?.projectId);
7116
+ let token = null;
7117
+ function getAvailableToken() {
7118
+ return token || getGlobalAvailableToken();
6945
7119
  }
6946
- async safeJson(resp) {
6947
- try {
6948
- return await resp.json();
6949
- } catch (_e) {
6950
- return null;
7120
+ try {
7121
+ if (opts?.projectId) {
7122
+ setDefaultProjectId(String(opts.projectId));
6951
7123
  }
7124
+ } catch {
6952
7125
  }
6953
- /**
6954
- * 按 ID 执行工作流:POST {baseUrl}/workflow/{workflowId}/execute
6955
- * body: { input, options }
6956
- */
6957
- async executeWorkflow(workflowId, inputs, options) {
6958
- if (!this.baseUrl) {
6959
- throw new Error("AI workflow client requires a baseUrl (e.g. https://evoagentx-server.fly.dev)");
6960
- }
6961
- const url = `${this.baseUrl}/workflow/${workflowId}/execute`;
7126
+ function applyToken(t) {
6962
7127
  try {
6963
- const res = await this.fetchImpl(url, {
6964
- method: "POST",
6965
- headers: this.buildHeaders(),
6966
- body: JSON.stringify({ inputs, options })
6967
- });
6968
- const data = await this.safeJson(res);
6969
- if (!res.ok) {
6970
- return { success: false, error: data?.error || `HTTP ${res.status}` };
6971
- }
6972
- if (data && data.status && data.status === 4003) {
6973
- showLimitUpgradeToast(
6974
- "Your credits are exhausted. Please upgrade your plan to continue generating projects.",
6975
- () => window.open("https://clayx.ai/pricing", "_blank")
6976
- );
6977
- return null;
7128
+ try {
7129
+ if (biz && biz.instance) {
7130
+ if (t) biz.instance.defaults.headers.common["Authorization"] = `Bearer ${t}`;
7131
+ else delete biz.instance.defaults.headers.common["Authorization"];
7132
+ }
7133
+ if (ai && ai.instance) {
7134
+ if (t) ai.instance.defaults.headers.common["Authorization"] = `Bearer ${t}`;
7135
+ else delete ai.instance.defaults.headers.common["Authorization"];
7136
+ }
7137
+ } catch (_e) {
6978
7138
  }
6979
- return data || { success: true };
6980
- } catch (error) {
6981
- return { success: false, error: error instanceof Error ? error.message : "Network error" };
7139
+ } catch (_e) {
6982
7140
  }
6983
7141
  }
6984
- };
6985
- function createAIWorkflowClient(options = {}) {
6986
- return new AIWorkflowClient(options);
6987
- }
6988
- var aiWorkflow = createAIWorkflowClient({ baseUrl: "https://evoagentx-server" });
6989
-
6990
- // src/services/request/index.ts
6991
- var import_axios = __toESM(require("axios"));
6992
- var Request = class {
6993
- constructor(config) {
6994
- this.abortControllers = /* @__PURE__ */ new Map();
6995
- this.instance = import_axios.default.create({
6996
- ...config,
6997
- validateStatus: (status) => {
6998
- return status >= 200 && status < 300;
7142
+ const workflowRequestWrapped = {
7143
+ get: ai.get.bind(ai),
7144
+ post: (config) => {
7145
+ const modifiedConfig = { ...config };
7146
+ if (opts?.projectId && modifiedConfig.url) {
7147
+ const workflowPattern = /^\/?(?:workflow\/)?([^\/]+)\/execute/;
7148
+ const match = modifiedConfig.url.match(workflowPattern);
7149
+ if (match) {
7150
+ const workflowId = match[1];
7151
+ modifiedConfig.url = `/workflow/${opts.projectId}/${workflowId}/execute`;
7152
+ }
6999
7153
  }
7000
- });
7001
- this.interceptors = config.interceptors;
7002
- this.instance.interceptors.request.use(
7003
- this.interceptors?.requestInterceptor,
7004
- this.interceptors?.requestInterceptorCatch
7005
- );
7006
- this.instance.interceptors.response.use(
7007
- this.interceptors?.responseInterceptor,
7008
- this.interceptors?.responseInterceptorCatch
7009
- );
7010
- this.instance.interceptors.request.use(
7011
- (config2) => {
7012
- return config2;
7013
- },
7014
- (err) => {
7015
- return Promise.reject(err);
7154
+ return ai.post(modifiedConfig);
7155
+ },
7156
+ put: ai.put.bind(ai),
7157
+ delete: ai.delete.bind(ai),
7158
+ request: ai.request.bind(ai),
7159
+ cancelRequest: ai.cancelRequest?.bind(ai),
7160
+ cancelAllRequests: ai.cancelAllRequests?.bind(ai)
7161
+ };
7162
+ return {
7163
+ // expose projectId so consumers can read it from the client instance
7164
+ projectId: opts?.projectId ?? null,
7165
+ request: bizWrapped,
7166
+ aiRequest: ai,
7167
+ workflowRequest: workflowRequestWrapped,
7168
+ // artifact helpers using artifacts-client
7169
+ artifacts: createArtifactsClient(biz),
7170
+ me: async () => {
7171
+ try {
7172
+ const t = token ?? (opts?.auth?.getToken ? await opts.auth.getToken() : null) ?? getToken();
7173
+ if (!t) return null;
7174
+ return parseUserFromToken(t);
7175
+ } catch (_e2) {
7176
+ return null;
7016
7177
  }
7017
- );
7018
- this.instance.interceptors.response.use(
7019
- (res) => {
7020
- return res.data;
7178
+ },
7179
+ // auth helpers
7180
+ auth: {
7181
+ setToken: (t) => {
7182
+ token = t;
7183
+ applyToken(t);
7021
7184
  },
7022
- (err) => {
7023
- if (import_axios.default.isCancel(err)) {
7024
- return Promise.reject({
7025
- isCanceled: true,
7026
- message: "request canceled",
7027
- originalError: err
7028
- });
7029
- }
7030
- if (err.response?.data?.error) {
7031
- return Promise.reject(err.response.data.error);
7185
+ getToken: () => token,
7186
+ isAuthenticated: () => Boolean(token),
7187
+ // minimal login/logout stubs - consumers can override behavior
7188
+ login: (redirect) => {
7189
+ if (typeof window === "undefined") return;
7190
+ const loc = redirect || window.location.href;
7191
+ try {
7192
+ const root = env2.baseUrl;
7193
+ const authUrl = new URL("/auth", String(root));
7194
+ authUrl.searchParams.set("redirect_uri", String(loc));
7195
+ if (opts?.projectId) authUrl.searchParams.set("project_id", String(opts.projectId));
7196
+ window.location.href = authUrl.toString();
7197
+ } catch {
7198
+ const encoded = encodeURIComponent(String(loc));
7199
+ const pid = opts?.projectId ? `&project_id=${encodeURIComponent(String(opts.projectId))}` : "";
7200
+ const root = env2.baseUrl;
7201
+ window.location.href = `${root}/auth?redirect_uri=${encoded}${pid}`;
7032
7202
  }
7033
- return Promise.reject(err);
7034
- }
7035
- );
7036
- }
7037
- cancelRequest(url) {
7038
- this.abortControllers.forEach((controller, key) => {
7039
- if (key.includes(url)) {
7040
- controller.abort();
7041
- this.abortControllers.delete(key);
7203
+ },
7204
+ logout: () => {
7205
+ token = null;
7206
+ applyToken(null);
7042
7207
  }
7043
- });
7208
+ },
7209
+ sanitizeUrl: (o) => {
7210
+ if (typeof window === "undefined") return;
7211
+ removeSensitiveParamsFromUrl({
7212
+ clearAll: o?.clearAll,
7213
+ sensitiveParams: o?.sensitiveParams
7214
+ });
7215
+ }
7216
+ };
7217
+ }
7218
+
7219
+ // src/hooks/use-mobile.ts
7220
+ var React8 = __toESM(require("react"));
7221
+ var MOBILE_BREAKPOINT = 768;
7222
+ function useIsMobile() {
7223
+ const [isMobile, setIsMobile] = React8.useState(void 0);
7224
+ React8.useEffect(() => {
7225
+ const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
7226
+ const onChange = () => {
7227
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
7228
+ };
7229
+ mql.addEventListener("change", onChange);
7230
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
7231
+ return () => mql.removeEventListener("change", onChange);
7232
+ }, []);
7233
+ return !!isMobile;
7234
+ }
7235
+
7236
+ // src/hooks/use-debounce.ts
7237
+ var import_react14 = require("react");
7238
+ function useDebounce(value, delay) {
7239
+ const [debouncedValue, setDebouncedValue] = (0, import_react14.useState)(value);
7240
+ (0, import_react14.useEffect)(() => {
7241
+ const handler = setTimeout(() => {
7242
+ setDebouncedValue(value);
7243
+ }, delay);
7244
+ return () => {
7245
+ clearTimeout(handler);
7246
+ };
7247
+ }, [value, delay]);
7248
+ return debouncedValue;
7249
+ }
7250
+
7251
+ // src/utils/unified-error-handler/simple.ts
7252
+ var SimpleErrorHandler = class {
7253
+ constructor() {
7254
+ this.initialized = false;
7044
7255
  }
7045
- cancelAllRequests() {
7046
- this.abortControllers.forEach((controller) => {
7047
- controller.abort();
7256
+ // 使用明确赋值断言,因为在 init() 方法中会初始化
7257
+ /**
7258
+ * 初始化错误处理器
7259
+ */
7260
+ init() {
7261
+ if (this.initialized) return;
7262
+ this.sendMessage = createSimpleSendFunction({
7263
+ addTimestamp: false,
7264
+ // 简化版自己处理时间戳
7265
+ enableDebugLog: false
7048
7266
  });
7049
- this.abortControllers.clear();
7267
+ this.setupErrorListeners();
7268
+ this.setupCompatibility();
7269
+ this.initialized = true;
7270
+ console.log("[\u7B80\u5316\u9519\u8BEF\u5904\u7406] \u521D\u59CB\u5316\u5B8C\u6210");
7050
7271
  }
7051
- request(config) {
7052
- const controller = new AbortController();
7053
- const url = config.url || "";
7054
- const method = config.method || "GET";
7055
- const key = `${method}:${url}`;
7056
- this.abortControllers.set(key, controller);
7057
- config.signal = controller.signal;
7058
- return new Promise((resolve, reject) => {
7059
- if (config.interceptors?.requestInterceptor) {
7060
- config = config.interceptors.requestInterceptor(config);
7061
- }
7062
- this.instance.request(config).then((res) => {
7063
- this.abortControllers.delete(key);
7064
- if (config.interceptors?.responseInterceptor) {
7065
- res = config.interceptors.responseInterceptor(res);
7066
- }
7067
- resolve(res);
7068
- }).catch((err) => {
7069
- this.abortControllers.delete(key);
7070
- reject(err);
7272
+ /**
7273
+ * 设置错误监听器
7274
+ */
7275
+ setupErrorListeners() {
7276
+ window.addEventListener("error", (event) => {
7277
+ this.sendError(event.error || new Error(event.message), {
7278
+ filename: event.filename,
7279
+ lineno: event.lineno,
7280
+ colno: event.colno,
7281
+ type: "runtime"
7071
7282
  });
7072
7283
  });
7284
+ window.addEventListener("unhandledrejection", (event) => {
7285
+ const error = event.reason instanceof Error ? event.reason : new Error(String(event.reason));
7286
+ this.sendError(error, { type: "promise" });
7287
+ });
7073
7288
  }
7074
- get(config) {
7075
- return this.request({ ...config, method: "GET" });
7076
- }
7077
- post(config) {
7078
- return this.request({ ...config, method: "POST" });
7079
- }
7080
- delete(config) {
7081
- return this.request({ ...config, method: "DELETE" });
7289
+ /**
7290
+ * 设置兼容性函数
7291
+ */
7292
+ setupCompatibility() {
7293
+ window.__SEND_ERROR_TO_PARENT__ = (error, details) => {
7294
+ const errorObj = error instanceof Error ? error : new Error(String(error));
7295
+ this.sendError(errorObj, details);
7296
+ };
7082
7297
  }
7083
- put(config) {
7084
- return this.request({ ...config, method: "PUT" });
7298
+ /**
7299
+ * 发送错误到父窗口
7300
+ */
7301
+ sendError(error, details = {}) {
7302
+ const payload = {
7303
+ message: error.message,
7304
+ stack: error.stack,
7305
+ filename: details.filename || details.file,
7306
+ lineno: details.lineno || details.line,
7307
+ colno: details.colno || details.column,
7308
+ timestamp: Date.now(),
7309
+ type: details.type || "unknown",
7310
+ severity: "medium",
7311
+ // 简化版使用默认严重性级别
7312
+ details
7313
+ };
7314
+ try {
7315
+ this.sendMessage({
7316
+ type: "ERROR_EVENT",
7317
+ payload,
7318
+ timestamp: Date.now()
7319
+ });
7320
+ } catch (e) {
7321
+ const originalConsole = window.__originalConsole;
7322
+ if (originalConsole?.error) {
7323
+ originalConsole.error("[\u7B80\u5316\u9519\u8BEF\u5904\u7406] \u53D1\u9001\u5931\u8D25:", e);
7324
+ }
7325
+ }
7085
7326
  }
7086
- patch(config) {
7087
- return this.request({ ...config, method: "PATCH" });
7327
+ /**
7328
+ * 手动捕获错误
7329
+ */
7330
+ captureError(error, details) {
7331
+ this.sendError(error, details);
7088
7332
  }
7089
7333
  };
7090
- var request_default = Request;
7091
7334
 
7092
- // src/services/ai-workflow-axios.ts
7093
- function createAIWorkflowClientAxios(options = {}) {
7094
- const basePath = options.basePath ?? "/api";
7095
- const baseUrl = (options.baseUrl || "https://evoagentx-server.fly.dev").replace(/\/+$/, "");
7096
- const baseAPI = `${baseUrl}${basePath.startsWith("/") ? "" : "/"}${basePath}`.replace(/\/+$/, "");
7097
- const client = options.requestInstance || new request_default({
7098
- baseURL: baseAPI,
7099
- timeout: options.timeout ?? 6e4,
7100
- interceptors: {
7101
- requestInterceptor: (config) => {
7102
- config.headers = config.headers || {};
7103
- if (options.apiKey && !config.headers["Authorization"]) {
7104
- config.headers["Authorization"] = `Bearer ${options.apiKey}`;
7105
- }
7106
- if (options.headers) {
7107
- config.headers = { ...config.headers || {}, ...options.headers };
7108
- }
7109
- return config;
7110
- },
7111
- requestInterceptorCatch: (err) => Promise.reject(err),
7112
- responseInterceptor: (res) => res,
7113
- responseInterceptorCatch: (err) => Promise.reject(err)
7114
- }
7115
- });
7116
- return {
7117
- async executeWorkflow(workflowId, inputs, opts) {
7118
- const url = `${baseUrl}/workflow/${workflowId}/execute`;
7119
- const data = await client.post({ url, data: { inputs, options: opts } });
7120
- return data;
7121
- }
7122
- };
7123
- }
7335
+ // src/index.ts
7336
+ init_config();
7124
7337
 
7125
- // src/services/artifact-types.ts
7126
- function canAccessArtifact(a, ctx = {}) {
7127
- if (!a) return false;
7128
- if (a.visibility === "public") return true;
7129
- if (a.visibility === "project") {
7130
- if (ctx.projectId && a.projectId && ctx.projectId === a.projectId) return true;
7131
- if (ctx.tokenScopes && ctx.tokenScopes.includes("project:read")) return true;
7132
- return false;
7133
- }
7134
- if (a.visibility === "private") {
7135
- if (ctx.userId && a.ownerId && ctx.userId === a.ownerId) return true;
7136
- if (ctx.tokenScopes && (ctx.tokenScopes.includes("artifact:read:all") || ctx.tokenScopes.includes("admin"))) return true;
7137
- return false;
7338
+ // src/utils/iframe-navigation.ts
7339
+ function getNavState() {
7340
+ if (typeof window === "undefined") {
7341
+ return {
7342
+ navigationHistory: [],
7343
+ currentHistoryIndex: -1,
7344
+ initialized: false
7345
+ };
7138
7346
  }
7139
- if (a.visibility === "shared") {
7140
- if (ctx.userId && a.sharedWith && a.sharedWith.includes(ctx.userId)) return true;
7141
- if (ctx.tokenScopes && (ctx.tokenScopes.includes("artifact:read:all") || ctx.tokenScopes.includes("admin"))) return true;
7142
- return false;
7347
+ if (!window.customNavigationState) {
7348
+ window.customNavigationState = {
7349
+ navigationHistory: [],
7350
+ currentHistoryIndex: -1,
7351
+ initialized: false
7352
+ };
7143
7353
  }
7144
- return false;
7354
+ return window.customNavigationState;
7145
7355
  }
7146
-
7147
- // src/services/artifacts-client.ts
7148
- function createArtifactsClient(req) {
7149
- return {
7150
- async create(input) {
7151
- return await req.post({ url: "/artifacts", data: input });
7152
- },
7153
- async list(query) {
7154
- return await req.get({ url: "/artifacts", params: query });
7155
- },
7156
- async get(id) {
7157
- return await req.get({ url: `/artifacts/${encodeURIComponent(id)}` });
7158
- },
7159
- async setVisibility(id, visibility) {
7160
- await req.patch({ url: `/artifacts/${encodeURIComponent(id)}/visibility`, data: { visibility } });
7161
- },
7162
- async delete(id) {
7163
- await req.delete({ url: `/artifacts/${encodeURIComponent(id)}` });
7164
- },
7165
- // convenience local check (server is authoritative)
7166
- canAccessLocal(a, ctx) {
7167
- if (!a) return false;
7168
- if (a.visibility === "public") return true;
7169
- if (a.visibility === "project") return Boolean(ctx.projectId && a.projectId && ctx.projectId === a.projectId);
7170
- if (a.visibility === "private") return Boolean(ctx.userId && a.ownerId && ctx.userId === a.ownerId);
7171
- if (a.visibility === "shared") return Boolean(ctx.userId && a.sharedWith && a.sharedWith.includes(ctx.userId));
7172
- return false;
7173
- }
7174
- };
7356
+ function getElementSelectorState() {
7357
+ if (typeof window === "undefined") {
7358
+ return { active: false, callback: null };
7359
+ }
7360
+ if (!window.elementSelectorState) {
7361
+ window.elementSelectorState = {
7362
+ active: false,
7363
+ callback: null
7364
+ };
7365
+ }
7366
+ return window.elementSelectorState;
7175
7367
  }
7176
-
7177
- // src/services/index.ts
7178
- init_auth();
7179
- init_config();
7180
- init_config();
7181
- init_auth();
7182
-
7183
- // src/utils/urlSanitizer.ts
7184
- var DEFAULT_SENSITIVE = ["token", "access_token", "auth", "auth_token"];
7185
- function removeSensitiveParamsFromUrl(opts) {
7186
- if (typeof window === "undefined") return;
7187
- try {
7188
- const { clearAll, sensitiveParams, includeHash = true, onChanged } = opts || {};
7189
- const sens = (sensitiveParams && sensitiveParams.length > 0 ? sensitiveParams : DEFAULT_SENSITIVE).map((s) => s.toLowerCase());
7190
- const before = window.location.href;
7191
- const url = new URL(before);
7192
- if (clearAll) {
7193
- url.search = "";
7194
- } else if (url.search) {
7195
- let changed = false;
7196
- for (const [k] of url.searchParams) {
7197
- if (sens.includes(k.toLowerCase())) {
7198
- url.searchParams.delete(k);
7199
- changed = true;
7200
- }
7201
- }
7202
- if (changed) {
7203
- const qs = url.searchParams.toString();
7204
- url.search = qs ? `?${qs}` : "";
7205
- }
7368
+ function sendNavigationState(targetWindow, targetOrigin) {
7369
+ const navState = getNavState();
7370
+ const canGoBack = navState.currentHistoryIndex > 0;
7371
+ const canGoForward = navState.currentHistoryIndex < navState.navigationHistory.length - 1;
7372
+ const state = {
7373
+ type: "NAVIGATION_STATE",
7374
+ payload: {
7375
+ canGoBack,
7376
+ canGoForward,
7377
+ historyLength: navState.navigationHistory.length,
7378
+ currentIndex: navState.currentHistoryIndex,
7379
+ maxIndex: navState.navigationHistory.length - 1
7206
7380
  }
7207
- if (includeHash && url.hash) {
7208
- const raw = url.hash.slice(1);
7209
- if (raw.includes("=")) {
7210
- const hp = new URLSearchParams(raw);
7211
- let changed = false;
7212
- for (const [k] of hp) {
7213
- if (clearAll || sens.includes(k.toLowerCase())) {
7214
- hp.delete(k);
7215
- changed = true;
7216
- }
7217
- }
7218
- if (changed) {
7219
- const hs = hp.toString();
7220
- url.hash = hs ? `#${hs}` : "";
7221
- }
7222
- } else {
7223
- if (!clearAll && sens.some((p) => raw.toLowerCase().startsWith(p))) {
7224
- url.hash = "";
7225
- } else if (clearAll) {
7226
- url.hash = "";
7227
- }
7381
+ };
7382
+ if (targetWindow && targetOrigin) {
7383
+ try {
7384
+ targetWindow.postMessage(state, targetOrigin);
7385
+ } catch (e) {
7386
+ if (typeof console !== "undefined" && console.warn) {
7387
+ console.warn("Failed to send navigation state:", e.message);
7228
7388
  }
7229
7389
  }
7230
- const next = url.pathname + url.search + url.hash;
7231
- if (next !== window.location.pathname + window.location.search + window.location.hash) {
7232
- window.history.replaceState(window.history.state, document.title, next);
7233
- onChanged && onChanged(next);
7234
- }
7235
- } catch (e) {
7236
- console.warn("[howone][urlSanitizer] failed", e);
7237
7390
  }
7238
7391
  }
7239
-
7240
- // src/services/index.ts
7241
- function getGlobalAvailableToken() {
7242
- try {
7243
- return getToken() || null;
7244
- } catch {
7245
- return null;
7392
+ function addToNavigationHistory(url, title) {
7393
+ const navState = getNavState();
7394
+ if (navState.currentHistoryIndex < navState.navigationHistory.length - 1) {
7395
+ navState.navigationHistory = navState.navigationHistory.slice(
7396
+ 0,
7397
+ navState.currentHistoryIndex + 1
7398
+ );
7246
7399
  }
7247
- }
7248
- function wrapRequestWithProjectPrefix(biz, projectId) {
7249
- if (!projectId) return biz;
7250
- const prefix = `/entities/apps/${String(projectId)}`;
7251
- function shouldPrefix(url) {
7252
- if (!url) return false;
7253
- const u = String(url);
7254
- if (u.startsWith(prefix)) return false;
7255
- if (/^https?:\/\//.test(u) || u.startsWith("//")) return false;
7256
- if (u.startsWith("/data")) return true;
7257
- return false;
7400
+ const currentPage = navState.navigationHistory[navState.currentHistoryIndex];
7401
+ if (currentPage && currentPage.url === url) {
7402
+ return;
7258
7403
  }
7259
- const wrapped = {
7260
- instance: biz.instance,
7261
- request: (config) => {
7262
- try {
7263
- if (config && typeof config.url === "string" && shouldPrefix(config.url)) {
7264
- config = { ...config, url: `${prefix}${config.url}` };
7265
- }
7266
- } catch (_e) {
7267
- }
7268
- return biz.request(config);
7269
- },
7270
- get: (config) => wrapped.request({ ...config, method: "GET" }),
7271
- post: (config) => wrapped.request({ ...config, method: "POST" }),
7272
- put: (config) => wrapped.request({ ...config, method: "PUT" }),
7273
- patch: (config) => wrapped.request({ ...config, method: "PATCH" }),
7274
- delete: (config) => wrapped.request({ ...config, method: "DELETE" }),
7275
- cancelRequest: (url) => biz.cancelRequest(url),
7276
- cancelAllRequests: () => biz.cancelAllRequests()
7404
+ const pageInfo = {
7405
+ url,
7406
+ title: title || (typeof document !== "undefined" ? document.title : "") || url,
7407
+ timestamp: Date.now()
7277
7408
  };
7278
- return wrapped;
7279
- }
7280
- function createClient(opts) {
7281
- const envValue = opts.env || getGlobalEnvironment() || "prod";
7282
- const env2 = setEnvironment(envValue);
7283
- function makeRequestFromBase(base) {
7284
- return new request_default({
7285
- baseURL: base,
7286
- timeout: 6e4,
7287
- interceptors: {
7288
- requestInterceptor: (config) => {
7289
- config.headers = config.headers || {};
7290
- if (!config.headers["Authorization"]) {
7291
- const availableToken = getAvailableToken();
7292
- if (availableToken) {
7293
- config.headers["Authorization"] = `Bearer ${availableToken}`;
7294
- }
7295
- }
7296
- return config;
7297
- },
7298
- requestInterceptorCatch: (err) => Promise.reject(err),
7299
- responseInterceptor: (res) => {
7300
- const data = res.data;
7301
- if (data && data.status && data.status === 4003) {
7302
- showLimitUpgradeToast(
7303
- "Your credits are exhausted. Please upgrade your plan to continue generating projects.",
7304
- () => window.open(`${getEnvs().AUTH_ROOT_VALUE}/price`, "_blank")
7305
- );
7306
- return res;
7307
- }
7308
- return res;
7309
- },
7310
- responseInterceptorCatch: (err) => Promise.reject(err)
7311
- }
7312
- });
7409
+ navState.navigationHistory.push(pageInfo);
7410
+ navState.currentHistoryIndex = navState.navigationHistory.length - 1;
7411
+ if (typeof window !== "undefined" && window.parent && window.parent !== window) {
7412
+ sendNavigationState(window.parent, "*");
7313
7413
  }
7314
- const biz = makeRequestFromBase(env2.baseUrl);
7315
- const ai = makeRequestFromBase(env2.aiBaseUrl);
7316
- const bizWrapped = wrapRequestWithProjectPrefix(biz, opts?.projectId);
7317
- let token = null;
7318
- function getAvailableToken() {
7319
- return token || getGlobalAvailableToken();
7414
+ }
7415
+ function customGoBack() {
7416
+ const navState = getNavState();
7417
+ if (navState.currentHistoryIndex > 0) {
7418
+ navState.currentHistoryIndex--;
7419
+ if (typeof window !== "undefined" && window.parent && window.parent !== window) {
7420
+ sendNavigationState(window.parent, "*");
7421
+ }
7422
+ return true;
7320
7423
  }
7321
- try {
7322
- if (opts?.projectId) {
7323
- setDefaultProjectId(String(opts.projectId));
7424
+ return false;
7425
+ }
7426
+ function customGoForward() {
7427
+ const navState = getNavState();
7428
+ if (navState.currentHistoryIndex < navState.navigationHistory.length - 1) {
7429
+ navState.currentHistoryIndex++;
7430
+ if (typeof window !== "undefined" && window.parent && window.parent !== window) {
7431
+ sendNavigationState(window.parent, "*");
7324
7432
  }
7325
- } catch {
7433
+ return true;
7326
7434
  }
7327
- function applyToken(t) {
7435
+ return false;
7436
+ }
7437
+ function triggerElementSelection() {
7438
+ if (typeof window === "undefined") return;
7439
+ const event = new CustomEvent("howone:start-element-selection");
7440
+ window.dispatchEvent(event);
7441
+ getElementSelectorState().active = true;
7442
+ }
7443
+ function cancelElementSelection() {
7444
+ if (typeof window === "undefined") return;
7445
+ const event = new CustomEvent("howone:cancel-element-selection");
7446
+ window.dispatchEvent(event);
7447
+ getElementSelectorState().active = false;
7448
+ }
7449
+ function handlePageChange() {
7450
+ if (typeof window === "undefined") return;
7451
+ const currentUrl = window.location.href;
7452
+ const currentTitle = document.title;
7453
+ addToNavigationHistory(currentUrl, currentTitle);
7454
+ }
7455
+ function initIframeNavigation() {
7456
+ if (typeof window === "undefined") return;
7457
+ const navState = getNavState();
7458
+ window.addEventListener("keydown", function(e) {
7459
+ if (e.key === "Escape" && getElementSelectorState().active) {
7460
+ cancelElementSelection();
7461
+ }
7462
+ });
7463
+ window.addEventListener("message", (event) => {
7328
7464
  try {
7329
- try {
7330
- if (biz && biz.instance) {
7331
- if (t) biz.instance.defaults.headers.common["Authorization"] = `Bearer ${t}`;
7332
- else delete biz.instance.defaults.headers.common["Authorization"];
7333
- }
7334
- if (ai && ai.instance) {
7335
- if (t) ai.instance.defaults.headers.common["Authorization"] = `Bearer ${t}`;
7336
- else delete ai.instance.defaults.headers.common["Authorization"];
7337
- }
7338
- } catch (_e) {
7465
+ const { type, payload } = event.data;
7466
+ switch (type) {
7467
+ case "NAVIGATE_BACK":
7468
+ case "GO_BACK":
7469
+ customGoBack();
7470
+ break;
7471
+ case "NAVIGATE_FORWARD":
7472
+ case "GO_FORWARD":
7473
+ customGoForward();
7474
+ break;
7475
+ case "REQUEST_NAVIGATION_STATE":
7476
+ case "CHECK_NAVIGATION_STATE":
7477
+ sendNavigationState(event.source, event.origin);
7478
+ break;
7479
+ case "START_ELEMENT_SELECTION":
7480
+ triggerElementSelection();
7481
+ break;
7482
+ case "ELEMENT_SELECTED":
7483
+ if (event.source && event.source !== window) {
7484
+ window.parent.postMessage(
7485
+ {
7486
+ type: "ELEMENT_SELECTED",
7487
+ payload
7488
+ },
7489
+ "*"
7490
+ );
7491
+ }
7492
+ break;
7493
+ case "CANCEL_ELEMENT_SELECTION":
7494
+ cancelElementSelection();
7495
+ break;
7496
+ }
7497
+ } catch (e) {
7498
+ }
7499
+ });
7500
+ window.addEventListener("popstate", () => {
7501
+ setTimeout(() => {
7502
+ if (window.parent && window.parent !== window) {
7503
+ sendNavigationState(window.parent, "*");
7504
+ }
7505
+ }, 50);
7506
+ });
7507
+ window.addEventListener("hashchange", () => {
7508
+ handlePageChange();
7509
+ });
7510
+ window.addEventListener("load", () => {
7511
+ if (!navState.initialized) {
7512
+ addToNavigationHistory(window.location.href, document.title);
7513
+ navState.initialized = true;
7514
+ }
7515
+ setTimeout(() => {
7516
+ if (window.parent && window.parent !== window) {
7517
+ sendNavigationState(window.parent, "*");
7518
+ }
7519
+ }, 500);
7520
+ });
7521
+ if (document.readyState === "loading") {
7522
+ document.addEventListener("DOMContentLoaded", () => {
7523
+ if (!navState.initialized) {
7524
+ addToNavigationHistory(window.location.href, document.title);
7525
+ navState.initialized = true;
7339
7526
  }
7340
- } catch (_e) {
7341
- }
7527
+ });
7528
+ } else if (!navState.initialized) {
7529
+ addToNavigationHistory(window.location.href, document.title);
7530
+ navState.initialized = true;
7342
7531
  }
7343
- const workflowRequestWrapped = {
7344
- get: ai.get.bind(ai),
7345
- post: (config) => {
7346
- const modifiedConfig = { ...config };
7347
- if (opts?.projectId && modifiedConfig.url) {
7348
- const workflowPattern = /^\/?(?:workflow\/)?([^\/]+)\/execute/;
7349
- const match = modifiedConfig.url.match(workflowPattern);
7350
- if (match) {
7351
- const workflowId = match[1];
7352
- modifiedConfig.url = `/workflow/${opts.projectId}/${workflowId}/execute`;
7353
- }
7354
- }
7355
- return ai.post(modifiedConfig);
7356
- },
7357
- put: ai.put.bind(ai),
7358
- delete: ai.delete.bind(ai),
7359
- request: ai.request.bind(ai),
7360
- cancelRequest: ai.cancelRequest?.bind(ai),
7361
- cancelAllRequests: ai.cancelAllRequests?.bind(ai)
7532
+ window.iframeElementSelector = {
7533
+ startSelection: function() {
7534
+ triggerElementSelection();
7535
+ }
7362
7536
  };
7363
- return {
7364
- // expose projectId so consumers can read it from the client instance
7365
- projectId: opts?.projectId ?? null,
7366
- request: bizWrapped,
7367
- aiRequest: ai,
7368
- workflowRequest: workflowRequestWrapped,
7369
- // artifact helpers using artifacts-client
7370
- artifacts: createArtifactsClient(biz),
7371
- me: async () => {
7372
- try {
7373
- const t = token ?? (opts?.auth?.getToken ? await opts.auth.getToken() : null) ?? getToken();
7374
- if (!t) return null;
7375
- return parseUserFromToken(t);
7376
- } catch (_e2) {
7377
- return null;
7378
- }
7537
+ window.iframeNavigation = {
7538
+ addPage: function(url, title) {
7539
+ addToNavigationHistory(
7540
+ url || window.location.href,
7541
+ title || document.title
7542
+ );
7379
7543
  },
7380
- // auth helpers
7381
- auth: {
7382
- setToken: (t) => {
7383
- token = t;
7384
- applyToken(t);
7385
- },
7386
- getToken: () => token,
7387
- isAuthenticated: () => Boolean(token),
7388
- // minimal login/logout stubs - consumers can override behavior
7389
- login: (redirect) => {
7390
- if (typeof window === "undefined") return;
7391
- const loc = redirect || window.location.href;
7392
- try {
7393
- const root = env2.baseUrl;
7394
- const authUrl = new URL("/auth", String(root));
7395
- authUrl.searchParams.set("redirect_uri", String(loc));
7396
- if (opts?.projectId) authUrl.searchParams.set("project_id", String(opts.projectId));
7397
- window.location.href = authUrl.toString();
7398
- } catch {
7399
- const encoded = encodeURIComponent(String(loc));
7400
- const pid = opts?.projectId ? `&project_id=${encodeURIComponent(String(opts.projectId))}` : "";
7401
- const root = env2.baseUrl;
7402
- window.location.href = `${root}/auth?redirect_uri=${encoded}${pid}`;
7403
- }
7404
- },
7405
- logout: () => {
7406
- token = null;
7407
- applyToken(null);
7408
- }
7544
+ getState: function() {
7545
+ return {
7546
+ canGoBack: navState.currentHistoryIndex > 0,
7547
+ canGoForward: navState.currentHistoryIndex < navState.navigationHistory.length - 1,
7548
+ historyLength: navState.navigationHistory.length,
7549
+ currentIndex: navState.currentHistoryIndex,
7550
+ currentPage: navState.navigationHistory[navState.currentHistoryIndex]
7551
+ };
7409
7552
  },
7410
- sanitizeUrl: (o) => {
7411
- if (typeof window === "undefined") return;
7412
- removeSensitiveParamsFromUrl({
7413
- clearAll: o?.clearAll,
7414
- sensitiveParams: o?.sensitiveParams
7415
- });
7553
+ updateState: function() {
7554
+ if (window.parent && window.parent !== window) {
7555
+ sendNavigationState(window.parent, "*");
7556
+ }
7416
7557
  }
7417
7558
  };
7418
7559
  }
7419
-
7420
- // src/hooks/use-mobile.ts
7421
- var React8 = __toESM(require("react"));
7422
- var MOBILE_BREAKPOINT = 768;
7423
- function useIsMobile() {
7424
- const [isMobile, setIsMobile] = React8.useState(void 0);
7425
- React8.useEffect(() => {
7426
- const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
7427
- const onChange = () => {
7428
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
7429
- };
7430
- mql.addEventListener("change", onChange);
7431
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
7432
- return () => mql.removeEventListener("change", onChange);
7433
- }, []);
7434
- return !!isMobile;
7435
- }
7436
-
7437
- // src/hooks/use-debounce.ts
7438
- var import_react14 = require("react");
7439
- function useDebounce(value, delay) {
7440
- const [debouncedValue, setDebouncedValue] = (0, import_react14.useState)(value);
7441
- (0, import_react14.useEffect)(() => {
7442
- const handler = setTimeout(() => {
7443
- setDebouncedValue(value);
7444
- }, delay);
7445
- return () => {
7446
- clearTimeout(handler);
7447
- };
7448
- }, [value, delay]);
7449
- return debouncedValue;
7450
- }
7451
-
7452
- // src/utils/unified-error-handler/simple.ts
7453
- var SimpleErrorHandler = class {
7454
- constructor() {
7455
- this.initialized = false;
7456
- }
7457
- // 使用明确赋值断言,因为在 init() 方法中会初始化
7560
+ var iframeNavigation = {
7458
7561
  /**
7459
- * 初始化错误处理器
7562
+ * Initialize the navigation system
7460
7563
  */
7461
- init() {
7462
- if (this.initialized) return;
7463
- this.sendMessage = createSimpleSendFunction({
7464
- addTimestamp: false,
7465
- // 简化版自己处理时间戳
7466
- enableDebugLog: false
7467
- });
7468
- this.setupErrorListeners();
7469
- this.setupCompatibility();
7470
- this.initialized = true;
7471
- console.log("[\u7B80\u5316\u9519\u8BEF\u5904\u7406] \u521D\u59CB\u5316\u5B8C\u6210");
7472
- }
7564
+ init: initIframeNavigation,
7473
7565
  /**
7474
- * 设置错误监听器
7566
+ * Add a page to navigation history
7475
7567
  */
7476
- setupErrorListeners() {
7477
- window.addEventListener("error", (event) => {
7478
- this.sendError(event.error || new Error(event.message), {
7479
- filename: event.filename,
7480
- lineno: event.lineno,
7481
- colno: event.colno,
7482
- type: "runtime"
7483
- });
7484
- });
7485
- window.addEventListener("unhandledrejection", (event) => {
7486
- const error = event.reason instanceof Error ? event.reason : new Error(String(event.reason));
7487
- this.sendError(error, { type: "promise" });
7488
- });
7489
- }
7568
+ addPage: (url, title) => {
7569
+ if (typeof window === "undefined") return;
7570
+ addToNavigationHistory(
7571
+ url || window.location.href,
7572
+ title || (typeof document !== "undefined" ? document.title : "")
7573
+ );
7574
+ },
7490
7575
  /**
7491
- * 设置兼容性函数
7576
+ * Get current navigation state
7492
7577
  */
7493
- setupCompatibility() {
7494
- window.__SEND_ERROR_TO_PARENT__ = (error, details) => {
7495
- const errorObj = error instanceof Error ? error : new Error(String(error));
7496
- this.sendError(errorObj, details);
7578
+ getState: () => {
7579
+ const navState = getNavState();
7580
+ return {
7581
+ canGoBack: navState.currentHistoryIndex > 0,
7582
+ canGoForward: navState.currentHistoryIndex < navState.navigationHistory.length - 1,
7583
+ historyLength: navState.navigationHistory.length,
7584
+ currentIndex: navState.currentHistoryIndex,
7585
+ currentPage: navState.navigationHistory[navState.currentHistoryIndex]
7497
7586
  };
7498
- }
7587
+ },
7499
7588
  /**
7500
- * 发送错误到父窗口
7589
+ * Update navigation state (send to parent)
7501
7590
  */
7502
- sendError(error, details = {}) {
7503
- const payload = {
7504
- message: error.message,
7505
- stack: error.stack,
7506
- filename: details.filename || details.file,
7507
- lineno: details.lineno || details.line,
7508
- colno: details.colno || details.column,
7509
- timestamp: Date.now(),
7510
- type: details.type || "unknown",
7511
- severity: "medium",
7512
- // 简化版使用默认严重性级别
7513
- details
7514
- };
7515
- try {
7516
- this.sendMessage({
7517
- type: "ERROR_EVENT",
7518
- payload,
7519
- timestamp: Date.now()
7520
- });
7521
- } catch (e) {
7522
- const originalConsole = window.__originalConsole;
7523
- if (originalConsole?.error) {
7524
- originalConsole.error("[\u7B80\u5316\u9519\u8BEF\u5904\u7406] \u53D1\u9001\u5931\u8D25:", e);
7525
- }
7591
+ updateState: () => {
7592
+ if (typeof window !== "undefined" && window.parent && window.parent !== window) {
7593
+ sendNavigationState(window.parent, "*");
7526
7594
  }
7527
- }
7595
+ },
7528
7596
  /**
7529
- * 手动捕获错误
7597
+ * Go back in history
7530
7598
  */
7531
- captureError(error, details) {
7532
- this.sendError(error, details);
7533
- }
7599
+ goBack: customGoBack,
7600
+ /**
7601
+ * Go forward in history
7602
+ */
7603
+ goForward: customGoForward
7604
+ };
7605
+ var elementSelector = {
7606
+ /**
7607
+ * Start element selection mode
7608
+ */
7609
+ startSelection: triggerElementSelection,
7610
+ /**
7611
+ * Cancel element selection mode
7612
+ */
7613
+ cancel: cancelElementSelection,
7614
+ /**
7615
+ * Check if selector is active
7616
+ */
7617
+ isActive: () => getElementSelectorState().active
7534
7618
  };
7535
-
7536
- // src/index.ts
7537
- init_config();
7538
7619
  // Annotate the CommonJS export names for ESM import in node:
7539
7620
  0 && (module.exports = {
7540
7621
  AUTH_TOKEN_KEY,