@lowdefy/server-dev 7.0.0 → 7.2.0

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 (445) hide show
  1. package/client/Inspector.jsx +24 -75
  2. package/client/Page.jsx +8 -0
  3. package/client/Routing.jsx +0 -2
  4. package/client/clientBuildImports.test.mjs +5 -3
  5. package/client/devStreamConnections.test.mjs +1 -0
  6. package/client/journeyObserver/startJourneyObserver.test.mjs +11 -11
  7. package/client/openInEditor/OpenInEditorListener.jsx +36 -29
  8. package/client/openInEditor/OpenInEditorListener.test.mjs +116 -0
  9. package/client/{feedback → openInEditor}/elementInspect.js +9 -44
  10. package/client/openInEditor/findBlockLocation.js +2 -2
  11. package/client/openInEditor/openInEditorStyles.js +56 -0
  12. package/client/recorder/createPairingBuffer.test.mjs +27 -9
  13. package/client/recorder/createRecorder.js +11 -7
  14. package/client/recorder/createRecorder.test.mjs +9 -9
  15. package/client/recorder/isPasswordElement.js +41 -0
  16. package/client/recorder/keyChord.test.mjs +1 -0
  17. package/{client/recorder/toJsonSafe.js → lib/build/mobileConfig.js} +9 -12
  18. package/lib/client/auth/AuthConfigured.jsx +75 -48
  19. package/lib/client/auth/authNotConfiguredParity.test.mjs +1 -0
  20. package/lib/client/auth/authTemplateSync.test.mjs +1 -0
  21. package/lib/client/auth/betterAuthSessionContract.test.mjs +2 -1
  22. package/lib/client/auth/sessionCaller.js +56 -0
  23. package/lib/client/auth/sessionCaller.test.mjs +78 -0
  24. package/lib/client/getPagePath.test.mjs +1 -0
  25. package/lib/client/utils/formatErrorsForCopy.test.mjs +1 -0
  26. package/lib/client/utils/getErrorBarColor.test.mjs +1 -0
  27. package/lib/client/utils/usePageConfig.test.mjs +15 -15
  28. package/lib/configTree/buildConfigTree.test.mjs +6 -8
  29. package/lib/configTree/collectConfigText.test.mjs +1 -0
  30. package/lib/configTree/runConfigTreeBuild.mjs +2 -1
  31. package/lib/configTree/runConfigTreeBuild.skipPluginChecks.test.mjs +11 -11
  32. package/lib/configTree/runConfigTreeBuild.test.mjs +2 -2
  33. package/lib/docs/addNestedEndpoints.test.mjs +1 -0
  34. package/lib/docs/checkAgentFiles.test.mjs +1 -0
  35. package/lib/docs/checkStepReferences.test.mjs +3 -3
  36. package/lib/docs/clientErrorStore.test.mjs +4 -4
  37. package/lib/docs/createBrowserLifecycle.test.mjs +40 -24
  38. package/lib/docs/createDocsMcpServer.js +195 -138
  39. package/lib/docs/createDocsMcpServer.test.mjs +331 -25
  40. package/lib/docs/createDocsMcpServerRunJourney.test.mjs +5 -5
  41. package/lib/docs/createJourneyActors.chromium.test.mjs +3 -3
  42. package/lib/docs/createJourneyActors.test.mjs +4 -4
  43. package/lib/docs/dataSets/checkSharedCollectionIds.js +20 -9
  44. package/lib/docs/dataSets/dataSetJourneys.chromium.mongodb.test.mjs +59 -11
  45. package/{src/routes/docs/content.js → lib/docs/dataSets/describeTargetKey.js} +10 -14
  46. package/lib/docs/dataSets/drainSessionWork.test.mjs +21 -5
  47. package/lib/docs/dataSets/getDataStore.js +11 -3
  48. package/lib/docs/dataSets/getDataStore.mongodb.test.mjs +3 -3
  49. package/lib/docs/dataSets/getDataStore.test.mjs +32 -20
  50. package/lib/docs/dataSets/groupDataSetByCollection.js +19 -11
  51. package/lib/docs/dataSets/mergeCollectionIndexes.test.mjs +1 -0
  52. package/lib/docs/dataSets/openDataSession.js +36 -20
  53. package/lib/docs/dataSets/openDataSession.mongodb.test.mjs +175 -7
  54. package/lib/docs/dataSets/pickDataStorePort.test.mjs +2 -2
  55. package/lib/docs/dataSets/readDataSession.test.mjs +1 -0
  56. package/lib/docs/dataSets/readDataSet.js +34 -19
  57. package/lib/docs/dataSets/readDataSet.test.mjs +57 -25
  58. package/lib/docs/dataSets/resolveJourneyDataSet.test.mjs +1 -0
  59. package/lib/docs/dataSets/sessionDatabaseName.js +32 -0
  60. package/lib/docs/dataSets/sweepOrphanDatabases.js +7 -4
  61. package/lib/docs/dataSets/test/app/lowdefy.yaml +22 -0
  62. package/lib/docs/dataSets/test/app/tests/data/shop.yaml +4 -0
  63. package/lib/docs/dataSets/test/buildTestApp.mjs +1 -1
  64. package/lib/docs/devEventBus.js +7 -2
  65. package/lib/docs/devEventBus.test.mjs +12 -10
  66. package/lib/docs/devToolDefinitions.js +87 -135
  67. package/lib/docs/device/buildDeviceCommand.js +103 -0
  68. package/lib/docs/device/buildDeviceCommand.test.mjs +142 -0
  69. package/lib/docs/device/captureDevice.js +85 -0
  70. package/lib/docs/device/checkShownPage.js +56 -0
  71. package/lib/docs/device/createFakePhoneTab.mjs +77 -0
  72. package/lib/docs/device/deviceAction.js +74 -0
  73. package/lib/docs/device/deviceTools.test.mjs +604 -0
  74. package/lib/docs/device/findDeviceTab.js +50 -0
  75. package/lib/docs/device/findDeviceTarget.js +73 -0
  76. package/lib/docs/device/injectDevice.js +160 -0
  77. package/lib/docs/device/listDevices.js +100 -0
  78. package/lib/docs/device/listDevices.test.mjs +105 -0
  79. package/lib/docs/device/runDeviceJourney.js +68 -0
  80. package/lib/docs/device/runDeviceSteps.js +164 -0
  81. package/lib/docs/device/screenshotDevice.js +68 -0
  82. package/lib/docs/device/sendDeviceStep.js +52 -0
  83. package/lib/docs/device/startDevice.js +150 -0
  84. package/lib/docs/docs.test.mjs +44 -28
  85. package/lib/docs/docsIndex.test.mjs +1 -0
  86. package/lib/docs/findConfig.js +3 -4
  87. package/lib/docs/findPageBlock.js +35 -0
  88. package/lib/docs/findPageBlock.test.mjs +45 -0
  89. package/lib/docs/fitResponse.js +18 -17
  90. package/lib/docs/fitResponse.test.mjs +18 -0
  91. package/lib/docs/getBrowser.js +4 -4
  92. package/lib/docs/getBrowser.test.mjs +32 -16
  93. package/lib/docs/getBuildId.test.mjs +1 -0
  94. package/lib/docs/getBuildStatus.js +29 -3
  95. package/lib/docs/getBuildStatus.test.mjs +108 -12
  96. package/lib/docs/getBuildStatusAfterEdits.test.mjs +8 -8
  97. package/{src/routes/docs/appMap.js → lib/docs/getConfigDirectory.js} +3 -5
  98. package/lib/docs/getHazards.js +4 -1
  99. package/lib/docs/getHazards.test.mjs +9 -7
  100. package/lib/docs/getOverview.js +22 -44
  101. package/lib/docs/getOverviewBasePath.test.mjs +1 -0
  102. package/lib/docs/getStaleStatus.test.mjs +1 -0
  103. package/lib/docs/inspectState.js +78 -3
  104. package/lib/docs/inspectState.test.mjs +61 -9
  105. package/lib/docs/inspectStateFromTab.js +38 -6
  106. package/lib/docs/inspectStateFromTab.test.mjs +79 -0
  107. package/lib/docs/inspectStateHeadless.js +98 -34
  108. package/lib/docs/inspectStateHeadless.test.mjs +17 -5
  109. package/lib/docs/installHeadlessShell.failure.test.mjs +9 -5
  110. package/lib/docs/installHeadlessShell.js +5 -2
  111. package/lib/docs/installHeadlessShell.test.mjs +8 -5
  112. package/lib/docs/installHeadlessShell.timeout.test.mjs +32 -12
  113. package/lib/docs/isDeepEqual.js +37 -0
  114. package/lib/docs/isHeadlessShellIncomplete.test.mjs +1 -0
  115. package/lib/docs/isPageReady.test.mjs +1 -0
  116. package/lib/docs/journeyMutantCookie.chromium.test.mjs +3 -3
  117. package/lib/docs/journeyRunRecording.test.mjs +1 -0
  118. package/lib/docs/keepEventStreamAlive.test.mjs +1 -0
  119. package/lib/docs/launchBrowser.test.mjs +8 -8
  120. package/lib/docs/listTypes.js +58 -8
  121. package/lib/docs/loadFrameworkHazards.test.mjs +1 -0
  122. package/lib/docs/matchJourneyRoute.test.mjs +1 -0
  123. package/lib/docs/observe/createJourneyAppErrors.test.mjs +3 -3
  124. package/lib/docs/observe/evaluateInvariants.test.mjs +1 -0
  125. package/lib/docs/observe/hasNoEffect.test.mjs +1 -0
  126. package/lib/docs/observe/withAppErrors.test.mjs +1 -0
  127. package/lib/docs/openJourneyEmail.test.mjs +6 -6
  128. package/lib/docs/pageBuildStatus.test.mjs +6 -6
  129. package/lib/docs/pollTab.js +100 -0
  130. package/lib/docs/pollTab.test.mjs +64 -0
  131. package/lib/docs/rails/authEngineActions.test.mjs +1 -0
  132. package/lib/docs/rails/authEngineMethods.test.mjs +2 -1
  133. package/lib/docs/rails/checkAuthActionsRan.test.mjs +5 -5
  134. package/lib/docs/rails/createDataSetRails.test.mjs +1 -0
  135. package/lib/docs/rails/findExternalBlocks.js +3 -3
  136. package/lib/docs/rails/findExternalBlocks.test.mjs +1 -0
  137. package/lib/docs/readJourneyEmailMatch.test.mjs +2 -2
  138. package/lib/docs/readJourneySession.js +1 -1
  139. package/lib/docs/reportDevToolFault.js +29 -0
  140. package/lib/docs/reportDevToolFault.test.mjs +34 -0
  141. package/lib/docs/requestRestart.test.mjs +1 -0
  142. package/lib/docs/resolvePageInstance.test.mjs +1 -0
  143. package/lib/docs/resolveSource.js +2 -2
  144. package/lib/docs/resolveSource.test.mjs +6 -6
  145. package/lib/docs/reviewPageBuilds.test.mjs +2 -2
  146. package/lib/docs/runCheck.test.mjs +3 -3
  147. package/lib/docs/runCheckChild.js +2 -1
  148. package/lib/docs/runEndpoint.js +23 -10
  149. package/lib/docs/runEndpoint.test.mjs +42 -37
  150. package/lib/docs/runErrorBuffers.test.mjs +1 -0
  151. package/lib/docs/runJourney.js +21 -1
  152. package/lib/docs/runJourney.test.mjs +119 -99
  153. package/lib/docs/runJourneyDataSet.test.mjs +26 -26
  154. package/lib/docs/runJourneySteps.js +8 -29
  155. package/lib/docs/runRequest.js +6 -6
  156. package/lib/docs/runRequest.test.mjs +22 -22
  157. package/lib/docs/screenshotPage.js +6 -7
  158. package/lib/docs/screenshotPage.test.mjs +46 -46
  159. package/lib/docs/screenshotPageClip.test.mjs +10 -10
  160. package/lib/docs/searchDocs.test.mjs +1 -0
  161. package/lib/docs/searchIcons.test.mjs +5 -5
  162. package/lib/docs/selectFinalState.test.mjs +1 -0
  163. package/lib/docs/serverErrorStore.test.mjs +4 -4
  164. package/lib/docs/setupTestFixtures.mjs +25 -0
  165. package/lib/docs/splitSearchTerms.test.mjs +1 -0
  166. package/lib/docs/tabAvailable.js +1 -1
  167. package/lib/docs/tabChannel.js +90 -14
  168. package/lib/docs/tabChannel.test.mjs +40 -15
  169. package/lib/docs/validateJourneyTimeout.test.mjs +1 -0
  170. package/lib/docs/validateStateSelection.test.mjs +1 -0
  171. package/lib/docs/validateViewport.test.mjs +1 -0
  172. package/lib/docs/waitForBuild.test.mjs +1 -0
  173. package/lib/docs/withBrowserSlot.test.mjs +5 -5
  174. package/lib/docs/withDataSession.js +2 -2
  175. package/lib/server/applyDataSetRedirect.js +14 -5
  176. package/lib/server/applyDataSetRedirect.test.mjs +121 -15
  177. package/lib/server/applyDataSetRedirectTenantReach.test.mjs +5 -1
  178. package/lib/server/applyDataSetRedirectWalled.test.mjs +5 -1
  179. package/lib/server/auth/getHeadlessUser.js +6 -0
  180. package/lib/server/auth/getHeadlessUser.test.mjs +13 -2
  181. package/lib/server/auth/resolveHeadlessUser.test.mjs +1 -0
  182. package/lib/server/contextMapBudget.test.mjs +3 -3
  183. package/lib/server/continueJitKeys.test.mjs +1 -0
  184. package/lib/server/createLowdefyContext.js +8 -4
  185. package/lib/server/createLowdefyContext.test.mjs +38 -35
  186. package/lib/server/getClientAddress.test.mjs +2 -2
  187. package/lib/server/getPageJitEnrichment.test.mjs +1 -0
  188. package/lib/server/importAppCode.test.mjs +2 -2
  189. package/lib/server/jitPageBuilder.js +27 -3
  190. package/lib/server/jitPageBuilder.mobileTypes.test.mjs +65 -0
  191. package/lib/server/jitPageBuilder.skipPluginChecks.test.mjs +5 -6
  192. package/lib/server/jitPageBuilder.test.mjs +4 -4
  193. package/lib/server/journeyCookies.test.mjs +1 -0
  194. package/lib/server/loadDynamicJsMap.js +10 -1
  195. package/lib/server/log/createHandleError.js +10 -5
  196. package/lib/server/log/createHandleError.test.mjs +19 -8
  197. package/lib/server/log/createLogger.test.mjs +2 -2
  198. package/lib/server/mutantDataSetWrappers.test.mjs +5 -1
  199. package/lib/server/mutants/listMutants.test.mjs +1 -0
  200. package/lib/server/mutants/mutantRuns.test.mjs +1 -0
  201. package/lib/server/mutants/operators.test.mjs +1 -0
  202. package/lib/server/pageBuildRecords.test.mjs +1 -0
  203. package/lib/server/pageCache.test.mjs +1 -0
  204. package/lib/server/pageRebuilds.test.mjs +3 -3
  205. package/{src/routes/docs/examples.js → lib/server/pairingHeaders.js} +8 -15
  206. package/lib/server/pruneJitMaps.test.mjs +1 -0
  207. package/lib/server/readBuildApiArtifacts.test.mjs +1 -0
  208. package/lib/server/readInstanceRecord.test.mjs +24 -8
  209. package/lib/server/readMergedMaps.test.mjs +1 -0
  210. package/lib/server/recording/errorRecordingStamp.test.mjs +1 -0
  211. package/lib/server/recording/readRecordingCookie.test.mjs +2 -0
  212. package/lib/server/recording/servedBuilds.test.mjs +1 -0
  213. package/lib/server/sinkExternalConnections.test.mjs +6 -6
  214. package/lib/server/skipStaleMapWrites.test.mjs +12 -12
  215. package/lib/server/startIdleGc.test.mjs +25 -9
  216. package/lib/server/testFixtures/importAppCodeTwice.mjs +2 -2
  217. package/lib/vite/createDevServerExclude.test.mjs +1 -0
  218. package/manager/getContext.mjs +11 -2
  219. package/manager/processes/checkPendingPlugins.mjs +49 -0
  220. package/manager/processes/checkPendingPlugins.test.mjs +107 -0
  221. package/manager/processes/createIdleChild.mjs +141 -0
  222. package/manager/processes/createIdleChild.test.mjs +209 -0
  223. package/manager/processes/initialBuild.mjs +4 -15
  224. package/manager/processes/initialBuild.test.mjs +8 -37
  225. package/manager/processes/lowdefyBuild.mjs +11 -7
  226. package/manager/processes/lowdefyBuild.skipPluginChecks.test.mjs +23 -13
  227. package/manager/processes/lowdefyBuild.test.mjs +17 -15
  228. package/manager/processes/restartServer.test.mjs +63 -15
  229. package/manager/processes/shutdownServer.test.mjs +3 -3
  230. package/manager/processes/startFirstServer.test.mjs +23 -22
  231. package/manager/processes/startMailSink.mjs +11 -3
  232. package/manager/processes/startMailSink.test.mjs +28 -2
  233. package/manager/processes/startProxy.mjs +158 -27
  234. package/manager/processes/startProxy.pairing.test.mjs +204 -0
  235. package/manager/processes/startProxy.test.mjs +127 -2
  236. package/manager/processes/startServer.mjs +5 -7
  237. package/manager/processes/startServer.test.mjs +10 -9
  238. package/manager/processes/syncServer.mjs +31 -4
  239. package/manager/processes/syncServer.test.mjs +71 -6
  240. package/manager/processes/waitForDevServer.test.mjs +21 -6
  241. package/manager/run.mjs +32 -8
  242. package/manager/utils/BatchChanges.mjs +1 -1
  243. package/manager/utils/BatchChanges.test.mjs +4 -4
  244. package/manager/utils/acquireDevInstance.test.mjs +1 -0
  245. package/manager/utils/checkPairing.mjs +45 -0
  246. package/manager/utils/checkPairing.test.mjs +53 -0
  247. package/manager/utils/createBuildActivity.mjs +5 -1
  248. package/manager/utils/createBuildActivity.test.mjs +2 -2
  249. package/manager/utils/createChangeSignal.test.mjs +5 -5
  250. package/manager/utils/createCustomPluginMessagesMap.mjs +8 -3
  251. package/manager/utils/createCustomPluginTypesMap.mjs +48 -12
  252. package/manager/utils/createCustomPluginTypesMap.test.mjs +181 -19
  253. package/manager/utils/createDotPathIgnore.test.mjs +1 -0
  254. package/manager/utils/createGlobIgnore.mjs +45 -0
  255. package/manager/utils/createGlobIgnore.test.mjs +58 -0
  256. package/manager/utils/createGlobWatchPaths.mjs +75 -0
  257. package/manager/utils/createGlobWatchPaths.test.mjs +67 -0
  258. package/manager/utils/createIdleGc.test.mjs +31 -15
  259. package/manager/utils/createLanPairing.mjs +34 -0
  260. package/manager/utils/createLanPairing.test.mjs +46 -0
  261. package/manager/utils/createRequestActivity.mjs +30 -3
  262. package/manager/utils/createRequestActivity.test.mjs +76 -22
  263. package/manager/utils/createServerArtifactTracker.mjs +1 -0
  264. package/manager/utils/createServerArtifactTracker.test.mjs +1 -0
  265. package/manager/utils/findBuildFilesOutsideWatch.test.mjs +1 -0
  266. package/{client/recorder/collectEventActions.js → manager/utils/findSignInCode.mjs} +13 -10
  267. package/manager/utils/findSignInCode.test.mjs +33 -0
  268. package/manager/utils/formatLanPairing.mjs +32 -0
  269. package/manager/utils/formatLanPairing.test.mjs +40 -0
  270. package/manager/utils/getLanAddress.mjs +83 -0
  271. package/manager/utils/getLanAddress.test.mjs +70 -0
  272. package/manager/utils/importFresh.test.mjs +1 -0
  273. package/{src/routes/docs/icons.js → manager/utils/isLoopbackAddress.mjs} +11 -10
  274. package/manager/utils/pluginTypeCache.mjs +100 -0
  275. package/manager/utils/pluginTypeCache.test.mjs +141 -0
  276. package/manager/utils/pruneRecordings.test.mjs +1 -0
  277. package/manager/utils/publishBuildDirectory.order.test.mjs +2 -2
  278. package/manager/utils/publishBuildDirectory.test.mjs +6 -7
  279. package/manager/utils/readBasePath.test.mjs +1 -0
  280. package/manager/utils/readManagerVersion.test.mjs +1 -0
  281. package/manager/utils/readPluginDefinitions.mjs +6 -6
  282. package/manager/utils/renderTerminalQr.mjs +54 -0
  283. package/manager/utils/resolveDevAuthUrl.test.mjs +1 -0
  284. package/manager/utils/setupWatcher.mjs +19 -4
  285. package/manager/utils/startRecordingPruner.test.mjs +24 -8
  286. package/manager/utils/waitForChildExit.test.mjs +2 -2
  287. package/manager/utils/writeBuildStatus.test.mjs +1 -0
  288. package/manager/watchers/envWatcher.mjs +3 -0
  289. package/manager/watchers/envWatcher.test.mjs +19 -7
  290. package/manager/watchers/listServerPluginFiles.mjs +188 -0
  291. package/manager/watchers/listServerPluginFiles.test.mjs +257 -0
  292. package/manager/watchers/lowdefyBuildWatcher.mjs +5 -0
  293. package/manager/watchers/lowdefyBuildWatcher.test.mjs +63 -10
  294. package/manager/watchers/pluginSourceWatcher.mjs +45 -17
  295. package/manager/watchers/pluginSourceWatcher.test.mjs +97 -21
  296. package/manager/watchers/resolveFile.mjs +46 -0
  297. package/manager/watchers/resolveFile.test.mjs +67 -0
  298. package/manager/watchers/resolvePackageSpecifier.mjs +127 -0
  299. package/manager/watchers/resolvePackageSpecifier.test.mjs +151 -0
  300. package/manager/watchers/restartRequestWatcher.mjs +7 -4
  301. package/manager/watchers/restartRequestWatcher.test.mjs +43 -6
  302. package/manager/watchers/selectLocalPluginPackages.test.mjs +1 -0
  303. package/package.json +50 -49
  304. package/package.original.json +50 -49
  305. package/src/app.js +83 -85
  306. package/src/html/renderDevPage.test.mjs +1 -0
  307. package/src/lib/getPathSegments.js +16 -1
  308. package/src/{routes/docs/checkpointsList.js → lib/getRequestSurface.js} +6 -4
  309. package/src/lib/isTabAnswer.js +32 -0
  310. package/src/lib/isTabChannelCaller.js +35 -0
  311. package/src/middleware/apiContext.js +4 -2
  312. package/src/middleware/createSameOriginGuard.test.mjs +1 -0
  313. package/src/middleware/errorHandler.js +33 -45
  314. package/src/middleware/errorHandler.test.mjs +10 -10
  315. package/src/middleware/isRebindingSafeHost.test.mjs +1 -0
  316. package/src/middleware/localDevToolsOnly.js +13 -1
  317. package/src/middleware/localDevToolsOnly.test.mjs +36 -2
  318. package/src/middleware/noStore.test.mjs +1 -0
  319. package/src/middleware/staleFlag.test.mjs +1 -0
  320. package/src/middleware/stampCaller.test.mjs +1 -0
  321. package/src/routes/agentBearer.test.mjs +183 -0
  322. package/src/routes/auth.test.mjs +10 -10
  323. package/src/routes/clientError.js +21 -4
  324. package/src/routes/clientError.test.mjs +127 -0
  325. package/src/routes/devInspect.js +6 -51
  326. package/src/routes/devInspect.test.mjs +128 -3
  327. package/src/routes/devRecording.js +6 -17
  328. package/src/routes/devRecording.test.mjs +54 -3
  329. package/src/routes/docs/buildStatus.test.mjs +6 -6
  330. package/src/routes/docs/events.test.mjs +4 -4
  331. package/src/routes/docs/find.js +3 -3
  332. package/src/routes/docs/journey.test.mjs +8 -8
  333. package/src/routes/docs/journeyRefusals.test.mjs +9 -9
  334. package/src/routes/docs/loadDocsRoutes.js +70 -0
  335. package/src/routes/docs/loadDocsRoutes.test.mjs +110 -0
  336. package/src/routes/docs/mcp.test.mjs +5 -5
  337. package/src/routes/docs/mutants.js +7 -0
  338. package/src/routes/docs/mutants.test.mjs +20 -6
  339. package/src/routes/docs/parsePathParamsParam.test.mjs +1 -0
  340. package/src/routes/docs/parseUserParam.test.mjs +1 -0
  341. package/src/routes/docs/restart.test.mjs +1 -0
  342. package/src/routes/endpoints.js +24 -0
  343. package/src/routes/endpointsLink.test.mjs +111 -0
  344. package/src/routes/endpointsTextAnswer.test.mjs +8 -8
  345. package/src/routes/jitPage.js +13 -1
  346. package/src/routes/jitPage.test.mjs +36 -11
  347. package/src/routes/mcp.js +6 -0
  348. package/src/routes/mcp.test.mjs +23 -8
  349. package/src/routes/mcpMemberToken.test.mjs +8 -8
  350. package/src/routes/mcpProtectedResourceMetadata.test.mjs +2 -2
  351. package/src/routes/{docs/checkpointsRevert.js → mobileRoot.js} +10 -13
  352. package/src/routes/mobileRoutes.test.mjs +223 -0
  353. package/src/routes/mobileSignIn.js +58 -0
  354. package/src/routes/mobileSignIn.test.mjs +59 -0
  355. package/src/routes/mobileSignInCallback.js +34 -0
  356. package/src/routes/mobileSignInCallback.test.mjs +51 -0
  357. package/src/routes/mountDevPageRoutes.js +10 -2
  358. package/src/routes/mountDevPageRoutes.test.mjs +25 -1
  359. package/src/routes/mountMobileWellKnown.js +35 -0
  360. package/src/routes/mountMobileWellKnown.test.mjs +79 -0
  361. package/src/routes/mountOauthDiscovery.test.mjs +5 -5
  362. package/src/routes/normalizeMcpProtocolVersionHeader.test.mjs +1 -0
  363. package/src/routes/reload.js +101 -20
  364. package/src/routes/reload.test.mjs +153 -0
  365. package/src/routes/request.js +1 -22
  366. package/src/routes/request.test.mjs +7 -24
  367. package/src/routes/requestBody.test.mjs +14 -27
  368. package/src/routes/websocket.test.mjs +2 -2
  369. package/src/routes/wellKnownFallback.test.mjs +2 -2
  370. package/src/websocket/devWebSocket.test.mjs +12 -12
  371. package/vite.config.js +13 -1
  372. package/client/feedback/FeedbackMount.jsx +0 -83
  373. package/client/feedback/FeedbackOverlay.jsx +0 -904
  374. package/client/feedback/captureTabScreenshot.js +0 -84
  375. package/client/feedback/copyToClipboard.js +0 -45
  376. package/client/feedback/drawAnnotationsSvg.js +0 -119
  377. package/client/feedback/feedbackStyles.js +0 -304
  378. package/client/feedback/pinResponsiveImages.js +0 -59
  379. package/client/feedback/sendFeedback.js +0 -39
  380. package/client/feedback/useFeedbackToggle.js +0 -70
  381. package/client/recorder/buildEngineRecord.js +0 -37
  382. package/client/recorder/buildInteractionRecord.js +0 -64
  383. package/client/recorder/buildTraceEvent.js +0 -57
  384. package/client/recorder/buildTraceEvent.test.mjs +0 -81
  385. package/client/recorder/chunkRecords.js +0 -69
  386. package/client/recorder/chunkRecords.test.mjs +0 -59
  387. package/client/recorder/collectEventEndpoints.js +0 -40
  388. package/client/recorder/collectEventRequests.js +0 -39
  389. package/client/recorder/createPairingBuffer.js +0 -187
  390. package/client/recorder/createPasswordRedactor.js +0 -84
  391. package/client/recorder/createRecordBatcher.js +0 -54
  392. package/client/recorder/createRecordBatcher.test.mjs +0 -76
  393. package/client/recorder/createRecordingSession.js +0 -61
  394. package/client/recorder/createRecordingSession.test.mjs +0 -72
  395. package/client/recorder/diffStateWrites.js +0 -77
  396. package/client/recorder/diffStateWrites.test.mjs +0 -66
  397. package/client/recorder/isEventCall.js +0 -30
  398. package/client/recorder/jsonType.js +0 -39
  399. package/client/recorder/sendRecords.js +0 -40
  400. package/lib/docs/captureAnnotatedScreenshot.js +0 -99
  401. package/lib/docs/checkpointPaths.js +0 -91
  402. package/lib/docs/checkpointStore.js +0 -243
  403. package/lib/docs/checkpointToMocks.js +0 -65
  404. package/lib/docs/configCheckpoints.test.mjs +0 -156
  405. package/lib/docs/createConfigCheckpoint.js +0 -92
  406. package/lib/docs/dataSets/findCollectionCollisions.js +0 -52
  407. package/lib/docs/devMockRegistry.js +0 -68
  408. package/lib/docs/enrichFeedback.js +0 -71
  409. package/lib/docs/evalOperator.js +0 -49
  410. package/lib/docs/evalOperator.test.mjs +0 -157
  411. package/lib/docs/evalOperatorHeadless.js +0 -159
  412. package/lib/docs/evalOperatorHeadless.test.mjs +0 -78
  413. package/lib/docs/evalOperatorInTab.js +0 -49
  414. package/lib/docs/formatFeedback.js +0 -142
  415. package/lib/docs/formatFeedback.test.mjs +0 -252
  416. package/lib/docs/getPluginDoc.js +0 -53
  417. package/lib/docs/listConfigCheckpoints.js +0 -55
  418. package/lib/docs/loadState.js +0 -220
  419. package/lib/docs/revertConfigCheckpoint.js +0 -73
  420. package/lib/docs/saveAnnotatedScreenshot.js +0 -43
  421. package/lib/docs/scaffoldPage.js +0 -77
  422. package/lib/docs/scaffoldPage.test.mjs +0 -97
  423. package/lib/docs/snapshotState.js +0 -67
  424. package/lib/docs/stateCheckpoints.test.mjs +0 -443
  425. package/manager/watchers/listServerSidePackages.mjs +0 -47
  426. package/manager/watchers/listServerSidePackages.test.mjs +0 -38
  427. package/src/routes/docs/checkpointsCreate.js +0 -28
  428. package/src/routes/docs/evalOperator.js +0 -70
  429. package/src/routes/docs/inspectState.js +0 -59
  430. package/src/routes/docs/loadState.js +0 -51
  431. package/src/routes/docs/pluginDoc.js +0 -33
  432. package/src/routes/docs/plugins.js +0 -23
  433. package/src/routes/docs/runEndpoint.js +0 -54
  434. package/src/routes/docs/runEndpoint.test.mjs +0 -165
  435. package/src/routes/docs/runRequest.js +0 -53
  436. package/src/routes/docs/runRequest.test.mjs +0 -92
  437. package/src/routes/docs/schema.js +0 -37
  438. package/src/routes/docs/screenshot.js +0 -120
  439. package/src/routes/docs/screenshot.test.mjs +0 -117
  440. package/src/routes/docs/search.js +0 -40
  441. package/src/routes/docs/snapshotState.js +0 -50
  442. package/src/routes/docs/stateCheckpointsList.js +0 -26
  443. package/src/routes/docs/types.js +0 -33
  444. package/src/routes/feedback.js +0 -107
  445. package/src/routes/feedback.test.mjs +0 -204
@@ -20,6 +20,8 @@ import net from 'node:net';
20
20
  import { devPassiveHeader } from '@lowdefy/node-utils';
21
21
 
22
22
  import buildWaitHeader from '../../lib/docs/buildWaitHeader.js';
23
+ import { pairHeader, remoteCallerHeader } from '../../lib/server/pairingHeaders.js';
24
+ import checkPairing from '../utils/checkPairing.mjs';
23
25
  import readBuildStatusWait from '../utils/readBuildStatusWait.mjs';
24
26
 
25
27
  /*
@@ -50,6 +52,15 @@ until then it still answers the probe. A GET or HEAD that never reached the
50
52
  child (a refused connect, or a keep-alive socket the dying child had closed)
51
53
  is replayed through the hold rather than answered 502: a child can close its
52
54
  sockets before the manager sees it exit.
55
+
56
+ A child stopped for being idle (createIdleChild) is started again only by a
57
+ request that is use (isActivity), which is held as for a restart. A request
58
+ that is not use - a passive read, an event-stream GET, a websocket upgrade -
59
+ is answered 503 at once with Retry-After, so status checks and reconnecting
60
+ streams neither wake the child nor wait out the hold.
61
+
62
+ The proxy also counts the tabs holding a reload stream open, from the
63
+ stream's response start until it closes: an open tab keeps the child up.
53
64
  */
54
65
 
55
66
  const RETRY_MS = 250;
@@ -69,10 +80,16 @@ function probeChild(port) {
69
80
  });
70
81
  }
71
82
 
72
- async function waitForChild({ port, deadline }) {
83
+ function isChildStopped(context) {
84
+ return context.idleChild?.isStopped() === true;
85
+ }
86
+
87
+ // givesUp ends the wait early: a request that does not wake the child stops
88
+ // waiting once the child is idle-stopped.
89
+ async function waitForChild({ port, deadline, givesUp = () => false }) {
73
90
  for (;;) {
74
91
  if (await probeChild(port)) return true;
75
- if (Date.now() > deadline) return false;
92
+ if (Date.now() > deadline || givesUp()) return false;
76
93
  await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
77
94
  }
78
95
  }
@@ -94,13 +111,17 @@ function waitUntil({ promise, deadline }) {
94
111
  ]);
95
112
  }
96
113
 
97
- async function waitForConfirmedChild({ context, proxyState, deadline }) {
114
+ async function waitForConfirmedChild({ context, proxyState, deadline, wakes }) {
98
115
  if (isConfirmedChild({ context, proxyState })) {
99
116
  return true;
100
117
  }
101
118
  await waitUntil({ promise: context.devServerExited, deadline });
102
119
  const child = context.devServer;
103
- const up = await waitForChild({ port: context.internalPort, deadline });
120
+ const up = await waitForChild({
121
+ port: context.internalPort,
122
+ deadline,
123
+ givesUp: () => !wakes && isChildStopped(context),
124
+ });
104
125
  if (up) {
105
126
  proxyState.confirmedChild = child;
106
127
  }
@@ -109,6 +130,25 @@ async function waitForConfirmedChild({ context, proxyState, deadline }) {
109
130
 
110
131
  const REPLAYABLE_METHODS = ['GET', 'HEAD'];
111
132
 
133
+ const IDLE_RETRY_AFTER_S = 5;
134
+
135
+ function answerIdle(res) {
136
+ res.writeHead(503, {
137
+ 'content-type': 'application/json',
138
+ 'retry-after': String(IDLE_RETRY_AFTER_S),
139
+ 'x-lowdefy-child': 'stopped',
140
+ });
141
+ res.end(JSON.stringify({ message: 'Lowdefy dev server is idle.' }));
142
+ }
143
+
144
+ function isReloadStream({ context, req }) {
145
+ if (req.method !== 'GET') {
146
+ return false;
147
+ }
148
+ const { pathname } = new URL(req.url, 'http://localhost');
149
+ return pathname === `${context.basePath ?? ''}/api/reload`;
150
+ }
151
+
112
152
  // Nothing reached the child: the connect was refused, or the keep-alive socket
113
153
  // the agent reused had already been closed by a child that is going away.
114
154
  function isUnsentError({ error, proxyReq }) {
@@ -117,17 +157,26 @@ function isUnsentError({ error, proxyReq }) {
117
157
  );
118
158
  }
119
159
 
120
- function forwardRequest({ body, context, proxyState }, req, res, deadline = Date.now() + HOLD_MS) {
160
+ function forwardRequest(
161
+ { body, context, proxyState, wakes },
162
+ req,
163
+ res,
164
+ deadline = Date.now() + HOLD_MS
165
+ ) {
121
166
  // Wait for a live child BEFORE piping the request body — the body stream can
122
167
  // only be consumed once, so retrying after a failed proxy request would need
123
168
  // full-body buffering. Only a bodiless GET or HEAD that never reached the
124
169
  // child is replayed; any other request that loses the child mid-forward
125
170
  // surfaces as one 502, which the client's next attempt resolves through the
126
171
  // hold.
127
- waitForConfirmedChild({ context, proxyState, deadline }).then((up) => {
172
+ waitForConfirmedChild({ context, proxyState, deadline, wakes }).then((up) => {
128
173
  // The response, not the request: an incoming request reads as destroyed
129
174
  // once its body has been read, which a replayed GET's has.
130
175
  if (res.destroyed) return;
176
+ if (!up && !wakes && isChildStopped(context)) {
177
+ answerIdle(res);
178
+ return;
179
+ }
131
180
  if (!up) {
132
181
  res.writeHead(503, { 'content-type': 'application/json' });
133
182
  res.end(JSON.stringify({ message: 'Lowdefy dev server is restarting.' }));
@@ -141,6 +190,9 @@ function forwardRequest({ body, context, proxyState }, req, res, deadline = Date
141
190
  headers: req.headers,
142
191
  });
143
192
  proxyReq.on('response', (proxyRes) => {
193
+ if (proxyRes.statusCode === 200 && isReloadStream({ context, req })) {
194
+ context.requestActivity.trackTab(res);
195
+ }
144
196
  res.writeHead(proxyRes.statusCode, proxyRes.headers);
145
197
  // flushHeaders so SSE endpoints (reload stream, MCP notifications)
146
198
  // reach the client before the first event.
@@ -154,7 +206,7 @@ function forwardRequest({ body, context, proxyState }, req, res, deadline = Date
154
206
  REPLAYABLE_METHODS.includes(req.method) &&
155
207
  isUnsentError({ error, proxyReq })
156
208
  ) {
157
- forwardRequest({ body, context, proxyState }, req, res, deadline);
209
+ forwardRequest({ body, context, proxyState, wakes }, req, res, deadline);
158
210
  return;
159
211
  }
160
212
  if (res.headersSent) {
@@ -203,9 +255,42 @@ function isActivity(req) {
203
255
  // latest edits, restarts included, and only then forwarded: a restart ends
204
256
  // the dev server process, and any wait running in it. The header tells the
205
257
  // dev server what this wait saw, so it does not wait again.
258
+ // The pairing gate sits here, in front of Vite and the app alike, because the
259
+ // child only ever sees the proxy's loopback address. The child learns that a
260
+ // caller is remote from remoteCallerHeader, which only the proxy sets.
261
+ function readAccess({ context, req }) {
262
+ return checkPairing({
263
+ remoteAddress: req.socket.remoteAddress,
264
+ pairToken: context.lan?.token,
265
+ providedToken: req.headers[pairHeader],
266
+ });
267
+ }
268
+
269
+ const PAIRING_REFUSAL =
270
+ 'This dev server answers other machines only with the pairing token that `lowdefy dev --lan` prints.';
271
+
206
272
  async function handleRequest({ context, proxyState }, req, res) {
207
- if (isActivity(req)) {
273
+ const access = readAccess({ context, req });
274
+ if (access === 'refused') {
275
+ res.writeHead(401, { 'content-type': 'application/json' });
276
+ res.end(JSON.stringify({ message: PAIRING_REFUSAL }));
277
+ return;
278
+ }
279
+ delete req.headers[pairHeader];
280
+ delete req.headers[remoteCallerHeader];
281
+ if (access === 'paired') {
282
+ req.headers[remoteCallerHeader] = '1';
283
+ }
284
+ const wakes = isActivity(req);
285
+ if (!wakes && isChildStopped(context)) {
286
+ answerIdle(res);
287
+ return;
288
+ }
289
+ if (wakes) {
208
290
  context.requestActivity.trackResponse(res);
291
+ if (isChildStopped(context)) {
292
+ context.idleChild.wake().catch((error) => context.logger.error(error));
293
+ }
209
294
  }
210
295
  delete req.headers[buildWaitHeader];
211
296
  const { wait, body } = await readBuildStatusWait({ basePath: context.basePath, req });
@@ -217,12 +302,39 @@ async function handleRequest({ context, proxyState }, req, res) {
217
302
  waitedMs: String(waited.waitedMs),
218
303
  }).toString();
219
304
  }
220
- forwardRequest({ body, context, proxyState }, req, res);
305
+ forwardRequest({ body, context, proxyState, wakes }, req, res);
221
306
  }
222
307
 
308
+ const IDLE_UPGRADE_RESPONSE = [
309
+ 'HTTP/1.1 503 Service Unavailable',
310
+ `retry-after: ${IDLE_RETRY_AFTER_S}`,
311
+ 'x-lowdefy-child: stopped',
312
+ 'connection: close',
313
+ '',
314
+ '',
315
+ ].join('\r\n');
316
+
317
+ // An upgrade is never use (see isActivity), so it never wakes an idle-stopped child.
223
318
  function forwardUpgrade(context, req, socket, head) {
224
- waitForChild({ port: context.internalPort, deadline: Date.now() + HOLD_MS }).then((up) => {
319
+ const access = readAccess({ context, req });
320
+ if (access === 'refused') {
321
+ socket.end('HTTP/1.1 401 Unauthorized\r\nconnection: close\r\n\r\n');
322
+ return;
323
+ }
324
+ if (isChildStopped(context)) {
325
+ socket.end(IDLE_UPGRADE_RESPONSE);
326
+ return;
327
+ }
328
+ waitForChild({
329
+ port: context.internalPort,
330
+ deadline: Date.now() + HOLD_MS,
331
+ givesUp: () => isChildStopped(context),
332
+ }).then((up) => {
225
333
  if (socket.destroyed) return;
334
+ if (!up && isChildStopped(context)) {
335
+ socket.end(IDLE_UPGRADE_RESPONSE);
336
+ return;
337
+ }
226
338
  if (!up) {
227
339
  socket.end('HTTP/1.1 503 Service Unavailable\r\nconnection: close\r\n\r\n');
228
340
  return;
@@ -233,7 +345,13 @@ function forwardUpgrade(context, req, socket, head) {
233
345
  // websockets both pass through untouched.
234
346
  const lines = [`${req.method} ${req.url} HTTP/1.1`];
235
347
  for (let i = 0; i < req.rawHeaders.length; i += 2) {
236
- lines.push(`${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}`);
348
+ const name = req.rawHeaders[i].toLowerCase();
349
+ if (name !== pairHeader && name !== remoteCallerHeader) {
350
+ lines.push(`${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}`);
351
+ }
352
+ }
353
+ if (access === 'paired') {
354
+ lines.push(`${remoteCallerHeader}: 1`);
237
355
  }
238
356
  upstream.write(lines.join('\r\n') + '\r\n\r\n');
239
357
  if (head?.length) upstream.write(head);
@@ -247,9 +365,17 @@ function forwardUpgrade(context, req, socket, head) {
247
365
  });
248
366
  }
249
367
 
250
- function startProxy(context) {
251
- if (context.proxyServer) return Promise.resolve();
252
- const proxyState = { confirmedChild: null };
368
+ function listen({ server, port, host }) {
369
+ return new Promise((resolve, reject) => {
370
+ server.once('error', reject);
371
+ server.listen(port, host, () => {
372
+ server.removeListener('error', reject);
373
+ resolve();
374
+ });
375
+ });
376
+ }
377
+
378
+ function createProxyServer({ context, proxyState }) {
253
379
  const proxy = http.createServer((req, res) => {
254
380
  // A client that drops an MCP request while its body is read.
255
381
  handleRequest({ context, proxyState }, req, res).catch(() => res.destroy());
@@ -259,19 +385,24 @@ function startProxy(context) {
259
385
  // request timeout; keep the proxy transparent.
260
386
  proxy.requestTimeout = 0;
261
387
  proxy.headersTimeout = 60000;
262
- context.proxyServer = proxy;
263
- return new Promise((resolve, reject) => {
264
- proxy.once('error', reject);
265
- // 'localhost' for parity with the Vite default host the child used to bind
266
- // — the dev server stays loopback-only, not exposed on the LAN.
267
- proxy.listen(context.options.port, 'localhost', () => {
268
- proxy.removeListener('error', reject);
269
- context.logger.debug(
270
- `Proxy listening on port ${context.options.port}, forwarding to ${context.internalPort}.`
271
- );
272
- resolve();
273
- });
274
- });
388
+ return proxy;
389
+ }
390
+
391
+ async function startProxy(context) {
392
+ if (context.proxyServer) return;
393
+ const proxyState = { confirmedChild: null };
394
+ const { port } = context.options;
395
+ context.proxyServer = createProxyServer({ context, proxyState });
396
+ // 'localhost' for parity with the Vite default host the child used to bind
397
+ // - the dev server stays loopback-only unless --lan asks for the network.
398
+ await listen({ server: context.proxyServer, port, host: 'localhost' });
399
+ // --lan adds a listener on the chosen interface's address only, not on every
400
+ // interface, so a VPN or Docker network does not reach the server too.
401
+ if (context.lan) {
402
+ context.lanProxyServer = createProxyServer({ context, proxyState });
403
+ await listen({ server: context.lanProxyServer, port, host: context.lan.address });
404
+ }
405
+ context.logger.debug(`Proxy listening on port ${port}, forwarding to ${context.internalPort}.`);
275
406
  }
276
407
 
277
408
  export default startProxy;
@@ -0,0 +1,204 @@
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 dns from 'node:dns';
18
+ import http from 'node:http';
19
+ import net from 'node:net';
20
+
21
+ import { vi, afterEach, beforeEach, expect, test } from 'vitest';
22
+
23
+ // Every test request comes from this computer. Mocking the loopback check
24
+ // makes the proxy treat it as a request from a phone on the network.
25
+ const mockIsLoopbackAddress = vi.fn();
26
+ vi.doMock('../utils/isLoopbackAddress.mjs', () => ({
27
+ default: mockIsLoopbackAddress,
28
+ }));
29
+
30
+ const { default: startProxy } = await import('./startProxy.mjs');
31
+ const { default: createBuildActivity } = await import('../utils/createBuildActivity.mjs');
32
+ const { default: createRequestActivity } = await import('../utils/createRequestActivity.mjs');
33
+
34
+ const TOKEN = 'a'.repeat(43);
35
+
36
+ function listen(server) {
37
+ return new Promise((resolve) => {
38
+ server.listen(0, '127.0.0.1', () => resolve(server.address().port));
39
+ });
40
+ }
41
+
42
+ function close(server) {
43
+ return new Promise((resolve) => {
44
+ server.closeAllConnections?.();
45
+ server.close(() => resolve());
46
+ });
47
+ }
48
+
49
+ function getFreePort() {
50
+ return new Promise((resolve) => {
51
+ const server = net.createServer();
52
+ server.listen(0, '127.0.0.1', () => {
53
+ const { port } = server.address();
54
+ server.close(() => resolve(port));
55
+ });
56
+ });
57
+ }
58
+
59
+ // The loopback address 'localhost' does not bind, so the LAN listener can
60
+ // share the port in a test.
61
+ async function getOtherLoopbackAddress() {
62
+ const { address } = await dns.promises.lookup('localhost');
63
+ return address === '::1' ? '127.0.0.1' : '::1';
64
+ }
65
+
66
+ let child;
67
+ let context;
68
+ let seen;
69
+
70
+ beforeEach(() => {
71
+ mockIsLoopbackAddress.mockReturnValue(true);
72
+ });
73
+
74
+ afterEach(async () => {
75
+ if (context?.proxyServer) await close(context.proxyServer);
76
+ if (context?.lanProxyServer) await close(context.lanProxyServer);
77
+ if (child) await close(child);
78
+ child = undefined;
79
+ context = undefined;
80
+ });
81
+
82
+ async function startChildAndProxy({ lan } = {}) {
83
+ seen = [];
84
+ child = http.createServer((req, res) => {
85
+ seen.push(req.headers);
86
+ res.end('ok');
87
+ });
88
+ child.on('upgrade', (req, socket) => {
89
+ seen.push(req.headers);
90
+ socket.write(
91
+ 'HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: upgrade\r\n\r\n'
92
+ );
93
+ socket.destroy();
94
+ });
95
+ const internalPort = await listen(child);
96
+ context = {
97
+ basePath: '',
98
+ buildActivity: createBuildActivity({ onChange: () => {} }),
99
+ internalPort,
100
+ lan,
101
+ logger: { debug: vi.fn() },
102
+ options: { port: await getFreePort() },
103
+ requestActivity: createRequestActivity({ onChange: () => {}, throttleMs: 0 }),
104
+ };
105
+ await startProxy(context);
106
+ return context.options.port;
107
+ }
108
+
109
+ test('startProxy lets a request from this computer through without a pairing token', async () => {
110
+ const port = await startChildAndProxy({ lan: { address: '127.0.0.1', token: TOKEN } });
111
+ const response = await fetch(`http://localhost:${port}/api/ping`);
112
+ expect(response.status).toBe(200);
113
+ expect(seen[0]['x-lowdefy-dev-remote']).toBeUndefined();
114
+ });
115
+
116
+ test('startProxy strips a remote marker a local caller sends itself', async () => {
117
+ const port = await startChildAndProxy();
118
+ await fetch(`http://localhost:${port}/api/ping`, { headers: { 'x-lowdefy-dev-remote': '1' } });
119
+ expect(seen[0]['x-lowdefy-dev-remote']).toBeUndefined();
120
+ });
121
+
122
+ test('startProxy refuses a request from another machine without the pairing token', async () => {
123
+ const port = await startChildAndProxy({ lan: { address: '127.0.0.1', token: TOKEN } });
124
+ mockIsLoopbackAddress.mockReturnValue(false);
125
+ const response = await fetch(`http://localhost:${port}/api/mobile/root`);
126
+ expect(response.status).toBe(401);
127
+ expect((await response.json()).message).toContain('pairing token');
128
+ expect(seen).toEqual([]);
129
+ });
130
+
131
+ test('startProxy refuses a request from another machine with the wrong pairing token', async () => {
132
+ const port = await startChildAndProxy({ lan: { address: '127.0.0.1', token: TOKEN } });
133
+ mockIsLoopbackAddress.mockReturnValue(false);
134
+ const response = await fetch(`http://localhost:${port}/api/mobile/root`, {
135
+ headers: { 'x-lowdefy-pair': 'b'.repeat(43) },
136
+ });
137
+ expect(response.status).toBe(401);
138
+ expect(seen).toEqual([]);
139
+ });
140
+
141
+ test('startProxy refuses every request from another machine when --lan is off', async () => {
142
+ const port = await startChildAndProxy();
143
+ mockIsLoopbackAddress.mockReturnValue(false);
144
+ const response = await fetch(`http://localhost:${port}/api/mobile/root`, {
145
+ headers: { 'x-lowdefy-pair': TOKEN },
146
+ });
147
+ expect(response.status).toBe(401);
148
+ });
149
+
150
+ test('startProxy forwards a paired request marked remote, without the token', async () => {
151
+ const port = await startChildAndProxy({ lan: { address: '127.0.0.1', token: TOKEN } });
152
+ mockIsLoopbackAddress.mockReturnValue(false);
153
+ const response = await fetch(`http://localhost:${port}/api/mobile/root`, {
154
+ headers: { 'x-lowdefy-pair': TOKEN },
155
+ });
156
+ expect(response.status).toBe(200);
157
+ expect(seen[0]['x-lowdefy-dev-remote']).toBe('1');
158
+ expect(seen[0]['x-lowdefy-pair']).toBeUndefined();
159
+ });
160
+
161
+ function upgrade({ port, headers }) {
162
+ return new Promise((resolve) => {
163
+ const clientRequest = http.get(`http://localhost:${port}/hmr`, {
164
+ headers: { connection: 'upgrade', upgrade: 'websocket', ...headers },
165
+ });
166
+ clientRequest.on('upgrade', (res, socket) => {
167
+ socket.destroy();
168
+ resolve(res.statusCode);
169
+ });
170
+ clientRequest.on('response', (res) => {
171
+ res.resume();
172
+ resolve(res.statusCode);
173
+ });
174
+ });
175
+ }
176
+
177
+ test('startProxy refuses a websocket upgrade from another machine without the token', async () => {
178
+ const port = await startChildAndProxy({ lan: { address: '127.0.0.1', token: TOKEN } });
179
+ mockIsLoopbackAddress.mockReturnValue(false);
180
+ expect(await upgrade({ port, headers: {} })).toBe(401);
181
+ expect(seen).toEqual([]);
182
+ });
183
+
184
+ test('startProxy forwards a paired websocket upgrade marked remote, without the token', async () => {
185
+ const port = await startChildAndProxy({ lan: { address: '127.0.0.1', token: TOKEN } });
186
+ mockIsLoopbackAddress.mockReturnValue(false);
187
+ expect(await upgrade({ port, headers: { 'x-lowdefy-pair': TOKEN } })).toBe(101);
188
+ expect(seen[0]['x-lowdefy-dev-remote']).toBe('1');
189
+ expect(seen[0]['x-lowdefy-pair']).toBeUndefined();
190
+ });
191
+
192
+ test('startProxy also listens on the --lan address, behind the same pairing gate', async () => {
193
+ const address = await getOtherLoopbackAddress();
194
+ const port = await startChildAndProxy({ lan: { address, token: TOKEN } });
195
+ expect(context.lanProxyServer.address()).toMatchObject({ address, port });
196
+ mockIsLoopbackAddress.mockReturnValue(false);
197
+ const host = address.includes(':') ? `[${address}]` : address;
198
+ const refused = await fetch(`http://${host}:${port}/api/ping`);
199
+ expect(refused.status).toBe(401);
200
+ const paired = await fetch(`http://${host}:${port}/api/ping`, {
201
+ headers: { 'x-lowdefy-pair': TOKEN },
202
+ });
203
+ expect(paired.status).toBe(200);
204
+ });
@@ -17,7 +17,7 @@
17
17
  import http from 'node:http';
18
18
  import net from 'node:net';
19
19
 
20
- import { jest } from '@jest/globals';
20
+ import { vi, afterEach, expect, test } from 'vitest';
21
21
 
22
22
  const { default: startProxy } = await import('./startProxy.mjs');
23
23
  const { default: createBuildActivity } = await import('../utils/createBuildActivity.mjs');
@@ -64,7 +64,7 @@ async function startChildAndProxy(handler) {
64
64
  context = {
65
65
  internalPort,
66
66
  options: { port: await getFreePort() },
67
- logger: { debug: jest.fn() },
67
+ logger: { debug: vi.fn() },
68
68
  requestActivity: createRequestActivity({
69
69
  onChange: (fields) => activityRecords.push(fields),
70
70
  throttleMs: 0,
@@ -466,3 +466,128 @@ test('startProxy keeps a request held through a child restart counted', async ()
466
466
  expect(await pending).toBe('new');
467
467
  await waitFor(() => activeRequests() === 0);
468
468
  });
469
+
470
+ function stopChildIdle() {
471
+ const idleChild = { stopped: true };
472
+ idleChild.isStopped = () => idleChild.stopped;
473
+ idleChild.wake = vi.fn(async () => {
474
+ idleChild.stopped = false;
475
+ });
476
+ context.idleChild = idleChild;
477
+ return idleChild;
478
+ }
479
+
480
+ test.each([
481
+ ['a passive read', { method: 'GET', headers: { 'x-lowdefy-passive': '1' } }, '/build-status'],
482
+ [
483
+ 'a reload stream reconnect',
484
+ { method: 'GET', headers: { accept: 'text/event-stream' } },
485
+ '/api/reload',
486
+ ],
487
+ [
488
+ 'an MCP push stream reconnect',
489
+ { method: 'GET', headers: { accept: 'text/event-stream' } },
490
+ '/lowdefy-docs/mcp',
491
+ ],
492
+ ])(
493
+ 'startProxy answers %s at once without waking an idle-stopped child',
494
+ async (_, init, requestPath) => {
495
+ let childRequests = 0;
496
+ const port = await startChildAndProxy((req, res) => {
497
+ childRequests += 1;
498
+ res.end('ok');
499
+ });
500
+ context.basePath = '';
501
+ const idleChild = stopChildIdle();
502
+
503
+ const started = Date.now();
504
+ const response = await fetch(`http://localhost:${port}${requestPath}`, init);
505
+ expect(Date.now() - started).toBeLessThan(1000);
506
+ expect(response.status).toBe(503);
507
+ expect(response.headers.get('retry-after')).toBe('5');
508
+ expect(response.headers.get('x-lowdefy-child')).toBe('stopped');
509
+ expect(await response.json()).toEqual({ message: 'Lowdefy dev server is idle.' });
510
+ expect(idleChild.wake).not.toHaveBeenCalled();
511
+ expect(childRequests).toBe(0);
512
+ }
513
+ );
514
+
515
+ test('startProxy answers a websocket upgrade 503 at once while the child is idle-stopped', async () => {
516
+ const port = await startChildAndProxy((req, res) => res.end('ok'));
517
+ const idleChild = stopChildIdle();
518
+ const clientRequest = http.get(`http://localhost:${port}/hmr`, {
519
+ headers: { connection: 'upgrade', upgrade: 'websocket' },
520
+ });
521
+ const response = await new Promise((resolve) => clientRequest.on('response', resolve));
522
+ expect(response.statusCode).toBe(503);
523
+ expect(response.headers['x-lowdefy-child']).toBe('stopped');
524
+ expect(idleChild.wake).not.toHaveBeenCalled();
525
+ });
526
+
527
+ test('startProxy wakes an idle-stopped child for a request that is use and holds it until the child answers', async () => {
528
+ const port = await startChildAndProxy((req, res) => res.end('old'));
529
+ context.basePath = '';
530
+ await close(child);
531
+ const idleChild = stopChildIdle();
532
+ idleChild.wake.mockImplementation(async () => {
533
+ idleChild.stopped = false;
534
+ await new Promise((resolve) => setTimeout(resolve, 300));
535
+ child = http.createServer((req, res) => res.end('woken'));
536
+ await new Promise((resolve) => child.listen(context.internalPort, '127.0.0.1', resolve));
537
+ context.devServer = { exitCode: null, signalCode: null };
538
+ });
539
+
540
+ const response = await fetch(`http://localhost:${port}/page/home`);
541
+ expect(await response.text()).toBe('woken');
542
+ expect(idleChild.wake).toHaveBeenCalledTimes(1);
543
+ });
544
+
545
+ test('startProxy answers a held passive read idle once the child is idle-stopped', async () => {
546
+ const port = await startChildAndProxy((req, res) => res.end('ok'));
547
+ await close(child);
548
+ context.idleChild = { isStopped: () => false, wake: vi.fn() };
549
+
550
+ const pending = fetch(`http://localhost:${port}/build-status`, {
551
+ headers: { 'x-lowdefy-passive': '1' },
552
+ });
553
+ await new Promise((resolve) => setTimeout(resolve, 300));
554
+ context.idleChild.isStopped = () => true;
555
+ const response = await pending;
556
+ expect(response.status).toBe(503);
557
+ expect(response.headers.get('x-lowdefy-child')).toBe('stopped');
558
+ });
559
+
560
+ test('startProxy counts a tab while its reload stream is open', async () => {
561
+ const child$ = heldHandler({ contentType: 'text/event-stream' });
562
+ const port = await startChildAndProxy(child$.handler);
563
+ context.basePath = '/base';
564
+
565
+ const clientRequest = http.get(`http://localhost:${port}/base/api/reload`, {
566
+ headers: { accept: 'text/event-stream' },
567
+ });
568
+ clientRequest.on('error', () => {});
569
+ await new Promise((resolve) => clientRequest.on('response', resolve));
570
+ await waitFor(() => context.requestActivity.snapshot().openTabs === 1);
571
+ expect(activityRecords.at(-1).openTabs).toBe(1);
572
+ expect(activeRequests()).toBe(0);
573
+
574
+ clientRequest.destroy();
575
+ await waitFor(() => context.requestActivity.snapshot().openTabs === 0);
576
+ child$.release();
577
+ });
578
+
579
+ test('startProxy does not count other event streams as tabs', async () => {
580
+ const child$ = heldHandler({ contentType: 'text/event-stream' });
581
+ const port = await startChildAndProxy(child$.handler);
582
+ context.basePath = '';
583
+
584
+ const clientRequest = http.get(`http://localhost:${port}/lowdefy-docs/mcp`, {
585
+ headers: { accept: 'text/event-stream' },
586
+ });
587
+ clientRequest.on('error', () => {});
588
+ await new Promise((resolve) => clientRequest.on('response', resolve));
589
+ await waitFor(() => child$.held.length === 1);
590
+ expect(context.requestActivity.snapshot().openTabs).toBe(0);
591
+ clientRequest.destroy();
592
+ child$.release();
593
+ });
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { spawn } from 'child_process';
18
18
  import crypto from 'crypto';
19
+ import readline from 'readline';
19
20
 
20
21
  import createServerEnv from '../utils/createServerEnv.mjs';
21
22
  import killTaggedBrowser from '../utils/killTaggedBrowser.mjs';
@@ -98,14 +99,11 @@ function startServer(context) {
98
99
  }
99
100
  );
100
101
 
102
+ // Whole lines, not chunks: a chunk boundary can fall inside a line, which
103
+ // split an uncaught crash's stack into many separate ERROR fragments.
101
104
  const stdErrLineHandler = createStdErrLineHandler({ context });
102
- devServer.stderr.on('data', (data) => {
103
- data
104
- .toString('utf8')
105
- .split('\n')
106
- .forEach((line) => {
107
- if (line) stdErrLineHandler(line);
108
- });
105
+ readline.createInterface({ input: devServer.stderr, crlfDelay: Infinity }).on('line', (line) => {
106
+ if (line) stdErrLineHandler(line);
109
107
  });
110
108
 
111
109
  context.logger.debug(`Started dev server with pid ${devServer.pid}.`);