@lowdefy/server-dev 0.0.0-experimental-20260720072521 → 0.0.0-experimental-20260720135014

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.
Files changed (196) hide show
  1. package/.eslintrc.yaml +1 -0
  2. package/lib/build/app.js +1 -8
  3. package/lib/build/appMeta.js +1 -8
  4. package/lib/build/auth.js +1 -8
  5. package/lib/build/config.js +1 -8
  6. package/lib/build/i18n.js +1 -8
  7. package/lib/build/logger.js +1 -8
  8. package/lib/build/theme.js +1 -8
  9. package/lib/client/App.js +80 -0
  10. package/{client/Page.jsx → lib/client/Page.js} +5 -5
  11. package/{client/Reload.jsx → lib/client/Reload.js} +7 -5
  12. package/lib/client/auth/{Auth.jsx → Auth.js} +5 -12
  13. package/lib/client/auth/AuthConfigured.js +61 -0
  14. package/lib/client/auth/AuthNotConfigured.js +2 -22
  15. package/lib/client/setPageId.js +5 -6
  16. package/lib/client/utils/useMutateCache.js +1 -14
  17. package/lib/client/utils/usePageConfig.js +11 -31
  18. package/lib/server/apiWrapper.js +116 -0
  19. package/lib/server/auth/{getStrategies.js → getAuthOptions.js} +9 -14
  20. package/lib/server/auth/{getMockUser.js → getMockSession.js} +19 -10
  21. package/{src/routes/docs/checkpointsRevert.js → lib/server/auth/getServerSession.js} +13 -11
  22. package/lib/server/compileCss.js +39 -0
  23. package/lib/server/jitPageBuilder.js +11 -36
  24. package/lib/server/log/logRequest.js +3 -1
  25. package/manager/getContext.mjs +7 -3
  26. package/manager/processes/compileCss.mjs +54 -0
  27. package/manager/processes/initialBuild.mjs +2 -0
  28. package/manager/processes/installPlugins.mjs +11 -19
  29. package/manager/processes/lowdefyBuild.mjs +7 -29
  30. package/manager/processes/nextBuild.mjs +50 -0
  31. package/manager/processes/readDotEnv.mjs +1 -13
  32. package/manager/processes/shutdownServer.mjs +6 -6
  33. package/manager/processes/startServer.mjs +7 -8
  34. package/manager/processes/startWatchers.mjs +2 -2
  35. package/manager/run.mjs +0 -41
  36. package/manager/utils/createCustomPluginMessagesMap.mjs +1 -8
  37. package/manager/utils/createCustomPluginTypesMap.mjs +2 -3
  38. package/manager/utils/{getViteBin.mjs → getNextBin.mjs} +10 -7
  39. package/manager/utils/updatePageTailwindCss.mjs +1 -7
  40. package/manager/watchers/lowdefyBuildWatcher.mjs +1 -0
  41. package/manager/watchers/moduleBuildWatcher.mjs +1 -0
  42. package/manager/watchers/{serverArtifactWatcher.mjs → nextBuildWatcher.mjs} +22 -18
  43. package/next.config.js +25 -0
  44. package/package.json +47 -63
  45. package/package.original.json +55 -66
  46. package/{src/routes/devTools.js → pages/404.js} +2 -4
  47. package/{src/routes/docs/appMap.js → pages/[[...pageId]].js} +2 -6
  48. package/{client/App.jsx → pages/_app.js} +33 -21
  49. package/pages/_document.js +107 -0
  50. package/pages/api/agent/[...path].js +86 -0
  51. package/pages/api/auth/[...nextauth].js +48 -0
  52. package/pages/api/client-error.js +45 -0
  53. package/{src/routes/docs/buildStatus.js → pages/api/dev-tools.js} +4 -5
  54. package/{lib/docs/clientErrorStore.js → pages/api/endpoints/[...endpointId].js} +11 -15
  55. package/{src/lib/serveBuildJs.js → pages/api/icons/dynamic.js} +12 -8
  56. package/{src/routes/jsEnv.js → pages/api/js/[env].js} +20 -8
  57. package/pages/api/page/[...pageId].js +74 -0
  58. package/{src/routes → pages/api}/ping.js +2 -4
  59. package/pages/api/reload.js +53 -0
  60. package/pages/api/request/[...path].js +41 -0
  61. package/{src/routes → pages/api}/root.js +4 -4
  62. package/client/Inspector.jsx +0 -206
  63. package/client/Routing.jsx +0 -106
  64. package/client/feedback/FeedbackMount.jsx +0 -83
  65. package/client/feedback/FeedbackOverlay.jsx +0 -901
  66. package/client/feedback/captureTabScreenshot.js +0 -84
  67. package/client/feedback/copyToClipboard.js +0 -45
  68. package/client/feedback/drawAnnotationsSvg.js +0 -119
  69. package/client/feedback/elementInspect.js +0 -99
  70. package/client/feedback/feedbackStyles.js +0 -301
  71. package/client/feedback/pinResponsiveImages.js +0 -59
  72. package/client/feedback/sendFeedback.js +0 -39
  73. package/client/feedback/useFeedbackToggle.js +0 -70
  74. package/client/main.jsx +0 -42
  75. package/client/openInEditor/OpenInEditorListener.jsx +0 -261
  76. package/client/openInEditor/findBlockLocation.js +0 -51
  77. package/lib/client/auth/AuthConfigured.jsx +0 -155
  78. package/lib/docs/captureAnnotatedScreenshot.js +0 -88
  79. package/lib/docs/checkpointPaths.js +0 -91
  80. package/lib/docs/checkpointStore.js +0 -234
  81. package/lib/docs/checkpointToMocks.js +0 -65
  82. package/lib/docs/configCheckpoints.test.mjs +0 -156
  83. package/lib/docs/createConfigCheckpoint.js +0 -92
  84. package/lib/docs/createDocsMcpServer.js +0 -506
  85. package/lib/docs/createDocsMcpServer.test.mjs +0 -123
  86. package/lib/docs/devMockRegistry.js +0 -68
  87. package/lib/docs/docs.test.mjs +0 -448
  88. package/lib/docs/enrichFeedback.js +0 -71
  89. package/lib/docs/evalOperator.js +0 -39
  90. package/lib/docs/evalOperator.test.mjs +0 -112
  91. package/lib/docs/evalOperatorHeadless.js +0 -87
  92. package/lib/docs/evalOperatorHeadless.test.mjs +0 -72
  93. package/lib/docs/evalOperatorInTab.js +0 -48
  94. package/lib/docs/findConfig.js +0 -260
  95. package/lib/docs/formatFeedback.js +0 -121
  96. package/lib/docs/formatFeedback.test.mjs +0 -204
  97. package/lib/docs/getAppMap.js +0 -180
  98. package/lib/docs/getBrowser.js +0 -115
  99. package/lib/docs/getBuildStatus.js +0 -37
  100. package/lib/docs/getCoreDoc.js +0 -63
  101. package/lib/docs/getDocsManifest.js +0 -40
  102. package/lib/docs/getExamples.js +0 -58
  103. package/lib/docs/getOverview.js +0 -115
  104. package/lib/docs/getPageConfig.js +0 -53
  105. package/lib/docs/getPluginDoc.js +0 -55
  106. package/lib/docs/getSchema.js +0 -65
  107. package/lib/docs/inspectState.js +0 -41
  108. package/lib/docs/inspectState.test.mjs +0 -91
  109. package/lib/docs/inspectStateFromTab.js +0 -40
  110. package/lib/docs/inspectStateHeadless.js +0 -84
  111. package/lib/docs/inspectStateHeadless.test.mjs +0 -60
  112. package/lib/docs/isWriteRequestsAllowed.js +0 -50
  113. package/lib/docs/listConfigCheckpoints.js +0 -55
  114. package/lib/docs/listPlugins.js +0 -80
  115. package/lib/docs/listTypes.js +0 -105
  116. package/lib/docs/loadState.js +0 -139
  117. package/lib/docs/mapPageBuildErrors.js +0 -28
  118. package/lib/docs/normalizeTypeKind.js +0 -40
  119. package/lib/docs/readBuildArtifact.js +0 -35
  120. package/lib/docs/readPageArtifact.js +0 -26
  121. package/lib/docs/resolvePluginDir.js +0 -49
  122. package/lib/docs/revertConfigCheckpoint.js +0 -73
  123. package/lib/docs/runRequest.js +0 -141
  124. package/lib/docs/saveAnnotatedScreenshot.js +0 -43
  125. package/lib/docs/scaffoldPage.js +0 -75
  126. package/lib/docs/scaffoldPage.test.mjs +0 -97
  127. package/lib/docs/screenshotPage.js +0 -109
  128. package/lib/docs/screenshotPage.test.mjs +0 -59
  129. package/lib/docs/screenshotPageClip.test.mjs +0 -102
  130. package/lib/docs/searchDocs.js +0 -67
  131. package/lib/docs/setupTestFixtures.mjs +0 -335
  132. package/lib/docs/snapshotState.js +0 -59
  133. package/lib/docs/stateCheckpoints.test.mjs +0 -348
  134. package/lib/docs/tabAvailable.js +0 -28
  135. package/lib/docs/tabChannel.js +0 -119
  136. package/lib/docs/tabChannel.test.mjs +0 -130
  137. package/lib/server/auth/createSystemContext.js +0 -70
  138. package/lib/server/auth/getAuth.js +0 -46
  139. package/lib/server/auth/getHeadlessUser.js +0 -39
  140. package/lib/server/auth/headlessUser.js +0 -30
  141. package/lib/server/createLowdefyContext.js +0 -133
  142. package/lib/server/loadDynamicJsMap.js +0 -47
  143. package/manager/processes/lowdefyBuild.test.mjs +0 -102
  144. package/manager/utils/formatNoticeBox.mjs +0 -30
  145. package/manager/utils/writeBuildStatus.mjs +0 -39
  146. package/manager/utils/writeBuildStatus.test.mjs +0 -76
  147. package/postcss.config.cjs +0 -1
  148. package/src/app.js +0 -188
  149. package/src/html/renderDevPage.js +0 -86
  150. package/src/lib/getPathSegments.js +0 -25
  151. package/src/lib/safeScriptJson.js +0 -38
  152. package/src/middleware/apiContext.js +0 -32
  153. package/src/middleware/errorHandler.js +0 -55
  154. package/src/routes/agent.js +0 -64
  155. package/src/routes/auth.js +0 -43
  156. package/src/routes/clientError.js +0 -57
  157. package/src/routes/cron.js +0 -44
  158. package/src/routes/detached.js +0 -51
  159. package/src/routes/devInspect.js +0 -94
  160. package/src/routes/docs/checkpointsCreate.js +0 -28
  161. package/src/routes/docs/checkpointsList.js +0 -23
  162. package/src/routes/docs/content.js +0 -31
  163. package/src/routes/docs/evalOperator.js +0 -46
  164. package/src/routes/docs/examples.js +0 -33
  165. package/src/routes/docs/find.js +0 -30
  166. package/src/routes/docs/index.js +0 -23
  167. package/src/routes/docs/inspectState.js +0 -34
  168. package/src/routes/docs/loadState.js +0 -38
  169. package/src/routes/docs/mcp.js +0 -30
  170. package/src/routes/docs/pageConfig.js +0 -36
  171. package/src/routes/docs/pluginDoc.js +0 -33
  172. package/src/routes/docs/plugins.js +0 -23
  173. package/src/routes/docs/runRequest.js +0 -34
  174. package/src/routes/docs/schema.js +0 -37
  175. package/src/routes/docs/screenshot.js +0 -66
  176. package/src/routes/docs/search.js +0 -27
  177. package/src/routes/docs/snapshotState.js +0 -36
  178. package/src/routes/docs/stateCheckpointsList.js +0 -26
  179. package/src/routes/docs/types.js +0 -33
  180. package/src/routes/endpoints.js +0 -76
  181. package/src/routes/feedback.js +0 -110
  182. package/src/routes/feedback.test.mjs +0 -204
  183. package/src/routes/iconsDynamic.js +0 -25
  184. package/src/routes/jitPage.js +0 -99
  185. package/src/routes/reload.js +0 -81
  186. package/src/routes/request.js +0 -66
  187. package/src/routes/usage.js +0 -46
  188. package/src/routes/user.js +0 -27
  189. package/src/routes/websocket.js +0 -33
  190. package/src/websocket/devWebSocket.js +0 -78
  191. package/vite.config.js +0 -111
  192. /package/lib/client/{BuildErrorPage.jsx → BuildErrorPage.js} +0 -0
  193. /package/lib/client/{BuildingPage.jsx → BuildingPage.js} +0 -0
  194. /package/lib/client/{ErrorBar.jsx → ErrorBar.js} +0 -0
  195. /package/lib/client/{InstallingPluginsPage.jsx → InstallingPluginsPage.js} +0 -0
  196. /package/lib/client/{RestartingPage.jsx → RestartingPage.js} +0 -0
@@ -14,7 +14,14 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
+ // CSS layer order — MUST be the first CSS import. Turbopack treats this as critical
18
+ // CSS that loads before hydration, locking the cascade priority (antd > base/preflight)
19
+ // before antd's StyleProvider injects @layer antd {} at runtime.
20
+ import '../build/layer-order.css';
21
+
17
22
  import React, { Suspense, useCallback, useEffect, useRef, useState } from 'react';
23
+ import dynamic from 'next/dynamic';
24
+ import { useRouter } from 'next/router';
18
25
  import useSWR from 'swr';
19
26
 
20
27
  import { ErrorBoundary } from '@lowdefy/block-utils';
@@ -26,10 +33,13 @@ import { XProvider } from '@ant-design/x';
26
33
  import antdLocaleLoaders from '../build/i18n/antdLocales.js';
27
34
  import antdXLocaleLoaders from '../build/i18n/antdXLocales.js';
28
35
  import dayjsLocaleMap from '../build/i18n/dayjsLocales.js';
29
- import Auth from '../lib/client/auth/Auth.jsx';
30
- import ErrorBar from '../lib/client/ErrorBar.jsx';
36
+ import Auth from '../lib/client/auth/Auth.js';
37
+ import ErrorBar from '../lib/client/ErrorBar.js';
31
38
  import request from '../lib/client/utils/request.js';
32
- import Routing from './Routing.jsx';
39
+
40
+ // Full Tailwind CSS — also loaded via <link href="tailwind-jit.css"> in _document.js
41
+ // for hot-reloading. The Turbopack chunk provides layer ordering guarantee on initial load.
42
+ import '../build/globals.css';
33
43
 
34
44
  function ThemeTokenResolver({ lowdefyRef, children }) {
35
45
  const { token } = antdTheme.useToken();
@@ -40,11 +50,12 @@ function ThemeTokenResolver({ lowdefyRef, children }) {
40
50
  return children;
41
51
  }
42
52
 
43
- function App({ router }) {
53
+ function App({ Component }) {
54
+ const router = useRouter();
44
55
  const lowdefyRef = useRef({});
45
56
  const [runtimeErrors, setRuntimeErrors] = useState([]);
46
- // Subscribe to rootConfig SWR cache — deduplicates with Routing's fetch.
47
- // Without suspense so App doesn't suspend — just re-renders when data arrives.
57
+ // Subscribe to rootConfig SWR cache — deduplicates with inner App.js fetch.
58
+ // Without suspense so _app.js doesn't suspend — just re-renders when data arrives.
48
59
  const { data: rootConfig } = useSWR(`${router.basePath}/api/root`, (url) => request({ url }));
49
60
  if (rootConfig?.theme) {
50
61
  lowdefyRef.current.theme = rootConfig.theme;
@@ -55,11 +66,7 @@ function App({ router }) {
55
66
  configDarkMode: lowdefyRef.current.theme?.darkMode,
56
67
  });
57
68
 
58
- const {
59
- active: activeLocale,
60
- antdLocale,
61
- antdXLocale,
62
- } = useLocale({
69
+ const { active: activeLocale, antdLocale, antdXLocale } = useLocale({
63
70
  i18n: rootConfig?.i18n,
64
71
  antdLocaleLoaders,
65
72
  antdXLocaleLoaders,
@@ -92,10 +99,12 @@ function App({ router }) {
92
99
  ]);
93
100
  }, []);
94
101
 
95
- // Clear runtime errors on navigation
102
+ // Clear runtime errors on route change
96
103
  useEffect(() => {
97
- return router.subscribe(() => setRuntimeErrors([]));
98
- }, [router]);
104
+ const clearErrors = () => setRuntimeErrors([]);
105
+ router.events.on('routeChangeStart', clearErrors);
106
+ return () => router.events.off('routeChangeStart', clearErrors);
107
+ }, [router.events]);
99
108
 
100
109
  const handleError = useCallback((error) => {
101
110
  if (lowdefyRef.current?._internal?.handleError) {
@@ -106,11 +115,10 @@ function App({ router }) {
106
115
  }, []);
107
116
 
108
117
  // XProvider extends antd's ConfigProvider; merging antd + antd-X locale packs
109
- // gives X components (Bubble, Sender, Conversations, ...) their built-in strings
110
- // alongside antd's. antd X ships only en_US + zh_CN; other locales fall back
111
- // to en_US for X-native strings.
112
- const mergedLocale =
113
- antdLocale || antdXLocale ? { ...(antdLocale ?? {}), ...(antdXLocale ?? {}) } : undefined;
118
+ // gives X components their built-in strings alongside antd's.
119
+ const mergedLocale = antdLocale || antdXLocale
120
+ ? { ...(antdLocale ?? {}), ...(antdXLocale ?? {}) }
121
+ : undefined;
114
122
 
115
123
  return (
116
124
  <StyleProvider layer>
@@ -145,7 +153,7 @@ function App({ router }) {
145
153
  >
146
154
  <Auth>
147
155
  {(auth) => {
148
- return <Routing auth={auth} lowdefy={lowdefyRef.current} router={router} />;
156
+ return <Component auth={auth} lowdefy={lowdefyRef.current} />;
149
157
  }}
150
158
  </Auth>
151
159
  </Suspense>
@@ -158,4 +166,8 @@ function App({ router }) {
158
166
  );
159
167
  }
160
168
 
161
- export default App;
169
+ const DynamicApp = dynamic(() => Promise.resolve(App), {
170
+ ssr: false,
171
+ });
172
+
173
+ export default DynamicApp;
@@ -0,0 +1,107 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import React from 'react';
18
+ import Document, { Html, Head, Main, NextScript } from 'next/document';
19
+
20
+ import appJson from '../lib/build/app.js';
21
+ import lowdefyConfig from '../lib/build/config.js';
22
+ import themeConfig from '../lib/build/theme.js';
23
+
24
+ const basePath = lowdefyConfig.basePath ?? '';
25
+ const VALID_COLOR_MODES = ['system', 'light', 'dark'];
26
+ const configColorMode = VALID_COLOR_MODES.includes(themeConfig.darkMode)
27
+ ? themeConfig.darkMode
28
+ : 'system';
29
+ const darkBg = themeConfig?.antd?.darkToken?.colorBgLayout ?? '#000';
30
+ const lightBg = themeConfig?.antd?.lightToken?.colorBgLayout ?? '';
31
+
32
+ // Escape characters that could break out of the enclosing <script> tag or
33
+ // terminate a JS string literal. Used to defuse the js/bad-code-sanitization
34
+ // class of injection for values embedded into the pre-hydration inline script.
35
+ const SCRIPT_ESCAPES = {
36
+ '<': '\\u003C',
37
+ '>': '\\u003E',
38
+ '\b': '\\b',
39
+ '\f': '\\f',
40
+ '\n': '\\n',
41
+ '\r': '\\r',
42
+ '\t': '\\t',
43
+ '\0': '\\0',
44
+ '\u2028': '\\u2028',
45
+ '\u2029': '\\u2029',
46
+ };
47
+ function safeScriptJson(value) {
48
+ return JSON.stringify(value).replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, (c) => SCRIPT_ESCAPES[c]);
49
+ }
50
+
51
+ class LowdefyDocument extends Document {
52
+ render() {
53
+ return (
54
+ <Html className="lowdefy">
55
+ <Head>
56
+ {/* Synchronous script that creates the @layer order declaration and keeps
57
+ it as the first child of <head> via MutationObserver. antd's CSS-in-JS
58
+ uses prependQueue to inject <style> tags at the top of <head>, which
59
+ would otherwise make @layer antd the first (lowest priority) layer.
60
+ MutationObserver fires before paint, so the browser never sees the
61
+ wrong cascade order. */}
62
+ <script
63
+ dangerouslySetInnerHTML={{
64
+ __html: `(function(){var s=document.createElement("style");s.id="__lf-layer-order";s.textContent="@layer theme, base, antd, components, utilities;";document.head.prepend(s);new MutationObserver(function(){if(document.head.firstChild!==s)document.head.prepend(s)}).observe(document.head,{childList:true})})();`,
65
+ }}
66
+ />
67
+ {/* Synchronous pre-hydration background script — prevents mode-mismatch
68
+ flash on page navigation. Mirrors useDarkMode.js resolution order:
69
+ configDarkMode → localStorage → prefers-color-scheme. Uses the user's
70
+ configured colorBgLayout tokens when present (theme.antd.darkToken and
71
+ theme.antd.lightToken), falling back to #000 in dark and no inline style
72
+ in light so default behavior is unchanged. */}
73
+ <script
74
+ dangerouslySetInnerHTML={{
75
+ __html: `(function(){var c=${safeScriptJson(configColorMode)};var db=${safeScriptJson(
76
+ darkBg
77
+ )};var lb=${safeScriptJson(
78
+ lightBg
79
+ )};var d;if(c==="dark")d=true;else if(c==="light")d=false;else{try{var p=localStorage.getItem("lowdefy_darkMode");if(p==="dark")d=true;else if(p==="light")d=false;else d=window.matchMedia("(prefers-color-scheme:dark)").matches}catch(e){d=window.matchMedia("(prefers-color-scheme:dark)").matches}}var bg=d?db:lb;if(bg)document.documentElement.style.backgroundColor=bg})();`,
80
+ }}
81
+ />
82
+ <link rel="manifest" href={`${basePath}/manifest.webmanifest`} />
83
+ <link rel="icon" type="image/svg+xml" href={`${basePath}/icon.svg`} />
84
+ <link rel="apple-touch-icon" href={`${basePath}/apple-touch-icon.png`} />
85
+ <link id="tailwind-jit-css" rel="stylesheet" href={`${basePath}/tailwind-jit.css`} />
86
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
87
+ <script
88
+ dangerouslySetInnerHTML={{
89
+ __html: `/* start of Lowdefy append head */</script>${appJson.html.appendHead}<script>/* end of Lowdefy append head */`,
90
+ }}
91
+ />
92
+ </Head>
93
+ <body>
94
+ <Main />
95
+ <NextScript />
96
+ <script
97
+ dangerouslySetInnerHTML={{
98
+ __html: `/* start of Lowdefy append body */</script>${appJson.html.appendBody}<script>/* end of Lowdefy append body */`,
99
+ }}
100
+ />
101
+ </body>
102
+ </Html>
103
+ );
104
+ }
105
+ }
106
+
107
+ export default LowdefyDocument;
@@ -0,0 +1,86 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { callAgent } from '@lowdefy/api';
18
+ import { translate, type } from '@lowdefy/helpers';
19
+
20
+ import apiWrapper from '../../../lib/server/apiWrapper.js';
21
+
22
+ async function handler({ context, req, res }) {
23
+ const t = (key, values) => translate({ key, values, i18n: context.i18n });
24
+ if (req.method !== 'POST') {
25
+ throw new Error(t('agent.runtime.methodNotAllowed'));
26
+ }
27
+ const segments = req.query.path;
28
+ if (!Array.isArray(segments) || segments.length < 2) {
29
+ res.status(400).json({ error: t('agent.runtime.invalidPath') });
30
+ return;
31
+ }
32
+ const agentId = segments[segments.length - 1];
33
+ const pageId = segments.slice(0, -1).join('/');
34
+ context.logger.info({ color: 'gray' }, `Agent: ${pageId} → ${agentId}`);
35
+ const { conversationId } = req.query;
36
+ const { messages, urlQuery, sharedState } = req.body;
37
+ if (!Array.isArray(messages)) {
38
+ res.status(400).json({ error: t('agent.runtime.messagesMustBeArray') });
39
+ return;
40
+ }
41
+ if (urlQuery != null && (typeof urlQuery !== 'object' || Array.isArray(urlQuery))) {
42
+ res.status(400).json({ error: t('agent.runtime.urlQueryMustBeObject') });
43
+ return;
44
+ }
45
+ if (sharedState != null && !type.isObject(sharedState)) {
46
+ res.status(400).json({ error: t('agent.runtime.sharedStateMustBeObject') });
47
+ return;
48
+ }
49
+ const { response: webResponse } = await callAgent(context, {
50
+ agentId,
51
+ pageId,
52
+ messages,
53
+ conversationId: conversationId ?? undefined,
54
+ sharedState: sharedState ?? undefined,
55
+ urlQuery: urlQuery ?? undefined,
56
+ });
57
+
58
+ // Stream the Web Response body to the Next.js response
59
+ res.setHeader('Content-Type', 'text/event-stream');
60
+ res.setHeader('Cache-Control', 'no-cache');
61
+ res.setHeader('Connection', 'keep-alive');
62
+ res.setHeader('Content-Encoding', 'none');
63
+ res.setHeader('Transfer-Encoding', 'chunked');
64
+
65
+ const reader = webResponse.body.getReader();
66
+ const decoder = new TextDecoder();
67
+ let done = false;
68
+ while (!done) {
69
+ const { value, done: readerDone } = await reader.read();
70
+ done = readerDone;
71
+ if (value) {
72
+ res.write(decoder.decode(value, { stream: true }));
73
+ }
74
+ }
75
+ res.end();
76
+ }
77
+
78
+ export const config = {
79
+ api: {
80
+ bodyParser: {
81
+ sizeLimit: '10mb',
82
+ },
83
+ },
84
+ };
85
+
86
+ export default apiWrapper(handler);
@@ -0,0 +1,48 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import NextAuth from 'next-auth';
18
+
19
+ import apiWrapper from '../../../lib/server/apiWrapper.js';
20
+ import authJson from '../../../lib/build/auth.js';
21
+ import getMockSession from '../../../lib/server/auth/getMockSession.js';
22
+
23
+ async function handler({ context, req, res }) {
24
+ if (authJson.configured !== true) {
25
+ return res.status(404).json({
26
+ message: 'Auth not configured',
27
+ });
28
+ }
29
+
30
+ // Required for emails in corporate networks, see:
31
+ // https://next-auth.js.org/tutorials/avoid-corporate-link-checking-email-provider
32
+ if (req.method === 'HEAD') {
33
+ return res.status(200).end();
34
+ }
35
+
36
+ // Return mock session for session requests (dev server only)
37
+ const nextauthPath = req.query.nextauth ?? [];
38
+ if (nextauthPath[0] === 'session') {
39
+ const mockSession = await getMockSession();
40
+ if (mockSession) {
41
+ return res.status(200).json(mockSession);
42
+ }
43
+ }
44
+
45
+ return NextAuth(req, res, context.authOptions);
46
+ }
47
+
48
+ export default apiWrapper(handler);
@@ -0,0 +1,45 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { logClientError } from '@lowdefy/api';
18
+
19
+ import apiWrapper from '../../lib/server/apiWrapper.js';
20
+
21
+ async function handler({ context, req, res }) {
22
+ if (req.method !== 'POST') {
23
+ throw new Error('Only POST requests are supported.');
24
+ }
25
+
26
+ const origin = req.headers.origin;
27
+ if (!origin) {
28
+ res.status(403).json({ error: 'Forbidden' });
29
+ return;
30
+ }
31
+ try {
32
+ if (new URL(origin).host !== req.headers.host) {
33
+ res.status(403).json({ error: 'Forbidden' });
34
+ return;
35
+ }
36
+ } catch {
37
+ res.status(403).json({ error: 'Forbidden' });
38
+ return;
39
+ }
40
+
41
+ const { error, ...response } = await logClientError(context, req.body);
42
+ res.status(200).json(response);
43
+ }
44
+
45
+ export default apiWrapper(handler);
@@ -13,11 +13,10 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */
16
+ import apiWrapper from '../../lib/server/apiWrapper.js';
16
17
 
17
- import getBuildStatus from '../../../lib/docs/getBuildStatus.js';
18
-
19
- function docsBuildStatusHandler(c) {
20
- return c.json(getBuildStatus());
18
+ async function handler({ req, res }) {
19
+ res.status(200).json({ directories: { config: process.env.LOWDEFY_DIRECTORY_CONFIG } });
21
20
  }
22
21
 
23
- export default docsBuildStatusHandler;
22
+ export default apiWrapper(handler);
@@ -14,23 +14,19 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- // Module-level ring buffer of recent client-reported errors — feeds the
18
- // getBuildStatus feedback endpoint so agents can see browser errors without
19
- // tailing server logs. Deliberately in-memory only: entries are lost on
20
- // server restart, which is fine since this is a live-session debugging aid.
21
- const MAX_ENTRIES = 50;
17
+ import { callEndpoint } from '@lowdefy/api';
22
18
 
23
- const entries = [];
19
+ import apiWrapper from '../../../lib/server/apiWrapper.js';
24
20
 
25
- function push(entry) {
26
- entries.push(entry);
27
- if (entries.length > MAX_ENTRIES) {
28
- entries.shift();
21
+ async function handler({ context, req, res }) {
22
+ if (req.method !== 'POST') {
23
+ throw new Error('Only POST requests are supported.');
29
24
  }
25
+ const endpointId = req.query.endpointId.join('/');
26
+ const { blockId, payload, pageId } = req.body;
27
+ context.logger.info({ event: 'call_api_endpoint', blockId, endpointId, pageId });
28
+ const response = await callEndpoint(context, { blockId, endpointId, pageId, payload });
29
+ res.status(200).json(response);
30
30
  }
31
31
 
32
- function list() {
33
- return [...entries];
34
- }
35
-
36
- export default { push, list };
32
+ export default apiWrapper(handler);
@@ -14,17 +14,21 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import fs from 'node:fs';
18
- import path from 'node:path';
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+
20
+ async function handler(req, res) {
21
+ const filePath = path.join(process.cwd(), 'build', 'plugins', 'iconsDynamic.js');
19
22
 
20
- function serveBuildJs(relativePath) {
21
- const filePath = path.join(process.cwd(), 'build', ...relativePath);
22
23
  try {
23
- return fs.readFileSync(filePath, 'utf8');
24
+ const content = fs.readFileSync(filePath, 'utf8');
25
+ res.setHeader('Content-Type', 'application/javascript');
26
+ res.status(200).send(content);
24
27
  } catch {
25
- // Empty default export if the file doesn't exist yet
26
- return 'export default {};';
28
+ // Return empty default export if file doesn't exist yet
29
+ res.setHeader('Content-Type', 'application/javascript');
30
+ res.status(200).send('export default {};');
27
31
  }
28
32
  }
29
33
 
30
- export default serveBuildJs;
34
+ export default handler;
@@ -14,17 +14,29 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import serveBuildJs from '../lib/serveBuildJs.js';
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+
20
+ async function handler(req, res) {
21
+ const { env } = req.query;
18
22
 
19
- function jsEnvHandler(c) {
20
- const env = c.req.param('env');
21
23
  if (env !== 'client' && env !== 'server') {
22
- return c.text('Invalid env parameter. Use "client" or "server".', 400);
24
+ res.status(400).send('Invalid env parameter. Use "client" or "server".');
25
+ return;
23
26
  }
27
+
24
28
  const fileName = env === 'client' ? 'clientJsMap.js' : 'serverJsMap.js';
25
- return c.body(serveBuildJs(['plugins', 'operators', fileName]), 200, {
26
- 'Content-Type': 'application/javascript',
27
- });
29
+ const filePath = path.join(process.cwd(), 'build', 'plugins', 'operators', fileName);
30
+
31
+ try {
32
+ const content = fs.readFileSync(filePath, 'utf8');
33
+ res.setHeader('Content-Type', 'application/javascript');
34
+ res.status(200).send(content);
35
+ } catch {
36
+ // Return empty default export if file doesn't exist yet
37
+ res.setHeader('Content-Type', 'application/javascript');
38
+ res.status(200).send('export default {};');
39
+ }
28
40
  }
29
41
 
30
- export default jsEnvHandler;
42
+ export default handler;
@@ -0,0 +1,74 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { getPageConfig } from '@lowdefy/api';
18
+
19
+ import apiWrapper from '../../../lib/server/apiWrapper.js';
20
+ import buildPageIfNeeded from '../../../lib/server/jitPageBuilder.js';
21
+
22
+ async function handler({ context, req, res }) {
23
+ const pageId = req.query.pageId.join('/');
24
+
25
+ // Attempt JIT build if page not yet compiled
26
+ let buildResult;
27
+ try {
28
+ buildResult = await buildPageIfNeeded({
29
+ pageId,
30
+ buildDirectory: context.buildDirectory,
31
+ configDirectory: context.configDirectory,
32
+ });
33
+ } catch (error) {
34
+ const rawErrors = error.buildErrors ?? [error];
35
+ const errors = [];
36
+ for (const err of rawErrors) {
37
+ await context.handleError(err);
38
+ errors.push({
39
+ type: err.name ?? 'Error',
40
+ message: err.message,
41
+ source: err.source ?? null,
42
+ stack: err.stack ?? null,
43
+ });
44
+ }
45
+ res.status(500).json({
46
+ buildError: true,
47
+ errors,
48
+ // Keep top-level message/source for backward compatibility
49
+ message: error.message,
50
+ source: error.source ?? null,
51
+ });
52
+ return;
53
+ }
54
+
55
+ if (buildResult && buildResult.installing) {
56
+ res.status(200).json({
57
+ installing: true,
58
+ packages: buildResult.packages,
59
+ });
60
+ return;
61
+ }
62
+
63
+ const pageConfig = await getPageConfig(context, { pageId });
64
+ if (pageConfig === null) {
65
+ res.status(404).send('Page not found.');
66
+ } else {
67
+ if (buildResult?.warnings?.length > 0) {
68
+ pageConfig._warnings = buildResult.warnings;
69
+ }
70
+ res.status(200).json(pageConfig);
71
+ }
72
+ }
73
+
74
+ export default apiWrapper(handler);
@@ -14,8 +14,6 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- function pingHandler(c) {
18
- return c.json({ timestamp: new Date().toISOString() });
17
+ export default async function handler(req, res) {
18
+ res.status(200).json({ timestamp: new Date().toISOString() });
19
19
  }
20
-
21
- export default pingHandler;
@@ -0,0 +1,53 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import chokidar from 'chokidar';
18
+
19
+ const handler = async (req, res) => {
20
+ res.setHeader('Content-Type', 'text/event-stream;charset=utf-8');
21
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
22
+ res.setHeader('X-Accel-Buffering', 'no');
23
+ res.setHeader('Connection', 'keep-alive');
24
+
25
+ const watcher = chokidar.watch(['./build/reload'], {
26
+ persistent: true,
27
+ ignoreInitial: true,
28
+ });
29
+
30
+ const reload = () => {
31
+ try {
32
+ res.write(`event: reload\ndata: ${JSON.stringify({})}\n\n`);
33
+ } catch (e) {
34
+ console.error(e);
35
+ }
36
+ };
37
+ watcher.on('add', () => reload());
38
+ watcher.on('change', () => reload());
39
+ // Do not reload on unlink — cleanBuildDirectory deletes build/reload during
40
+ // skeleton rebuilds, which would send a premature SSE event before the new
41
+ // build artifacts are written. The real reload comes via add/change when
42
+ // reloadClients() creates the file after the build completes.
43
+
44
+ // TODO: This isn't working.
45
+ req.on('close', () => {
46
+ console.log('req closed');
47
+ watcher.close().then(() => {
48
+ console.log('watcher closed');
49
+ });
50
+ });
51
+ };
52
+
53
+ export default handler;