gloomberb 0.19.5 → 0.20.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 (318) hide show
  1. package/LICENSE +0 -4
  2. package/package.json +6 -5
  3. package/patches/@opentui%2Fcore@0.3.2.patch +86 -25
  4. package/patches/electrobun-devkit@2.0.5.patch +148 -0
  5. package/src/api-client/bond-trades.ts +59 -0
  6. package/src/api-client/data.ts +21 -0
  7. package/src/api-client/equity-screener.ts +23 -0
  8. package/src/api-client/index.ts +2 -0
  9. package/src/api-client/types/account.ts +86 -0
  10. package/src/api-client/types/assist.ts +32 -0
  11. package/src/api-client/types/auth.ts +63 -0
  12. package/src/api-client/types/billing.ts +54 -0
  13. package/src/api-client/types/chat.ts +180 -0
  14. package/src/api-client/types/congress.ts +107 -0
  15. package/src/api-client/types/credit.ts +110 -0
  16. package/src/api-client/types/econ.ts +158 -0
  17. package/src/api-client/types/equity-diagnostic.ts +73 -0
  18. package/src/api-client/types/filings-and-calls.ts +350 -0
  19. package/src/api-client/types/index.ts +25 -0
  20. package/src/api-client/types/jobs.ts +147 -0
  21. package/src/api-client/types/market.ts +122 -0
  22. package/src/api-client/types/news.ts +91 -0
  23. package/src/api-client/types/notes-and-theses.ts +172 -0
  24. package/src/api-client/types/quotes.ts +28 -0
  25. package/src/api-client/types/scanners.ts +125 -0
  26. package/src/api-client/types/screener.ts +65 -0
  27. package/src/api-client/types/search.ts +107 -0
  28. package/src/api-client/types/sync.ts +14 -0
  29. package/src/api-client/types/team-collections.ts +43 -0
  30. package/src/api-client/types/team-views.ts +32 -0
  31. package/src/api-client/types/teams.ts +135 -0
  32. package/src/api-client/types/ticker-data.ts +57 -0
  33. package/src/api-client/types/tweets.ts +59 -0
  34. package/src/api-client/types/world-venues.ts +23 -0
  35. package/src/app/pane-runtime/index.tsx +2 -0
  36. package/src/app/pane-runtime/plugin-bindings.ts +10 -1
  37. package/src/app/runtime/desktop-deeplink.ts +41 -6
  38. package/src/app/star-prompt/status-line.tsx +1 -1
  39. package/src/app.tsx +64 -23
  40. package/src/architecture/ui-tokens-allowlist.json +0 -8
  41. package/src/cli/commands/market.ts +149 -10
  42. package/src/cli/commands/search.ts +21 -3
  43. package/src/cli/commands/ticker.ts +90 -36
  44. package/src/cli/desktop-pane-shot-browser.ts +69 -3
  45. package/src/cli/glossary.ts +3 -3
  46. package/src/cli/known-gaps.ts +8 -0
  47. package/src/cli/listing-arg.ts +12 -0
  48. package/src/cli/pane-functions/capabilities.ts +2 -0
  49. package/src/cli/pane-functions/catalog.ts +25 -5
  50. package/src/cli/pane-functions/function-help.ts +8 -5
  51. package/src/cli/pane-functions/headless.ts +4 -3
  52. package/src/cli/pane-functions/resolver.ts +75 -2
  53. package/src/cli/quote-answer.ts +9 -0
  54. package/src/cli/symbol-list.ts +54 -2
  55. package/src/cli/symbol-rows.ts +14 -2
  56. package/src/cli/ticker-resolution.ts +89 -20
  57. package/src/components/chart/composite/axis-overlays.tsx +60 -27
  58. package/src/components/chart/composite/composite-chart.tsx +118 -63
  59. package/src/components/chart/composite/cursor-source.ts +111 -0
  60. package/src/components/chart/composite/format.ts +168 -6
  61. package/src/components/chart/composite/legend.tsx +8 -4
  62. package/src/components/chart/composite/panel-labels.ts +20 -1
  63. package/src/components/chart/composite/panel-surface.tsx +201 -92
  64. package/src/components/chart/composite/price-axis-labels.tsx +92 -46
  65. package/src/components/chart/composite/price-series.ts +31 -8
  66. package/src/components/chart/composite/scene.ts +154 -59
  67. package/src/components/chart/composite/series-axis-tags.tsx +4 -2
  68. package/src/components/chart/composite/time-axis.ts +13 -5
  69. package/src/components/chart/composite/time-scale.ts +211 -56
  70. package/src/components/chart/composite/types.ts +11 -1
  71. package/src/components/chart/composite/use-composite-chart-keyboard.ts +43 -14
  72. package/src/components/chart/curve/curve-surface.tsx +5 -2
  73. package/src/components/chart/curve/model.ts +4 -1
  74. package/src/components/chart/native/use-bitmap-metrics.ts +81 -0
  75. package/src/components/chart/static/series.ts +3 -0
  76. package/src/components/command-bar/commands/collection-list.ts +81 -0
  77. package/src/components/command-bar/commands/direct/index.ts +6 -0
  78. package/src/components/command-bar/commands/registry.ts +8 -0
  79. package/src/components/command-bar/layout-items/current-layout.ts +22 -1
  80. package/src/components/command-bar/layout-items/focused-pane.ts +22 -1
  81. package/src/components/command-bar/pane-templates/items.ts +19 -3
  82. package/src/components/command-bar/pane-templates/workflow.ts +5 -0
  83. package/src/components/command-bar/routes/root/results.ts +23 -3
  84. package/src/components/command-bar/routes/root/selection.ts +4 -2
  85. package/src/components/command-bar/routes/root/shortcut-feedback.ts +1 -1
  86. package/src/components/command-bar/routes/root/shortcut-items.ts +3 -4
  87. package/src/components/command-bar/routes/root/shortcuts.ts +58 -14
  88. package/src/components/command-bar/routes/root/ticker-first.ts +32 -0
  89. package/src/components/command-bar/surface/environment.ts +2 -0
  90. package/src/components/command-bar/view-model.ts +7 -0
  91. package/src/components/command-bar/workflow/ops.ts +2 -1
  92. package/src/components/command-bar/workflow/tickers.ts +20 -0
  93. package/src/components/data-table/export.ts +4 -1
  94. package/src/components/layout/detached-pane-shell.tsx +10 -37
  95. package/src/components/layout/double-escape-close.ts +90 -0
  96. package/src/components/layout/header.tsx +3 -2
  97. package/src/components/layout/market-summary.ts +6 -3
  98. package/src/components/layout/pane/footer/index.tsx +2 -6
  99. package/src/components/layout/pane/footer/model.ts +6 -12
  100. package/src/components/layout/shell/active-drag.ts +53 -11
  101. package/src/components/layout/shell/drag/magnets.ts +128 -19
  102. package/src/components/layout/shell/menu.ts +15 -1
  103. package/src/components/layout/shell/pane/actions.ts +10 -2
  104. package/src/components/layout/shell/pane/management-shortcuts.ts +13 -51
  105. package/src/components/layout/shell/ticker-link-menu.ts +12 -3
  106. package/src/components/layout/status-bar.tsx +24 -78
  107. package/src/components/layout/status-widget-space.ts +5 -5
  108. package/src/components/onboarding/onboarding-keyboard.ts +5 -1
  109. package/src/components/onboarding/onboarding-wizard.tsx +15 -4
  110. package/src/components/onboarding/portfolio-step/positions-panel.tsx +9 -6
  111. package/src/components/onboarding/use-onboarding-progress.ts +20 -1
  112. package/src/components/price-sparkline/view.tsx +14 -6
  113. package/src/components/ticker/badge/index.tsx +8 -4
  114. package/src/components/ticker/badge/list.tsx +23 -7
  115. package/src/components/ui/column-grid.tsx +8 -2
  116. package/src/components/ui/data-table/index.tsx +5 -1
  117. package/src/components/ui/data-table/opentui/model.ts +4 -1
  118. package/src/components/ui/data-table/render-cell.ts +19 -0
  119. package/src/components/ui/delayed-mark.tsx +59 -7
  120. package/src/components/ui/icon.tsx +1 -8
  121. package/src/components/ui/menu.tsx +6 -1
  122. package/src/components/ui/tabs.tsx +5 -2
  123. package/src/core/state/app/layout.ts +18 -3
  124. package/src/core/state/app/state.ts +2 -0
  125. package/src/core/state/app/types.ts +5 -0
  126. package/src/data/config/layout.ts +3 -0
  127. package/src/data/config/store/normalize.ts +39 -4
  128. package/src/i18n/es.ts +13 -3
  129. package/src/i18n/ja.ts +13 -3
  130. package/src/i18n/ko.ts +13 -3
  131. package/src/i18n/zh-cn.ts +13 -3
  132. package/src/i18n/zh-tw.ts +13 -3
  133. package/src/layout/pane-manager/floating-placement.ts +7 -4
  134. package/src/layout/pane-manager/floating.ts +5 -2
  135. package/src/market-data/bond-funds.ts +19 -0
  136. package/src/market-data/futures-contract.ts +14 -3
  137. package/src/market-data/market/freshness.ts +18 -0
  138. package/src/market-data/market/status.ts +15 -2
  139. package/src/plugins/builtin/bond-calculator/headless.ts +2 -1
  140. package/src/plugins/builtin/bond-calculator/index.tsx +1 -1
  141. package/src/plugins/builtin/bond-calculator/model.ts +14 -5
  142. package/src/plugins/builtin/bond-calculator/pane.tsx +1 -1
  143. package/src/plugins/builtin/buildout/cells.tsx +25 -45
  144. package/src/plugins/builtin/buildout/detail/company.tsx +3 -3
  145. package/src/plugins/builtin/buildout/detail/index.tsx +1 -1
  146. package/src/plugins/builtin/buildout/detail/intel.tsx +4 -7
  147. package/src/plugins/builtin/buildout/detail/site.tsx +4 -4
  148. package/src/plugins/builtin/buildout/detail/ui.tsx +39 -38
  149. package/src/plugins/builtin/buildout/format.ts +23 -1
  150. package/src/plugins/builtin/buildout/model/types.ts +1 -0
  151. package/src/plugins/builtin/buildout/pane/index.tsx +2 -8
  152. package/src/plugins/builtin/buildout/table-model.ts +12 -4
  153. package/src/plugins/builtin/cds/headless.ts +1 -0
  154. package/src/plugins/builtin/cds/index.tsx +1 -1
  155. package/src/plugins/builtin/chat/content/composer.tsx +21 -27
  156. package/src/plugins/builtin/chat/content/index.tsx +31 -3
  157. package/src/plugins/builtin/chat/content/shortcuts.ts +4 -2
  158. package/src/plugins/builtin/chat/content/snapshot.ts +0 -3
  159. package/src/plugins/builtin/cloud/auth-actions.tsx +51 -23
  160. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  161. package/src/plugins/builtin/cloud/trial-offer-status-widget.tsx +3 -3
  162. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +44 -12
  163. package/src/plugins/builtin/congress-trades/model.ts +2 -1
  164. package/src/plugins/builtin/congress-trades/pane.tsx +3 -0
  165. package/src/plugins/builtin/correlation/headless.ts +3 -2
  166. package/src/plugins/builtin/crypto-board/pane.tsx +5 -4
  167. package/src/plugins/builtin/custom-view/index.tsx +1 -1
  168. package/src/plugins/builtin/custom-view/loader.ts +85 -8
  169. package/src/plugins/builtin/custom-view/view-spec.ts +28 -0
  170. package/src/plugins/builtin/debt-maturities/headless.ts +11 -2
  171. package/src/plugins/builtin/debt-maturities/model.ts +66 -0
  172. package/src/plugins/builtin/debt-maturities/pane.tsx +23 -4
  173. package/src/plugins/builtin/earnings-ripple/pane.tsx +1 -1
  174. package/src/plugins/builtin/econ/calendar-model.ts +28 -6
  175. package/src/plugins/builtin/equity-screener/client.ts +1 -1
  176. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +16 -19
  177. package/src/plugins/builtin/equity-screener/headless.ts +37 -3
  178. package/src/plugins/builtin/equity-screener/ideas.ts +67 -3
  179. package/src/plugins/builtin/equity-screener/model.ts +238 -27
  180. package/src/plugins/builtin/equity-screener/pane.tsx +88 -18
  181. package/src/plugins/builtin/equity-screener/screen-check.ts +7 -4
  182. package/src/plugins/builtin/equity-screener/watchlist.ts +33 -0
  183. package/src/plugins/builtin/executives/format.ts +5 -4
  184. package/src/plugins/builtin/executives/pane.tsx +1 -1
  185. package/src/plugins/builtin/futures-curve/client.ts +19 -0
  186. package/src/plugins/builtin/futures-curve/headless.ts +52 -13
  187. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  188. package/src/plugins/builtin/futures-curve/model.ts +77 -6
  189. package/src/plugins/builtin/futures-curve/pane.tsx +19 -3
  190. package/src/plugins/builtin/help/index.tsx +55 -1
  191. package/src/plugins/builtin/insider/model.ts +30 -2
  192. package/src/plugins/builtin/jobs/model.ts +2 -2
  193. package/src/plugins/builtin/macro-day/client.ts +41 -0
  194. package/src/plugins/builtin/macro-day/headless.ts +19 -9
  195. package/src/plugins/builtin/macro-day/model.ts +3 -1
  196. package/src/plugins/builtin/market-movers/index.tsx +4 -3
  197. package/src/plugins/builtin/mna/distress/headless.ts +1 -0
  198. package/src/plugins/builtin/mna/model.ts +2 -2
  199. package/src/plugins/builtin/notes/files.ts +2 -0
  200. package/src/plugins/builtin/notes/owner.tsx +20 -1
  201. package/src/plugins/builtin/notes/quick-notes-pane.tsx +22 -4
  202. package/src/plugins/builtin/notes/store.ts +6 -1
  203. package/src/plugins/builtin/perps/pane.tsx +3 -1
  204. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +17 -0
  205. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +2 -1
  206. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
  207. package/src/plugins/builtin/portfolio-list/header.tsx +1 -1
  208. package/src/plugins/builtin/rate-path/headless.ts +24 -10
  209. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -25
  210. package/src/plugins/builtin/research/event-model.ts +10 -3
  211. package/src/plugins/builtin/research/events-headless.ts +20 -2
  212. package/src/plugins/builtin/sec/fund-facts.ts +17 -1
  213. package/src/plugins/builtin/sec/index.tsx +1 -1
  214. package/src/plugins/builtin/series-inventory.ts +1 -0
  215. package/src/plugins/builtin/shared/earnings-report.ts +7 -2
  216. package/src/plugins/builtin/shared/members-menu.tsx +103 -38
  217. package/src/plugins/builtin/shared/use-quote-board.ts +85 -46
  218. package/src/plugins/builtin/short-interest/headless.ts +1 -1
  219. package/src/plugins/builtin/short-interest/model.ts +15 -6
  220. package/src/plugins/builtin/short-interest/publications-model.ts +22 -1
  221. package/src/plugins/builtin/short-interest/publications-pane.tsx +13 -4
  222. package/src/plugins/builtin/short-interest/types.ts +2 -0
  223. package/src/plugins/builtin/short-interest/watch-model.ts +1 -1
  224. package/src/plugins/builtin/thirteenf/overlap-pane.tsx +3 -0
  225. package/src/plugins/builtin/thirteenf/pane.tsx +3 -0
  226. package/src/plugins/builtin/ticker-detail/overview/model.ts +5 -3
  227. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +4 -4
  228. package/src/plugins/builtin/time-sales/pane.tsx +3 -2
  229. package/src/plugins/builtin/trace-bonds/client.ts +7 -4
  230. package/src/plugins/builtin/trace-bonds/detail.tsx +198 -0
  231. package/src/plugins/builtin/trace-bonds/headless.ts +62 -4
  232. package/src/plugins/builtin/trace-bonds/history.ts +155 -0
  233. package/src/plugins/builtin/trace-bonds/index.tsx +1 -1
  234. package/src/plugins/builtin/trace-bonds/pane.tsx +64 -5
  235. package/src/plugins/builtin/volatility/client.ts +6 -1
  236. package/src/plugins/builtin/volatility/headless.ts +0 -1
  237. package/src/plugins/builtin/yield-curve/curves.ts +15 -0
  238. package/src/plugins/builtin/yield-curve/headless.ts +6 -1
  239. package/src/plugins/builtin/yield-curve/index.tsx +5 -8
  240. package/src/plugins/host-modules.ts +22 -3
  241. package/src/plugins/host-smoke.ts +6 -3
  242. package/src/plugins/installer.ts +16 -3
  243. package/src/plugins/plugin-names.ts +11 -2
  244. package/src/portfolio/collection-name.ts +19 -0
  245. package/src/remote/controller.ts +9 -2
  246. package/src/remote/schema.ts +2 -1
  247. package/src/renderers/browser/http-proxy-transport.ts +78 -8
  248. package/src/renderers/cloudflare/http-proxy.ts +73 -3
  249. package/src/renderers/cloudflare/proxy-session.ts +47 -24
  250. package/src/renderers/cloudflare/worker.ts +44 -4
  251. package/src/renderers/desktop/geometry.ts +279 -0
  252. package/src/renderers/desktop/screen-setup.ts +246 -0
  253. package/src/renderers/desktop/sequential-window-host.ts +179 -0
  254. package/src/renderers/desktop/test-utils.ts +71 -0
  255. package/src/renderers/desktop/window-controller.ts +433 -0
  256. package/src/renderers/desktop/window-host.ts +70 -0
  257. package/src/renderers/desktop/window-layouts.ts +630 -0
  258. package/src/renderers/dom/data-frames.ts +15 -4
  259. package/src/renderers/dom/desktop/icons.tsx +0 -2
  260. package/src/renderers/dom/styles.css +0 -3
  261. package/src/renderers/electrobun/bun/application-menu/click.ts +1 -0
  262. package/src/renderers/electrobun/bun/application-menu/index.ts +4 -1
  263. package/src/renderers/electrobun/bun/desktop/backend-requests.ts +19 -8
  264. package/src/renderers/electrobun/bun/desktop/backend.ts +320 -19
  265. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +83 -61
  266. package/src/renderers/electrobun/bun/desktop/host-requests.ts +4 -14
  267. package/src/renderers/electrobun/bun/desktop/initialization.ts +30 -11
  268. package/src/renderers/electrobun/bun/desktop/install-records.ts +59 -0
  269. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +208 -592
  270. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +14 -0
  271. package/src/renderers/electrobun/bun/desktop/screen-setup-file.ts +55 -0
  272. package/src/renderers/electrobun/bun/desktop/state-broadcaster.ts +44 -8
  273. package/src/renderers/electrobun/bun/desktop/update.ts +1 -1
  274. package/src/renderers/electrobun/bun/desktop/workspace/index.ts +298 -97
  275. package/src/renderers/electrobun/bun/desktop/workspace/requests.ts +44 -6
  276. package/src/renderers/electrobun/bun/index.ts +22 -109
  277. package/src/renderers/electrobun/bun/window/create.ts +23 -3
  278. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +306 -0
  279. package/src/renderers/electrobun/bun/window/events.ts +4 -4
  280. package/src/renderers/electrobun/bun/window/focus.ts +0 -25
  281. package/src/renderers/electrobun/bun/window/frame.ts +2 -1
  282. package/src/renderers/electrobun/bun/window/native-min-size.ts +322 -0
  283. package/src/renderers/electrobun/bun/window/remembered-frame.ts +4 -82
  284. package/src/renderers/electrobun/shared/protocol.ts +44 -2
  285. package/src/renderers/electrobun/view/backend-rpc.ts +16 -1
  286. package/src/renderers/electrobun/view/desktop/window/bridge.ts +63 -3
  287. package/src/renderers/electrobun/view/main.tsx +13 -7
  288. package/src/series/fred-argument.ts +17 -0
  289. package/src/sources/gloomberb-cloud/index.ts +5 -7
  290. package/src/sources/provider-router/batches.ts +18 -3
  291. package/src/sources/provider-router/financial-routes.ts +7 -1
  292. package/src/sources/provider-router/financials.ts +18 -4
  293. package/src/state/app/context/index.tsx +16 -2
  294. package/src/state/desktop-windows.ts +63 -0
  295. package/src/sync/other-window-tabs.ts +62 -0
  296. package/src/tickers/company-name-listing.ts +23 -3
  297. package/src/tickers/listing-fate.ts +147 -1
  298. package/src/tickers/terminal-codes.ts +5 -0
  299. package/src/time-series/types.ts +6 -0
  300. package/src/types/config.ts +10 -1
  301. package/src/types/data-provider.ts +14 -0
  302. package/src/types/desktop-window.ts +71 -2
  303. package/src/types/financials.ts +19 -3
  304. package/src/types/headless.ts +21 -0
  305. package/src/types/plugin.ts +6 -0
  306. package/src/ui/index.tsx +14 -13
  307. package/src/ui/same-props.ts +58 -0
  308. package/src/utils/cli-output.ts +33 -4
  309. package/src/utils/double-escape-close.ts +38 -16
  310. package/src/utils/format.ts +30 -5
  311. package/src/utils/futures-generic.ts +12 -0
  312. package/src/utils/http-proxy-upstream.ts +6 -2
  313. package/src/utils/plugin-proxy-hosts.json +0 -4
  314. package/src/utils/plugin-proxy-hosts.ts +22 -0
  315. package/src/utils/price-earnings.ts +18 -0
  316. package/src/utils/sec-filings.ts +7 -1
  317. package/patches/electrobun@1.18.1.patch +0 -633
  318. package/src/api-client/types.ts +0 -2441
@@ -25,6 +25,60 @@ import { fetchCheckingRedirects, readBytesWithin, type ProxyUpstreamResult } fro
25
25
  import type { ProxySessionGate } from "./proxy-session";
26
26
 
27
27
  const PROXY_METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
28
+
29
+ /** Requests a caller without a confirmed session may send to one host. */
30
+ export interface SignedOutRoute {
31
+ methods: readonly ("GET" | "HEAD" | "POST")[];
32
+ /** A path and anything under it; one ending in a slash covers only what is under it. */
33
+ path: string;
34
+ }
35
+
36
+ const READ = ["GET", "HEAD"] as const;
37
+
38
+ /**
39
+ * What a caller without a confirmed session may send, host by host: the
40
+ * reads the plugins that work signed out make, and nothing else. The Origin
41
+ * check is no barrier to a script, so anonymous use stays a read-only proxy
42
+ * to those endpoints (a POST carries a search, as FINRA's tape and Pascal's
43
+ * market search do), never to the rest of an exchange's API. Every proxied
44
+ * host is listed, with no routes when it needs a sign-in; a test holds the
45
+ * two lists together.
46
+ */
47
+ export const SIGNED_OUT_ROUTES: Readonly<Record<string, readonly SignedOutRoute[]>> = {
48
+ "api.crypto.com": [{ methods: READ, path: "/dcm/v1/public/" }],
49
+ "api.elections.kalshi.com": [{ methods: READ, path: "/trade-api/v2/" }],
50
+ "api.fda.gov": [{ methods: READ, path: "/" }],
51
+ "api.gemini.com": [{ methods: READ, path: "/v1/prediction-markets/" }],
52
+ "api.limitless.exchange": [{ methods: READ, path: "/markets/" }],
53
+ "api.votehub.com": [{ methods: READ, path: "/polls" }],
54
+ "clinicaltrials.gov": [{ methods: READ, path: "/api/v2/" }],
55
+ "data.pascal.trade": [
56
+ { methods: READ, path: "/api/v1/markets" },
57
+ { methods: ["POST"], path: "/api/v1/markets/text-search" },
58
+ ],
59
+ "efts.sec.gov": [{ methods: READ, path: "/LATEST/search-index" }],
60
+ "forms13f.com": [{ methods: READ, path: "/api/v1/" }],
61
+ "gateway.polymarket.us": [{ methods: READ, path: "/v1/markets" }],
62
+ "markets.newyorkfed.org": [{ methods: READ, path: "/api/" }],
63
+ "nasdaqtrader.com": [{ methods: READ, path: "/rss.aspx" }],
64
+ "production.dataviz.cnn.io": [{ methods: READ, path: "/index/fearandgreed/" }],
65
+ "services-dynarep.ddwa.finra.org": [{ methods: ["POST"], path: "/public/reporting/v2/data/group/" }],
66
+ };
67
+
68
+ /** Whether a caller without a confirmed session may send `method` to `url`. */
69
+ export function signedOutRouteAllows(
70
+ url: URL,
71
+ method: string,
72
+ routes: Readonly<Record<string, readonly SignedOutRoute[]>> = SIGNED_OUT_ROUTES,
73
+ ): boolean {
74
+ const host = url.hostname.toLowerCase();
75
+ const entry = Object.entries(routes).find(([allowed]) => host === allowed || host.endsWith(`.${allowed}`));
76
+ return !!entry?.[1].some((route) => (route.methods as readonly string[]).includes(method) && (
77
+ route.path.endsWith("/")
78
+ ? url.pathname.startsWith(route.path)
79
+ : url.pathname === route.path || url.pathname.startsWith(`${route.path}/`)
80
+ ));
81
+ }
28
82
  const MAX_BODY_BYTES = 5 * 1024 * 1024;
29
83
  /** Plugin request bodies are small JSON; anything near this is not one. */
30
84
  const MAX_REQUEST_BYTES = 1024 * 1024;
@@ -74,14 +128,22 @@ function proxyError(message: string, status: number, headers: Record<string, str
74
128
  return Response.json({ error: message }, { status, headers: { "cache-control": "no-store", ...headers } });
75
129
  }
76
130
 
131
+ /** The pane shows `error` as is, so it says what happened in plain words. */
77
132
  function upstreamFailure(error: unknown): Response {
78
133
  const timedOut = error instanceof Error && error.name === "TimeoutError";
79
- return proxyError(timedOut ? "The upstream request timed out." : "The upstream request failed.", 504);
134
+ return proxyError(timedOut ? "The data source timed out. Try again shortly." : "The data source could not be reached. Try again shortly.", 504);
80
135
  }
81
136
 
82
137
  export interface HttpProxyOptions {
83
- /** Confirms the caller is signed in. One per isolate, so its cache is shared. */
138
+ /** Rate limits the caller, by user when signed in. One per isolate, so its cache is shared. */
84
139
  sessions: ProxySessionGate;
140
+ /**
141
+ * The limit on signed-out calls across isolates (Cloudflare's rate limiting
142
+ * binding): false once the caller's address, or signed-out callers as a
143
+ * whole, have had their share. Absent where there is none, as in tests.
144
+ */
145
+ signedOutLimit?: (request: Request) => Promise<boolean>;
146
+ signedOutRoutes?: Readonly<Record<string, readonly SignedOutRoute[]>>;
85
147
  /** Reaches the Gloomberb API for that check. */
86
148
  fetchApi: (request: Request) => Promise<Response>;
87
149
  /** Reaches the plugin's target. */
@@ -95,7 +157,7 @@ export interface HttpProxyOptions {
95
157
  * to a third party, which is the opposite of what this exists to do.
96
158
  */
97
159
  export async function handleHttpProxy(request: Request, options: HttpProxyOptions): Promise<Response> {
98
- const { sessions, fetchApi, fetchUpstream = fetch, hosts = PROXY_ALLOWED_HOSTS } = options;
160
+ const { sessions, fetchApi, fetchUpstream = fetch, hosts = PROXY_ALLOWED_HOSTS, signedOutRoutes = SIGNED_OUT_ROUTES } = options;
99
161
  if (request.method !== "POST") {
100
162
  return proxyError("Method not allowed", 405);
101
163
  }
@@ -134,6 +196,14 @@ export async function handleHttpProxy(request: Request, options: HttpProxyOption
134
196
  if (!PROXY_METHODS.has(init.method)) {
135
197
  return proxyError("Method not allowed", 405);
136
198
  }
199
+ if (!admission.signedIn) {
200
+ if (!signedOutRouteAllows(target.url, init.method, signedOutRoutes)) {
201
+ return proxyError("Sign in to Gloom to send this request.", 401);
202
+ }
203
+ if (options.signedOutLimit && !(await options.signedOutLimit(request).catch(() => true))) {
204
+ return proxyError("Too many requests right now. Sign in to Gloom, or try again in a minute.", 429, { "retry-after": "60" });
205
+ }
206
+ }
137
207
 
138
208
  const signal = AbortSignal.timeout(Math.min(init.timeoutMs ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS));
139
209
  let result: ProxyUpstreamResult;
@@ -1,11 +1,15 @@
1
1
  /**
2
- * Who may use the plugin HTTP proxy: a signed-in Gloomberb session, confirmed
3
- * by the API rather than by the cookie merely being present.
2
+ * How much of the plugin HTTP proxy a caller gets. Everyone may use it, since
3
+ * the functions behind it show free public data that works signed out on the
4
+ * desktop too; what differs is the rate limit. A signed-in Gloomberb session,
5
+ * confirmed by the API rather than by the cookie merely being present, is
6
+ * counted per user. Everyone else, including a session the API rejects or
7
+ * cannot confirm right now, is counted per IP address against a smaller
8
+ * window, so a failed check never grants more than signing out would.
4
9
  *
5
10
  * Plugin panes fire requests in bursts, so a confirmed session is remembered
6
11
  * for a minute per isolate and concurrent requests share one check. A session
7
- * the API rejects is not remembered, so signing in again works at once. When
8
- * the API cannot answer, the proxy refuses rather than guessing.
12
+ * the API rejects is not remembered, so signing in again works at once.
9
13
  *
10
14
  * The cache is keyed by the exact cookies that were confirmed, but the rate
11
15
  * limit is keyed by the user the API named. The API reads only part of those
@@ -42,6 +46,12 @@ const SHARED_CHECK_GRACE_MS = 500;
42
46
  * stopping a script from turning one account into a free proxy.
43
47
  */
44
48
  const DEFAULT_REQUESTS_PER_WINDOW = 300;
49
+ /**
50
+ * Per IP address, per isolate, for callers without a confirmed session. A
51
+ * signed-out layout of the heaviest proxied panes (prediction markets, bond
52
+ * tape, Treasury, halts) stays well under this; a script does not.
53
+ */
54
+ const DEFAULT_ANONYMOUS_REQUESTS_PER_WINDOW = 240;
45
55
  const DEFAULT_WINDOW_MS = 60_000;
46
56
  /**
47
57
  * Confirmed cookie variants one user may hold in the cache at once. A user
@@ -69,7 +79,8 @@ interface RateWindow {
69
79
  }
70
80
 
71
81
  type ProxyAdmission =
72
- | { ok: true }
82
+ /** `signedIn` is true only for a session the API confirmed. */
83
+ | { ok: true; signedIn: boolean }
73
84
  | { ok: false; status: number; error: string; retryAfterSeconds?: number };
74
85
 
75
86
  export interface ProxySessionGate {
@@ -84,16 +95,26 @@ export interface ProxySessionGateOptions {
84
95
  maxEntries?: number;
85
96
  maxEntriesPerUser?: number;
86
97
  requestsPerWindow?: number;
98
+ anonymousRequestsPerWindow?: number;
87
99
  windowMs?: number;
88
100
  checkTimeoutMs?: number;
89
101
  }
90
102
 
91
- const SIGN_IN: ProxyAdmission = { ok: false, status: 401, error: "Sign in to use plugin requests." };
92
- const UNAVAILABLE: ProxyAdmission = {
93
- ok: false,
94
- status: 503,
95
- error: "Could not confirm your session right now. Try again shortly.",
96
- };
103
+ /**
104
+ * The window an anonymous caller is counted in. Cloudflare sets
105
+ * `cf-connecting-ip` on every request that reaches the worker. An IPv6 caller
106
+ * is counted by its /64, the block one subscriber is usually handed, so
107
+ * rotating through it does not open fresh windows.
108
+ */
109
+ export function anonymousRateKey(request: Request): string {
110
+ const ip = request.headers.get("cf-connecting-ip")?.trim().toLowerCase() ?? "";
111
+ if (!ip.includes(":")) return `ip:${ip || "unknown"}`;
112
+ const [head = "", tail] = ip.split("::", 2);
113
+ const front = head ? head.split(":") : [];
114
+ const back = tail === undefined ? [] : tail ? tail.split(":") : [];
115
+ const groups = tail === undefined ? front : [...front, ...Array(Math.max(0, 8 - front.length - back.length)).fill("0"), ...back];
116
+ return `ip6:${groups.slice(0, 4).map((group) => group.replace(/^0+(?=.)/, "")).join(":")}`;
117
+ }
97
118
 
98
119
  /** The session cookies (and `dont_remember`) from a Cookie header, in order. */
99
120
  function forwardedCookies(header: string | null): string | null {
@@ -186,13 +207,18 @@ export function createProxySessionGate(options: ProxySessionGateOptions): ProxyS
186
207
  const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
187
208
  const maxEntriesPerUser = Math.max(1, options.maxEntriesPerUser ?? DEFAULT_MAX_ENTRIES_PER_USER);
188
209
  const requestsPerWindow = options.requestsPerWindow ?? DEFAULT_REQUESTS_PER_WINDOW;
210
+ const anonymousRequestsPerWindow = options.anonymousRequestsPerWindow ?? DEFAULT_ANONYMOUS_REQUESTS_PER_WINDOW;
189
211
  const windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
190
212
  const checkTimeoutMs = options.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
191
213
  const sharedWaitMs = checkTimeoutMs + SHARED_CHECK_GRACE_MS;
192
214
  /** Cookie key to whose session it is and when that stops being trusted. */
193
215
  const confirmed = new Map<string, Confirmation>();
194
216
  const pending = new Map<string, PendingCheck>();
195
- /** Keyed by user id, not cookie, so every variant of a session shares one window. */
217
+ /**
218
+ * Keyed by user id, not cookie, so every variant of a session shares one
219
+ * window, or by address for anonymous callers. The prefixes keep the two
220
+ * apart.
221
+ */
196
222
  const windows = new Map<string, RateWindow>();
197
223
 
198
224
  /** Remembers `key` for `userId`, first dropping that user's oldest variants past the per-user cap. */
@@ -237,21 +263,21 @@ export function createProxySessionGate(options: ProxySessionGateOptions): ProxyS
237
263
  return verdict;
238
264
  }
239
265
 
240
- function withinRate(userId: string): ProxyAdmission {
266
+ function withinRate(windowKey: string, limit: number, signedIn: boolean): ProxyAdmission {
241
267
  const at = now();
242
- let window = windows.get(userId);
268
+ let window = windows.get(windowKey);
243
269
  if (!window || at - window.startedAt >= windowMs) {
244
- windows.delete(userId);
270
+ windows.delete(windowKey);
245
271
  makeRoom(windows, maxEntries, (entry) => at - entry.startedAt >= windowMs);
246
272
  window = { startedAt: at, count: 0 };
247
- windows.set(userId, window);
273
+ windows.set(windowKey, window);
248
274
  }
249
275
  window.count += 1;
250
- if (window.count <= requestsPerWindow) return { ok: true };
276
+ if (window.count <= limit) return { ok: true, signedIn };
251
277
  return {
252
278
  ok: false,
253
279
  status: 429,
254
- error: "Too many plugin requests. Try again in a minute.",
280
+ error: "Too many requests right now. Try again in a minute.",
255
281
  retryAfterSeconds: Math.max(1, Math.ceil((window.startedAt + windowMs - at) / 1_000)),
256
282
  };
257
283
  }
@@ -259,12 +285,9 @@ export function createProxySessionGate(options: ProxySessionGateOptions): ProxyS
259
285
  return {
260
286
  async admit(request, fetchApi) {
261
287
  const cookie = forwardedCookies(request.headers.get("cookie"));
262
- if (!cookie) return SIGN_IN;
263
- const key = await cacheKey(cookie);
264
- const verdict = await verdictFor(key, cookie, request, fetchApi);
265
- if (verdict === "invalid") return SIGN_IN;
266
- if (verdict === "unavailable") return UNAVAILABLE;
267
- return withinRate(verdict.userId);
288
+ const verdict = cookie ? await verdictFor(await cacheKey(cookie), cookie, request, fetchApi) : "invalid";
289
+ if (typeof verdict === "object") return withinRate(`user:${verdict.userId}`, requestsPerWindow, true);
290
+ return withinRate(anonymousRateKey(request), anonymousRequestsPerWindow, false);
268
291
  },
269
292
  };
270
293
  }
@@ -1,13 +1,36 @@
1
1
  import { handleHttpProxy } from "./http-proxy";
2
- import { createProxySessionGate } from "./proxy-session";
3
- import { HTTP_PROXY_PATH } from "../../utils/plugin-proxy-hosts";
2
+ import { anonymousRateKey, createProxySessionGate } from "./proxy-session";
3
+ import { HTTP_PROXY_PATH, WEB_DIRECT_HOSTS } from "../../utils/plugin-proxy-hosts";
4
4
 
5
5
  interface StaticAssetsBinding {
6
6
  fetch(request: Request): Promise<Response>;
7
7
  }
8
8
 
9
+ /** Cloudflare's rate limiting binding: counts per key, per location, across isolates. */
10
+ interface RateLimitBinding {
11
+ limit(options: { key: string }): Promise<{ success: boolean }>;
12
+ }
13
+
9
14
  export interface WorkerEnv {
10
15
  ASSETS: StaticAssetsBinding;
16
+ /** Signed-out plugin proxy calls per address (wrangler.jsonc `ratelimits`). */
17
+ SIGNED_OUT_PROXY_PER_ADDRESS?: RateLimitBinding;
18
+ /** Signed-out plugin proxy calls from everyone together. */
19
+ SIGNED_OUT_PROXY_TOTAL?: RateLimitBinding;
20
+ }
21
+
22
+ /**
23
+ * The isolate's own window can be dodged by landing on many isolates, so a
24
+ * signed-out call also counts against Cloudflare's limits per address and
25
+ * for every signed-out caller together. Either one spent refuses it.
26
+ */
27
+ export function signedOutProxyLimit(env: WorkerEnv): ((request: Request) => Promise<boolean>) | undefined {
28
+ const { SIGNED_OUT_PROXY_PER_ADDRESS: perAddress, SIGNED_OUT_PROXY_TOTAL: total } = env;
29
+ if (!perAddress && !total) return undefined;
30
+ return async (request) => {
31
+ if (perAddress && !(await perAddress.limit({ key: anonymousRateKey(request) })).success) return false;
32
+ return !total || (await total.limit({ key: "signed-out" })).success;
33
+ };
11
34
  }
12
35
 
13
36
  const SHARE_PATH = /^\/s\/[a-f0-9]{32}\/?$/;
@@ -70,8 +93,21 @@ type ApiFetch = (request: Request) => Promise<Response>;
70
93
  /** Module scope, so every request this isolate serves shares one session cache. */
71
94
  const proxySessions = createProxySessionGate({ sessionUrl: `${API_ORIGIN}/auth/get-session` });
72
95
 
96
+ /**
97
+ * What the page may fetch: itself (the API and the plugin proxy are both
98
+ * same-origin), the app's own hosts, and the plugin hosts the browser calls
99
+ * directly. Every other plugin host goes through the proxy.
100
+ */
101
+ const CONNECT_SRC = [
102
+ "'self'",
103
+ "https://api.github.com",
104
+ "https://plugins.gloom.sh",
105
+ "https://gloom.sh",
106
+ ...WEB_DIRECT_HOSTS.map((host) => `https://${host}`),
107
+ ].join(" ");
108
+
73
109
  export const SECURITY_HEADERS = {
74
- "content-security-policy": "default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; media-src 'self' https:; connect-src 'self' https://api.github.com https://api.fiscaldata.treasury.gov https://plugins.gloom.sh https://gloom.sh; form-action 'self'; upgrade-insecure-requests",
110
+ "content-security-policy": `default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; media-src 'self' https:; connect-src ${CONNECT_SRC}; form-action 'self'; upgrade-insecure-requests`,
75
111
  "cross-origin-opener-policy": "same-origin",
76
112
  "cross-origin-resource-policy": "same-origin",
77
113
  "permissions-policy": "camera=(), geolocation=(), microphone=(), payment=(), usb=()",
@@ -116,7 +152,11 @@ export async function handleRequest(request: Request, env: WorkerEnv, fetchApi:
116
152
  if (API_PATH.test(url.pathname)) return proxyApi(request, fetchApi);
117
153
  // Before the GET/HEAD gate below, since plugin requests arrive as POST.
118
154
  if (url.pathname === HTTP_PROXY_PATH) {
119
- return withSecurityHeaders(await handleHttpProxy(request, { sessions: proxySessions, fetchApi }));
155
+ return withSecurityHeaders(await handleHttpProxy(request, {
156
+ sessions: proxySessions,
157
+ fetchApi,
158
+ signedOutLimit: signedOutProxyLimit(env),
159
+ }));
120
160
  }
121
161
 
122
162
  if (request.method !== "GET" && request.method !== "HEAD") {
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Screens and window frames for the desktop app, in the coordinates the
3
+ * shell reports them in: one virtual desktop where every display has its
4
+ * place. Nothing here talks to a shell; the window host does (window-host.ts).
5
+ */
6
+
7
+ export interface Rect {
8
+ x: number;
9
+ y: number;
10
+ width: number;
11
+ height: number;
12
+ }
13
+
14
+ export interface DesktopDisplay {
15
+ /** The shell's id. It can change when a display is plugged in again, so placements never key on it. */
16
+ id: string;
17
+ bounds: Rect;
18
+ /** The bounds less the menu bar, Dock or task bar. */
19
+ workArea: Rect;
20
+ scaleFactor: number;
21
+ primary: boolean;
22
+ }
23
+
24
+ /** How much of a title bar has to sit on a screen for a window to count as reachable: enough to grab and drag. */
25
+ const REACHABLE_STRIP_HEIGHT = 24;
26
+ const REACHABLE_STRIP_WIDTH = 96;
27
+ /**
28
+ * How far past a screen's edge a frame may reach and still count as on it:
29
+ * shadows and the invisible resize borders Windows counts in a frame.
30
+ */
31
+ const EDGE_SLACK = 8;
32
+
33
+ function finite(value: number): number {
34
+ return Number.isFinite(value) ? Math.round(value) : 0;
35
+ }
36
+
37
+ export function sameRect(a: Rect | null | undefined, b: Rect | null | undefined): boolean {
38
+ if (!a || !b) return a === b;
39
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
40
+ }
41
+
42
+ export function isUsableRect(rect: Rect | null | undefined): rect is Rect {
43
+ return !!rect
44
+ && [rect.x, rect.y, rect.width, rect.height].every((value) => typeof value === "number" && Number.isFinite(value))
45
+ && rect.width >= 1
46
+ && rect.height >= 1;
47
+ }
48
+
49
+ /** Displays the shell reported with a real size, primary first and then left to right, top to bottom. */
50
+ export function usableDisplays(displays: readonly DesktopDisplay[]): DesktopDisplay[] {
51
+ return displays
52
+ .filter((display) => isUsableRect(display.bounds) && isUsableRect(display.workArea))
53
+ .sort((a, b) => (
54
+ Number(b.primary) - Number(a.primary)
55
+ || a.bounds.x - b.bounds.x
56
+ || a.bounds.y - b.bounds.y
57
+ ));
58
+ }
59
+
60
+ /**
61
+ * One display, as placements remember it: where it sits, its size and its
62
+ * scale. A display unplugged and plugged back in the same place gets the
63
+ * same key, whatever id the shell gives it.
64
+ */
65
+ export function displayKey(display: DesktopDisplay): string {
66
+ const { x, y, width, height } = display.bounds;
67
+ const scale = Math.round((display.scaleFactor || 1) * 100) / 100;
68
+ return `${finite(x)},${finite(y)} ${finite(width)}x${finite(height)}@${scale}`;
69
+ }
70
+
71
+ /**
72
+ * The monitor arrangement a screen setup is saved under: every display's
73
+ * key, in a fixed order. Moving, adding or removing a display, or changing
74
+ * its resolution or scale, makes another arrangement.
75
+ */
76
+ export function arrangementKey(displays: readonly DesktopDisplay[]): string {
77
+ const keys = usableDisplays(displays).map(displayKey).sort();
78
+ return keys.length > 0 ? keys.join(" | ") : "none";
79
+ }
80
+
81
+ function overlapArea(a: Rect, b: Rect): number {
82
+ const width = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
83
+ const height = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
84
+ return width > 0 && height > 0 ? width * height : 0;
85
+ }
86
+
87
+ function clamp(value: number, min: number, max: number): number {
88
+ return Math.min(max, Math.max(min, value));
89
+ }
90
+
91
+ /** The display a frame is on: the one holding its centre, else the one it overlaps most. Null when it is on none. */
92
+ export function displayForFrame(frame: Rect, displays: readonly DesktopDisplay[]): DesktopDisplay | null {
93
+ const usable = usableDisplays(displays);
94
+ const centerX = frame.x + frame.width / 2;
95
+ const centerY = frame.y + frame.height / 2;
96
+ const containing = usable.find(({ bounds }) => (
97
+ centerX >= bounds.x && centerX < bounds.x + bounds.width
98
+ && centerY >= bounds.y && centerY < bounds.y + bounds.height
99
+ ));
100
+ if (containing) return containing;
101
+ let best: DesktopDisplay | null = null;
102
+ let bestArea = 0;
103
+ for (const display of usable) {
104
+ const area = overlapArea(frame, display.bounds);
105
+ if (area > bestArea) {
106
+ best = display;
107
+ bestArea = area;
108
+ }
109
+ }
110
+ return best;
111
+ }
112
+
113
+ /**
114
+ * Whether a person can reach the window to move it: a stretch of its title
115
+ * bar lies in some display's work area, not under the menu bar or off the
116
+ * edge of every screen.
117
+ */
118
+ export function isFrameReachable(frame: Rect, displays: readonly DesktopDisplay[]): boolean {
119
+ const titleBar: Rect = { x: frame.x, y: frame.y, width: frame.width, height: REACHABLE_STRIP_HEIGHT };
120
+ return usableDisplays(displays).some(({ workArea }) => {
121
+ const width = Math.min(titleBar.x + titleBar.width, workArea.x + workArea.width) - Math.max(titleBar.x, workArea.x);
122
+ const height = Math.min(titleBar.y + titleBar.height, workArea.y + workArea.height) - Math.max(titleBar.y, workArea.y);
123
+ return width >= Math.min(REACHABLE_STRIP_WIDTH, frame.width) && height >= Math.min(REACHABLE_STRIP_HEIGHT, frame.height);
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Whether a window is on screen: all of it lies on the connected displays
129
+ * (across two of them counts), give or take its shadow, and its title bar
130
+ * sits in a work area where it can be grabbed.
131
+ */
132
+ export function isFrameVisible(frame: Rect, displays: readonly DesktopDisplay[]): boolean {
133
+ const usable = usableDisplays(displays);
134
+ const insetX = Math.min(EDGE_SLACK, Math.floor(frame.width / 4));
135
+ const insetY = Math.min(EDGE_SLACK, Math.floor(frame.height / 4));
136
+ const inner: Rect = {
137
+ x: frame.x + insetX,
138
+ y: frame.y + insetY,
139
+ width: frame.width - insetX * 2,
140
+ height: frame.height - insetY * 2,
141
+ };
142
+ // Mirrored displays share their bounds: count each place once.
143
+ const places = new Set<string>();
144
+ let covered = 0;
145
+ for (const { bounds } of usable) {
146
+ const place = `${bounds.x},${bounds.y},${bounds.width},${bounds.height}`;
147
+ if (places.has(place)) continue;
148
+ places.add(place);
149
+ covered += overlapArea(inner, bounds);
150
+ }
151
+ return covered >= inner.width * inner.height - 1 && isFrameReachable(frame, usable);
152
+ }
153
+
154
+ /** The display closest to a frame on none: the shortest way from its centre to a work area. */
155
+ function nearestDisplay(frame: Rect, displays: readonly DesktopDisplay[]): DesktopDisplay | null {
156
+ const centerX = frame.x + frame.width / 2;
157
+ const centerY = frame.y + frame.height / 2;
158
+ let best: DesktopDisplay | null = null;
159
+ let bestDistance = Infinity;
160
+ for (const display of displays) {
161
+ const area = display.workArea;
162
+ const dx = Math.max(area.x - centerX, 0, centerX - (area.x + area.width));
163
+ const dy = Math.max(area.y - centerY, 0, centerY - (area.y + area.height));
164
+ const distance = dx * dx + dy * dy;
165
+ if (distance < bestDistance) {
166
+ best = display;
167
+ bestDistance = distance;
168
+ }
169
+ }
170
+ return best;
171
+ }
172
+
173
+ /** A frame inside a work area, moved as little as it takes and shrunk to it when bigger. */
174
+ function fitFrameInArea(frame: Rect, area: Rect): Rect {
175
+ const width = Math.min(Math.round(frame.width), area.width);
176
+ const height = Math.min(Math.round(frame.height), area.height);
177
+ return {
178
+ x: clamp(Math.round(frame.x), area.x, area.x + area.width - width),
179
+ y: clamp(Math.round(frame.y), area.y, area.y + area.height - height),
180
+ width,
181
+ height,
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Puts a window on a screen. One already on screen stays as it is. Any
187
+ * other moves onto the display it is mostly on, or the nearest one, by as
188
+ * little as it takes to lie in that display's work area, shrinking to it
189
+ * when it is bigger. Shells do not do this themselves: asked to open a
190
+ * window past a screen's edge, Electrobun leaves it there.
191
+ */
192
+ export function clampFrameToScreens(frame: Rect, displays: readonly DesktopDisplay[]): Rect {
193
+ const usable = usableDisplays(displays);
194
+ if (usable.length === 0 || isFrameVisible(frame, usable)) return frame;
195
+ const display = displayForFrame(frame, usable) ?? nearestDisplay(frame, usable) ?? usable[0]!;
196
+ return fitFrameInArea(frame, display.workArea);
197
+ }
198
+
199
+ /** A display as `displayKey` wrote it, for a placement saved under screens that are not all connected now. */
200
+ export function displayFromKey(key: string): DesktopDisplay | null {
201
+ const match = /^(-?\d+),(-?\d+) (\d+)x(\d+)@([\d.]+)$/.exec(key);
202
+ if (!match) return null;
203
+ const bounds = { x: Number(match[1]), y: Number(match[2]), width: Number(match[3]), height: Number(match[4]) };
204
+ if (!isUsableRect(bounds)) return null;
205
+ return { id: "", bounds, workArea: bounds, scaleFactor: Number(match[5]) || 1, primary: false };
206
+ }
207
+
208
+ /**
209
+ * The connected display a display that is gone became: the one at the same
210
+ * place (a new resolution keeps a screen's corner), else the one with its id.
211
+ */
212
+ function sameScreen(display: DesktopDisplay, displays: readonly DesktopDisplay[]): DesktopDisplay | null {
213
+ const { x, y } = display.bounds;
214
+ return displays.find(({ bounds }) => bounds.x === x && bounds.y === y)
215
+ ?? (display.id ? displays.find(({ id }) => id === display.id) : undefined)
216
+ ?? null;
217
+ }
218
+
219
+ /**
220
+ * Where a window that sat on `from` goes on the displays connected now,
221
+ * always on screen. Its display still there: where it was. The same screen
222
+ * at another resolution or place: the same place on it, in proportion.
223
+ * Its display gone: the same place in proportion on `fallback`. On no
224
+ * display at all: onto the nearest one.
225
+ */
226
+ export function relocateFrame(
227
+ frame: Rect,
228
+ from: DesktopDisplay | null,
229
+ displays: readonly DesktopDisplay[],
230
+ fallback: DesktopDisplay,
231
+ ): Rect {
232
+ const usable = usableDisplays(displays);
233
+ if (!from || usable.some((display) => displayKey(display) === displayKey(from))) {
234
+ return clampFrameToScreens(frame, usable);
235
+ }
236
+ const target = sameScreen(from, usable) ?? fallback;
237
+ return clampFrameToScreens(moveFrameToDisplay(frame, from, target), usable);
238
+ }
239
+
240
+ /**
241
+ * A window moving from one display to another keeps its place on the screen
242
+ * in proportion: a window on the right half of the old display lands on the
243
+ * right half of the new one, at the same size where it fits.
244
+ */
245
+ export function moveFrameToDisplay(frame: Rect, from: DesktopDisplay | null, to: DesktopDisplay): Rect {
246
+ const area = to.workArea;
247
+ const width = Math.min(frame.width, area.width);
248
+ const height = Math.min(frame.height, area.height);
249
+ if (!from) {
250
+ return {
251
+ x: area.x + Math.round((area.width - width) / 2),
252
+ y: area.y + Math.round((area.height - height) / 2),
253
+ width,
254
+ height,
255
+ };
256
+ }
257
+ const source = from.workArea;
258
+ const slackX = Math.max(0, source.width - frame.width);
259
+ const slackY = Math.max(0, source.height - frame.height);
260
+ const fractionX = slackX > 0 ? clamp((frame.x - source.x) / slackX, 0, 1) : 0.5;
261
+ const fractionY = slackY > 0 ? clamp((frame.y - source.y) / slackY, 0, 1) : 0;
262
+ return {
263
+ x: area.x + Math.round((area.width - width) * fractionX),
264
+ y: area.y + Math.round((area.height - height) * fractionY),
265
+ width,
266
+ height,
267
+ };
268
+ }
269
+
270
+ /** A frame `step` points down and to the right of `frame`, wrapped back to the work area's corner when it would leave it. */
271
+ export function cascadeFrame(frame: Rect, display: DesktopDisplay, step = 32): Rect {
272
+ const area = display.workArea;
273
+ const width = Math.min(frame.width, area.width);
274
+ const height = Math.min(frame.height, area.height);
275
+ const x = frame.x + step;
276
+ const y = frame.y + step;
277
+ const fits = x + width <= area.x + area.width && y + height <= area.y + area.height;
278
+ return fitFrameInArea(fits ? { x, y, width, height } : { x: area.x + step, y: area.y + step, width, height }, area);
279
+ }