@johnhenry/mallory-cli 0.0.0-stage → 0.1.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 (760) hide show
  1. package/README.md +60 -2
  2. package/bin/mallory.mjs +51 -0
  3. package/package.json +51 -4
  4. package/src/a2a/client.js +511 -0
  5. package/src/a2a/demo-agent.js +396 -0
  6. package/src/a2a/hub.js +578 -0
  7. package/src/a2a/settings.js +88 -0
  8. package/src/a2a/task.js +358 -0
  9. package/src/acp/client.js +573 -0
  10. package/src/acp/demo-agent.js +332 -0
  11. package/src/acp/hub.js +632 -0
  12. package/src/acp/settings.js +78 -0
  13. package/src/actions/map.js +524 -0
  14. package/src/agent/cloud.js +77 -0
  15. package/src/agent/compact.js +84 -0
  16. package/src/agent/constants.js +39 -0
  17. package/src/agent/diff.js +101 -0
  18. package/src/agent/fork.js +159 -0
  19. package/src/agent/grounding.js +73 -0
  20. package/src/agent/guards.js +129 -0
  21. package/src/agent/local-transport.js +152 -0
  22. package/src/agent/loop.js +479 -0
  23. package/src/agent/park-store.js +77 -0
  24. package/src/agent/park.js +76 -0
  25. package/src/agent/ports.js +28 -0
  26. package/src/agent/providers.js +591 -0
  27. package/src/agent/restart.js +51 -0
  28. package/src/agent/router.js +380 -0
  29. package/src/agent/run.js +861 -0
  30. package/src/agent/tools.js +247 -0
  31. package/src/agent-library/engine.js +43 -0
  32. package/src/ai/bridge.js +155 -0
  33. package/src/ai/policy.js +131 -0
  34. package/src/aimatey/vendor.js +18 -0
  35. package/src/audio/container-duration.js +35 -0
  36. package/src/audio/instruments.js +776 -0
  37. package/src/audio/lanes.js +230 -0
  38. package/src/audio/patch.js +1410 -0
  39. package/src/audio/plan.js +276 -0
  40. package/src/audio/rack.js +1006 -0
  41. package/src/audio/sample-trim.js +293 -0
  42. package/src/audio/soundfont.js +243 -0
  43. package/src/audio/take-store.js +87 -0
  44. package/src/audio/takes.js +129 -0
  45. package/src/audio/wav.js +170 -0
  46. package/src/audio/zzfx.js +333 -0
  47. package/src/autonomy/bundle.js +207 -0
  48. package/src/autonomy/confine.js +61 -0
  49. package/src/autonomy/enforce.js +155 -0
  50. package/src/autonomy/file-kv.js +88 -0
  51. package/src/autonomy/ledger.js +203 -0
  52. package/src/autonomy/pins.js +50 -0
  53. package/src/autonomy/psl/index.js +32 -0
  54. package/src/autonomy/psl/suffixes.json +1 -0
  55. package/src/autonomy/record.js +28 -0
  56. package/src/autonomy/routines.js +107 -0
  57. package/src/autonomy/server.js +175 -0
  58. package/src/autonomy/signer-node.js +167 -0
  59. package/src/autonomy/store.js +43 -0
  60. package/src/autonomy/unattended.js +13 -0
  61. package/src/bytes/bytes.js +378 -0
  62. package/src/calc/syntax.js +125 -0
  63. package/src/calc/tex.js +28 -0
  64. package/src/calendar/vendor.js +2 -0
  65. package/src/clipboard.js +130 -0
  66. package/src/clsh/clsh.js +3417 -0
  67. package/src/codec/capnp.js +1804 -0
  68. package/src/codec/core.js +2043 -0
  69. package/src/codec/vendor/avro.js +136 -0
  70. package/src/codec/vendor/cbor.js +25 -0
  71. package/src/codec/vendor/flatbuffers.js +206 -0
  72. package/src/codec/vendor/msgpack.js +9 -0
  73. package/src/codec/vendor/protobuf.js +53 -0
  74. package/src/delegation/caps.js +60 -0
  75. package/src/delegation/config.js +32 -0
  76. package/src/device/model.js +246 -0
  77. package/src/device/recording.js +198 -0
  78. package/src/device/stream-model.js +151 -0
  79. package/src/documents/documents.js +1224 -0
  80. package/src/effects/catalog.js +63 -0
  81. package/src/effects/extras.js +133 -0
  82. package/src/effects/parse.js +339 -0
  83. package/src/embed/protocol.js +131 -0
  84. package/src/env/env.js +159 -0
  85. package/src/exact/vendor.js +45 -0
  86. package/src/example-meta.js +164 -0
  87. package/src/examples.js +94 -0
  88. package/src/export/canvas-image.js +217 -0
  89. package/src/export/expr-latex-lazy.js +8 -0
  90. package/src/export/formats.js +322 -0
  91. package/src/export/latex.js +183 -0
  92. package/src/export/pane.js +184 -0
  93. package/src/export/value.js +452 -0
  94. package/src/export/zip.js +214 -0
  95. package/src/ext/access.js +58 -0
  96. package/src/ext/btasks.js +225 -0
  97. package/src/ext/client.js +209 -0
  98. package/src/ext/tools.js +69 -0
  99. package/src/ext/view.js +105 -0
  100. package/src/ext/webmcp-tabs.js +299 -0
  101. package/src/files/archive.js +232 -0
  102. package/src/files/files.js +317 -0
  103. package/src/formats/json.js +24 -0
  104. package/src/formats/jupyter.js +188 -0
  105. package/src/formats/markdown.js +254 -0
  106. package/src/formats/n8n.js +276 -0
  107. package/src/formats/node-red.js +363 -0
  108. package/src/formats/registry.js +177 -0
  109. package/src/formats/rivet.js +259 -0
  110. package/src/formats/shared.js +98 -0
  111. package/src/formats/structure.js +182 -0
  112. package/src/formats/yaml.js +127 -0
  113. package/src/frame/frame.js +962 -0
  114. package/src/frame/vendor.js +1484 -0
  115. package/src/gate/audit.js +116 -0
  116. package/src/gate/gate.js +365 -0
  117. package/src/gate/policy.js +295 -0
  118. package/src/gate/scripted.js +110 -0
  119. package/src/gate/seams.js +32 -0
  120. package/src/gate/store.js +66 -0
  121. package/src/geometry/model.js +533 -0
  122. package/src/grant-key.js +149 -0
  123. package/src/graph/model.js +381 -0
  124. package/src/headless/a2a-push.js +123 -0
  125. package/src/headless/channels/config.js +142 -0
  126. package/src/headless/channels/connectors.js +283 -0
  127. package/src/headless/channels/index.js +257 -0
  128. package/src/headless/channels/mail.js +197 -0
  129. package/src/headless/channels/mailnet.js +223 -0
  130. package/src/headless/channels/platforms.js +194 -0
  131. package/src/headless/channels/replay.js +49 -0
  132. package/src/headless/cli.js +1397 -0
  133. package/src/headless/companion-client.js +182 -0
  134. package/src/headless/cost-cli.js +177 -0
  135. package/src/headless/deprecations-cli.js +102 -0
  136. package/src/headless/examples.js +48 -0
  137. package/src/headless/ffmpeg-exec.js +217 -0
  138. package/src/headless/gateways/config.js +213 -0
  139. package/src/headless/gateways/homeassistant.js +159 -0
  140. package/src/headless/gateways/index.js +121 -0
  141. package/src/headless/gateways/matter.js +150 -0
  142. package/src/headless/gateways/mqtt-client.js +177 -0
  143. package/src/headless/gateways/mqtt.js +70 -0
  144. package/src/headless/gateways/netway.js +226 -0
  145. package/src/headless/gateways/serverpod-worker.mjs +16 -0
  146. package/src/headless/gateways/serverpod.js +71 -0
  147. package/src/headless/gateways/util.js +27 -0
  148. package/src/headless/grant-cli.js +208 -0
  149. package/src/headless/guard.js +125 -0
  150. package/src/headless/guards.js +124 -0
  151. package/src/headless/machine-cli.js +853 -0
  152. package/src/headless/mcp-endpoint.js +287 -0
  153. package/src/headless/mcp-roots.js +38 -0
  154. package/src/headless/model-endpoint.js +88 -0
  155. package/src/headless/net.js +151 -0
  156. package/src/headless/node.js +263 -0
  157. package/src/headless/npm-tarball.js +29 -0
  158. package/src/headless/operator-page.js +112 -0
  159. package/src/headless/operator.js +242 -0
  160. package/src/headless/people.js +34 -0
  161. package/src/headless/pkg-cli.js +1103 -0
  162. package/src/headless/pkg-serve.js +138 -0
  163. package/src/headless/process-worker.js +88 -0
  164. package/src/headless/runner-remote.js +477 -0
  165. package/src/headless/sandbox-child.mjs +21 -0
  166. package/src/headless/scheduled.js +557 -0
  167. package/src/headless/serve-stream.js +97 -0
  168. package/src/headless/serve.js +2238 -0
  169. package/src/headless/short-links.js +158 -0
  170. package/src/headless/static-dirs.js +207 -0
  171. package/src/headless/trust-file.js +51 -0
  172. package/src/headless/watch.js +291 -0
  173. package/src/headless/ws-connect.js +65 -0
  174. package/src/headless/ws-connections.js +44 -0
  175. package/src/headless/ws-echo.js +150 -0
  176. package/src/headless/ws-proxy.js +354 -0
  177. package/src/headless/ws-ticket.js +48 -0
  178. package/src/hooks/config.js +50 -0
  179. package/src/hooks/engine.js +189 -0
  180. package/src/input/log.js +613 -0
  181. package/src/input/player.js +217 -0
  182. package/src/input/replay.js +209 -0
  183. package/src/jth/vendor.js +28 -0
  184. package/src/ledger/tx.js +94 -0
  185. package/src/machine/apply.js +193 -0
  186. package/src/machine/diff.js +168 -0
  187. package/src/machine/drive.js +296 -0
  188. package/src/machine/engine.js +478 -0
  189. package/src/machine/files-tool.js +76 -0
  190. package/src/machine/lint.js +139 -0
  191. package/src/machine/llmtm-trace.js +117 -0
  192. package/src/machine/llmtm.js +475 -0
  193. package/src/machine/otel.js +80 -0
  194. package/src/machine/pane-provider.js +51 -0
  195. package/src/machine/propose.js +159 -0
  196. package/src/machine/random.js +52 -0
  197. package/src/machine/risk.js +107 -0
  198. package/src/machine/session.js +1017 -0
  199. package/src/machine/shell-tool.js +45 -0
  200. package/src/machine/tape.js +349 -0
  201. package/src/machine/templates.js +104 -0
  202. package/src/machine/trace.js +664 -0
  203. package/src/machine/view.js +73 -0
  204. package/src/machine/vm-tool.js +47 -0
  205. package/src/machine/watchdog.js +46 -0
  206. package/src/mcp/app-args.js +51 -0
  207. package/src/mcp/app-run.js +56 -0
  208. package/src/mcp/apps.js +468 -0
  209. package/src/mcp/cache.js +232 -0
  210. package/src/mcp/client.js +507 -0
  211. package/src/mcp/demo-app.js +183 -0
  212. package/src/mcp/demo-server.js +602 -0
  213. package/src/mcp/elicitation.js +116 -0
  214. package/src/mcp/hub.js +1326 -0
  215. package/src/mcp/roots.js +139 -0
  216. package/src/mcp/sampling.js +105 -0
  217. package/src/mcp/settings.js +125 -0
  218. package/src/mcp/tape.js +292 -0
  219. package/src/mcp/uri-template.js +156 -0
  220. package/src/mcp/wsh-client.js +164 -0
  221. package/src/media/animated-codec.js +7 -0
  222. package/src/media/animated.js +623 -0
  223. package/src/media/compare-agent.js +70 -0
  224. package/src/media/compare-job.js +63 -0
  225. package/src/media/compare-page.js +296 -0
  226. package/src/media/compare-worker.js +14 -0
  227. package/src/media/compare.js +600 -0
  228. package/src/media/contract.js +62 -0
  229. package/src/media/decode-frame.js +57 -0
  230. package/src/media/decode-pool.js +188 -0
  231. package/src/media/ffmpeg-edit.js +344 -0
  232. package/src/media/ffmpeg-wasm-client.js +121 -0
  233. package/src/media/ffmpeg-wasm-session.js +79 -0
  234. package/src/media/ffmpeg-wasm.js +139 -0
  235. package/src/media/ffmpeg-worker.js +23 -0
  236. package/src/media/ffmpeg.js +903 -0
  237. package/src/media/helpers.js +419 -0
  238. package/src/media/keep.js +108 -0
  239. package/src/media/metadata-worker.js +16 -0
  240. package/src/media/metadata.js +2518 -0
  241. package/src/media/mime.js +102 -0
  242. package/src/media/page-decode.js +74 -0
  243. package/src/media/persist.js +114 -0
  244. package/src/media/png.js +226 -0
  245. package/src/media/sample-input.js +67 -0
  246. package/src/media/store.js +86 -0
  247. package/src/media/wav.js +109 -0
  248. package/src/midi/mappings.js +250 -0
  249. package/src/midi/message.js +125 -0
  250. package/src/model/action-hub.js +143 -0
  251. package/src/model/adapters.js +284 -0
  252. package/src/model/agent-runs.js +12 -0
  253. package/src/model/arrange.js +308 -0
  254. package/src/model/automation-clock.js +494 -0
  255. package/src/model/automation.js +653 -0
  256. package/src/model/batches.js +78 -0
  257. package/src/model/binary-view.js +195 -0
  258. package/src/model/breakpoints.js +392 -0
  259. package/src/model/calc-settings.js +65 -0
  260. package/src/model/calendar.js +254 -0
  261. package/src/model/canvas-id.js +5 -0
  262. package/src/model/canvas.js +5048 -0
  263. package/src/model/channel-names.js +29 -0
  264. package/src/model/channels.js +692 -0
  265. package/src/model/chart-clock.js +631 -0
  266. package/src/model/chart-code.js +69 -0
  267. package/src/model/codecs.js +60 -0
  268. package/src/model/companion-access.js +271 -0
  269. package/src/model/companion-pane.js +50 -0
  270. package/src/model/composite.js +324 -0
  271. package/src/model/context.js +380 -0
  272. package/src/model/controls.js +231 -0
  273. package/src/model/converter-presets.js +368 -0
  274. package/src/model/cost.js +580 -0
  275. package/src/model/curve-transform.js +122 -0
  276. package/src/model/cycles.js +176 -0
  277. package/src/model/debug-log.js +168 -0
  278. package/src/model/decision-clock.js +100 -0
  279. package/src/model/decisions.js +265 -0
  280. package/src/model/desk.js +87 -0
  281. package/src/model/device-hub.js +400 -0
  282. package/src/model/diff.js +445 -0
  283. package/src/model/emit-events.js +179 -0
  284. package/src/model/errors.js +238 -0
  285. package/src/model/event-presets.js +297 -0
  286. package/src/model/events.js +1303 -0
  287. package/src/model/explicit-setters.js +139 -0
  288. package/src/model/field-mapping.js +623 -0
  289. package/src/model/files-pane.js +263 -0
  290. package/src/model/flow-idle.js +89 -0
  291. package/src/model/foreach.js +549 -0
  292. package/src/model/frame-loop.js +71 -0
  293. package/src/model/frame-pressure.js +180 -0
  294. package/src/model/function-scaffold.js +1000 -0
  295. package/src/model/geometry-settings.js +54 -0
  296. package/src/model/goals.js +176 -0
  297. package/src/model/graph-settings.js +76 -0
  298. package/src/model/grid-widget.js +175 -0
  299. package/src/model/groups.js +332 -0
  300. package/src/model/hash.js +21 -0
  301. package/src/model/history.js +259 -0
  302. package/src/model/http-copy.js +88 -0
  303. package/src/model/http-send-companion.js +110 -0
  304. package/src/model/http-send.js +163 -0
  305. package/src/model/http-tap.js +521 -0
  306. package/src/model/http-tools.js +1138 -0
  307. package/src/model/import-lock.js +78 -0
  308. package/src/model/imports.js +258 -0
  309. package/src/model/infer-outputs.js +822 -0
  310. package/src/model/ink-connect.js +150 -0
  311. package/src/model/ink-diff.js +75 -0
  312. package/src/model/ink-gone.js +71 -0
  313. package/src/model/ink-route.js +120 -0
  314. package/src/model/ink-svg.js +206 -0
  315. package/src/model/ink.js +739 -0
  316. package/src/model/input-log-hub.js +456 -0
  317. package/src/model/input-split.js +69 -0
  318. package/src/model/json-schema-host.js +9 -0
  319. package/src/model/json-schema.js +368 -0
  320. package/src/model/jth.js +78 -0
  321. package/src/model/latex-expr.js +528 -0
  322. package/src/model/layout-history.js +120 -0
  323. package/src/model/lazy-map.js +88 -0
  324. package/src/model/ledger-pane.js +101 -0
  325. package/src/model/legacy-viaframe.js +90 -0
  326. package/src/model/lessons.js +448 -0
  327. package/src/model/links.js +981 -0
  328. package/src/model/live.js +411 -0
  329. package/src/model/math-widget.js +53 -0
  330. package/src/model/memory-settings.js +33 -0
  331. package/src/model/midi-controls.js +350 -0
  332. package/src/model/nl-time.js +408 -0
  333. package/src/model/notebook.js +137 -0
  334. package/src/model/pane-view-store.js +15 -0
  335. package/src/model/partial.js +115 -0
  336. package/src/model/pause-clock.js +53 -0
  337. package/src/model/peer-pane.js +32 -0
  338. package/src/model/persist-state.js +290 -0
  339. package/src/model/person-only.js +122 -0
  340. package/src/model/pin.js +209 -0
  341. package/src/model/plot-3d.js +213 -0
  342. package/src/model/plot-series.js +157 -0
  343. package/src/model/plot-settings.js +531 -0
  344. package/src/model/ports.js +312 -0
  345. package/src/model/presentation.js +222 -0
  346. package/src/model/preset-apply.js +316 -0
  347. package/src/model/preset-banks.js +335 -0
  348. package/src/model/preset-morph.js +263 -0
  349. package/src/model/preset-ops.js +205 -0
  350. package/src/model/preset-player.js +283 -0
  351. package/src/model/preset-states.js +172 -0
  352. package/src/model/profile-settings.js +109 -0
  353. package/src/model/promote.js +103 -0
  354. package/src/model/protected.js +10 -0
  355. package/src/model/proxy-log.js +230 -0
  356. package/src/model/proxy.js +367 -0
  357. package/src/model/quantity-widget.js +61 -0
  358. package/src/model/queue-book.js +359 -0
  359. package/src/model/quick-add.js +224 -0
  360. package/src/model/rate-limit.js +313 -0
  361. package/src/model/rate.js +95 -0
  362. package/src/model/recovery.js +216 -0
  363. package/src/model/rename-follow.js +113 -0
  364. package/src/model/repeater.js +1126 -0
  365. package/src/model/retention.js +664 -0
  366. package/src/model/route-edit.js +132 -0
  367. package/src/model/router.js +155 -0
  368. package/src/model/runaway.js +232 -0
  369. package/src/model/runlog.js +1033 -0
  370. package/src/model/runners/a2a.js +2 -0
  371. package/src/model/runners/acp.js +2 -0
  372. package/src/model/runners/actions.js +4 -0
  373. package/src/model/runners/agent.js +4 -0
  374. package/src/model/runners/audio.js +21 -0
  375. package/src/model/runners/automation.js +2 -0
  376. package/src/model/runners/calc.js +23 -0
  377. package/src/model/runners/catch.js +10 -0
  378. package/src/model/runners/codec.js +24 -0
  379. package/src/model/runners/companion-run.js +2 -0
  380. package/src/model/runners/device.js +7 -0
  381. package/src/model/runners/dom.js +13 -0
  382. package/src/model/runners/effects.js +2 -0
  383. package/src/model/runners/embed.js +11 -0
  384. package/src/model/runners/eval.js +2 -0
  385. package/src/model/runners/files.js +19 -0
  386. package/src/model/runners/geometry.js +23 -0
  387. package/src/model/runners/goals.js +18 -0
  388. package/src/model/runners/graph.js +23 -0
  389. package/src/model/runners/html.js +2 -0
  390. package/src/model/runners/http-proxy.js +185 -0
  391. package/src/model/runners/http-send.js +61 -0
  392. package/src/model/runners/http-static.js +83 -0
  393. package/src/model/runners/http-tap.js +26 -0
  394. package/src/model/runners/http.js +40 -0
  395. package/src/model/runners/import.js +2 -0
  396. package/src/model/runners/index.js +74 -0
  397. package/src/model/runners/input.js +14 -0
  398. package/src/model/runners/inputlog.js +7 -0
  399. package/src/model/runners/ledger.js +15 -0
  400. package/src/model/runners/machine.js +4 -0
  401. package/src/model/runners/mcp.js +2 -0
  402. package/src/model/runners/mcpapp.js +2 -0
  403. package/src/model/runners/media.js +18 -0
  404. package/src/model/runners/memory.js +28 -0
  405. package/src/model/runners/mesh-inspect.js +13 -0
  406. package/src/model/runners/peer.js +14 -0
  407. package/src/model/runners/plot.js +22 -0
  408. package/src/model/runners/render.js +14 -0
  409. package/src/model/runners/respond.js +2 -0
  410. package/src/model/runners/sample-soundfont.js +85 -0
  411. package/src/model/runners/sample.js +159 -0
  412. package/src/model/runners/scene.js +8 -0
  413. package/src/model/runners/score.js +24 -0
  414. package/src/model/runners/secret.js +10 -0
  415. package/src/model/runners/select.js +2 -0
  416. package/src/model/runners/shared.js +4 -0
  417. package/src/model/runners/shares.js +15 -0
  418. package/src/model/runners/shell.js +7 -0
  419. package/src/model/runners/skill.js +26 -0
  420. package/src/model/runners/state.js +2 -0
  421. package/src/model/runners/statechart.js +4 -0
  422. package/src/model/runners/subgraph.js +9 -0
  423. package/src/model/runners/tabs.js +25 -0
  424. package/src/model/runners/terminal.js +5 -0
  425. package/src/model/runners/text.js +4 -0
  426. package/src/model/runners/timer.js +7 -0
  427. package/src/model/runners/traffic.js +65 -0
  428. package/src/model/runners/trigger.js +2 -0
  429. package/src/model/runners/verdict.js +29 -0
  430. package/src/model/runners/vm.js +7 -0
  431. package/src/model/runners/wait.js +4 -0
  432. package/src/model/runners/ws-client.js +57 -0
  433. package/src/model/safe-regex.js +719 -0
  434. package/src/model/sample-settings.js +43 -0
  435. package/src/model/sample-source.js +47 -0
  436. package/src/model/saved-mapping.js +153 -0
  437. package/src/model/score-controllers.js +87 -0
  438. package/src/model/score-edit.js +399 -0
  439. package/src/model/score-instruments.js +300 -0
  440. package/src/model/score-library.js +407 -0
  441. package/src/model/score-markup.js +235 -0
  442. package/src/model/score-mix.js +248 -0
  443. package/src/model/score-patterns.js +276 -0
  444. package/src/model/score-selection.js +34 -0
  445. package/src/model/score-time.js +139 -0
  446. package/src/model/score-transforms.js +336 -0
  447. package/src/model/score-transport.js +192 -0
  448. package/src/model/selection.js +351 -0
  449. package/src/model/serial-controls.js +328 -0
  450. package/src/model/shares-pane.js +17 -0
  451. package/src/model/shell-pane.js +106 -0
  452. package/src/model/signature.js +1122 -0
  453. package/src/model/size-hints.js +106 -0
  454. package/src/model/size-ratio.js +12 -0
  455. package/src/model/skill-settings.js +23 -0
  456. package/src/model/snapping.js +466 -0
  457. package/src/model/split.js +375 -0
  458. package/src/model/spring-player.js +222 -0
  459. package/src/model/statecharts.js +1369 -0
  460. package/src/model/states-preset.js +208 -0
  461. package/src/model/static-route.js +100 -0
  462. package/src/model/step-words.js +45 -0
  463. package/src/model/subgraph.js +1042 -0
  464. package/src/model/switch.js +98 -0
  465. package/src/model/tabs-store.js +10 -0
  466. package/src/model/tensor-view.js +146 -0
  467. package/src/model/timer-clock.js +361 -0
  468. package/src/model/timers.js +422 -0
  469. package/src/model/timing.js +212 -0
  470. package/src/model/traffic-agent.js +111 -0
  471. package/src/model/traffic-store.js +20 -0
  472. package/src/model/traffic.js +665 -0
  473. package/src/model/transport.js +364 -0
  474. package/src/model/turns.js +86 -0
  475. package/src/model/types.js +425 -0
  476. package/src/model/value-path.js +138 -0
  477. package/src/model/versions.js +535 -0
  478. package/src/model/view-outputs.js +144 -0
  479. package/src/model/viewport-bookmarks.js +194 -0
  480. package/src/model/virtual-clock.js +85 -0
  481. package/src/model/vm-pane.js +258 -0
  482. package/src/model/wait-clock.js +715 -0
  483. package/src/model/wait-persist.js +248 -0
  484. package/src/model/waits.js +431 -0
  485. package/src/model/watch.js +80 -0
  486. package/src/model/webhook.js +496 -0
  487. package/src/model/when.js +48 -0
  488. package/src/model/widget-values.js +392 -0
  489. package/src/model/window-commands.js +278 -0
  490. package/src/model/windows.js +348 -0
  491. package/src/model/wire-inspect.js +343 -0
  492. package/src/model/wire-ops.js +324 -0
  493. package/src/model/wire-pipeline.js +378 -0
  494. package/src/model/wire-route.js +637 -0
  495. package/src/model/workspaces.js +122 -0
  496. package/src/model/ws-client.js +155 -0
  497. package/src/model/ws-demo.js +31 -0
  498. package/src/model/ws-frames.js +141 -0
  499. package/src/model/ws-hub.js +219 -0
  500. package/src/model/ws-served.js +13 -0
  501. package/src/model/xstate.js +374 -0
  502. package/src/narrative/narrative.js +1557 -0
  503. package/src/network/auth.js +224 -0
  504. package/src/network/csp-frame.js +197 -0
  505. package/src/network/declarative-shadow.js +27 -0
  506. package/src/network/frame-net-shim.js +962 -0
  507. package/src/network/hosts.js +157 -0
  508. package/src/network/policy.js +520 -0
  509. package/src/network/rtc-shim.js +418 -0
  510. package/src/network/secret-gate.js +78 -0
  511. package/src/network/secrets.js +261 -0
  512. package/src/network/sockets.js +287 -0
  513. package/src/network/store.js +186 -0
  514. package/src/network/streams.js +99 -0
  515. package/src/packages/asset-values.js +50 -0
  516. package/src/packages/assets.js +99 -0
  517. package/src/packages/deprecation.js +203 -0
  518. package/src/packages/fetch.js +152 -0
  519. package/src/packages/function-canvas.js +73 -0
  520. package/src/packages/module.js +120 -0
  521. package/src/packages/package.js +474 -0
  522. package/src/packages/published.js +27 -0
  523. package/src/packages/requires.js +83 -0
  524. package/src/packages/signing.js +145 -0
  525. package/src/packages/trust.js +107 -0
  526. package/src/panes/a2a.js +51 -0
  527. package/src/panes/acp.js +60 -0
  528. package/src/panes/actions.js +54 -0
  529. package/src/panes/agent.js +83 -0
  530. package/src/panes/audio.js +103 -0
  531. package/src/panes/automation.js +112 -0
  532. package/src/panes/calc.js +67 -0
  533. package/src/panes/catch.js +52 -0
  534. package/src/panes/codec.js +59 -0
  535. package/src/panes/colors.js +12 -0
  536. package/src/panes/companion.js +54 -0
  537. package/src/panes/decision.js +65 -0
  538. package/src/panes/device.js +56 -0
  539. package/src/panes/dom.js +37 -0
  540. package/src/panes/effects.js +118 -0
  541. package/src/panes/embed.js +30 -0
  542. package/src/panes/eval.js +186 -0
  543. package/src/panes/fields.js +299 -0
  544. package/src/panes/files.js +45 -0
  545. package/src/panes/gate.js +70 -0
  546. package/src/panes/geometry.js +64 -0
  547. package/src/panes/goals.js +75 -0
  548. package/src/panes/graph.js +66 -0
  549. package/src/panes/html.js +54 -0
  550. package/src/panes/http.js +82 -0
  551. package/src/panes/import.js +38 -0
  552. package/src/panes/input.js +124 -0
  553. package/src/panes/inputlog.js +66 -0
  554. package/src/panes/ledger.js +56 -0
  555. package/src/panes/machine.js +138 -0
  556. package/src/panes/mcp.js +85 -0
  557. package/src/panes/mcpapp.js +64 -0
  558. package/src/panes/media.js +38 -0
  559. package/src/panes/memory.js +46 -0
  560. package/src/panes/mesh-inspect.js +49 -0
  561. package/src/panes/note.js +38 -0
  562. package/src/panes/peer.js +44 -0
  563. package/src/panes/plot.js +196 -0
  564. package/src/panes/registry.js +475 -0
  565. package/src/panes/render.js +87 -0
  566. package/src/panes/respond.js +44 -0
  567. package/src/panes/router.js +84 -0
  568. package/src/panes/sample.js +75 -0
  569. package/src/panes/scene.js +55 -0
  570. package/src/panes/score.js +87 -0
  571. package/src/panes/secret.js +38 -0
  572. package/src/panes/select.js +67 -0
  573. package/src/panes/shader.js +166 -0
  574. package/src/panes/shared.js +33 -0
  575. package/src/panes/shares.js +43 -0
  576. package/src/panes/shell.js +47 -0
  577. package/src/panes/skill.js +44 -0
  578. package/src/panes/state.js +91 -0
  579. package/src/panes/statechart.js +63 -0
  580. package/src/panes/story.js +33 -0
  581. package/src/panes/subgraph.js +94 -0
  582. package/src/panes/tabs.js +52 -0
  583. package/src/panes/terminal.js +57 -0
  584. package/src/panes/text.js +36 -0
  585. package/src/panes/timer.js +55 -0
  586. package/src/panes/traffic.js +59 -0
  587. package/src/panes/verdict.js +62 -0
  588. package/src/panes/vm.js +46 -0
  589. package/src/panes/wait.js +61 -0
  590. package/src/panes/watch.js +57 -0
  591. package/src/panes/webhook.js +67 -0
  592. package/src/panes/ws-client.js +67 -0
  593. package/src/persist.js +281 -0
  594. package/src/plot/tex.js +19 -0
  595. package/src/plot/vendor.js +59 -0
  596. package/src/plot/view-vendor.js +5 -0
  597. package/src/privacy/levels.js +108 -0
  598. package/src/protocol/devtools.js +116 -0
  599. package/src/protocol/inspector.js +368 -0
  600. package/src/render/time.js +381 -0
  601. package/src/rooms/mesh-metrics.js +162 -0
  602. package/src/run/companion.js +355 -0
  603. package/src/run/describe.js +114 -0
  604. package/src/run/local-model.js +150 -0
  605. package/src/run/monitor.js +208 -0
  606. package/src/run/publish.js +360 -0
  607. package/src/run/respond-outcome.js +12 -0
  608. package/src/run/run.js +820 -0
  609. package/src/run/runner-pairing.js +243 -0
  610. package/src/run/values.js +122 -0
  611. package/src/runtime/compile.js +122 -0
  612. package/src/runtime/console-tag.js +64 -0
  613. package/src/runtime/frame-signals.js +126 -0
  614. package/src/runtime/iteration-push.js +19 -0
  615. package/src/runtime/keys.js +474 -0
  616. package/src/runtime/midi-input.js +170 -0
  617. package/src/runtime/person-waits.js +140 -0
  618. package/src/runtime/resource-timing.js +56 -0
  619. package/src/runtime/runtime.js +2150 -0
  620. package/src/runtime/sandbox-modules.js +163 -0
  621. package/src/runtime/spring.js +246 -0
  622. package/src/runtime/strict.js +215 -0
  623. package/src/runtime/transfer.js +75 -0
  624. package/src/runtime/tween.js +158 -0
  625. package/src/runtime/wasm-fuel.js +596 -0
  626. package/src/runtime/worker/00-prelude.js +88 -0
  627. package/src/runtime/worker/10-helpers.js +295 -0
  628. package/src/runtime/worker/20-io.js +645 -0
  629. package/src/runtime/worker/30-previews.js +210 -0
  630. package/src/runtime/worker/40-profile-lineage.js +278 -0
  631. package/src/runtime/worker/50-own-worker.js +233 -0
  632. package/src/runtime/worker/60-timers.js +172 -0
  633. package/src/runtime/worker/70-state-keyed.js +193 -0
  634. package/src/runtime/worker/80-each-compile-generators.js +619 -0
  635. package/src/runtime/worker/90-events-operators.js +655 -0
  636. package/src/runtime/worker/95-agents-batches.js +1820 -0
  637. package/src/runtime/worker/96-plot.js +47 -0
  638. package/src/runtime/worker/97-calc.js +28 -0
  639. package/src/runtime/worker/98-geometry.js +24 -0
  640. package/src/runtime/worker/99-graph.js +30 -0
  641. package/src/runtime/worker/99-shell.js +30 -0
  642. package/src/safety/config.js +57 -0
  643. package/src/safety/engine.js +324 -0
  644. package/src/scene/pixi-scene.js +806 -0
  645. package/src/scene/scene-assets.js +241 -0
  646. package/src/scene/scene-edit.js +319 -0
  647. package/src/secret/settings.js +41 -0
  648. package/src/security/multipart.js +257 -0
  649. package/src/security/redact.js +261 -0
  650. package/src/serial/broker.js +473 -0
  651. package/src/serial/config.js +185 -0
  652. package/src/serial/framers.js +389 -0
  653. package/src/serial/packets.js +64 -0
  654. package/src/shader/audio-texture.js +87 -0
  655. package/src/shader/channels.js +496 -0
  656. package/src/shader/common.js +90 -0
  657. package/src/shader/model.js +867 -0
  658. package/src/shader/passes.js +150 -0
  659. package/src/shader/shadertoy.js +198 -0
  660. package/src/shell/hub.js +287 -0
  661. package/src/sim/checkpoints.js +850 -0
  662. package/src/sim/compile.js +37 -0
  663. package/src/sim/fixed.js +377 -0
  664. package/src/sim/headless.js +205 -0
  665. package/src/sim/physics.js +399 -0
  666. package/src/smf-helper/vendor.js +2 -0
  667. package/src/sources/config.js +435 -0
  668. package/src/storage.js +153 -0
  669. package/src/table/table-geo.js +2344 -0
  670. package/src/table/table-lineage.js +808 -0
  671. package/src/table/table-quality.js +355 -0
  672. package/src/table/table-schema.js +392 -0
  673. package/src/table/table-sql.js +1650 -0
  674. package/src/table/table-stats.js +480 -0
  675. package/src/table/table.js +2102 -0
  676. package/src/tensor/tensor.js +1153 -0
  677. package/src/terminal/hub.js +715 -0
  678. package/src/terminal/screen.js +516 -0
  679. package/src/tests/capture.js +88 -0
  680. package/src/tests/compare.js +480 -0
  681. package/src/tests/dataset.js +170 -0
  682. package/src/tests/evaluate.js +286 -0
  683. package/src/tests/from-runs.js +99 -0
  684. package/src/tests/judge.js +134 -0
  685. package/src/tests/matchers.js +263 -0
  686. package/src/tests/matrix-spec.js +87 -0
  687. package/src/tests/matrix.js +397 -0
  688. package/src/tests/metrics.js +369 -0
  689. package/src/tests/no-value.js +42 -0
  690. package/src/tests/pane-check.js +45 -0
  691. package/src/tests/report.js +124 -0
  692. package/src/tests/reporters.js +140 -0
  693. package/src/tests/run.js +155 -0
  694. package/src/tilemap/tilemap.js +1122 -0
  695. package/src/units/units.js +3 -0
  696. package/src/util/bytes-text.js +21 -0
  697. package/src/util/num.js +10 -0
  698. package/src/util/regexp.js +2 -0
  699. package/src/util/text.js +38 -0
  700. package/src/verdict/engine.js +154 -0
  701. package/src/vm/guest-wsh.js +108 -0
  702. package/src/vm/hub.js +457 -0
  703. package/src/vm/image-files.js +4 -0
  704. package/src/vm/image.js +33 -0
  705. package/src/vm/image.lock.json +13 -0
  706. package/src/vm/link.js +266 -0
  707. package/src/vm/mount.js +212 -0
  708. package/src/vm/net.js +85 -0
  709. package/src/vm/pipe-ws.js +187 -0
  710. package/src/vm/v86-loader.js +11 -0
  711. package/src/webmcp/args.js +212 -0
  712. package/src/webmcp/hidden.js +218 -0
  713. package/src/webmcp/text.js +250 -0
  714. package/src/webmcp/tools/bookmark-tools.js +106 -0
  715. package/src/webmcp/tools/breakpoint-tools.js +48 -0
  716. package/src/webmcp/tools/canvases.js +208 -0
  717. package/src/webmcp/tools/context-tools.js +84 -0
  718. package/src/webmcp/tools/core.js +170 -0
  719. package/src/webmcp/tools/devices.js +41 -0
  720. package/src/webmcp/tools/edit.js +357 -0
  721. package/src/webmcp/tools/event-tools.js +145 -0
  722. package/src/webmcp/tools/image-tools.js +173 -0
  723. package/src/webmcp/tools/ink-tools.js +247 -0
  724. package/src/webmcp/tools/input-log-tools.js +163 -0
  725. package/src/webmcp/tools/live.js +166 -0
  726. package/src/webmcp/tools/machine-tools.js +74 -0
  727. package/src/webmcp/tools/media.js +161 -0
  728. package/src/webmcp/tools/midi-tools.js +32 -0
  729. package/src/webmcp/tools/preset-tools.js +184 -0
  730. package/src/webmcp/tools/quick-add-tools.js +95 -0
  731. package/src/webmcp/tools/reshape.js +152 -0
  732. package/src/webmcp/tools/run-tools.js +309 -0
  733. package/src/webmcp/tools/runs.js +101 -0
  734. package/src/webmcp/tools/scaffold-tools.js +161 -0
  735. package/src/webmcp/tools/serial-tools.js +36 -0
  736. package/src/webmcp/tools/shared.js +338 -0
  737. package/src/webmcp/tools/subgraphs.js +360 -0
  738. package/src/webmcp/tools/tests.js +170 -0
  739. package/src/webmcp/tools/traffic-tools.js +70 -0
  740. package/src/webmcp/tools/transport-tools.js +65 -0
  741. package/src/webmcp/tools/version-tools.js +126 -0
  742. package/src/webmcp/tools/versions.js +11 -0
  743. package/src/webmcp/tools/wire-tools.js +90 -0
  744. package/src/webmcp/tools/workspace-tools.js +93 -0
  745. package/src/webmcp/tools.js +1323 -0
  746. package/src/wsh/connect.js +347 -0
  747. package/src/wsh/demo-host.js +361 -0
  748. package/src/wsh/e2e.js +27 -0
  749. package/src/wsh/keys.js +154 -0
  750. package/src/wsh/known-hosts.js +39 -0
  751. package/src/wsh/private-key.js +95 -0
  752. package/src/wsh/reverse.js +34 -0
  753. package/src/wsh/settings.js +118 -0
  754. package/src/wsh/transfer.js +62 -0
  755. package/src/wsh/vendor.js +5 -0
  756. package/src/x402/challenge.js +171 -0
  757. package/src/x402/demo-server.js +127 -0
  758. package/src/x402/pay.js +125 -0
  759. package/src/x402/retry.js +95 -0
  760. package/src/x402/store.js +76 -0
@@ -0,0 +1,2344 @@
1
+ // Local GeoJSON transforms: a plugin of the table helper (docs/tables.md),
2
+ // loaded as the module "mallory:table/geo" (src/runtime/sources.js) and installed
3
+ // with `install(table)`. Self-contained: no imports, no network, no storage, no eval,
4
+ // no tiles, no geocoding. Pure JavaScript on JSON.
5
+ //
6
+ // WHAT IT PROMISES (and what it refuses)
7
+ //
8
+ // Coordinates are GeoJSON's (RFC 7946): WGS84 (EPSG:4326, also called CRS84),
9
+ // [longitude, latitude] in degrees, in that order. Data in Web Mercator (EPSG:3857)
10
+ // or a WGS84 UTM zone (EPSG:326xx / 327xx) is reprojected when the caller says so
11
+ // (`crs`, or `geoReproject`'s `from`); a document that says it is in any other CRS,
12
+ // or whose numbers are outside -180..180 / -90..90 with no CRS named, is refused
13
+ // with the reason and the fix (`incompatible-crs`, `out-of-range`), never guessed.
14
+ // Data written as [latitude, longitude] is read with `axisOrder: "latlon"`, which
15
+ // the caller must say.
16
+ //
17
+ // Distances and lengths are metres along great circles on a sphere of radius
18
+ // 6,371,008.8 m (haversine: within about 0.5 % of the ellipsoid). Areas are
19
+ // square metres on the same sphere. Centroids, extents and point-in-polygon tests
20
+ // are planar in longitude/latitude (edges are straight in degrees), after one step
21
+ // that makes the antimeridian (+/-180) harmless: an edge whose longitudes differ by
22
+ // more than 180 degrees is read as crossing it (the short way round, as the distance
23
+ // and area maths already do), so a Fiji polygon written with 179 then -179 is a thin
24
+ // shape, not one 358 degrees wide, and the parts of a MultiPolygon cut at +/-180 are put
25
+ // side by side. Then a centroid east of 180 comes back as a longitude from -180, a
26
+ // bbox across it has west > east (RFC 7946 section 5.2), and a point at -179 is inside
27
+ // a polygon that spans 179 to -179. A polygon that encloses a pole (its longitudes run
28
+ // all the way round) is the cap its winding says, by the right-hand rule of RFC 7946: counter-clockwise,
29
+ // so eastward round the north pole or westward round the south, has the pole inside. Its area is that
30
+ // cap's, and for centroid, extent and point-in-polygon it is flattened with the pole as its edge (the
31
+ // centroid is of that flat shape). A point on a polygon's boundary is inside.
32
+ //
33
+ // Supported geometry: Point, MultiPoint, LineString, MultiLineString, Polygon,
34
+ // MultiPolygon. A GeometryCollection, and a measure that does not exist for a type
35
+ // (the area of a line), are `unsupported-geometry` errors that name the fix. A
36
+ // position's altitude, if any, is ignored.
37
+ //
38
+ // Outside data (retrieved by an http pane under the canvas's network approval, never by this module) can carry its
39
+ // `source` ({ url, retrieved, license }): geoParse / toGeoJSON check the record is complete and pass it along.
40
+ //
41
+ // Every operation is bounded: `limits` (maxRows, maxCells, maxMs) as for the core
42
+ // operations, `maxCoordinates` for a parsed document, `maxPairs` for a spatial join.
43
+ //
44
+ // OPERATIONS (all return the usual result: rows, schema, errors, notes, and with
45
+ // `trace: true` an `origin` per output row, the lineage contract)
46
+ //
47
+ // geoParse(geojson, opts) FeatureCollection / Feature / Geometry (or its JSON text) -> rows
48
+ // `{ id, ...properties, geometry }`, with `rejected` features and
49
+ // `rejections` (`{ index, id, code, reason }`) for the invalid ones
50
+ // geoMeasure(rows, opts) bbox / centroid / area / length / distance columns
51
+ // geoReproject(rows, opts) a geometry column moved between WGS84, Web Mercator and UTM
52
+ // geoBuffer(rows, opts) a geodesic circle around each point; a stadium round each segment of a line or polygon, dissolved
53
+ // geoCell(rows, opts) the cell of an equal-angle grid (a small stand-in for H3) a point is in
54
+ // geoWithin(rows, opts) keep the rows whose geometry is inside a region (`excluded`: the rest)
55
+ // geoJoin({ left, right }, o) spatial join: `within`, `dwithin`, `intersects`, `overlaps` or `nearest`, with a grid
56
+ // index for big joins; rows / matched / leftOnly / rightOnly
57
+ // toGeoJSON(rows, opts) rows back to a FeatureCollection (invalid rows come out as `rejected`)
58
+ //
59
+ // And pure helpers on `table.geo` (validate, extent, centroid, area, length, distance, buffer,
60
+ // contains, intersects, overlaps, gap, reproject, crs, cell, cellBounds, cellNeighbors,
61
+ // drawable) and SQL functions ST_DISTANCE, ST_AREA, ST_LENGTH, ST_WITHIN, ST_CONTAINS,
62
+ // ST_INTERSECTS, ST_GAP, ST_BUFFER, ST_TRANSFORM, ST_CELL, ST_CENTROID, ST_X, ST_Y.
63
+
64
+ export function install(t) {
65
+ const { TableError, defineOp, functions, parseIso } = t;
66
+
67
+ const EARTH_RADIUS_M = 6371008.8;
68
+ const RAD = Math.PI / 180;
69
+ const CRS = Object.freeze({ name: "WGS84", code: "EPSG:4326", alias: "CRS84", axisOrder: "lonlat", coordinates: "[longitude, latitude] in degrees", distance: "metres, great circle on a sphere (haversine)", area: "square metres, spherical" });
70
+ const TYPES = ["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon"];
71
+ const DEFAULT_MAX_COORDINATES = 2_000_000;
72
+ const DEFAULT_MAX_PAIRS = 10_000_000;
73
+ const UNITS = { length: { m: 1, km: 1000, mi: 1609.344 }, area: { m2: 1, km2: 1e6, ha: 1e4 } };
74
+
75
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
76
+ const fin = Number.isFinite;
77
+ const bad = (op, message) => new TableError("bad-option", `${op}: ${message}`);
78
+ const show = (v) => (typeof v === "string" ? JSON.stringify(v) : JSON.stringify(v) ?? String(v));
79
+ const problem = (code, reason) => ({ code, reason });
80
+
81
+ // ── validation ───────────────────────────────────────────────────────────
82
+
83
+ /** Why a position is not a valid WGS84 [longitude, latitude], or null. `loose` checks only that it is two numbers (a projected CRS has metres). */
84
+ function positionProblem(p, loose = false) {
85
+ if (!Array.isArray(p) || p.length < 2 || !fin(p[0]) || !fin(p[1])) return problem("bad-coordinates", `a position is [longitude, latitude] (two numbers), not ${show(p)}`);
86
+ if (loose) return null;
87
+ const [x, y] = p;
88
+ if (x >= -180 && x <= 180 && y >= -90 && y <= 90) return null;
89
+ if (y >= -180 && y <= 180 && x >= -90 && x <= 90) return problem("out-of-range", `[${x}, ${y}] is outside longitude -180..180, latitude -90..90; it looks like [latitude, longitude]. GeoJSON order is [longitude, latitude]: fix the data or read it with axisOrder: "latlon"`);
90
+ return problem("out-of-range", `[${x}, ${y}] is outside longitude -180..180, latitude -90..90; values this large look like a projected CRS (metres, e.g. EPSG:3857). Say which with the crs option of geoParse (or geoReproject with from), for example crs: "EPSG:3857" or a UTM zone like "EPSG:32633", or reproject to WGS84 degrees first`);
91
+ }
92
+
93
+ const closed = (ring) => ring.length >= 4 && ring[0][0] === ring.at(-1)[0] && ring[0][1] === ring.at(-1)[1];
94
+
95
+ /** Why a geometry is not usable, as `{ code, reason }`, or null. `count` (an object with n) counts the positions seen. */
96
+ function validateGeometry(g, count = { n: 0 }, loose = false) {
97
+ if (g === null || g === undefined) return problem("no-geometry", "the feature has no geometry (geometry is null)");
98
+ if (!isObj(g) || typeof g.type !== "string") return problem("bad-geometry", `a geometry is an object with a type and coordinates, not ${show(g).slice(0, 60)}`);
99
+ if (g.type === "GeometryCollection") return problem("unsupported-geometry", "GeometryCollection is not supported: split it into one feature per geometry first");
100
+ if (!TYPES.includes(g.type)) return problem("unsupported-geometry", `${show(g.type)} is not a GeoJSON geometry type; supported: ${TYPES.join(", ")}`);
101
+ const c = g.coordinates;
102
+ if (!Array.isArray(c)) return problem("bad-geometry", `${g.type} has no coordinates array`);
103
+ const pos = (p) => {
104
+ count.n++;
105
+ return positionProblem(p, loose);
106
+ };
107
+ const line = (l, min, what) => {
108
+ if (!Array.isArray(l) || l.length < min) return problem("too-few-positions", `${what} needs at least ${min} positions, has ${Array.isArray(l) ? l.length : 0}`);
109
+ for (const p of l) {
110
+ const e = pos(p);
111
+ if (e) return e;
112
+ }
113
+ return null;
114
+ };
115
+ const ring = (r, what) => line(r, 4, what) ?? (closed(r) ? null : problem("ring-not-closed", `${what} must end where it starts (first and last position equal)`));
116
+ const poly = (p) => {
117
+ if (!Array.isArray(p) || !p.length) return problem("too-few-positions", "a Polygon needs at least its outer ring");
118
+ for (let i = 0; i < p.length; i++) {
119
+ const e = ring(p[i], i === 0 ? "the outer ring" : `hole ${i}`);
120
+ if (e) return e;
121
+ }
122
+ return null;
123
+ };
124
+ const each = (list, f) => {
125
+ if (!list.length) return problem("too-few-positions", `${g.type} has no members`);
126
+ for (const m of list) {
127
+ const e = f(m);
128
+ if (e) return e;
129
+ }
130
+ return null;
131
+ };
132
+ switch (g.type) {
133
+ case "Point":
134
+ return pos(c);
135
+ case "MultiPoint":
136
+ return each(c, pos);
137
+ case "LineString":
138
+ return line(c, 2, "a LineString");
139
+ case "MultiLineString":
140
+ return each(c, (l) => line(l, 2, "a line"));
141
+ case "Polygon":
142
+ return poly(c);
143
+ default:
144
+ return each(c, poly);
145
+ }
146
+ }
147
+
148
+ /** A geometry from a cell: a geometry object, a Feature (its geometry) or JSON text of either. `{ g }` or `{ problem }`. */
149
+ function geometryOf(cell) {
150
+ let v = cell;
151
+ if (typeof v === "string" && /^\s*[{[]/.test(v)) {
152
+ try {
153
+ v = JSON.parse(v);
154
+ } catch {
155
+ return { problem: problem("bad-geometry", "the cell is text that isn't JSON") };
156
+ }
157
+ }
158
+ if (Array.isArray(v) && v.length >= 2 && fin(v[0]) && fin(v[1])) v = { type: "Point", coordinates: v }; // a bare [longitude, latitude]
159
+ if (isObj(v) && v.type === "Feature") v = v.geometry;
160
+ const p = validateGeometry(v);
161
+ return p ? { problem: p } : { g: v };
162
+ }
163
+
164
+ // ── geometry maths ───────────────────────────────────────────────────────
165
+
166
+ /** Every position of a geometry, in order. */
167
+ function* positions(g) {
168
+ const c = g.coordinates;
169
+ switch (g.type) {
170
+ case "Point":
171
+ yield c;
172
+ break;
173
+ case "MultiPoint":
174
+ case "LineString":
175
+ yield* c;
176
+ break;
177
+ case "MultiLineString":
178
+ case "Polygon":
179
+ for (const l of c) yield* l;
180
+ break;
181
+ default:
182
+ for (const p of c) for (const r of p) yield* r;
183
+ }
184
+ }
185
+
186
+ const polygonsOf = (g) => (g.type === "Polygon" ? [g.coordinates] : g.type === "MultiPolygon" ? g.coordinates : []);
187
+ const linesOf = (g) => (g.type === "LineString" ? [g.coordinates] : g.type === "MultiLineString" ? g.coordinates : []);
188
+ const pointsOf = (g) => (g.type === "Point" ? [g.coordinates] : g.type === "MultiPoint" ? g.coordinates : []);
189
+
190
+ // ── the antimeridian ─────────────────────────────────────────────────────
191
+
192
+ /** `x` as a longitude in -180..180 (a value already there is untouched). */
193
+ const wrapLon = (x) => (x > 180 ? x - 360 : x < -180 ? x + 360 : x);
194
+ /** The longitude difference `d` as the short way round, in -180..180. */
195
+ const shortWay = (d) => (d > 180 ? d - 360 : d < -180 ? d + 360 : d);
196
+
197
+ /** The rings or lines of a geometry, each a list of positions, grouped by part: Point -> [[ [p] ]], Polygon -> [rings], MultiPolygon -> a part per polygon. */
198
+ const partsOf = (g) => {
199
+ const c = g.coordinates;
200
+ switch (g.type) {
201
+ case "Point":
202
+ return [[[c]]];
203
+ case "MultiPoint":
204
+ return c.map((p) => [[p]]);
205
+ case "LineString":
206
+ return [[c]];
207
+ case "MultiLineString":
208
+ return c.map((l) => [l]);
209
+ case "Polygon":
210
+ return [c];
211
+ default:
212
+ return c;
213
+ }
214
+ };
215
+
216
+ const unwrapped = new WeakMap();
217
+ /**
218
+ * The geometry with its longitudes made continuous (maybe beyond +/-180): each position moves by a
219
+ * multiple of 360 to lie within 180 of the one before it, and each part (a polygon of a MultiPolygon, a
220
+ * point of a MultiPoint) within 180 of the geometry's first position. The geometry itself when nothing
221
+ * had to move (the usual case), so a result is cached per geometry object.
222
+ */
223
+ function unwrap(g) {
224
+ if (unwrapped.has(g)) return unwrapped.get(g);
225
+ const first = [...positions(g)][0];
226
+ let moved = false;
227
+ const near = (x, ref) => {
228
+ const n = -Math.round((x - ref) / 360);
229
+ if (n !== 0) moved = true;
230
+ return n === 0 ? x : x + 360 * n;
231
+ };
232
+ const run = (list, anchor, hole) => {
233
+ const out = [];
234
+ let prev = anchor;
235
+ for (const q of list) {
236
+ const x = near(q[0], prev);
237
+ out.push(x === q[0] ? q : [x, ...q.slice(1)]);
238
+ prev = x;
239
+ }
240
+ // A ring that round a pole ends 360 degrees from where it starts. Flattened, it is an open path across the whole width
241
+ // of the map; closing it along the pole (up the end, back along latitude +/-90, down to the start) makes it the
242
+ // planar polygon of the cap it bounds: the pole is on the side to its left (RFC 7946: a hole's inside is on its right).
243
+ const turns = Math.round((out.at(-1)[0] - out[0][0]) / 360);
244
+ if (turns !== 0 && out.length > 1) {
245
+ moved = true;
246
+ const pole = (turns > 0) !== Boolean(hole) ? 90 : -90;
247
+ const [a, b] = [out[0], out.at(-1)];
248
+ out.push([b[0], pole], [a[0], pole], a);
249
+ }
250
+ return out;
251
+ };
252
+ const part = (rings) => {
253
+ const anchor = near(rings[0][0][0], first[0]);
254
+ const outer = run(rings[0], anchor, false);
255
+ let west = Infinity;
256
+ for (const q of outer) if (q[0] < west) west = q[0];
257
+ // A hole is placed within the width of its outer ring (not within 180 of where that begins, which a ring round a pole is wider than).
258
+ const inside = (x) => {
259
+ const n = Math.ceil((west - x) / 360);
260
+ if (n !== 0) moved = true;
261
+ return x + 360 * n;
262
+ };
263
+ return [outer, ...rings.slice(1).map((r) => run(r, inside(r[0][0]), true))];
264
+ };
265
+ let result = g;
266
+ if (first) {
267
+ const parts = partsOf(g).map(part);
268
+ if (moved) {
269
+ switch (g.type) {
270
+ case "Point":
271
+ result = { ...g, coordinates: parts[0][0][0] };
272
+ break;
273
+ case "MultiPoint":
274
+ result = { ...g, coordinates: parts.map((p) => p[0][0]) };
275
+ break;
276
+ case "LineString":
277
+ result = { ...g, coordinates: parts[0][0] };
278
+ break;
279
+ case "MultiLineString":
280
+ result = { ...g, coordinates: parts.map((p) => p[0]) };
281
+ break;
282
+ case "Polygon":
283
+ result = { ...g, coordinates: parts[0] };
284
+ break;
285
+ default:
286
+ result = { ...g, coordinates: parts };
287
+ }
288
+ }
289
+ }
290
+ unwrapped.set(g, result);
291
+ return result;
292
+ }
293
+
294
+ /** [minLon, minLat, maxLon, maxLat] of a geometry with continuous longitudes (the max may pass 180). */
295
+ function extentU(g) {
296
+ let x0 = Infinity;
297
+ let y0 = Infinity;
298
+ let x1 = -Infinity;
299
+ let y1 = -Infinity;
300
+ for (const p of positions(unwrap(g))) {
301
+ if (p[0] < x0) x0 = p[0];
302
+ if (p[0] > x1) x1 = p[0];
303
+ if (p[1] < y0) y0 = p[1];
304
+ if (p[1] > y1) y1 = p[1];
305
+ }
306
+ return [x0, y0, x1, y1];
307
+ }
308
+
309
+ /** The smallest box holding two continuous boxes (longitudes are a circle: one may sit 360 away). */
310
+ function unionU(a, b) {
311
+ let best;
312
+ for (const k of [-360, 0, 360]) {
313
+ const lo = Math.min(a[0], b[0] + k);
314
+ const hi = Math.max(a[2], b[2] + k);
315
+ if (!best || hi - lo < best[1] - best[0]) best = [lo, hi];
316
+ }
317
+ return [best[0], Math.min(a[1], b[1]), best[1], Math.max(a[3], b[3])];
318
+ }
319
+
320
+ /** Is `x` in the continuous longitude range of a box (also its value 360 away, so -180 meets 180)? */
321
+ const lonIn = (box, x) => (x >= box[0] && x <= box[2]) || (x + 360 >= box[0] && x + 360 <= box[2]) || (x - 360 >= box[0] && x - 360 <= box[2]);
322
+ const inBoxU = (box, p) => p[1] >= box[1] && p[1] <= box[3] && lonIn(box, p[0]);
323
+
324
+ /** [west, south, east, north] as GeoJSON writes a bbox (RFC 7946 section 5.2): across the antimeridian west > east; all of the globe's width is -180..180. */
325
+ function bboxOf(u) {
326
+ if (u[2] - u[0] >= 360) return [-180, u[1], 180, u[3]];
327
+ return [wrapLon(u[0]), u[1], wrapLon(u[2]), u[3]];
328
+ }
329
+ const extentOf = (g) => bboxOf(extentU(g));
330
+
331
+ function haversine(a, b) {
332
+ const dLat = (b[1] - a[1]) * RAD;
333
+ const dLon = (b[0] - a[0]) * RAD;
334
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(a[1] * RAD) * Math.cos(b[1] * RAD) * Math.sin(dLon / 2) ** 2;
335
+ return 2 * EARTH_RADIUS_M * Math.asin(Math.min(1, Math.sqrt(h)));
336
+ }
337
+
338
+ function lengthOf(g) {
339
+ let total = 0;
340
+ for (const l of linesOf(g)) for (let i = 1; i < l.length; i++) total += haversine(l[i - 1], l[i]);
341
+ return total;
342
+ }
343
+
344
+ /**
345
+ * Area of a ring in square metres on the sphere (absolute value). A ring that goes round a pole bounds two regions
346
+ * and the winding says which: the one on its left (RFC 7946), or for a hole (`hole`) the one on its right.
347
+ */
348
+ function ringArea(ring, hole = false) {
349
+ let sum = 0;
350
+ let turn = 0;
351
+ for (let i = 1; i < ring.length; i++) {
352
+ const d = shortWay(ring[i][0] - ring[i - 1][0]);
353
+ turn += d;
354
+ sum += d * RAD * (2 + Math.sin(ring[i - 1][1] * RAD) + Math.sin(ring[i][1] * RAD));
355
+ }
356
+ const signed = (sum * EARTH_RADIUS_M * EARTH_RADIUS_M) / 2;
357
+ if (Math.round(turn / 360) === 0) return Math.abs(signed);
358
+ const globe = 4 * Math.PI * EARTH_RADIUS_M * EARTH_RADIUS_M;
359
+ const left = (((hole ? signed : -signed) % globe) + globe) % globe;
360
+ return left;
361
+ }
362
+
363
+ function areaOf(g) {
364
+ let total = 0;
365
+ for (const p of polygonsOf(g)) p.forEach((r, i) => (total += i === 0 ? ringArea(r) : -ringArea(r, true)));
366
+ return Math.max(0, total);
367
+ }
368
+
369
+ /** Planar shoelace area and centroid sum of a ring in degrees. */
370
+ function ringPlanar(ring) {
371
+ let a = 0;
372
+ let cx = 0;
373
+ let cy = 0;
374
+ for (let i = 1; i < ring.length; i++) {
375
+ const [x0, y0] = ring[i - 1];
376
+ const [x1, y1] = ring[i];
377
+ const f = x0 * y1 - x1 * y0;
378
+ a += f;
379
+ cx += (x0 + x1) * f;
380
+ cy += (y0 + y1) * f;
381
+ }
382
+ return { a: a / 2, cx, cy };
383
+ }
384
+
385
+ /** The centroid, planar in degrees on the unwrapped geometry, as a longitude in -180..180. */
386
+ function centroidOf(g) {
387
+ const [x, y] = centroidU(unwrap(g));
388
+ return [wrapLon(x), y];
389
+ }
390
+
391
+ function centroidU(g) {
392
+ const mean = (ps) => {
393
+ let x = 0;
394
+ let y = 0;
395
+ for (const p of ps) (x += p[0]), (y += p[1]);
396
+ return [x / ps.length, y / ps.length];
397
+ };
398
+ if (g.type === "Point") return [g.coordinates[0], g.coordinates[1]];
399
+ if (g.type === "MultiPoint") return mean(g.coordinates);
400
+ if (g.type === "LineString" || g.type === "MultiLineString") {
401
+ let w = 0;
402
+ let x = 0;
403
+ let y = 0;
404
+ for (const l of linesOf(g)) {
405
+ for (let i = 1; i < l.length; i++) {
406
+ const d = Math.hypot(l[i][0] - l[i - 1][0], l[i][1] - l[i - 1][1]);
407
+ w += d;
408
+ x += ((l[i][0] + l[i - 1][0]) / 2) * d;
409
+ y += ((l[i][1] + l[i - 1][1]) / 2) * d;
410
+ }
411
+ }
412
+ return w > 0 ? [x / w, y / w] : mean([...positions(g)]);
413
+ }
414
+ let area = 0;
415
+ let x = 0;
416
+ let y = 0;
417
+ for (const poly of polygonsOf(g)) {
418
+ poly.forEach((r, i) => {
419
+ const s = ringPlanar(r);
420
+ if (s.a === 0) return;
421
+ const w = Math.abs(s.a) * (i === 0 ? 1 : -1); // a hole takes its area away, whichever way it winds
422
+ area += w;
423
+ x += (s.cx / (6 * s.a)) * w;
424
+ y += (s.cy / (6 * s.a)) * w;
425
+ });
426
+ }
427
+ return area > 0 ? [x / area, y / area] : mean([...positions(g)]);
428
+ }
429
+
430
+ /** 0 outside, 1 on the boundary, 2 inside (ray casting in degrees). */
431
+ function locate(ring, p) {
432
+ const [px, py] = p;
433
+ let inside = false;
434
+ for (let i = 1; i < ring.length; i++) {
435
+ const [x0, y0] = ring[i - 1];
436
+ const [x1, y1] = ring[i];
437
+ const cross = (x1 - x0) * (py - y0) - (y1 - y0) * (px - x0);
438
+ if (cross === 0 && px >= Math.min(x0, x1) && px <= Math.max(x0, x1) && py >= Math.min(y0, y1) && py <= Math.max(y0, y1)) return 1;
439
+ if (y0 > py !== y1 > py && px < ((x1 - x0) * (py - y0)) / (y1 - y0) + x0) inside = !inside;
440
+ }
441
+ return inside ? 2 : 0;
442
+ }
443
+
444
+ /** Is a point in a polygon (rings: outer first, then holes)? The boundary of either counts as inside. */
445
+ function inPolygon(poly, p) {
446
+ const o = locate(poly[0], p);
447
+ if (o === 0) return false;
448
+ if (o === 1) return true;
449
+ for (let i = 1; i < poly.length; i++) {
450
+ const h = locate(poly[i], p);
451
+ if (h === 2) return false;
452
+ if (h === 1) return true;
453
+ }
454
+ return true;
455
+ }
456
+
457
+ /** Is the point inside a polygon of `g`? The polygons have continuous longitudes, and the point is moved by a multiple of 360 to lie beside each (-179 is inside 179..181). */
458
+ const inGeometry = (g, p) =>
459
+ polygonsOf(unwrap(g)).some((poly) => {
460
+ let west = Infinity;
461
+ let east = -Infinity;
462
+ for (const q of poly[0]) {
463
+ if (q[0] < west) west = q[0];
464
+ if (q[0] > east) east = q[0];
465
+ }
466
+ const turns = Math.floor((p[0] - west) / 360);
467
+ // The point as a longitude beside the polygon (and again 360 east, for a shape that is wider than the globe's width).
468
+ for (let x = p[0] - 360 * turns; x <= east; x += 360) if (inPolygon(poly, x === p[0] ? p : [x, p[1]])) return true;
469
+ return false;
470
+ });
471
+
472
+ /**
473
+ * The geodesic circle of `meters` around a point, counter-clockwise, `steps` vertices, as a list of closed rings.
474
+ * Usually one. A circle across the antimeridian is cut at +/-180 into two (an east and a west part, as RFC 7946
475
+ * writes it); one that goes round a pole is one ring whose longitude runs the whole way round (the polygon maths
476
+ * reads it as the cap, see `unwrap`).
477
+ */
478
+ function circle(center, meters, steps) {
479
+ const [lon, lat] = center;
480
+ const d = meters / EARTH_RADIUS_M;
481
+ const round7 = (v) => Math.round(v * 1e7) / 1e7;
482
+ const raw = [];
483
+ const atPole = Math.abs(lat) >= 90 - 1e-9;
484
+ for (let i = 0; i < steps; i++) {
485
+ const brg = (-2 * Math.PI * i) / steps;
486
+ let lat2;
487
+ let lon2;
488
+ if (atPole) {
489
+ // Every direction from a pole is the same way; the longitude is the bearing (the circle goes east round the north pole, west round the south).
490
+ lat2 = Math.sign(lat) * (Math.PI / 2 - d);
491
+ lon2 = lon * RAD + (lat > 0 ? -brg : brg);
492
+ } else {
493
+ lat2 = Math.asin(Math.sin(lat * RAD) * Math.cos(d) + Math.cos(lat * RAD) * Math.sin(d) * Math.cos(brg));
494
+ lon2 = lon * RAD + Math.atan2(Math.sin(brg) * Math.sin(d) * Math.cos(lat * RAD), Math.cos(d) - Math.sin(lat * RAD) * Math.sin(lat2));
495
+ }
496
+ raw.push([wrapLon(lon2 / RAD), lat2 / RAD]);
497
+ }
498
+ // Longitudes made continuous round the ring: its total turn says whether it goes round a pole.
499
+ const cont = [];
500
+ let prev = raw[0][0];
501
+ let turn = 0;
502
+ for (const [x] of raw) {
503
+ const nx = cont.length ? prev + shortWay(x - prev) : x;
504
+ cont.push(nx);
505
+ prev = nx;
506
+ }
507
+ turn = cont.at(-1) + shortWay(raw[0][0] - cont.at(-1)) - cont[0];
508
+ if (Math.round(turn / 360) !== 0) {
509
+ const ring = raw.map(([x, y]) => [round7(x), round7(y)]);
510
+ ring.push(ring[0]);
511
+ return [ring];
512
+ }
513
+ const pts = cont.map((x, i) => [round7(x), round7(raw[i][1])]);
514
+ const hi = Math.max(...pts.map((p) => p[0]));
515
+ const lo = Math.min(...pts.map((p) => p[0]));
516
+ // Cut at the antimeridian the circle is across (a vertex exactly on it doesn't cross it).
517
+ const cut = hi > 180 ? 180 : lo < -180 ? -180 : null;
518
+ const close = (r) => [...r, r[0]];
519
+ if (cut === null) return [close(pts)];
520
+ // Sutherland-Hodgman against the meridian: a circle is convex along both axes, so each side is one piece.
521
+ const side = (keep) => {
522
+ const out = [];
523
+ for (let i = 0; i < pts.length; i++) {
524
+ const a = pts[(i + pts.length - 1) % pts.length];
525
+ const b = pts[i];
526
+ const ina = keep(a[0]);
527
+ const inb = keep(b[0]);
528
+ if (ina !== inb) out.push([cut, round7(a[1] + ((cut - a[0]) * (b[1] - a[1])) / (b[0] - a[0]))]);
529
+ if (inb) out.push(b);
530
+ }
531
+ return out;
532
+ };
533
+ const shift = cut > 0 ? -360 : 360; // the part past the cut, moved to the other side of the map
534
+ const inner = side(cut > 0 ? (x) => x <= cut : (x) => x >= cut);
535
+ const outer = side(cut > 0 ? (x) => x >= cut : (x) => x <= cut).map(([x, y]) => [x === cut ? x + shift : round7(x + shift), y]);
536
+ return [close(inner), close(outer)];
537
+ }
538
+
539
+ /** Smallest distance in metres between two sets of points. */
540
+ function pointDistance(a, b) {
541
+ let best = Infinity;
542
+ for (const p of a) for (const q of b) best = Math.min(best, haversine(p, q));
543
+ return best;
544
+ }
545
+
546
+ const unsupported = (what, g, fix) => problem("unsupported-geometry", `${what} is not defined for a ${g.type}${fix ? `: ${fix}` : ""}`);
547
+
548
+ // ── the pure helpers ─────────────────────────────────────────────────────
549
+
550
+ function use(cell) {
551
+ const r = geometryOf(cell);
552
+ if (r.problem) throw new TableError(r.problem.code, `geo: ${r.problem.reason}`);
553
+ return r.g;
554
+ }
555
+ const area = (cell) => {
556
+ const g = use(cell);
557
+ if (!polygonsOf(g).length) throw new TableError("unsupported-geometry", `geo: ${unsupported("area", g, "use a Polygon or MultiPolygon").reason}`);
558
+ return areaOf(g);
559
+ };
560
+ const length = (cell) => {
561
+ const g = use(cell);
562
+ if (!linesOf(g).length) throw new TableError("unsupported-geometry", `geo: ${unsupported("length", g, "use a LineString or MultiLineString").reason}`);
563
+ return lengthOf(g);
564
+ };
565
+ const distance = (a, b) => {
566
+ const ga = use(a);
567
+ const gb = use(b);
568
+ const pa = pointsOf(ga);
569
+ const pb = pointsOf(gb);
570
+ if (!pa.length || !pb.length) throw new TableError("unsupported-geometry", `geo: distance is defined between points (Point, MultiPoint), not ${!pa.length ? ga.type : gb.type}; take its centroid first (geoMeasure with measures: ["centroid"], or ST_CENTROID in SQL)`);
571
+ return pointDistance(pa, pb);
572
+ };
573
+ const contains = (region, cell) => {
574
+ const gr = use(region);
575
+ const g = use(cell);
576
+ if (!polygonsOf(gr).length) throw new TableError("unsupported-geometry", `geo: a region is a Polygon or MultiPolygon, not a ${gr.type}`);
577
+ const pts = pointsOf(g);
578
+ if (!pts.length) throw new TableError("unsupported-geometry", `geo: only points can be tested against a region, not a ${g.type}; take its centroid first`);
579
+ return pts.every((p) => inGeometry(gr, p));
580
+ };
581
+ // ── buffers of lines and polygons ────────────────────────────────────────
582
+
583
+ const MAX_BUFFER_SEGMENTS = 20_000;
584
+
585
+ /** The point `d` radians along an initial bearing `brg` (radians clockwise from north) from `p`, as [longitude, latitude] degrees. */
586
+ function destination(p, brg, d) {
587
+ const lat1 = p[1] * RAD;
588
+ const lat2 = Math.asin(Math.sin(lat1) * Math.cos(d) + Math.cos(lat1) * Math.sin(d) * Math.cos(brg));
589
+ const lon2 = p[0] * RAD + Math.atan2(Math.sin(brg) * Math.sin(d) * Math.cos(lat1), Math.cos(d) - Math.sin(lat1) * Math.sin(lat2));
590
+ return [wrapLon(((lon2 / RAD + 540) % 360) - 180), lat2 / RAD];
591
+ }
592
+
593
+ /** Initial great-circle bearing from `a` to `b`, in radians clockwise from north. */
594
+ function bearing(a, b) {
595
+ const f1 = a[1] * RAD;
596
+ const f2 = b[1] * RAD;
597
+ const dl = shortWay(b[0] - a[0]) * RAD;
598
+ return Math.atan2(Math.sin(dl) * Math.cos(f2), Math.cos(f1) * Math.sin(f2) - Math.sin(f1) * Math.cos(f2) * Math.cos(dl));
599
+ }
600
+
601
+ /**
602
+ * The stadium round a segment: a ring (counter-clockwise, closed) of every point within `d` radians of it, with `half` steps in each end cap.
603
+ * Its longitudes continue from the segment's own (they may pass +/-180); a segment of no length is a circle.
604
+ */
605
+ function capsule(a, b, d, half) {
606
+ const same = a[0] === b[0] && a[1] === b[1];
607
+ const t1 = same ? 0 : bearing(a, b);
608
+ const t2 = same ? 0 : bearing(b, a) + Math.PI;
609
+ const round7 = (v) => Math.round(v * 1e7) / 1e7;
610
+ const ring = [];
611
+ const cap = (c, from) => {
612
+ for (let i = 0; i <= half; i++) {
613
+ const q = destination(c, from - (Math.PI * i) / half, d);
614
+ ring.push([c[0] + shortWay(q[0] - c[0]), q[1]]);
615
+ }
616
+ };
617
+ cap(b, t2 + Math.PI / 2);
618
+ cap(a, t1 - Math.PI / 2);
619
+ const out = ring.map(([x, y]) => [round7(x), round7(y)]);
620
+ out.push(out[0]);
621
+ return out;
622
+ }
623
+
624
+ // ── dissolving polygons ──────────────────────────────────────────────────
625
+ //
626
+ // The union of polygons in the plane of longitude and latitude (what the rest of this file's polygon maths uses), as
627
+ // non-overlapping polygons. An arrangement, not a clipper: every ring is cut at every place it meets another (positions
628
+ // snapped to 1e-9 degrees, about a tenth of a millimetre), each piece is kept when the union lies on exactly one side of
629
+ // it, and the kept pieces are joined into rings. Shared and overlapping edges are counted, not special cases.
630
+
631
+ const SNAP = 1e9;
632
+ const SNAP_TOL = 2e-9;
633
+
634
+ const planarSigned = (ring) => {
635
+ let s = 0;
636
+ for (let i = 1; i < ring.length; i++) s += ring[i - 1][0] * ring[i][1] - ring[i][0] * ring[i - 1][1];
637
+ return s / 2;
638
+ };
639
+
640
+ /** A polygon's rings with the outer one counter-clockwise and the holes clockwise: the inside is on the left of every edge. */
641
+ const wound = (rings) =>
642
+ rings.map((r, i) => {
643
+ const a = planarSigned(r);
644
+ return (i === 0) === a < 0 ? r.slice().reverse() : r;
645
+ });
646
+
647
+ /** A point-in-rings test (outer ring and holes) by ray casting; a long ring is cut into bands of latitude first, so a query meets only some of its edges. */
648
+ function locatorOf(rings) {
649
+ const parts = rings.map((ring) => {
650
+ const n = ring.length - 1;
651
+ const xs = new Float64Array(n + 1);
652
+ const ys = new Float64Array(n + 1);
653
+ let y0 = Infinity;
654
+ let y1 = -Infinity;
655
+ for (let i = 0; i <= n; i++) {
656
+ xs[i] = ring[i][0];
657
+ ys[i] = ring[i][1];
658
+ if (ys[i] < y0) y0 = ys[i];
659
+ if (ys[i] > y1) y1 = ys[i];
660
+ }
661
+ let bins = null;
662
+ let h = 0;
663
+ if (n > 48 && y1 > y0) {
664
+ const count = Math.min(2048, Math.ceil(Math.sqrt(n) * 2));
665
+ h = (y1 - y0) / count;
666
+ bins = Array.from({ length: count }, () => []);
667
+ for (let i = 0; i < n; i++) {
668
+ const lo = Math.min(count - 1, Math.floor((Math.min(ys[i], ys[i + 1]) - y0) / h));
669
+ const hi = Math.min(count - 1, Math.floor((Math.max(ys[i], ys[i + 1]) - y0) / h));
670
+ for (let b = lo; b <= hi; b++) bins[b].push(i);
671
+ }
672
+ }
673
+ return { n, xs, ys, y0, y1, bins, h };
674
+ });
675
+ const inRing = (r, px, py) => {
676
+ if (py < r.y0 || py > r.y1) return false;
677
+ let inside = false;
678
+ const test = (i) => {
679
+ const ya = r.ys[i];
680
+ const yb = r.ys[i + 1];
681
+ if (ya > py !== yb > py && px < ((r.xs[i + 1] - r.xs[i]) * (py - ya)) / (yb - ya) + r.xs[i]) inside = !inside;
682
+ };
683
+ if (r.bins) for (const i of r.bins[Math.min(r.bins.length - 1, Math.floor((py - r.y0) / r.h))]) test(i);
684
+ else for (let i = 0; i < r.n; i++) test(i);
685
+ return inside;
686
+ };
687
+ return (px, py) => {
688
+ if (!inRing(parts[0], px, py)) return false;
689
+ for (let i = 1; i < parts.length; i++) if (inRing(parts[i], px, py)) return false;
690
+ return true;
691
+ };
692
+ }
693
+
694
+ /**
695
+ * The edges that lie inside the interior of a convex polygon (from `convexFrom` on, the stadiums) of the union: both ends are
696
+ * strictly inside the same one, so the edge cannot be part of the union's outline and needs no cutting. For a line with many
697
+ * short segments that is most of the edges. Returns a Map from ring to a flag per vertex index (the edge ending there).
698
+ */
699
+ function coveredEdges(polys, convexFrom) {
700
+ const dropped = new Map();
701
+ const convex = [];
702
+ for (let p = convexFrom; p < polys.length; p++) {
703
+ const ring = polys[p].rings[0];
704
+ let x0 = Infinity;
705
+ let y0 = Infinity;
706
+ let x1 = -Infinity;
707
+ let y1 = -Infinity;
708
+ for (const [x, y] of ring) {
709
+ if (x < x0) x0 = x;
710
+ if (x > x1) x1 = x;
711
+ if (y < y0) y0 = y;
712
+ if (y > y1) y1 = y;
713
+ }
714
+ const lens = ring.slice(1).map((q, i) => Math.hypot(q[0] - ring[i][0], q[1] - ring[i][1]));
715
+ convex.push({ p, ring, lens, box: [x0, y0, x1, y1] });
716
+ }
717
+ if (convex.length < 2) return dropped;
718
+ let size = 0;
719
+ for (const c of convex) size += Math.max(c.box[2] - c.box[0], c.box[3] - c.box[1]);
720
+ const cell = Math.max((size / convex.length) * 1.5, 1e-6);
721
+ const gx0 = Math.min(...convex.map((c) => c.box[0]));
722
+ const gy0 = Math.min(...convex.map((c) => c.box[1]));
723
+ const grid = new Map();
724
+ const key = (x, y) => Math.floor((x - gx0) / cell) * 1048576 + Math.floor((y - gy0) / cell);
725
+ for (const c of convex) {
726
+ for (let i = Math.floor((c.box[0] - gx0) / cell); i <= Math.floor((c.box[2] - gx0) / cell); i++) {
727
+ for (let j = Math.floor((c.box[1] - gy0) / cell); j <= Math.floor((c.box[3] - gy0) / cell); j++) {
728
+ const list = grid.get(i * 1048576 + j);
729
+ if (list) list.push(c);
730
+ else grid.set(i * 1048576 + j, [c]);
731
+ }
732
+ }
733
+ }
734
+ // Strictly inside a convex counter-clockwise ring: left of every edge by more than a hair (1e-8 degrees, a centimetre).
735
+ const strictlyIn = (c, x, y) => {
736
+ if (x < c.box[0] || x > c.box[2] || y < c.box[1] || y > c.box[3]) return false;
737
+ const r = c.ring;
738
+ for (let i = 1; i < r.length; i++) if ((r[i][0] - r[i - 1][0]) * (y - r[i - 1][1]) - (r[i][1] - r[i - 1][1]) * (x - r[i - 1][0]) <= 1e-8 * c.lens[i - 1]) return false;
739
+ return true;
740
+ };
741
+ for (let p = 0; p < polys.length; p++) {
742
+ for (const ring of polys[p].rings) {
743
+ for (let i = 1; i < ring.length; i++) {
744
+ const [ax, ay] = ring[i - 1];
745
+ const [bx, by] = ring[i];
746
+ for (const c of grid.get(key(ax, ay)) ?? []) {
747
+ if (c.p === p || !strictlyIn(c, ax, ay) || !strictlyIn(c, bx, by)) continue;
748
+ let flags = dropped.get(ring);
749
+ if (!flags) dropped.set(ring, (flags = []));
750
+ flags[i] = true;
751
+ break;
752
+ }
753
+ }
754
+ }
755
+ }
756
+ return dropped;
757
+ }
758
+
759
+ /**
760
+ * The union of `input` (a list of polygons, each a list of rings with continuous longitudes) as a list of polygons,
761
+ * and with `clip` only the part of it between -180 and 180 degrees of longitude. Throws `error` when the pieces
762
+ * do not join into closed rings (a geometry too tangled to dissolve).
763
+ */
764
+ function dissolve(input, clip, convexFrom = Infinity, tol = SNAP_TOL) {
765
+ const polys = input.map((rings) => ({ layer: 0, rings: wound(rings) }));
766
+ const dropped = coveredEdges(polys, convexFrom);
767
+ if (clip) polys.push({ layer: 1, rings: [[[-180, -90], [180, -90], [180, 90], [-180, 90], [-180, -90]]] });
768
+ // Positions within `tol` degrees of each other are one vertex (the first one seen, to the nearest 1e-9).
769
+ const ids = new Map();
770
+ const vx = [];
771
+ const vy = [];
772
+ const hash = (i, j) => (i & 0x3ffffff) * 67108864 + (j & 0x3ffffff);
773
+ const vertex = (x, y) => {
774
+ const i = Math.floor(x / tol);
775
+ const j = Math.floor(y / tol);
776
+ for (let di = -1; di <= 1; di++) {
777
+ for (let dj = -1; dj <= 1; dj++) {
778
+ const list = ids.get(hash(i + di, j + dj));
779
+ if (list) for (const id of list) if (Math.abs(vx[id] - x) <= tol && Math.abs(vy[id] - y) <= tol) return id;
780
+ }
781
+ }
782
+ const id = vx.length;
783
+ vx.push(Math.round(x * SNAP) / SNAP);
784
+ vy.push(Math.round(y * SNAP) / SNAP);
785
+ const key = hash(i, j);
786
+ const list = ids.get(key);
787
+ if (list) list.push(id);
788
+ else ids.set(key, [id]);
789
+ return id;
790
+ };
791
+ const ea = [];
792
+ const eb = [];
793
+ const ep = [];
794
+ for (let p = 0; p < polys.length; p++) {
795
+ for (const ring of polys[p].rings) {
796
+ let prev = vertex(ring[0][0], ring[0][1]);
797
+ for (let i = 1; i < ring.length; i++) {
798
+ const cur = vertex(ring[i][0], ring[i][1]);
799
+ if (cur !== prev && !dropped.get(ring)?.[i]) {
800
+ ea.push(prev);
801
+ eb.push(cur);
802
+ ep.push(p);
803
+ }
804
+ prev = cur;
805
+ }
806
+ }
807
+ }
808
+ const n = ea.length;
809
+ // A uniform grid over the polygons (not the clip), for finding the edges near an edge.
810
+ let gx0 = Infinity;
811
+ let gy0 = Infinity;
812
+ let gx1 = -Infinity;
813
+ let gy1 = -Infinity;
814
+ let total = 0;
815
+ let counted = 0;
816
+ for (let e = 0; e < n; e++) {
817
+ if (polys[ep[e]].layer !== 0) continue;
818
+ for (const v of [ea[e], eb[e]]) {
819
+ if (vx[v] < gx0) gx0 = vx[v];
820
+ if (vx[v] > gx1) gx1 = vx[v];
821
+ if (vy[v] < gy0) gy0 = vy[v];
822
+ if (vy[v] > gy1) gy1 = vy[v];
823
+ }
824
+ total += Math.hypot(vx[ea[e]] - vx[eb[e]], vy[ea[e]] - vy[eb[e]]);
825
+ counted++;
826
+ }
827
+ if (!counted) return [];
828
+ const cell = Math.max((total / counted) * 2, (Math.max(gx1 - gx0, gy1 - gy0) || 1) / 700, 1e-6);
829
+ const nx = Math.floor((gx1 - gx0) / cell) + 1;
830
+ const ny = Math.floor((gy1 - gy0) / cell) + 1;
831
+ const cx = (x) => Math.max(0, Math.min(nx - 1, Math.floor((x - gx0) / cell)));
832
+ const cy = (y) => Math.max(0, Math.min(ny - 1, Math.floor((y - gy0) / cell)));
833
+ const grid = new Map();
834
+ for (let e = 0; e < n; e++) {
835
+ const x0 = cx(Math.min(vx[ea[e]], vx[eb[e]]));
836
+ const x1 = cx(Math.max(vx[ea[e]], vx[eb[e]]));
837
+ const y0 = cy(Math.min(vy[ea[e]], vy[eb[e]]));
838
+ const y1 = cy(Math.max(vy[ea[e]], vy[eb[e]]));
839
+ for (let i = x0; i <= x1; i++) {
840
+ for (let j = y0; j <= y1; j++) {
841
+ const key = i * ny + j;
842
+ const list = grid.get(key);
843
+ if (list) list.push(e);
844
+ else grid.set(key, [e]);
845
+ }
846
+ }
847
+ }
848
+
849
+ // Cut every edge where it meets another.
850
+ const splits = new Array(n);
851
+ const addSplit = (e, t, v) => (splits[e] ??= []).push([t, v]);
852
+ /** The parameter along edge `e` of vertex `p` when p lies on the edge's inside (within tol), else -1. */
853
+ const along = (e, p) => {
854
+ const ax = vx[ea[e]];
855
+ const ay = vy[ea[e]];
856
+ const dx = vx[eb[e]] - ax;
857
+ const dy = vy[eb[e]] - ay;
858
+ const len2 = dx * dx + dy * dy;
859
+ const px = vx[p] - ax;
860
+ const py = vy[p] - ay;
861
+ const t = (px * dx + py * dy) / len2;
862
+ if (t <= 0 || t >= 1) return -1;
863
+ const off = px * dy - py * dx;
864
+ return off * off > tol * tol * len2 ? -1 : t;
865
+ };
866
+ const stamp = new Int32Array(n).fill(-1);
867
+ const side = (ax, ay, bx, by, px, py) => (bx - ax) * (py - ay) - (by - ay) * (px - ax);
868
+ for (let i = 0; i < n; i++) {
869
+ const a = ea[i];
870
+ const b = eb[i];
871
+ const ix0 = Math.min(vx[a], vx[b]);
872
+ const ix1 = Math.max(vx[a], vx[b]);
873
+ const iy0 = Math.min(vy[a], vy[b]);
874
+ const iy1 = Math.max(vy[a], vy[b]);
875
+ for (let gi = cx(ix0); gi <= cx(ix1); gi++) {
876
+ for (let gj = cy(iy0); gj <= cy(iy1); gj++) {
877
+ const list = grid.get(gi * ny + gj);
878
+ if (!list) continue;
879
+ for (const j of list) {
880
+ if (j <= i || stamp[j] === i) continue;
881
+ stamp[j] = i;
882
+ const c = ea[j];
883
+ const d = eb[j];
884
+ if (Math.max(vx[c], vx[d]) < ix0 - tol || Math.min(vx[c], vx[d]) > ix1 + tol || Math.max(vy[c], vy[d]) < iy0 - tol || Math.min(vy[c], vy[d]) > iy1 + tol) continue;
885
+ let touched = false;
886
+ for (const p of [c, d]) {
887
+ if (p === a || p === b) continue;
888
+ const t = along(i, p);
889
+ if (t >= 0) {
890
+ addSplit(i, t, p);
891
+ touched = true;
892
+ }
893
+ }
894
+ for (const p of [a, b]) {
895
+ if (p === c || p === d) continue;
896
+ const t = along(j, p);
897
+ if (t >= 0) {
898
+ addSplit(j, t, p);
899
+ touched = true;
900
+ }
901
+ }
902
+ if (touched || a === c || a === d || b === c || b === d) continue;
903
+ const o1 = side(vx[a], vy[a], vx[b], vy[b], vx[c], vy[c]);
904
+ const o2 = side(vx[a], vy[a], vx[b], vy[b], vx[d], vy[d]);
905
+ const o3 = side(vx[c], vy[c], vx[d], vy[d], vx[a], vy[a]);
906
+ const o4 = side(vx[c], vy[c], vx[d], vy[d], vx[b], vy[b]);
907
+ if (((o1 > 0 && o2 < 0) || (o1 < 0 && o2 > 0)) && ((o3 > 0 && o4 < 0) || (o3 < 0 && o4 > 0))) {
908
+ const s = o3 / (o3 - o4);
909
+ const v = vertex(vx[a] + s * (vx[b] - vx[a]), vy[a] + s * (vy[b] - vy[a]));
910
+ addSplit(i, s, v);
911
+ addSplit(j, o1 / (o1 - o2), v);
912
+ }
913
+ }
914
+ }
915
+ }
916
+ }
917
+
918
+ // The pieces: each undirected piece once, with the polygons that have it and the way they run along it.
919
+ const BASE = 67108864;
920
+ const pieceAt = new Map();
921
+ const pu = [];
922
+ const pv = [];
923
+ const pown = [];
924
+ for (let e = 0; e < n; e++) {
925
+ const chain = [ea[e]];
926
+ const list = splits[e];
927
+ if (list) {
928
+ list.sort((p, q) => p[0] - q[0]);
929
+ for (const [, v] of list) if (v !== chain[chain.length - 1] && v !== eb[e]) chain.push(v);
930
+ }
931
+ chain.push(eb[e]);
932
+ for (let k = 1; k < chain.length; k++) {
933
+ const u = chain[k - 1];
934
+ const v = chain[k];
935
+ if (u === v) continue;
936
+ const lo = Math.min(u, v);
937
+ const hi = Math.max(u, v);
938
+ const key = lo * BASE + hi;
939
+ let id = pieceAt.get(key);
940
+ if (id === undefined) {
941
+ id = pu.length;
942
+ pieceAt.set(key, id);
943
+ pu.push(lo);
944
+ pv.push(hi);
945
+ pown.push([]);
946
+ }
947
+ pown[id].push(ep[e] * 2 + (u === lo ? 0 : 1)); // 0: the polygon is on the left of lo -> hi
948
+ }
949
+ }
950
+
951
+ // Which polygons could contain a point: a grid of their boxes (the big ones are tried every time).
952
+ const boxes = polys.map((poly) => {
953
+ let x0 = Infinity;
954
+ let y0 = Infinity;
955
+ let x1 = -Infinity;
956
+ let y1 = -Infinity;
957
+ for (const [x, y] of poly.rings[0]) {
958
+ if (x < x0) x0 = x;
959
+ if (x > x1) x1 = x;
960
+ if (y < y0) y0 = y;
961
+ if (y > y1) y1 = y;
962
+ }
963
+ return [x0, y0, x1, y1];
964
+ });
965
+ const near = new Map();
966
+ const wide = [];
967
+ const locate = new Array(polys.length);
968
+ const sizes = boxes.map((b) => Math.max(b[2] - b[0], b[3] - b[1])).sort((p, q) => p - q);
969
+ const pcell = Math.max(sizes[sizes.length >> 1], 1e-6);
970
+ const px = (x) => Math.floor((x - gx0) / pcell);
971
+ const py = (y) => Math.floor((y - gy0) / pcell);
972
+ for (let p = 0; p < polys.length; p++) {
973
+ const [x0, y0, x1, y1] = boxes[p];
974
+ const i0 = px(x0);
975
+ const i1 = px(x1);
976
+ const j0 = py(y0);
977
+ const j1 = py(y1);
978
+ if ((i1 - i0 + 1) * (j1 - j0 + 1) > 36) {
979
+ wide.push(p);
980
+ continue;
981
+ }
982
+ for (let i = i0; i <= i1; i++) {
983
+ for (let j = j0; j <= j1; j++) {
984
+ const list = near.get(i * 1048576 + j);
985
+ if (list) list.push(p);
986
+ else near.set(i * 1048576 + j, [p]);
987
+ }
988
+ }
989
+ }
990
+ const contains = (p, x, y) => {
991
+ const [x0, y0, x1, y1] = boxes[p];
992
+ if (x < x0 || x > x1 || y < y0 || y > y1) return false;
993
+ return (locate[p] ??= locatorOf(polys[p].rings))(x, y);
994
+ };
995
+
996
+ // Keep the pieces with the union on one side only, directed to keep it on their left.
997
+ const bf = [];
998
+ const bt = [];
999
+ for (let id = 0; id < pu.length; id++) {
1000
+ const mx = (vx[pu[id]] + vx[pv[id]]) / 2;
1001
+ const my = (vy[pu[id]] + vy[pv[id]]) / 2;
1002
+ const left = [0, 0];
1003
+ const right = [0, 0];
1004
+ const own = pown[id];
1005
+ for (const code of own) (code & 1 ? right : left)[polys[code >> 1].layer]++;
1006
+ const seen = (p) => own.some((code) => code >> 1 === p);
1007
+ const mark = (p) => {
1008
+ if (seen(p) || !contains(p, mx, my)) return;
1009
+ left[polys[p].layer]++;
1010
+ right[polys[p].layer]++;
1011
+ };
1012
+ for (const p of near.get(px(mx) * 1048576 + py(my)) ?? []) mark(p);
1013
+ for (const p of wide) mark(p);
1014
+ const inL = left[0] > 0 && (!clip || left[1] > 0);
1015
+ const inR = right[0] > 0 && (!clip || right[1] > 0);
1016
+ if (inL === inR) continue;
1017
+ if (inL) {
1018
+ bf.push(pu[id]);
1019
+ bt.push(pv[id]);
1020
+ } else {
1021
+ bf.push(pv[id]);
1022
+ bt.push(pu[id]);
1023
+ }
1024
+ }
1025
+
1026
+ // Join them into rings. Where several leave a vertex, take the one that turns the least clockwise from the way back: that keeps touching
1027
+ // regions apart and a hole that touches its outline a ring of its own.
1028
+ const head = new Int32Array(vx.length).fill(-1);
1029
+ const next = new Int32Array(bf.length).fill(-1);
1030
+ for (let e = bf.length - 1; e >= 0; e--) {
1031
+ next[e] = head[bf[e]];
1032
+ head[bf[e]] = e;
1033
+ }
1034
+ const TAU = Math.PI * 2;
1035
+ const successor = (e) => {
1036
+ const v = bt[e];
1037
+ const back = Math.atan2(vy[bf[e]] - vy[v], vx[bf[e]] - vx[v]);
1038
+ let best = -1;
1039
+ let bestTurn = Infinity;
1040
+ for (let k = head[v]; k >= 0; k = next[k]) {
1041
+ let turn = (((back - Math.atan2(vy[bt[k]] - vy[v], vx[bt[k]] - vx[v])) % TAU) + TAU) % TAU;
1042
+ if (turn === 0) turn = TAU;
1043
+ if (turn < bestTurn) {
1044
+ bestTurn = turn;
1045
+ best = k;
1046
+ }
1047
+ }
1048
+ return best;
1049
+ };
1050
+ const used = new Uint8Array(bf.length);
1051
+ const outers = [];
1052
+ const holes = [];
1053
+ for (let start = 0; start < bf.length; start++) {
1054
+ if (used[start]) continue;
1055
+ const ring = [];
1056
+ let e = start;
1057
+ do {
1058
+ if (e < 0 || used[e]) throw new TableError("error", "geo: the buffer could not be dissolved into closed outlines: simplify the geometry first");
1059
+ used[e] = 1;
1060
+ ring.push([vx[bf[e]], vy[bf[e]]]);
1061
+ e = successor(e);
1062
+ } while (e !== start);
1063
+ ring.push(ring[0]);
1064
+ const a = planarSigned(ring);
1065
+ if (a > 0) outers.push({ ring, a, locate: null });
1066
+ else if (a < 0) holes.push({ ring, a });
1067
+ }
1068
+ for (const o of outers) {
1069
+ let x0 = Infinity;
1070
+ let y0 = Infinity;
1071
+ let x1 = -Infinity;
1072
+ let y1 = -Infinity;
1073
+ for (const [x, y] of o.ring) {
1074
+ if (x < x0) x0 = x;
1075
+ if (x > x1) x1 = x;
1076
+ if (y < y0) y0 = y;
1077
+ if (y > y1) y1 = y;
1078
+ }
1079
+ o.box = [x0, y0, x1, y1];
1080
+ }
1081
+ const result = outers.map((o) => [o.ring]);
1082
+ for (const h of holes) {
1083
+ // The middle of the hole's first edge is never on another ring (rings share no pieces), so the test is clear.
1084
+ const x = (h.ring[0][0] + h.ring[1][0]) / 2;
1085
+ const y = (h.ring[0][1] + h.ring[1][1]) / 2;
1086
+ let owner = -1;
1087
+ for (let i = 0; i < outers.length; i++) {
1088
+ const o = outers[i];
1089
+ if (x < o.box[0] || x > o.box[2] || y < o.box[1] || y > o.box[3] || (owner >= 0 && o.a >= outers[owner].a)) continue;
1090
+ if (!(o.locate ??= locatorOf([o.ring]))(x, y)) continue;
1091
+ owner = i;
1092
+ }
1093
+ if (owner < 0) throw new TableError("error", "geo: the buffer could not be dissolved into closed outlines: simplify the geometry first");
1094
+ result[owner].push(h.ring);
1095
+ }
1096
+ return result;
1097
+ }
1098
+
1099
+ const DISSOLVE_GROUP = 16;
1100
+
1101
+ /**
1102
+ * The union of many polygons, `group` at a time and then the results `group` at a time again: a line of thousands of short segments is
1103
+ * many stadiums that all overlap their neighbours, and cutting every one against every other is far dearer than a few at a time.
1104
+ * The first `convexFrom` polygons are any shape; the rest are the stadiums (convex).
1105
+ */
1106
+ function dissolveTree(parts, convexFrom, group = DISSOLVE_GROUP) {
1107
+ let level = parts;
1108
+ let convex = convexFrom;
1109
+ while (level.length > group) {
1110
+ const next = [];
1111
+ for (let i = 0; i < level.length; i += group) next.push(...dissolve(level.slice(i, i + group), false, Math.max(0, convex - i)));
1112
+ level = next;
1113
+ convex = Infinity;
1114
+ }
1115
+ return dissolveAcross(level, convex);
1116
+ }
1117
+
1118
+ /** The union of polygons whose longitudes may pass +/-180, as polygons between -180 and 180 (a part past the seam is moved to the other side of the map). */
1119
+ function dissolveAcross(parts, convexFrom) {
1120
+ let lo = Infinity;
1121
+ let hi = -Infinity;
1122
+ for (const poly of parts) for (const q of poly[0]) (q[0] < lo && (lo = q[0]), q[0] > hi && (hi = q[0]));
1123
+ if (lo >= -180 && hi <= 180) return dissolve(parts, false, convexFrom);
1124
+ const shifted = (k) => parts.map((poly) => poly.map((ring) => ring.map(([x, y]) => [x + k, y])));
1125
+ const out = dissolve(parts, true, convexFrom);
1126
+ if (hi > 180) out.push(...dissolve(shifted(-360), true, convexFrom));
1127
+ if (lo < -180) out.push(...dissolve(shifted(360), true, convexFrom));
1128
+ return out;
1129
+ }
1130
+
1131
+ /** Every segment of a line or ring list, as [from, to] position pairs. */
1132
+ function* segmentsIn(lists) {
1133
+ for (const l of lists) for (let i = 1; i < l.length; i++) yield [l[i - 1], l[i]];
1134
+ }
1135
+
1136
+ /**
1137
+ * The area within `meters` of a line or polygon, as a MultiPolygon. A line's buffer is a stadium round each segment; a polygon's is
1138
+ * the polygon with a stadium round each segment of its boundary. The stadiums are dissolved into the fewest outlines: the polygons that
1139
+ * come out do not overlap (so the area of the whole is the sum of its parts), and a hole is a hole. Across the antimeridian it is cut at
1140
+ * +/-180, an east and a west part.
1141
+ */
1142
+ function bufferShape(g, meters, steps) {
1143
+ const lists = g.type === "Polygon" ? g.coordinates : g.type === "MultiPolygon" ? g.coordinates.flat() : linesOf(g);
1144
+ const d = meters / EARTH_RADIUS_M;
1145
+ const segments = [...segmentsIn(lists)];
1146
+ if (segments.length > MAX_BUFFER_SEGMENTS) throw new TableError("limit", `geo: a buffer of ${segments.length} segments is over ${MAX_BUFFER_SEGMENTS}: simplify the geometry first`);
1147
+ const reach = d / RAD;
1148
+ for (const l of lists) for (const p of l) if (Math.abs(p[1]) + reach >= 89.9) throw new TableError("unsupported-geometry", "geo: a line or polygon buffer that reaches a pole is not supported: use a smaller radius or buffer a point there");
1149
+ // Longitudes made continuous, so a shape across +/-180 is one piece in the plane.
1150
+ const flat = unwrap(g);
1151
+ for (const poly of polygonsOf(flat)) for (const ring of poly) for (const p of ring) if (Math.abs(p[1]) >= 90) throw new TableError("unsupported-geometry", "geo: a polygon that goes round a pole cannot be buffered: buffer its boundary line, or split it at the antimeridian");
1152
+ const half = Math.max(2, Math.round(steps / 2));
1153
+ const parts = polygonsOf(flat).slice();
1154
+ const convexFrom = parts.length;
1155
+ const flatLists = flat.type === "Polygon" ? flat.coordinates : flat.type === "MultiPolygon" ? flat.coordinates.flat() : linesOf(flat);
1156
+ for (const [a, b] of segmentsIn(flatLists)) parts.push([capsule(a, b, d, half)]);
1157
+ return { type: "MultiPolygon", coordinates: dissolveTree(parts, convexFrom) };
1158
+ }
1159
+
1160
+ function buffer(cell, meters, steps = 32) {
1161
+ const g = use(cell);
1162
+ if (!(meters > 0) || !fin(meters) || meters > 5_000_000) throw new TableError("bad-option", `geo: buffer meters should be a number from 0 (exclusive) to 5,000,000, not ${show(meters)}`);
1163
+ if (!Number.isInteger(steps) || steps < 8 || steps > 360) throw new TableError("bad-option", `geo: buffer steps should be a whole number from 8 to 360, not ${show(steps)}`);
1164
+ const pts = pointsOf(g);
1165
+ if (!pts.length) return bufferShape(g, meters, steps);
1166
+ const polygons = pts.flatMap((p) => circle(p, meters, steps).map((r) => [r]));
1167
+ return g.type === "Point" && polygons.length === 1 ? { type: "Polygon", coordinates: polygons[0] } : { type: "MultiPolygon", coordinates: polygons };
1168
+ }
1169
+
1170
+ // ── geometry against geometry (planar in degrees, like the region tests) ──
1171
+
1172
+ const orient = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
1173
+ const onSegment = (a, b, p) => p[0] >= Math.min(a[0], b[0]) && p[0] <= Math.max(a[0], b[0]) && p[1] >= Math.min(a[1], b[1]) && p[1] <= Math.max(a[1], b[1]);
1174
+ /** Do two segments cross strictly (not merely touch)? */
1175
+ function properCross(a, b, c, d) {
1176
+ const o1 = orient(a, b, c);
1177
+ const o2 = orient(a, b, d);
1178
+ const o3 = orient(c, d, a);
1179
+ const o4 = orient(c, d, b);
1180
+ return ((o1 > 0 && o2 < 0) || (o1 < 0 && o2 > 0)) && ((o3 > 0 && o4 < 0) || (o3 < 0 && o4 > 0));
1181
+ }
1182
+ /** Do two segments share a point (touching counts)? */
1183
+ function segmentsMeet(a, b, c, d) {
1184
+ if (properCross(a, b, c, d)) return true;
1185
+ return (orient(a, b, c) === 0 && onSegment(a, b, c)) || (orient(a, b, d) === 0 && onSegment(a, b, d)) || (orient(c, d, a) === 0 && onSegment(c, d, a)) || (orient(c, d, b) === 0 && onSegment(c, d, b));
1186
+ }
1187
+
1188
+ /** The pieces of a geometry with continuous longitudes: its points, its lines and rings as lists, and its polygons (rings). */
1189
+ function shapeOf(u) {
1190
+ const polys = polygonsOf(u);
1191
+ return { points: pointsOf(u), lists: [...linesOf(u), ...polys.flat()], polys };
1192
+ }
1193
+ const boxesMeet = (a, b) => a[1] <= b[3] && b[1] <= a[3] && [-360, 0, 360].some((k) => a[0] <= b[2] + k && b[0] + k <= a[2]);
1194
+ const shiftGeometry = (g, k) => {
1195
+ const move = (c) => (typeof c[0] === "number" ? [c[0] + k, ...c.slice(1)] : c.map(move));
1196
+ return { ...g, coordinates: move(g.coordinates) };
1197
+ };
1198
+
1199
+ /** Does a point touch a shape (inside a polygon, on its boundary or a line, or equal to a point)? */
1200
+ function touches(s, p) {
1201
+ if (s.polys.some((poly) => inPolygon(poly, p))) return true;
1202
+ for (const [a, b] of segmentsIn(s.lists)) if (orient(a, b, p) === 0 && onSegment(a, b, p)) return true;
1203
+ return s.points.some((q) => q[0] === p[0] && q[1] === p[1]);
1204
+ }
1205
+
1206
+ /** Do two geometries share a point? Both have continuous longitudes and sit beside each other. */
1207
+ function intersectsU(a, b) {
1208
+ const A = shapeOf(a);
1209
+ const B = shapeOf(b);
1210
+ if (A.points.some((p) => touches(B, p)) || B.points.some((p) => touches(A, p))) return true;
1211
+ const sb = [...segmentsIn(B.lists)];
1212
+ for (const [p, q] of segmentsIn(A.lists)) {
1213
+ const x0 = Math.min(p[0], q[0]);
1214
+ const x1 = Math.max(p[0], q[0]);
1215
+ const y0 = Math.min(p[1], q[1]);
1216
+ const y1 = Math.max(p[1], q[1]);
1217
+ for (const [r, s] of sb) {
1218
+ if (Math.max(r[0], s[0]) < x0 || Math.min(r[0], s[0]) > x1 || Math.max(r[1], s[1]) < y0 || Math.min(r[1], s[1]) > y1) continue;
1219
+ if (segmentsMeet(p, q, r, s)) return true;
1220
+ }
1221
+ }
1222
+ // No edge touches: one may lie wholly inside a polygon of the other.
1223
+ return A.lists.some((l) => B.polys.some((poly) => inPolygon(poly, l[0]))) || B.lists.some((l) => A.polys.some((poly) => inPolygon(poly, l[0])));
1224
+ }
1225
+
1226
+ /** Run `test(a, b)` on the two geometries unwrapped and beside each other (b moved a world's width east or west when that is where it sits). */
1227
+ function beside(ga, gb, test) {
1228
+ const a = unwrap(ga);
1229
+ const b = unwrap(gb);
1230
+ const ea = extentU(a);
1231
+ const eb = extentU(b);
1232
+ for (const k of [0, -360, 360]) {
1233
+ if (!(ea[1] <= eb[3] && eb[1] <= ea[3] && ea[0] <= eb[2] + k && eb[0] + k <= ea[2])) continue;
1234
+ if (test(a, k === 0 ? b : shiftGeometry(b, k))) return true;
1235
+ }
1236
+ return false;
1237
+ }
1238
+
1239
+ const intersectsGeometry = (ga, gb) => beside(ga, gb, intersectsU);
1240
+
1241
+ /** Does a point lie strictly inside a polygon (not on an edge, not in a hole)? */
1242
+ function strictlyInside(poly, p) {
1243
+ if (locate(poly[0], p) !== 2) return false;
1244
+ for (let i = 1; i < poly.length; i++) if (locate(poly[i], p) !== 0) return false;
1245
+ return true;
1246
+ }
1247
+ const ringPoints = (poly) => {
1248
+ const out = [];
1249
+ for (const r of poly) {
1250
+ for (let i = 0; i < r.length; i++) {
1251
+ out.push(r[i]);
1252
+ if (i) out.push([(r[i][0] + r[i - 1][0]) / 2, (r[i][1] + r[i - 1][1]) / 2]);
1253
+ }
1254
+ }
1255
+ return out;
1256
+ };
1257
+ function crossesAny(A, B) {
1258
+ const sb = [...segmentsIn(B.lists)];
1259
+ for (const [p, q] of segmentsIn(A.lists)) for (const [r, s] of sb) if (properCross(p, q, r, s)) return true;
1260
+ return false;
1261
+ }
1262
+ /** Does the polygon set A hold all of B (edges and boundary included)? */
1263
+ const covers = (A, B) => !crossesAny(A, B) && B.polys.every((poly) => ringPoints(poly).every((p) => A.polys.some((q) => inPolygon(q, p))));
1264
+ /** Do two polygon sets share area without either holding the other? */
1265
+ function overlapsU(a, b) {
1266
+ const A = shapeOf(a);
1267
+ const B = shapeOf(b);
1268
+ const meet = crossesAny(A, B) || A.polys.some((poly) => ringPoints(poly).some((p) => B.polys.some((q) => strictlyInside(q, p)))) || B.polys.some((poly) => ringPoints(poly).some((p) => A.polys.some((q) => strictlyInside(q, p))));
1269
+ return meet && !covers(A, B) && !covers(B, A);
1270
+ }
1271
+ const overlapsGeometry = (ga, gb) => beside(ga, gb, overlapsU);
1272
+
1273
+ /** Metres from a point to the segment a-b (the nearest point found in a local frame round the point, measured by haversine). */
1274
+ function pointSegment(p, a, b) {
1275
+ const k = Math.cos(p[1] * RAD) || 1e-9;
1276
+ const dx = shortWay(b[0] - a[0]);
1277
+ const dy = b[1] - a[1];
1278
+ const ax = shortWay(a[0] - p[0]) * k;
1279
+ const ay = a[1] - p[1];
1280
+ const len = (dx * k) ** 2 + dy ** 2;
1281
+ const t = len === 0 ? 0 : Math.max(0, Math.min(1, -(ax * dx * k + ay * dy) / len));
1282
+ return haversine(p, [wrapLon(a[0] + dx * t), a[1] + dy * t]);
1283
+ }
1284
+
1285
+ /** The shortest distance in metres between any two geometries: 0 when they touch, otherwise the closest vertex-to-edge pair. */
1286
+ function gapBetween(ga, gb) {
1287
+ if (intersectsGeometry(ga, gb)) return 0;
1288
+ const A = shapeOf(ga);
1289
+ const B = shapeOf(gb);
1290
+ let best = Infinity;
1291
+ const from = (X, Y) => {
1292
+ const vertices = [...X.points, ...X.lists.flat()];
1293
+ const edges = [...segmentsIn(Y.lists), ...Y.points.map((q) => [q, q])];
1294
+ for (const p of vertices) for (const [a, b] of edges) best = Math.min(best, a === b ? haversine(p, a) : pointSegment(p, a, b));
1295
+ };
1296
+ from(A, B);
1297
+ from(B, A);
1298
+ return best;
1299
+ }
1300
+
1301
+ // ── a grid index (instead of H3) ─────────────────────────────────────────
1302
+
1303
+ /**
1304
+ * A grid of equal-angle cells, aligned to (-180, -90): the cell of a point is `<size>/<column>/<row>` with
1305
+ * column = floor((longitude + 180) / size) and row = floor((latitude + 90) / size), the last column and row taking
1306
+ * the 180 and 90 edges. It is an index for grouping and joining by place, not an equal-area grid: a cell is
1307
+ * narrower in metres the nearer a pole it is. H3 (hexagons, equal-ish area, a hierarchy) needs a dependency.
1308
+ */
1309
+ function gridSize(size) {
1310
+ if (!(size > 0) || !fin(size) || size > 90) throw new TableError("bad-option", `geo: the grid size is a number of degrees from 0 (exclusive) to 90, not ${show(size)}`);
1311
+ const cols = Math.ceil(360 / size - 1e-9);
1312
+ const rows = Math.ceil(180 / size - 1e-9);
1313
+ if (cols * rows > 1e9) throw new TableError("bad-option", `geo: a grid size of ${size} degrees has more than a billion cells; use 0.00001 or more`);
1314
+ return { size, cols, rows };
1315
+ }
1316
+ const sizeText = (size) => String(+size.toPrecision(12));
1317
+ function cellOf(point, size = 1) {
1318
+ const grid = gridSize(size);
1319
+ const [x, y] = point;
1320
+ const col = Math.min(grid.cols - 1, Math.max(0, Math.floor((x + 180) / size + 1e-12)));
1321
+ const row = Math.min(grid.rows - 1, Math.max(0, Math.floor((y + 90) / size + 1e-12)));
1322
+ return `${sizeText(size)}/${col}/${row}`;
1323
+ }
1324
+ function parseCell(id) {
1325
+ const m = /^([0-9.eE+-]+)\/(\d+)\/(\d+)$/.exec(String(id));
1326
+ const size = m ? Number(m[1]) : NaN;
1327
+ if (!m || !(size > 0) || size > 90) throw new TableError("bad-option", `geo: ${show(id)} isn't a grid cell id (<size>/<column>/<row>, like 1/183/130)`);
1328
+ const grid = gridSize(size);
1329
+ const col = Number(m[2]);
1330
+ const row = Number(m[3]);
1331
+ if (col >= grid.cols || row >= grid.rows) throw new TableError("bad-option", `geo: ${show(id)} is outside the grid (columns 0..${grid.cols - 1}, rows 0..${grid.rows - 1} at ${size} degrees)`);
1332
+ return { size, col, row, grid };
1333
+ }
1334
+ /** The bounds of a cell: `{ bbox: [west, south, east, north], polygon }`. */
1335
+ function cellBounds(id) {
1336
+ const { size, col, row, grid } = parseCell(id);
1337
+ const r = (v) => Math.round(v * 1e9) / 1e9;
1338
+ const west = r(-180 + col * size);
1339
+ const south = r(-90 + row * size);
1340
+ const east = col === grid.cols - 1 ? 180 : r(-180 + (col + 1) * size);
1341
+ const north = row === grid.rows - 1 ? 90 : r(-90 + (row + 1) * size);
1342
+ return { bbox: [west, south, east, north], polygon: { type: "Polygon", coordinates: [[[west, south], [east, south], [east, north], [west, north], [west, south]]] } };
1343
+ }
1344
+ /** The ids of the cells within `rings` cells of a cell (the cell itself first, then by row and column; the grid wraps at the antimeridian and stops at the poles). */
1345
+ function cellNeighbors(id, rings = 1) {
1346
+ const { size, col, row, grid } = parseCell(id);
1347
+ if (!Number.isInteger(rings) || rings < 0 || rings > 100) throw new TableError("bad-option", `geo: rings is a whole number from 0 to 100, not ${show(rings)}`);
1348
+ const out = [id];
1349
+ const seen = new Set(out);
1350
+ for (let dr = -rings; dr <= rings; dr++) {
1351
+ const rr = row + dr;
1352
+ if (rr < 0 || rr >= grid.rows) continue;
1353
+ for (let dc = -rings; dc <= rings; dc++) {
1354
+ const cc = (((col + dc) % grid.cols) + grid.cols) % grid.cols;
1355
+ const next = `${sizeText(size)}/${cc}/${rr}`;
1356
+ if (!seen.has(next)) (seen.add(next), out.push(next));
1357
+ }
1358
+ }
1359
+ return out;
1360
+ }
1361
+
1362
+ // ── a box index for spatial joins ────────────────────────────────────────
1363
+
1364
+ /**
1365
+ * A uniform grid over boxes `[west, south, east, north]` (continuous longitudes: the east may pass 180). `query(box)` returns the
1366
+ * positions of the boxes that might meet it, ascending, with the longitude circle in mind (a box at 179..181 meets one at -180..-179).
1367
+ * A box that spans a good part of the grid is kept aside and offered to every query.
1368
+ */
1369
+ function boxIndex(boxes) {
1370
+ const norm = (x) => ((((x + 180) % 360) + 360) % 360) - 180;
1371
+ const items = [];
1372
+ let x0 = Infinity;
1373
+ let x1 = -Infinity;
1374
+ let y0 = Infinity;
1375
+ let y1 = -Infinity;
1376
+ boxes.forEach((b, j) => {
1377
+ if (!b) return;
1378
+ const w = Math.min(b[2] - b[0], 360);
1379
+ const west = norm(b[0]);
1380
+ items.push([j, west, b[1], west + w, b[3]]);
1381
+ x0 = Math.min(x0, west);
1382
+ x1 = Math.max(x1, west + w);
1383
+ y0 = Math.min(y0, b[1]);
1384
+ y1 = Math.max(y1, b[3]);
1385
+ });
1386
+ const n = items.length;
1387
+ const side = Math.max(1, Math.min(256, Math.ceil(Math.sqrt(n))));
1388
+ const cw = (x1 - x0) / side || 1;
1389
+ const ch = (y1 - y0) / side || 1;
1390
+ const col = (x) => Math.max(0, Math.min(side - 1, Math.floor((x - x0) / cw)));
1391
+ const row = (y) => Math.max(0, Math.min(side - 1, Math.floor((y - y0) / ch)));
1392
+ const cells = new Map();
1393
+ const big = [];
1394
+ for (const it of items) {
1395
+ const [c0, c1, r0, r1] = [col(it[1]), col(it[3]), row(it[2]), row(it[4])];
1396
+ if ((c1 - c0 + 1) * (r1 - r0 + 1) > Math.max(16, (side * side) / 4)) {
1397
+ big.push(it);
1398
+ continue;
1399
+ }
1400
+ for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) (cells.get(r * side + c) ?? cells.set(r * side + c, []).get(r * side + c)).push(it);
1401
+ }
1402
+ return {
1403
+ size: n,
1404
+ query(q) {
1405
+ if (!n) return [];
1406
+ const w = Math.min(q[2] - q[0], 360);
1407
+ const west = norm(q[0]);
1408
+ const found = new Set();
1409
+ const take = (it, a0, a1) => {
1410
+ if (it[1] <= a1 && it[3] >= a0 && it[2] <= q[3] && it[4] >= q[1]) found.add(it[0]);
1411
+ };
1412
+ for (const shift of [0, 360, -360]) {
1413
+ const a0 = west + shift;
1414
+ const a1 = a0 + w;
1415
+ if (a1 < x0 || a0 > x1 || q[3] < y0 || q[1] > y1) continue;
1416
+ for (const it of big) take(it, a0, a1);
1417
+ const [c0, c1, r0, r1] = [col(Math.max(a0, x0)), col(Math.min(a1, x1)), row(Math.max(q[1], y0)), row(Math.min(q[3], y1))];
1418
+ for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) for (const it of cells.get(r * side + c) ?? []) take(it, a0, a1);
1419
+ }
1420
+ return [...found].sort((a, b) => a - b);
1421
+ },
1422
+ };
1423
+ }
1424
+
1425
+ // ── coordinate reference systems ─────────────────────────────────────────
1426
+
1427
+ const MERCATOR_R = 6378137;
1428
+ const MERCATOR_MAX_LAT = 85.0511287798066;
1429
+ const UTM_K0 = 0.9996;
1430
+ const UTM = (() => {
1431
+ const f = 1 / 298.257223563;
1432
+ const n = f / (2 - f);
1433
+ const n2 = n * n;
1434
+ const n3 = n2 * n;
1435
+ const n4 = n3 * n;
1436
+ return {
1437
+ n,
1438
+ A: (6378137 / (1 + n)) * (1 + n2 / 4 + n4 / 64),
1439
+ alpha: [n / 2 - (2 / 3) * n2 + (5 / 16) * n3 + (41 / 180) * n4, (13 / 48) * n2 - (3 / 5) * n3 + (557 / 1440) * n4, (61 / 240) * n3 - (103 / 140) * n4, (49561 / 161280) * n4],
1440
+ beta: [n / 2 - (2 / 3) * n2 + (37 / 96) * n3 - (1 / 360) * n4, (1 / 48) * n2 + (1 / 15) * n3 - (437 / 1440) * n4, (17 / 480) * n3 - (37 / 840) * n4, (4397 / 161280) * n4],
1441
+ delta: [2 * n - (2 / 3) * n2 - 2 * n3 + (116 / 45) * n4, (7 / 3) * n2 - (8 / 5) * n3 - (227 / 45) * n4, (56 / 15) * n3 - (136 / 35) * n4, (4279 / 630) * n4],
1442
+ };
1443
+ })();
1444
+
1445
+ /** WGS84 [longitude, latitude] to UTM [easting, northing] metres in a zone (the south adds the false northing). */
1446
+ function utmForward([lon, lat], zone, south) {
1447
+ const lon0 = ((zone - 1) * 6 - 180 + 3) * RAD;
1448
+ const phi = lat * RAD;
1449
+ const dl = shortWay(lon - lon0 / RAD) * RAD;
1450
+ const e = (2 * Math.sqrt(UTM.n)) / (1 + UTM.n);
1451
+ const sinPhi = Math.sin(phi);
1452
+ const t = Math.sinh(Math.atanh(sinPhi) - e * Math.atanh(e * sinPhi));
1453
+ const xi0 = Math.atan2(t, Math.cos(dl));
1454
+ const eta0 = Math.asinh(Math.sin(dl) / Math.hypot(t, Math.cos(dl)));
1455
+ let xi = xi0;
1456
+ let eta = eta0;
1457
+ UTM.alpha.forEach((a, i) => {
1458
+ const j = 2 * (i + 1);
1459
+ xi += a * Math.sin(j * xi0) * Math.cosh(j * eta0);
1460
+ eta += a * Math.cos(j * xi0) * Math.sinh(j * eta0);
1461
+ });
1462
+ return [500000 + UTM_K0 * UTM.A * eta, (south ? 10000000 : 0) + UTM_K0 * UTM.A * xi];
1463
+ }
1464
+
1465
+ /** UTM [easting, northing] metres in a zone to WGS84 [longitude, latitude]. */
1466
+ function utmInverse([easting, northing], zone, south) {
1467
+ const lon0 = (zone - 1) * 6 - 180 + 3;
1468
+ const xi = ((northing - (south ? 10000000 : 0)) / (UTM_K0 * UTM.A));
1469
+ const eta = (easting - 500000) / (UTM_K0 * UTM.A);
1470
+ let xi0 = xi;
1471
+ let eta0 = eta;
1472
+ UTM.beta.forEach((b, i) => {
1473
+ const j = 2 * (i + 1);
1474
+ xi0 -= b * Math.sin(j * xi) * Math.cosh(j * eta);
1475
+ eta0 -= b * Math.cos(j * xi) * Math.sinh(j * eta);
1476
+ });
1477
+ const chi = Math.asin(Math.sin(xi0) / Math.cosh(eta0));
1478
+ let phi = chi;
1479
+ UTM.delta.forEach((d, i) => {
1480
+ phi += d * Math.sin(2 * (i + 1) * chi);
1481
+ });
1482
+ return [wrapLon(lon0 + (Math.atan2(Math.sinh(eta0), Math.cos(xi0)) / RAD)), phi / RAD];
1483
+ }
1484
+
1485
+ const WGS84 = Object.freeze({ code: "EPSG:4326", kind: "wgs84", toWgs: (p) => p, fromWgs: (p) => p });
1486
+
1487
+ /**
1488
+ * A CRS this package can reproject from or to: WGS84 (EPSG:4326, CRS84), Web Mercator (EPSG:3857, also 900913) and the WGS84 UTM
1489
+ * zones (EPSG:32601-32660 north, 32701-32760 south, or "UTM 33N" / "utm:17S"). `{ code, kind, toWgs, fromWgs }`, or null.
1490
+ */
1491
+ function crsOf(name) {
1492
+ if (isObj(name)) name = name.properties?.name ?? name.name;
1493
+ const s = String(name ?? "").trim();
1494
+ if (!s) return null;
1495
+ if (crsOk(s)) return WGS84;
1496
+ const utm = /^utm[\s:_-]*(\d{1,2})\s*([ns])$/i.exec(s);
1497
+ let code = utm ? (utm[2].toLowerCase() === "n" ? 32600 : 32700) + Number(utm[1]) : NaN;
1498
+ if (!utm) {
1499
+ const m = /(?:^|[:/])EPSG:{1,2}(?:\d+(?:\.\d+)?:)?(\d+)$/i.exec(s) ?? /EPSG\/\d+\/(\d+)$/i.exec(s);
1500
+ code = m ? Number(m[1]) : NaN;
1501
+ }
1502
+ if (code === 4326) return WGS84;
1503
+ if (code === 3857 || code === 900913) {
1504
+ return Object.freeze({
1505
+ code: "EPSG:3857",
1506
+ kind: "mercator",
1507
+ toWgs: ([x, y]) => [wrapLon(x / MERCATOR_R / RAD), (2 * Math.atan(Math.exp(y / MERCATOR_R)) - Math.PI / 2) / RAD],
1508
+ fromWgs: ([lon, lat]) => {
1509
+ if (Math.abs(lat) > MERCATOR_MAX_LAT) return [NaN, NaN];
1510
+ return [lon * RAD * MERCATOR_R, Math.log(Math.tan(Math.PI / 4 + (lat * RAD) / 2)) * MERCATOR_R];
1511
+ },
1512
+ });
1513
+ }
1514
+ const zone = code >= 32601 && code <= 32660 ? code - 32600 : code >= 32701 && code <= 32760 ? code - 32700 : 0;
1515
+ if (!zone) return null;
1516
+ const south = code >= 32700;
1517
+ return Object.freeze({
1518
+ code: `EPSG:${code}`,
1519
+ kind: "utm",
1520
+ zone,
1521
+ south,
1522
+ toWgs: (p) => utmInverse(p, zone, south),
1523
+ fromWgs: (p) => utmForward(p, zone, south),
1524
+ });
1525
+ }
1526
+ const SUPPORTED_CRS = "EPSG:4326 (WGS84), EPSG:3857 (Web Mercator), EPSG:326xx / EPSG:327xx (WGS84 UTM zones; or \"UTM 33N\")";
1527
+
1528
+ const mapPositions = (g, f) => {
1529
+ const go = (c) => (typeof c[0] === "number" ? f(c) : c.map(go));
1530
+ return { ...g, coordinates: go(g.coordinates) };
1531
+ };
1532
+
1533
+ /** A geometry's coordinates moved from one CRS to another. A position that can't be moved is a problem (`{ problem }`), not a guess. */
1534
+ function transformGeometry(g, from, to) {
1535
+ let failed = null;
1536
+ const moved = mapPositions(g, (p) => {
1537
+ const out = from === to ? [p[0], p[1]] : to.fromWgs(from.toWgs([p[0], p[1]]));
1538
+ if (!fin(out[0]) || !fin(out[1])) failed ??= problem("out-of-range", `[${p[0]}, ${p[1]}] can't be moved from ${from.code} to ${to.code}${to.kind === "mercator" ? ` (Web Mercator covers latitudes up to +/-${MERCATOR_MAX_LAT.toFixed(2)})` : ""}`);
1539
+ return p.length > 2 ? [out[0], out[1], ...p.slice(2)] : out;
1540
+ });
1541
+ return failed ? { problem: failed } : { g: moved };
1542
+ }
1543
+
1544
+ /** `table.geo.reproject(geometry, { from, to })`: a geometry (or Feature, or JSON text) moved between CRSs; `to` defaults to WGS84. */
1545
+ function reproject(cell, options = {}) {
1546
+ const from = crsOf(options.from ?? "EPSG:4326");
1547
+ const to = crsOf(options.to ?? "EPSG:4326");
1548
+ if (!from || !to) throw new TableError("incompatible-crs", `geo: reproject supports ${SUPPORTED_CRS}, not ${show(!from ? options.from : options.to)}`);
1549
+ let g = cell;
1550
+ if (typeof g === "string" && /^\s*[{[]/.test(g)) {
1551
+ try {
1552
+ g = JSON.parse(g);
1553
+ } catch {
1554
+ throw new TableError("bad-geometry", "geo: the cell is text that isn't JSON");
1555
+ }
1556
+ }
1557
+ if (isObj(g) && g.type === "Feature") g = g.geometry;
1558
+ const p = validateGeometry(g, { n: 0 }, from.kind !== "wgs84");
1559
+ if (p) throw new TableError(p.code, `geo: ${p.reason}`);
1560
+ const r = transformGeometry(g, from, to);
1561
+ if (r.problem) throw new TableError(r.problem.code, `geo: ${r.problem.reason}`);
1562
+ if (to.kind === "wgs84") {
1563
+ const q = validateGeometry(r.g);
1564
+ if (q) throw new TableError(q.code, `geo: the result isn't valid WGS84: ${q.reason}`);
1565
+ }
1566
+ return r.g;
1567
+ }
1568
+
1569
+ // ── where the data came from ─────────────────────────────────────────────
1570
+
1571
+ /**
1572
+ * A record of where outside data came from, for enrichment that was retrieved by other means (an http request under
1573
+ * the canvas's network approval): `{ url, retrieved, license, name? }`. This module never reaches the network; it only checks
1574
+ * that the record is complete, so the origin travels with the data.
1575
+ */
1576
+ function sourceRecord(op, s) {
1577
+ if (s === undefined || s === null) return undefined;
1578
+ if (!isObj(s)) throw bad(op, "source is { url, retrieved, license } (and optionally name).");
1579
+ const url = typeof s.url === "string" ? s.url.trim() : "";
1580
+ if (!/^https?:\/\/[^\s/]+/i.test(url)) throw bad(op, `source.url should be the http(s) address the data came from, not ${show(s.url)}.`);
1581
+ if (typeof s.retrieved !== "string" || Number.isNaN(parseIso(s.retrieved))) throw bad(op, `source.retrieved should be the ISO date the data was retrieved (like 2026-10-13), not ${show(s.retrieved)}.`);
1582
+ if (typeof s.license !== "string" || !s.license.trim()) throw bad(op, "source.license should name the data's license (like ODbL-1.0 or CC-BY-4.0); say \"unknown\" if it is.");
1583
+ return { url, retrieved: s.retrieved, license: s.license.trim(), ...(typeof s.name === "string" && s.name.trim() ? { name: s.name.trim() } : {}) };
1584
+ }
1585
+
1586
+ // ── geoParse ─────────────────────────────────────────────────────────────
1587
+
1588
+ const crsOk = (name) => /(^|[:/])(CRS84|4326)$/i.test(String(name).trim()) || /^urn:ogc:def:crs:OGC:1\.3:CRS84$/i.test(String(name).trim());
1589
+ /** The CRS a document or option declares: `undefined` when it says nothing, the CRS when this package can read it, otherwise `incompatible-crs`. */
1590
+ function declaredCrs(op, declared, where) {
1591
+ if (declared === undefined || declared === null || declared === "") return undefined;
1592
+ const name = isObj(declared) ? declared.properties?.name ?? (declared.type === "name" ? undefined : declared.type) : declared;
1593
+ const crs = typeof name === "string" ? crsOf(name) : null;
1594
+ if (crs) return crs;
1595
+ throw new TableError("incompatible-crs", `${op}: ${where} is in ${name === undefined ? "a CRS this package can't read" : show(name)}, but only ${SUPPORTED_CRS} can be read. Reproject the data to one of those first (for example with ogr2ogr -t_srs EPSG:4326), or drop the crs member if the numbers already are WGS84 degrees.`, { crs: name });
1596
+ }
1597
+
1598
+ const swapped = (g) => {
1599
+ if (!isObj(g) || !Array.isArray(g.coordinates)) return g;
1600
+ const flip = (c) => (Array.isArray(c) && typeof c[0] === "number" ? [c[1], c[0], ...c.slice(2)] : Array.isArray(c) ? c.map(flip) : c);
1601
+ return { ...g, coordinates: flip(g.coordinates) };
1602
+ };
1603
+
1604
+ function parseInput(op, input) {
1605
+ let doc = input;
1606
+ if (typeof doc === "string") {
1607
+ try {
1608
+ doc = JSON.parse(doc);
1609
+ } catch (error) {
1610
+ throw new TableError("bad-input", `${op}: the text isn't JSON (${error.message}). Give a GeoJSON object or its JSON text.`);
1611
+ }
1612
+ }
1613
+ if (!isObj(doc) || typeof doc.type !== "string") throw new TableError("bad-input", `${op}: expected a GeoJSON FeatureCollection, Feature or geometry (an object with a "type"), not ${Array.isArray(doc) ? "an array" : show(doc)?.slice(0, 40)}. Rows that already are a table go to the other geo panes as they are.`);
1614
+ return doc;
1615
+ }
1616
+
1617
+ const geoParse = defineOp(
1618
+ "geoParse",
1619
+ function* (input, o, ctx) {
1620
+ const doc = parseInput("geoParse", input);
1621
+ const idCol = o.id ?? "id";
1622
+ const geoCol = o.geometry ?? "geometry";
1623
+ const order = o.axisOrder ?? "lonlat";
1624
+ if (!["lonlat", "latlon"].includes(order)) throw bad("geoParse", `axisOrder is "lonlat" (GeoJSON's [longitude, latitude], the default) or "latlon" for data written [latitude, longitude], not ${show(order)}.`);
1625
+ if (typeof idCol !== "string" || typeof geoCol !== "string" || !idCol || !geoCol || idCol === geoCol) throw bad("geoParse", "id and geometry are two different column names.");
1626
+ const source = sourceRecord("geoParse", o.source ?? doc.source);
1627
+ const optionCrs = declaredCrs("geoParse", o.crs, "the crs option");
1628
+ const memberCrs = declaredCrs("geoParse", doc.crs, "the document's crs member");
1629
+ if (optionCrs && memberCrs && optionCrs.code !== memberCrs.code) throw bad("geoParse", `the crs option says ${optionCrs.code} but the document's crs member says ${memberCrs.code}: drop one.`);
1630
+ const from = optionCrs ?? memberCrs ?? WGS84;
1631
+ const projected = from.kind !== "wgs84";
1632
+ const maxCoordinates = o.maxCoordinates ?? DEFAULT_MAX_COORDINATES;
1633
+ if (!Number.isInteger(maxCoordinates) || maxCoordinates < 1) throw bad("geoParse", `maxCoordinates should be a whole number of at least 1, not ${show(o.maxCoordinates)}.`);
1634
+ let features;
1635
+ if (doc.type === "FeatureCollection") {
1636
+ if (!Array.isArray(doc.features)) throw new TableError("bad-input", "geoParse: the FeatureCollection has no features array.");
1637
+ features = doc.features;
1638
+ } else if (doc.type === "Feature") features = [doc];
1639
+ else features = [{ type: "Feature", properties: {}, geometry: doc }];
1640
+ ctx.checkRows(features.length, "the feature list");
1641
+
1642
+ const rows = [];
1643
+ const origin = [];
1644
+ const rejected = [];
1645
+ const rejections = [];
1646
+ const seen = new Map();
1647
+ const count = { n: 0 };
1648
+ let generated = 0;
1649
+ let renamed = 0;
1650
+ let box = null; // continuous longitudes (extentU)
1651
+ const reject = (i, id, p, feature) => {
1652
+ ctx.error({ row: i, column: geoCol, code: p.code, message: p.reason, ...(id !== undefined ? { id } : {}) });
1653
+ rejected.push(feature);
1654
+ rejections.push({ index: i, id: id ?? null, code: p.code, reason: p.reason });
1655
+ ctx.exclude({ input: "features", kind: "rejected", code: p.code, reason: p.reason }, i);
1656
+ };
1657
+ for (let i = 0; i < features.length; i++) {
1658
+ if (ctx.tick()) yield;
1659
+ const f = features[i];
1660
+ if (!isObj(f) || f.type !== "Feature") {
1661
+ reject(i, undefined, problem("not-a-feature", `features[${i}] isn't a GeoJSON Feature (an object with type "Feature")`), f);
1662
+ continue;
1663
+ }
1664
+ const props = isObj(f.properties) ? f.properties : {};
1665
+ let id = f.id ?? props[idCol];
1666
+ const hasId = typeof id === "string" || (typeof id === "number" && fin(id));
1667
+ let g = f.geometry;
1668
+ if (order === "latlon") g = swapped(g);
1669
+ let p = validateGeometry(g, count, projected);
1670
+ if (!p && projected) {
1671
+ const moved = transformGeometry(g, from, WGS84);
1672
+ p = moved.problem ?? validateGeometry((g = moved.g));
1673
+ }
1674
+ if (count.n > maxCoordinates) throw new TableError("limit", `geoParse: more than ${maxCoordinates} coordinates (maxCoordinates). Split the file, simplify the geometries, or raise maxCoordinates.`);
1675
+ if (p) {
1676
+ reject(i, hasId ? id : undefined, p, f);
1677
+ continue;
1678
+ }
1679
+ if (!hasId) {
1680
+ id = `feature-${i}`;
1681
+ generated++;
1682
+ }
1683
+ const key = `${typeof id}:${id}`;
1684
+ if (seen.has(key)) {
1685
+ reject(i, id, problem("duplicate-id", `the id ${show(id)} is already used by feature ${seen.get(key)}; ids name the rows for selection, so each must be unique`), f);
1686
+ continue;
1687
+ }
1688
+ seen.set(key, i);
1689
+ const row = { [idCol]: id };
1690
+ for (const [k, v] of Object.entries(props)) {
1691
+ if (k === idCol || k === geoCol) {
1692
+ if (k === geoCol || (f.id !== undefined && v !== f.id)) renamed++;
1693
+ continue;
1694
+ }
1695
+ row[k] = v === undefined ? null : v;
1696
+ }
1697
+ row[geoCol] = g;
1698
+ ctx.checkRows(rows.length + 1, "the result");
1699
+ rows.push(row);
1700
+ origin.push({ features: [i] });
1701
+ const e = extentU(g);
1702
+ box = box ? unionU(box, e) : e;
1703
+ }
1704
+ if (generated) ctx.note(`geoParse: ${generated} feature${generated === 1 ? " has" : "s have"} no id, so ${generated === 1 ? "it was" : "they were"} named feature-<position>. Positions are not stable if the file is reordered: give features an "id" for selections that must survive.`);
1705
+ if (renamed) ctx.note(`geoParse: ${renamed} propert${renamed === 1 ? "y" : "ies"} named "${idCol}" or "${geoCol}" ${renamed === 1 ? "was" : "were"} left out because the ${idCol} and ${geoCol} columns hold the feature id and geometry (set id/geometry to other column names to keep them).`);
1706
+ if (projected) ctx.note(`geoParse: coordinates were read as ${from.code} (metres: easting, northing) and reprojected to WGS84 degrees.`);
1707
+ if (order === "latlon") ctx.note("geoParse: axisOrder is latlon, so each position was read as [latitude, longitude] and written out as GeoJSON's [longitude, latitude].");
1708
+ const extent = rows.length && box ? bboxOf(box) : null;
1709
+ return { rows, origin, rejected, rejections, extent, crs: { ...CRS }, features: features.length, ...(projected ? { reprojected: { from: from.code } } : {}), ...(source ? { source } : {}) };
1710
+ },
1711
+ { inputs: "none" },
1712
+ );
1713
+
1714
+ // ── row operations ───────────────────────────────────────────────────────
1715
+
1716
+ /** The geometry column of a rows operation, checked to exist when there are rows. */
1717
+ function columnOf(op, rows, name) {
1718
+ const col = name ?? "geometry";
1719
+ if (typeof col !== "string" || !col) throw bad(op, "geometry is the name of the column that holds the GeoJSON geometry.");
1720
+ if (rows.length && !rows.some((r) => Object.prototype.hasOwnProperty.call(r, col))) {
1721
+ const cols = [...new Set(rows.slice(0, 50).flatMap((r) => Object.keys(r)))];
1722
+ throw new TableError("unknown-column", `${op}: no column "${col}". Columns: ${cols.map((c) => JSON.stringify(c)).join(", ") || "(none)"}. Set geometry to the column that holds the GeoJSON geometry (geoParse makes one called "geometry").`, { column: col, columns: cols });
1723
+ }
1724
+ return col;
1725
+ }
1726
+
1727
+ const unitOf = (op, kind, value, fallback) => {
1728
+ const u = value ?? fallback;
1729
+ if (!UNITS[kind][u]) throw bad(op, `${kind}Unit is one of ${Object.keys(UNITS[kind]).join(", ")}, not ${show(value)}.`);
1730
+ return u;
1731
+ };
1732
+
1733
+ /** Drop the rows ctx.rejected marks (onError "route"); returns [kept, rejected, keptOrigin]. */
1734
+ function routed(ctx, rows, out, origin) {
1735
+ if (!ctx.rejected.size) return [out, [], origin];
1736
+ const kept = [];
1737
+ const keptOrigin = [];
1738
+ const rejected = [];
1739
+ out.forEach((row, k) => {
1740
+ const i = origin[k].rows[0];
1741
+ if (ctx.rejected.has(`:${i}`)) {
1742
+ rejected.push(rows[i]);
1743
+ const why = ctx.errors.find((e) => e.row === i);
1744
+ ctx.exclude({ input: "rows", kind: "rejected", code: why?.code, reason: why?.message ?? "the row failed and onError is \"route\"" }, i);
1745
+ } else {
1746
+ kept.push(row);
1747
+ keptOrigin.push(origin[k]);
1748
+ }
1749
+ });
1750
+ return [kept, rejected, keptOrigin];
1751
+ }
1752
+
1753
+ const MEASURES = ["bbox", "centroid", "area", "length", "distance"];
1754
+
1755
+ const geoMeasure = defineOp("geoMeasure", function* (rows, o, ctx) {
1756
+ const col = columnOf("geoMeasure", rows, o.geometry);
1757
+ const measures = o.measures ?? ["bbox", "centroid"];
1758
+ if (!Array.isArray(measures) || !measures.length || measures.some((m) => !MEASURES.includes(m))) throw bad("geoMeasure", `measures is a list of ${MEASURES.join(", ")}, not ${show(o.measures)}.`);
1759
+ const lu = unitOf("geoMeasure", "length", o.lengthUnit, "m");
1760
+ const au = unitOf("geoMeasure", "area", o.areaUnit, "m2");
1761
+ let to;
1762
+ if (measures.includes("distance")) {
1763
+ if (o.to === undefined || o.to === null) throw bad("geoMeasure", 'distance needs `to`: a point ([longitude, latitude], a Point geometry or Feature) or { column: "other_geometry_column" }.');
1764
+ if (isObj(o.to) && typeof o.to.column === "string") to = { column: o.to.column };
1765
+ else {
1766
+ const r = geometryOf(o.to);
1767
+ if (r.problem) throw bad("geoMeasure", `to isn't a usable point: ${r.problem.reason}.`);
1768
+ to = { g: r.g };
1769
+ }
1770
+ }
1771
+ const out = [];
1772
+ const origin = [];
1773
+ for (let i = 0; i < rows.length; i++) {
1774
+ if (ctx.tick()) yield;
1775
+ const row = rows[i];
1776
+ const r = geometryOf(row[col]);
1777
+ const next = { ...row };
1778
+ const fail = (p) => {
1779
+ ctx.error({ row: i, column: col, code: p.code, message: p.reason });
1780
+ };
1781
+ if (r.problem) {
1782
+ fail(r.problem);
1783
+ for (const m of measures) next[m === "area" ? `area_${au}` : m === "length" ? `length_${lu}` : m === "distance" ? `distance_${lu}` : m] = null;
1784
+ } else {
1785
+ const g = r.g;
1786
+ for (const m of measures) {
1787
+ let value = null;
1788
+ let name = m;
1789
+ if (m === "bbox") value = extentOf(g);
1790
+ else if (m === "centroid") value = { type: "Point", coordinates: centroidOf(g) };
1791
+ else if (m === "area") {
1792
+ name = `area_${au}`;
1793
+ if (!polygonsOf(g).length) fail(unsupported("area", g, "use a Polygon or MultiPolygon"));
1794
+ else value = areaOf(g) / UNITS.area[au];
1795
+ } else if (m === "length") {
1796
+ name = `length_${lu}`;
1797
+ if (!linesOf(g).length) fail(unsupported("length", g, "use a LineString or MultiLineString (a polygon's boundary is not measured)"));
1798
+ else value = lengthOf(g) / UNITS.length[lu];
1799
+ } else {
1800
+ name = `distance_${lu}`;
1801
+ const other = to.column ? geometryOf(row[to.column]) : { g: to.g };
1802
+ const pa = pointsOf(g);
1803
+ if (other.problem) fail(problem(other.problem.code, `${to.column}: ${other.problem.reason}`));
1804
+ else if (!pa.length || !pointsOf(other.g).length) fail(problem("unsupported-geometry", `distance is defined between points, not ${!pa.length ? g.type : other.g.type}; take its centroid first (measures: ["centroid"], then measure from that column)`));
1805
+ else value = pointDistance(pa, pointsOf(other.g)) / UNITS.length[lu];
1806
+ }
1807
+ next[name] = value;
1808
+ }
1809
+ }
1810
+ out.push(next);
1811
+ origin.push({ rows: [i] });
1812
+ }
1813
+ const [kept, rejected, keptOrigin] = routed(ctx, rows, out, origin);
1814
+ ctx.note(`geoMeasure: ${CRS.name} ${CRS.coordinates}; distance and length ${CRS.distance}, area ${CRS.area}; centroid and bbox are planar in degrees after unwrapping the antimeridian (a bbox across it has west > east).`);
1815
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}) };
1816
+ });
1817
+
1818
+ const geoBuffer = defineOp("geoBuffer", function* (rows, o, ctx) {
1819
+ const col = columnOf("geoBuffer", rows, o.geometry);
1820
+ const into = o.into ?? "buffer";
1821
+ if (typeof into !== "string" || !into) throw bad("geoBuffer", "into is the name of the column for the buffer polygon.");
1822
+ const meters = Number(o.meters);
1823
+ const unit = unitOf("geoBuffer", "length", o.unit, "m");
1824
+ const radius = meters * UNITS.length[unit];
1825
+ if (!(radius > 0)) throw bad("geoBuffer", `meters is the radius (in ${unit}) and must be greater than 0, not ${show(o.meters)}.`);
1826
+ const steps = o.steps ?? 32;
1827
+ const out = [];
1828
+ const origin = [];
1829
+ for (let i = 0; i < rows.length; i++) {
1830
+ if (ctx.tick()) yield;
1831
+ let value = null;
1832
+ try {
1833
+ value = buffer(rows[i][col], radius, steps);
1834
+ } catch (error) {
1835
+ if (error.code === "bad-option") throw bad("geoBuffer", error.message.replace(/^geo: /, ""));
1836
+ ctx.error({ row: i, column: col, code: error.code ?? "error", message: error.message.replace(/^geo: /, "") });
1837
+ }
1838
+ out.push({ ...rows[i], [into]: value });
1839
+ origin.push({ rows: [i] });
1840
+ }
1841
+ const [kept, rejected, keptOrigin] = routed(ctx, rows, out, origin);
1842
+ ctx.note(`geoBuffer: a ${CRS.name} geodesic circle of ${radius} m (${steps} vertices) around each point${rows.some((r) => ["LineString", "MultiLineString", "Polygon", "MultiPolygon"].includes(r[col]?.type)) ? "; a line or polygon gets a stadium round each segment (and the polygon itself), dissolved into one or more outlines that do not overlap" : ""}; MultiPoint circles are not merged.`);
1843
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}) };
1844
+ });
1845
+
1846
+ // ── reprojection ─────────────────────────────────────────────────────────
1847
+
1848
+ const geoReproject = defineOp("geoReproject", function* (rows, o, ctx) {
1849
+ const col = columnOf("geoReproject", rows, o.geometry);
1850
+ const from = crsOf(o.from ?? "EPSG:4326");
1851
+ const to = crsOf(o.to ?? "EPSG:4326");
1852
+ if (!from) throw new TableError("incompatible-crs", `geoReproject: from is ${show(o.from)}, but only ${SUPPORTED_CRS} can be read.`, { crs: o.from });
1853
+ if (!to) throw new TableError("incompatible-crs", `geoReproject: to is ${show(o.to)}, but only ${SUPPORTED_CRS} can be written.`, { crs: o.to });
1854
+ if (from === to || from.code === to.code) throw bad("geoReproject", `from and to are both ${from.code}: there is nothing to move. Set from to the CRS the numbers are in (for example "EPSG:3857" or "EPSG:32633").`);
1855
+ const into = o.into ?? col;
1856
+ if (typeof into !== "string" || !into) throw bad("geoReproject", "into is the name of the column for the moved geometry (default: the geometry column itself).");
1857
+ const out = [];
1858
+ const origin = [];
1859
+ for (let i = 0; i < rows.length; i++) {
1860
+ if (ctx.tick()) yield;
1861
+ const cell = rows[i][col];
1862
+ let value = null;
1863
+ let g = cell;
1864
+ if (typeof g === "string" && /^\s*[{[]/.test(g)) {
1865
+ try {
1866
+ g = JSON.parse(g);
1867
+ } catch {
1868
+ g = undefined;
1869
+ }
1870
+ }
1871
+ if (isObj(g) && g.type === "Feature") g = g.geometry;
1872
+ const p = validateGeometry(g, { n: 0 }, from.kind !== "wgs84");
1873
+ if (p) ctx.error({ row: i, column: col, code: p.code, message: p.reason });
1874
+ else {
1875
+ const moved = transformGeometry(g, from, to);
1876
+ const q = moved.problem ?? (to.kind === "wgs84" ? validateGeometry(moved.g) : null);
1877
+ if (moved.problem) ctx.error({ row: i, column: col, code: moved.problem.code, message: moved.problem.reason });
1878
+ else if (q) ctx.error({ row: i, column: col, code: q.code, message: `the result isn't valid WGS84: ${q.reason}` });
1879
+ else value = moved.g;
1880
+ }
1881
+ out.push({ ...rows[i], [into]: value });
1882
+ origin.push({ rows: [i] });
1883
+ }
1884
+ const [kept, rejected, keptOrigin] = routed(ctx, rows, out, origin);
1885
+ ctx.note(`geoReproject: ${from.code} to ${to.code}${to.kind === "wgs84" ? ` (${CRS.coordinates})` : ": the result is in metres, which the other geo operations don't read (they are WGS84); this is for handing to other tools"}.`);
1886
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}) };
1887
+ });
1888
+
1889
+ // ── grid cells ───────────────────────────────────────────────────────────
1890
+
1891
+ const geoCell = defineOp("geoCell", function* (rows, o, ctx) {
1892
+ const col = columnOf("geoCell", rows, o.geometry);
1893
+ const into = o.into ?? "cell";
1894
+ if (typeof into !== "string" || !into) throw bad("geoCell", "into is the name of the column for the cell id.");
1895
+ const size = o.size === undefined || o.size === null || o.size === "" ? 1 : Number(o.size);
1896
+ try {
1897
+ gridSize(size);
1898
+ } catch (error) {
1899
+ throw bad("geoCell", error.message.replace(/^geo: /, ""));
1900
+ }
1901
+ const of = checkOf("geoCell", o.of);
1902
+ const out = [];
1903
+ const origin = [];
1904
+ for (let i = 0; i < rows.length; i++) {
1905
+ if (ctx.tick()) yield;
1906
+ const r = geometryOf(rows[i][col]);
1907
+ let value = null;
1908
+ if (r.problem) ctx.error({ row: i, column: col, code: r.problem.code, message: r.problem.reason });
1909
+ else {
1910
+ const pts = testPoints(r.g, of);
1911
+ if (pts.length !== 1) {
1912
+ const p = pts.length ? problem("unsupported-geometry", `a MultiPoint spans several cells: use geoCell with of: "centroid", or split it into one row per point`) : unsupported("a grid cell", r.g, 'set of: "centroid" to place it by its centroid');
1913
+ ctx.error({ row: i, column: col, code: p.code, message: p.reason });
1914
+ } else value = cellOf(pts[0], size);
1915
+ }
1916
+ out.push({ ...rows[i], [into]: value });
1917
+ origin.push({ rows: [i] });
1918
+ }
1919
+ const [kept, rejected, keptOrigin] = routed(ctx, rows, out, origin);
1920
+ ctx.note(`geoCell: an equal-angle grid of ${size} degree cells aligned to (-180, -90); the id is <size>/<column>/<row>. Cells are narrower in metres toward the poles, and the grid is not H3.`);
1921
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}) };
1922
+ });
1923
+
1924
+ /** A region (Polygon/MultiPolygon geometry, or a Feature of one) or a problem. */
1925
+ function regionOf(op, value) {
1926
+ const r = geometryOf(value);
1927
+ if (r.problem) throw bad(op, `region isn't a usable polygon: ${r.problem.reason}.`);
1928
+ if (!polygonsOf(r.g).length) throw bad(op, `region should be a Polygon or MultiPolygon, not a ${r.g.type}.`);
1929
+ return r.g;
1930
+ }
1931
+
1932
+ /** The points a feature is tested by: its own points, or its centroid with `of: "centroid"`. */
1933
+ function testPoints(g, of) {
1934
+ if (of === "centroid") return [centroidOf(g)];
1935
+ return pointsOf(g);
1936
+ }
1937
+ const checkOf = (op, of) => {
1938
+ if (of !== undefined && !["geometry", "centroid"].includes(of)) throw bad(op, `of is "geometry" (points as they are, the default) or "centroid" (test each feature by its centroid), not ${show(of)}.`);
1939
+ return of ?? "geometry";
1940
+ };
1941
+
1942
+ const geoWithin = defineOp("geoWithin", function* (rows, o, ctx) {
1943
+ const col = columnOf("geoWithin", rows, o.geometry);
1944
+ const region = regionOf("geoWithin", o.region);
1945
+ const of = checkOf("geoWithin", o.of);
1946
+ const box = extentU(region);
1947
+ const out = [];
1948
+ const origin = [];
1949
+ const excluded = [];
1950
+ const bad_ = [];
1951
+ for (let i = 0; i < rows.length; i++) {
1952
+ if (ctx.tick()) yield;
1953
+ const r = geometryOf(rows[i][col]);
1954
+ let pts;
1955
+ if (r.problem) ctx.error({ row: i, column: col, code: r.problem.code, message: r.problem.reason });
1956
+ else {
1957
+ pts = testPoints(r.g, of);
1958
+ if (!pts.length) {
1959
+ const p = unsupported("a point-in-region test", r.g, 'set of: "centroid" to test by its centroid');
1960
+ ctx.error({ row: i, column: col, code: p.code, message: p.reason });
1961
+ pts = undefined;
1962
+ }
1963
+ }
1964
+ if (!pts) {
1965
+ if (ctx.policy === "route") {
1966
+ bad_.push(rows[i]);
1967
+ ctx.exclude({ input: "rows", kind: "rejected", code: ctx.errors.at(-1).code, reason: ctx.errors.at(-1).message }, i);
1968
+ } else if (ctx.policy !== "fail") {
1969
+ excluded.push(rows[i]);
1970
+ ctx.exclude({ input: "rows", kind: "filtered", reason: "its geometry can't be tested (see errors)" }, i);
1971
+ }
1972
+ continue;
1973
+ }
1974
+ const inside = pts.every((p) => inBoxU(box, p) && inGeometry(region, p));
1975
+ if (inside) {
1976
+ out.push(rows[i]);
1977
+ origin.push({ rows: [i] });
1978
+ } else {
1979
+ excluded.push(rows[i]);
1980
+ ctx.exclude({ input: "rows", kind: "filtered", reason: "outside the region" }, i);
1981
+ }
1982
+ }
1983
+ ctx.note("geoWithin: a point on the region's boundary is inside; edges are straight lines in longitude/latitude.");
1984
+ return { rows: out, origin: ctx.trace ? origin : undefined, excluded, ...(bad_.length ? { rejected: bad_ } : {}) };
1985
+ });
1986
+
1987
+ // ── the spatial join ─────────────────────────────────────────────────────
1988
+
1989
+ const PREDICATE_WHY = {
1990
+ within: () => "is a polygon that contains it",
1991
+ dwithin: (distance, unit) => `within ${distance} ${unit}`,
1992
+ intersects: () => "touches it",
1993
+ overlaps: () => "is a polygon that overlaps it",
1994
+ nearest: (distance, unit) => (distance === undefined || distance === null || distance === "" ? "is nearest to it" : `is among its nearest within ${distance} ${unit}`),
1995
+ };
1996
+ /** The box of a list of points (continuous longitudes are not needed: a point is one place). */
1997
+ const pointsBox = (pts) => {
1998
+ let x0 = Infinity;
1999
+ let y0 = Infinity;
2000
+ let x1 = -Infinity;
2001
+ let y1 = -Infinity;
2002
+ for (const p of pts) {
2003
+ if (p[0] < x0) x0 = p[0];
2004
+ if (p[0] > x1) x1 = p[0];
2005
+ if (p[1] < y0) y0 = p[1];
2006
+ if (p[1] > y1) y1 = p[1];
2007
+ }
2008
+ return [x0, y0, x1, y1];
2009
+ };
2010
+ const PREDICATES = ["within", "dwithin", "intersects", "overlaps", "nearest"];
2011
+ const INDEX_FROM = 1000; // pairs: below this a join tests every pair (and counts them against maxPairs up front)
2012
+
2013
+ const geoJoin = defineOp(
2014
+ "geoJoin",
2015
+ function* ({ left, right }, o, ctx) {
2016
+ const lcol = columnOf("geoJoin", left, o.leftGeometry ?? o.geometry);
2017
+ const rcol = columnOf("geoJoin", right, o.rightGeometry ?? o.geometry);
2018
+ const predicate = o.predicate ?? "within";
2019
+ if (!PREDICATES.includes(predicate)) throw bad("geoJoin", `predicate is "within" (left points inside right polygons), "dwithin" (points within a distance), "intersects" (any two geometries that share a point), "overlaps" (polygons that share area, neither holding the other) or "nearest" (each left row to its nearest right feature), not ${show(o.predicate)}.`);
2020
+ const mode = o.mode ?? "inner";
2021
+ if (!["inner", "left"].includes(mode)) throw bad("geoJoin", `mode is "inner" or "left", not ${show(o.mode)}.`);
2022
+ const multiple = o.multiple ?? "all";
2023
+ if (!["all", "first", "error"].includes(multiple)) throw bad("geoJoin", `multiple is "all" (a row per match), "first" (the lowest right position) or "error", not ${show(o.multiple)}.`);
2024
+ const indexMode = o.index ?? "auto";
2025
+ if (!["auto", "grid", "none"].includes(indexMode)) throw bad("geoJoin", `index is "auto" (a grid index once left x right is over ${INDEX_FROM} pairs), "grid" or "none", not ${show(o.index)}.`);
2026
+ const of = checkOf("geoJoin", o.of);
2027
+ const unit = unitOf("geoJoin", "length", o.unit, "m");
2028
+ const hasDistance = o.distance !== undefined && o.distance !== null && o.distance !== "";
2029
+ let reach = predicate === "nearest" ? Infinity : 0;
2030
+ if (predicate === "dwithin" || (predicate === "nearest" && hasDistance)) {
2031
+ reach = Number(o.distance);
2032
+ if (!(reach >= 0) || !fin(reach) || !hasDistance) throw bad("geoJoin", `${predicate} needs distance (in ${unit}, from 0), not ${show(o.distance)}.`);
2033
+ reach *= UNITS.length[unit];
2034
+ }
2035
+ const k = predicate === "nearest" ? (o.k ?? 1) : 1;
2036
+ if (!Number.isInteger(k) || k < 1 || k > 100) throw bad("geoJoin", `k is how many nearest right features each left row gets (a whole number from 1 to 100), not ${show(o.k)}.`);
2037
+ const maxPairs = o.maxPairs ?? Math.min(DEFAULT_MAX_PAIRS, ctx.limits.maxCells);
2038
+ if (!Number.isInteger(maxPairs) || maxPairs < 1) throw bad("geoJoin", `maxPairs should be a whole number of at least 1, not ${show(o.maxPairs)}.`);
2039
+ const total = left.length * right.length;
2040
+ // An index finds the right features near a left one; "nearest" measures against all of them. Without one, every pair is tested and counted up front.
2041
+ const indexed = predicate !== "nearest" && (indexMode === "grid" || (indexMode === "auto" && total > INDEX_FROM));
2042
+ if (!indexed && total > maxPairs) throw new TableError("limit", `geoJoin: ${left.length} x ${right.length} = ${total} pairs to test, over maxPairs (${maxPairs}). Filter either side first (geoWithin with a bounding region), ${predicate === "nearest" ? "or raise maxPairs / limits.maxCells" : 'let the grid index narrow them (index: "auto" is the default, and the limit then counts only the pairs it leaves)'}, or raise maxPairs / limits.maxCells.`, { pairs: total, maxPairs });
2043
+ const needsPoints = predicate === "within" || predicate === "dwithin";
2044
+
2045
+ const rightRejected = [];
2046
+ const rshape = [];
2047
+ for (let j = 0; j < right.length; j++) {
2048
+ if (ctx.tick()) yield;
2049
+ const row = right[j];
2050
+ const r = geometryOf(row[rcol]);
2051
+ if (r.problem) {
2052
+ ctx.error({ row: j, side: "right", column: rcol, code: r.problem.code, message: `right: ${r.problem.reason}` });
2053
+ rightRejected.push(row);
2054
+ ctx.exclude({ input: "right", kind: "rejected", code: r.problem.code, reason: r.problem.reason }, j);
2055
+ rshape.push(null);
2056
+ continue;
2057
+ }
2058
+ if (predicate === "within") {
2059
+ if (!polygonsOf(r.g).length) throw new TableError("unsupported-geometry", `geoJoin: the right side of "within" is Polygon or MultiPolygon, but right row ${j} is a ${r.g.type}. For points near points use predicate "dwithin"; for any two shapes that touch, "intersects".`);
2060
+ rshape.push({ g: r.g, box: extentU(r.g) });
2061
+ continue;
2062
+ }
2063
+ if (predicate === "overlaps" && !polygonsOf(r.g).length) throw new TableError("unsupported-geometry", `geoJoin: "overlaps" compares polygons, but right row ${j} is a ${r.g.type}. Use "intersects" for lines and points.`);
2064
+ if (!needsPoints) {
2065
+ rshape.push({ g: r.g, box: extentU(r.g) });
2066
+ continue;
2067
+ }
2068
+ const pts = testPoints(r.g, of);
2069
+ if (!pts.length) throw new TableError("unsupported-geometry", `geoJoin: "dwithin" compares points, but right row ${j} is a ${r.g.type}. Set of: "centroid" to compare by centroid, or use "nearest" / "intersects" for shapes.`);
2070
+ rshape.push({ pts, box: pointsBox(pts) });
2071
+ }
2072
+ const index = indexed ? boxIndex(rshape.map((s) => s?.box ?? null)) : null;
2073
+ const allRight = indexed ? null : rshape.map((s, j) => (s ? j : -1)).filter((j) => j >= 0);
2074
+
2075
+ const rejected = [];
2076
+ const matches = []; // per left row: [[j, distance?]]
2077
+ let tested = 0;
2078
+ for (let i = 0; i < left.length; i++) {
2079
+ if (ctx.tick()) yield;
2080
+ const r = geometryOf(left[i][lcol]);
2081
+ let pts;
2082
+ let g;
2083
+ if (r.problem) ctx.error({ row: i, side: "left", column: lcol, code: r.problem.code, message: `left: ${r.problem.reason}` });
2084
+ else if (needsPoints) {
2085
+ pts = testPoints(r.g, of);
2086
+ if (!pts.length) {
2087
+ const p = unsupported(`"${predicate}"`, r.g, 'set of: "centroid" to test by its centroid, or use "intersects" / "nearest" for shapes');
2088
+ ctx.error({ row: i, side: "left", column: lcol, code: p.code, message: `left: ${p.reason}` });
2089
+ pts = undefined;
2090
+ }
2091
+ } else if (predicate === "overlaps" && !polygonsOf(r.g).length) {
2092
+ const p = unsupported('"overlaps"', r.g, 'use "intersects" for lines and points');
2093
+ ctx.error({ row: i, side: "left", column: lcol, code: p.code, message: `left: ${p.reason}` });
2094
+ } else g = r.g;
2095
+ if (!pts && !g) {
2096
+ matches.push(null);
2097
+ rejected.push(left[i]);
2098
+ ctx.exclude({ input: "left", kind: "rejected", code: ctx.errors.at(-1).code, reason: ctx.errors.at(-1).message }, i);
2099
+ continue;
2100
+ }
2101
+ const qbox = pts ? pointsBox(pts) : extentU(g);
2102
+ let cands = allRight;
2103
+ if (index) {
2104
+ let q = qbox;
2105
+ if (predicate === "dwithin") {
2106
+ const dLat = reach / (EARTH_RADIUS_M * RAD);
2107
+ const lat = Math.min(89.9, Math.max(Math.abs(q[1]), Math.abs(q[3])) + dLat);
2108
+ const dLon = dLat / Math.cos(lat * RAD);
2109
+ q = [q[0] - dLon, q[1] - dLat, q[2] + dLon, q[3] + dLat];
2110
+ }
2111
+ cands = index.query(q);
2112
+ }
2113
+ tested += cands.length;
2114
+ if (indexed && tested > maxPairs) throw new TableError("limit", `geoJoin: more than ${maxPairs} pairs left to test after the grid index (left row ${i}). Filter either side first (geoWithin with a bounding region), or raise maxPairs / limits.maxCells.`, { pairs: tested, maxPairs });
2115
+ const found = [];
2116
+ for (const j of cands) {
2117
+ if (ctx.tick()) yield;
2118
+ const s = rshape[j];
2119
+ if (predicate === "within") {
2120
+ if (pts.every((p) => inBoxU(s.box, p) && inGeometry(s.g, p))) found.push([j]);
2121
+ } else if (predicate === "dwithin") {
2122
+ const d = pointDistance(pts, s.pts);
2123
+ if (d <= reach) found.push([j, d]);
2124
+ } else if (predicate === "intersects") {
2125
+ if (intersectsGeometry(g, s.g)) found.push([j]);
2126
+ } else if (predicate === "overlaps") {
2127
+ if (overlapsGeometry(g, s.g)) found.push([j]);
2128
+ } else {
2129
+ const d = gapBetween(g, s.g);
2130
+ if (d <= reach) found.push([j, d]);
2131
+ }
2132
+ }
2133
+ if (predicate === "nearest") found.sort((a, b) => a[1] - b[1] || a[0] - b[0]).splice(k);
2134
+ if (found.length > 1 && multiple === "error") throw new TableError("duplicate-key", `geoJoin: left row ${i} matches ${found.length} right rows (${found.slice(0, 5).map((f) => f[0]).join(", ")}${found.length > 5 ? ", ..." : ""}); multiple is "error". Use "all" or "first", or make the right features disjoint.`);
2135
+ matches.push(multiple === "first" ? found.slice(0, 1) : found);
2136
+ }
2137
+ const pairs = indexed ? tested : total;
2138
+ const hasD = predicate === "dwithin" || predicate === "nearest";
2139
+
2140
+ const lnames = new Set(left.flatMap((r) => Object.keys(r)));
2141
+ const rcols = [...new Set(right.flatMap((r) => Object.keys(r)))].filter((c) => o.rightGeometry === true || c !== rcol);
2142
+ const suffix = o.suffix ?? "_right";
2143
+ const rname = (c) => (lnames.has(c) ? c + suffix : c);
2144
+ const names = rcols.map(rname);
2145
+ if (new Set([...lnames, ...names]).size !== lnames.size + names.length) throw bad("geoJoin", `the result would have a duplicate column name; change suffix (now ${show(suffix)}).`);
2146
+ const distCol = `distance_${unit}`;
2147
+ const rows = [];
2148
+ const matched = [];
2149
+ const origin = [];
2150
+ const leftOnly = [];
2151
+ const usedRight = new Uint8Array(right.length);
2152
+ let multi = 0;
2153
+ for (let i = 0; i < left.length; i++) {
2154
+ const found = matches[i];
2155
+ if (found === null) continue;
2156
+ if (!found.length) {
2157
+ leftOnly.push(left[i]);
2158
+ if (mode === "left") {
2159
+ const row = { ...left[i] };
2160
+ for (const c of rcols) row[rname(c)] = null;
2161
+ if (hasD) row[distCol] = null;
2162
+ ctx.checkRows(rows.length + 1, "the result");
2163
+ rows.push(row);
2164
+ origin.push({ left: [i], right: [] });
2165
+ } else ctx.exclude({ input: "left", kind: "unmatched", reason: `no right feature ${PREDICATE_WHY[predicate](o.distance, unit)} and mode is "inner"` }, i);
2166
+ continue;
2167
+ }
2168
+ if (found.length > 1) multi++;
2169
+ for (const [j, d] of found) {
2170
+ usedRight[j] = 1;
2171
+ const row = { ...left[i] };
2172
+ for (const c of rcols) row[rname(c)] = Object.prototype.hasOwnProperty.call(right[j], c) ? right[j][c] : null;
2173
+ if (hasD) row[distCol] = d / UNITS.length[unit];
2174
+ ctx.checkRows(rows.length + 1, "the result");
2175
+ rows.push(row);
2176
+ matched.push(row);
2177
+ origin.push({ left: [i], right: [j] });
2178
+ }
2179
+ }
2180
+ ctx.checkCells(rows.length, lnames.size + names.length, "the result");
2181
+ const rightOnly = [];
2182
+ right.forEach((r, j) => {
2183
+ if (!rshape[j] || usedRight[j]) return;
2184
+ rightOnly.push(r);
2185
+ ctx.exclude({ input: "right", kind: "unmatched", reason: `no left feature ${{ within: "is inside it", dwithin: "is near it", intersects: "touches it", overlaps: "overlaps it", nearest: "has it as one of its nearest" }[predicate]}` }, j);
2186
+ });
2187
+ if (multi) ctx.note(`geoJoin: ${multi} left row${multi === 1 ? " matches" : "s match"} more than one right feature (multiple: "${multiple}")${multiple === "all" ? ": it is repeated once per match" : ": only the lowest right position is used"}.`);
2188
+ ctx.note(`geoJoin: ${hasD ? `distances are ${CRS.distance}` : "a point on a polygon's boundary is inside; edges are straight lines in longitude/latitude"}; ${pairs} pair${pairs === 1 ? "" : "s"} tested${indexed ? ` of ${total} (a grid index narrowed them)` : ""} (limit ${maxPairs}).`);
2189
+ return { rows, origin: ctx.trace ? origin : undefined, matched, leftOnly, rightOnly, rejected, rightRejected, pairs };
2190
+ },
2191
+ { inputs: ["left", "right"] },
2192
+ );
2193
+
2194
+ // ── back to GeoJSON ──────────────────────────────────────────────────────
2195
+
2196
+ /**
2197
+ * Rows (with a geometry column) to a FeatureCollection: `{ geojson, rejected, rejections, notes }`. The id
2198
+ * column becomes the feature `id` (when it is a string or number), every other column but the geometry a
2199
+ * property. A row whose geometry is invalid comes out in `rejected` with its reason, never as a broken feature.
2200
+ */
2201
+ function toGeoJSON(rows, options = {}) {
2202
+ if (!Array.isArray(rows)) throw new TableError("bad-input", "toGeoJSON: rows isn't a table (an array of row objects).");
2203
+ const col = columnOf("toGeoJSON", rows, options.geometry);
2204
+ const idCol = options.id ?? "id";
2205
+ const features = [];
2206
+ const rejected = [];
2207
+ const rejections = [];
2208
+ const notes = [];
2209
+ rows.forEach((row, i) => {
2210
+ const r = geometryOf(row[col]);
2211
+ if (r.problem) {
2212
+ rejected.push(row);
2213
+ rejections.push({ index: i, id: row[idCol] ?? null, code: r.problem.code, reason: r.problem.reason });
2214
+ return;
2215
+ }
2216
+ const properties = {};
2217
+ for (const [k, v] of Object.entries(row)) if (k !== col && k !== idCol && v !== undefined) properties[k] = v;
2218
+ const id = row[idCol];
2219
+ features.push({ type: "Feature", ...(typeof id === "string" || (typeof id === "number" && fin(id)) ? { id } : {}), properties, geometry: r.g });
2220
+ });
2221
+ if (rejected.length) notes.push(`${rejected.length} row${rejected.length === 1 ? "" : "s"} left out: their geometry isn't valid (see rejections).`);
2222
+ const source = sourceRecord("toGeoJSON", options.source);
2223
+ return { geojson: { type: "FeatureCollection", ...(source ? { source } : {}), features }, rejected, rejections, notes };
2224
+ }
2225
+
2226
+ // ── what the map view draws ──────────────────────────────────────────────
2227
+
2228
+ /**
2229
+ * The geometry of the first `limit` rows, as the select pane's map draws it: `{ column, shapes: [{ i, g }], problems,
2230
+ * skipped, truncated, coordinates, hash }`. Bounded: shapes past `maxCoordinates` positions are left out and counted
2231
+ * (`truncated`). `hash` changes when any drawn coordinate does. `{ problem }` when no column holds geometry.
2232
+ */
2233
+ function drawable(rows, options = {}) {
2234
+ const limit = options.limit ?? 1000;
2235
+ const maxCoordinates = options.maxCoordinates ?? 100_000;
2236
+ const sample = rows.slice(0, limit);
2237
+ let column = options.geometry || "geometry";
2238
+ const objects = sample.filter(isObj);
2239
+ if (!objects.length) return { problem: "the rows aren't objects with a geometry" };
2240
+ if (!objects.some((r) => Object.prototype.hasOwnProperty.call(r, column))) {
2241
+ if (objects.some((r) => r.type === "Feature" && r.geometry)) column = null; // the rows are Features themselves
2242
+ else return { problem: `no "${column}" column holds geometry (set geometry to the column that does)` };
2243
+ }
2244
+ const shapes = [];
2245
+ const problems = [];
2246
+ let coordinates = 0;
2247
+ let truncated = 0;
2248
+ let hash = 2166136261;
2249
+ const mix = (n) => {
2250
+ hash = Math.imul(hash ^ Math.round(n * 1e6), 16777619) >>> 0;
2251
+ };
2252
+ sample.forEach((row, i) => {
2253
+ const r = geometryOf(isObj(row) ? (column === null ? row : row[column]) : null);
2254
+ if (r.problem) {
2255
+ if (problems.length < 20) problems.push({ i, code: r.problem.code, reason: r.problem.reason });
2256
+ return;
2257
+ }
2258
+ const n = [...positions(r.g)].length;
2259
+ if (coordinates + n > maxCoordinates) {
2260
+ truncated++;
2261
+ return;
2262
+ }
2263
+ coordinates += n;
2264
+ for (const p of positions(r.g)) (mix(p[0]), mix(p[1]));
2265
+ shapes.push({ i, g: { type: r.g.type, coordinates: r.g.coordinates } });
2266
+ });
2267
+ return { column: column ?? "(the row itself)", shapes, problems, skipped: sample.length - shapes.length - truncated, truncated, coordinates, hash: hash.toString(36) };
2268
+ }
2269
+
2270
+ // ── SQL functions ────────────────────────────────────────────────────────
2271
+
2272
+ const fn = (name, f) => {
2273
+ if (!functions.has(name)) functions.set(name, f);
2274
+ };
2275
+ fn("st_distance", (a, b) => distance(a, b));
2276
+ fn("st_area", (g) => area(g));
2277
+ fn("st_length", (g) => length(g));
2278
+ fn("st_within", (g, region) => contains(region, g));
2279
+ fn("st_contains", (region, g) => contains(region, g));
2280
+ fn("st_centroid", (g) => ({ type: "Point", coordinates: centroidOf(use(g)) }));
2281
+ fn("st_intersects", (a, b) => intersectsGeometry(use(a), use(b)));
2282
+ fn("st_gap", (a, b) => gapBetween(use(a), use(b)));
2283
+ fn("st_cell", (g, size = 1) => {
2284
+ const pts = pointsOf(use(g));
2285
+ if (pts.length !== 1) throw new TableError("unsupported-geometry", "geo: ST_CELL is defined for a single Point; take ST_CENTROID of a shape first");
2286
+ return cellOf(pts[0], size);
2287
+ });
2288
+ fn("st_transform", (g, from, to = "EPSG:4326") => reproject(g, { from, to }));
2289
+ fn("st_buffer", (g, meters) => buffer(g, meters));
2290
+ fn("st_x", (g) => {
2291
+ const p = pointsOf(use(g));
2292
+ if (p.length !== 1) throw new TableError("unsupported-geometry", "geo: ST_X is defined for a single Point");
2293
+ return p[0][0];
2294
+ });
2295
+ fn("st_y", (g) => {
2296
+ const p = pointsOf(use(g));
2297
+ if (p.length !== 1) throw new TableError("unsupported-geometry", "geo: ST_Y is defined for a single Point");
2298
+ return p[0][1];
2299
+ });
2300
+
2301
+ t.geoParse = geoParse;
2302
+ t.geoMeasure = geoMeasure;
2303
+ t.geoBuffer = geoBuffer;
2304
+ t.geoWithin = geoWithin;
2305
+ t.geoJoin = geoJoin;
2306
+ t.geoReproject = geoReproject;
2307
+ t.geoCell = geoCell;
2308
+ t.toGeoJSON = toGeoJSON;
2309
+ t.geo = Object.freeze({
2310
+ CRS,
2311
+ EARTH_RADIUS_M,
2312
+ TYPES,
2313
+ validate: (g) => validateGeometry(g),
2314
+ geometryOf,
2315
+ extent: (g) => extentOf(use(g)),
2316
+ centroid: (g) => centroidOf(use(g)),
2317
+ area,
2318
+ length,
2319
+ distance,
2320
+ buffer,
2321
+ contains,
2322
+ intersects: (a, b) => intersectsGeometry(use(a), use(b)),
2323
+ overlaps: (a, b) => {
2324
+ const ga = use(a);
2325
+ const gb = use(b);
2326
+ if (!polygonsOf(ga).length || !polygonsOf(gb).length) throw new TableError("unsupported-geometry", `geo: overlaps compares polygons, not a ${!polygonsOf(ga).length ? ga.type : gb.type}; use intersects for lines and points`);
2327
+ return overlapsGeometry(ga, gb);
2328
+ },
2329
+ gap: (a, b) => gapBetween(use(a), use(b)),
2330
+ reproject,
2331
+ crs: (name) => {
2332
+ const c = crsOf(name);
2333
+ return c ? { code: c.code, kind: c.kind, ...(c.zone ? { zone: c.zone, hemisphere: c.south ? "S" : "N" } : {}) } : null;
2334
+ },
2335
+ cell: (g, size = 1) => {
2336
+ const pts = pointsOf(use(g));
2337
+ if (pts.length !== 1) throw new TableError("unsupported-geometry", "geo: a grid cell is for a single Point; take its centroid first");
2338
+ return cellOf(pts[0], size);
2339
+ },
2340
+ cellBounds,
2341
+ cellNeighbors,
2342
+ drawable,
2343
+ });
2344
+ }