@sirenodeck/sirenodeck 0.2.10 → 0.4.1

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 (71) hide show
  1. package/config-ui/vite.config.ts +2 -0
  2. package/dist/main.mjs +1585 -807
  3. package/dist/{windows-CRWdUgCn.mjs → windows-BCvfQ3PA.mjs} +4 -4
  4. package/frontend/src/App.tsx +3 -0
  5. package/frontend/src/components/Deck.tsx +13 -2
  6. package/frontend/vite.config.ts +2 -0
  7. package/package.json +10 -1
  8. package/src/addon/api.ts +24 -1
  9. package/src/addon/data-directory.ts +52 -0
  10. package/src/api/protocol-internal.ts +5 -0
  11. package/src/builtin-addons/index.ts +0 -1
  12. package/src/builtin-addons/internal-settings/backend.ts +1 -1
  13. package/src/builtin-addons/internal-settings/buttons/brightness/common/frontend.tsx +14 -3
  14. package/src/builtin-addons/internal-settings/buttons/brightness-compact/frontend.tsx +6 -0
  15. package/src/builtin-addons/internal-settings/index.ts +15 -0
  16. package/src/builtin-addons/register-builtins.ts +0 -3
  17. package/src/cli/commands/addon-decks.ts +1 -0
  18. package/src/cli/commands/addon-setup-config.ts +85 -0
  19. package/src/cli/commands/addon-setup.ts +134 -0
  20. package/src/cli/commands/run.ts +57 -11
  21. package/src/cli/commands/service-manager.ts +3 -5
  22. package/src/cli/commands/start.ts +14 -81
  23. package/src/cli/commands/status-probes.ts +126 -0
  24. package/src/cli/commands/status.ts +166 -16
  25. package/src/cli/commands/stop.ts +4 -0
  26. package/src/cli/index.ts +2 -0
  27. package/src/config/environment.ts +44 -0
  28. package/src/config/loader.ts +17 -1
  29. package/src/config/schemas.ts +2 -1
  30. package/src/config/validation.ts +5 -1
  31. package/src/deck/addon-handler-bridge.ts +105 -6
  32. package/src/deck/addon-settings.ts +94 -0
  33. package/src/deck/deck-config.ts +1 -0
  34. package/src/deck/inject-config-ui-button.ts +25 -14
  35. package/src/deck/runtime/runtime.ts +175 -3
  36. package/src/deck/system-back-injection.ts +2 -0
  37. package/src/deck/system-buttons/registry.tsx +1 -0
  38. package/src/deck/system-buttons/types.ts +1 -0
  39. package/src/outputClient/real.ts +18 -1
  40. package/src/render/browser-renderer.ts +68 -12
  41. package/src/render/ws-bridge.ts +2 -0
  42. package/src/system/credentials/native.ts +74 -0
  43. package/src/system/credentials/store.ts +77 -0
  44. package/src/system/providers/notification/windows.ts +4 -4
  45. package/src/themes/default/sirenodeck.json +1 -0
  46. package/src/themes/light/sirenodeck.json +1 -0
  47. package/src/themes/manifest.ts +1 -0
  48. package/src/ui/primitives/Chip.tsx +1 -0
  49. package/src/ui/primitives/StatusIndicator.tsx +36 -0
  50. package/src/ui/primitives/index.ts +1 -0
  51. package/src/ui/surfaces/BinaryToggleSurface.tsx +52 -0
  52. package/src/ui/surfaces/LoadingSurface.tsx +34 -0
  53. package/src/ui/surfaces/index.ts +2 -0
  54. package/src/util/build-fingerprint.ts +32 -0
  55. package/src/util/daemon-control.ts +41 -0
  56. package/src/util/runtime-health.ts +57 -0
  57. package/src/util/runtime-identity.ts +25 -0
  58. package/src/vite/component-identity.ts +48 -0
  59. package/src/builtin-addons/brightness/README.md +0 -51
  60. package/src/builtin-addons/brightness/buttons/brightness/backend.ts +0 -13
  61. package/src/builtin-addons/brightness/buttons/brightness/config.ts +0 -20
  62. package/src/builtin-addons/brightness/buttons/brightness/frontend.tsx +0 -50
  63. package/src/builtin-addons/brightness/domain/macos.ts +0 -46
  64. package/src/builtin-addons/brightness/index.d.ts +0 -5
  65. package/src/builtin-addons/brightness/index.ts +0 -20
  66. package/src/builtin-addons/brightness/poller.ts +0 -27
  67. package/src/builtin-addons/brightness/sirenodeck.json +0 -6
  68. /package/src/builtin-addons/{brightness/providers → internal-settings/brightness-providers}/darwin.ts +0 -0
  69. /package/src/builtin-addons/{brightness/providers → internal-settings/brightness-providers}/index.ts +0 -0
  70. /package/src/builtin-addons/{brightness/providers → internal-settings/brightness-providers}/linux.ts +0 -0
  71. /package/src/builtin-addons/{brightness/providers → internal-settings/brightness-providers}/windows.ts +0 -0
@@ -46,7 +46,7 @@ import {
46
46
  } from "@/deck"
47
47
  import { paginateDeck } from "@/deck/paginate-deck"
48
48
  import { injectConfigUiButton } from "@/deck/inject-config-ui-button"
49
- import { positionSettingsVersionButton } from "@/deck/position-settings-version-button"
49
+ import { buildAddonSettingsDecks } from "@/deck/addon-settings"
50
50
  import { positionButtons } from "@/deck/position-buttons"
51
51
  import { subscribeNavigateDeck } from "@/deck/runtime-subscriptions"
52
52
  import {
@@ -96,6 +96,7 @@ import {
96
96
  import { getHostContext } from "@/deck/host-context"
97
97
  import { StatePublisher } from "@/render/state-publisher"
98
98
  import { startWsBridge, type WsBridge } from "@/render/ws-bridge"
99
+ import { runtimeHealth } from "@/util/runtime-health"
99
100
  import { DEFAULT_BRIDGE_PORT } from "./emulator-mode"
100
101
  import { createConfigMutationService } from "@/config/mutation"
101
102
  import {
@@ -207,6 +208,7 @@ export interface SetupAddonServicesOptions {
207
208
  readonly resolverOptions: ReturnType<typeof buildResolverOptions>
208
209
  /** Optional host callback that re-materializes addon decks (dynamic decks). */
209
210
  readonly requestDeckRebuild?: () => void
211
+ readonly addonServiceConfigs?: ReadonlyMap<string, unknown>
210
212
  }
211
213
 
212
214
  export interface SetupAddonServicesResult {
@@ -245,6 +247,7 @@ export const setupAddonServices = (
245
247
  methods,
246
248
  logger,
247
249
  requestDeckRebuild,
250
+ addonServiceConfigs,
248
251
  } = options
249
252
 
250
253
  const addonBridge = bridgeAddonServices({
@@ -260,6 +263,7 @@ export const setupAddonServices = (
260
263
  bridge,
261
264
  store,
262
265
  methods,
266
+ ...(addonServiceConfigs !== undefined ? { addonServiceConfigs } : {}),
263
267
  ...(requestDeckRebuild !== undefined ? { requestDeckRebuild } : {}),
264
268
  })
265
269
 
@@ -699,6 +703,7 @@ export const buildAddonConfigOverrides = (
699
703
  const {
700
704
  decks: perDeckRaw,
701
705
  defaults,
706
+ service: _service,
702
707
  ...rest
703
708
  } = cfg as {
704
709
  decks?: Record<
@@ -706,6 +711,7 @@ export const buildAddonConfigOverrides = (
706
711
  import("@/cli/commands/addon-decks").AddonDeckOverride
707
712
  >
708
713
  defaults?: { autoShow?: boolean }
714
+ service?: unknown
709
715
  } & Record<string, unknown>
710
716
  // ponytail: key on the loaded addon's manifest name — that's what
711
717
  // materializeAddonDecks looks up. The user wrote `src:` (path or npm
@@ -728,6 +734,21 @@ export const buildAddonConfigOverrides = (
728
734
  return overrides
729
735
  }
730
736
 
737
+ export const buildAddonServiceConfigs = (
738
+ addonEntries: ReadonlyArray<import("@/config/schemas").RawAddonEntry>,
739
+ addonSpecToName: ReadonlyMap<string, string>,
740
+ ): Map<string, unknown> => {
741
+ const configs = new Map<string, unknown>()
742
+ for (const entry of addonEntries) {
743
+ if (typeof entry === "string" || entry.enabled === false) continue
744
+ const name = addonSpecToName.get(entry.src)
745
+ if (name !== undefined && entry.config?.service !== undefined) {
746
+ configs.set(name, entry.config.service)
747
+ }
748
+ }
749
+ return configs
750
+ }
751
+
731
752
  const buildRuntime = (
732
753
  options: RunOptions,
733
754
  loaded: LoadConfigResult,
@@ -897,7 +918,11 @@ const buildRuntime = (
897
918
  config.lock?.buttons,
898
919
  addonConfigOverrides,
899
920
  )
900
- const sourceDecks = positionSettingsVersionButton(materializedDecks, keyCount)
921
+ const sourceDecks = buildAddonSettingsDecks(
922
+ materializedDecks,
923
+ registry.listAddons(),
924
+ keyCount,
925
+ )
901
926
  const allDecsWithSystemButtons = injectSystemButtons(sourceDecks, keyCount, {
902
927
  lockActive,
903
928
  })
@@ -913,7 +938,11 @@ const buildRuntime = (
913
938
  )
914
939
  if (token.length > 0) configUiUrl.searchParams.set("token", token)
915
940
  configUiUrl.hash = "/config"
916
- const runtimeDecks = injectConfigUiButton(allDecks, configUiUrl.toString())
941
+ const runtimeDecks = injectConfigUiButton(
942
+ allDecks,
943
+ configUiUrl.toString(),
944
+ keyCount,
945
+ )
917
946
  const { runtime, methods, pubSub, store } = createDeckRuntime({
918
947
  decks: runtimeDecks,
919
948
  logger,
@@ -990,6 +1019,8 @@ export const applyConfigErrorReplacements = (
990
1019
  path,
991
1020
  deck.id,
992
1021
  position,
1022
+ deck.addonOwner !== undefined &&
1023
+ btn.type.startsWith(`${deck.addonOwner.addonName}:`),
993
1024
  )
994
1025
  if (issues.length === 0) continue
995
1026
 
@@ -1159,12 +1190,16 @@ interface AddonRegistryBundle {
1159
1190
  // full core kit (any @sirenodeck/sirenodeck/ui component). Falls back to the
1160
1191
  // dist entry when src/index.ts doesn't exist (npm-cached third-party
1161
1192
  // addons ship compiled output only).
1162
- const browserFrontendMain = (entry: string): string => {
1193
+ const browserFrontendMain = (entry: string, dedicated = false): string => {
1163
1194
  const dir = dirname(entry)
1164
1195
  // Entry lives in <pkg>/dist (JSON-manifest addons, compiled) or directly
1165
1196
  // in <pkg> (regex-scanned builtins' index.ts). Normalize to pkg root.
1166
1197
  const pkgRoot = basename(dir) === "dist" ? dirname(dir) : dir
1167
- const src = resolvePath(pkgRoot, "src", "index.ts")
1198
+ const src = resolvePath(
1199
+ pkgRoot,
1200
+ "src",
1201
+ dedicated ? "frontend-entry.ts" : "index.ts",
1202
+ )
1168
1203
  return existsSync(src) ? src : entry
1169
1204
  }
1170
1205
 
@@ -1172,7 +1207,12 @@ export const addonSpecFromScanned = (s: ScannedAddon) => ({
1172
1207
  name: s.name,
1173
1208
  frontend:
1174
1209
  s.browserEntry != null
1175
- ? { main: browserFrontendMain(s.browserEntry) }
1210
+ ? {
1211
+ main: browserFrontendMain(
1212
+ s.browserEntry,
1213
+ s.browserEntry !== s.frontendEntry,
1214
+ ),
1215
+ }
1176
1216
  : s.frontendEntry !== null
1177
1217
  ? { main: browserFrontendMain(s.frontendEntry) }
1178
1218
  : undefined,
@@ -1615,10 +1655,10 @@ export const runPipeline = async (options: RunOptions): Promise<void> => {
1615
1655
  // session provider existed; if the OS is locked at boot, re-inject
1616
1656
  // without the n-1 so the deck structure is honest. Re-inject on every
1617
1657
  // subsequent lock transition so the source stays correct.
1658
+ let currentLoadedConfig = loadedConfig
1618
1659
  const reInjectedDecks = (isLocked: boolean): ReadonlyArray<RuntimeDeck> =>
1619
- injectSystemButtons(loaded.sourceDecks, descriptor!.keyCount, {
1620
- lockActive: isLocked,
1621
- })
1660
+ buildRuntime(options, currentLoadedConfig, descriptor!.keyCount, isLocked)
1661
+ .decks
1622
1662
  if (providers.session.getState() === "locked") {
1623
1663
  const reInjected = reInjectedDecks(true)
1624
1664
  runtime.setDecks(reInjected)
@@ -1718,7 +1758,6 @@ export const runPipeline = async (options: RunOptions): Promise<void> => {
1718
1758
  })
1719
1759
 
1720
1760
  const serviceDecks: RuntimeDeck[] = [...decks]
1721
- let currentLoadedConfig = loadedConfig
1722
1761
  const nextMainDeckId = (
1723
1762
  config: typeof currentLoadedConfig.config,
1724
1763
  ): string =>
@@ -1739,7 +1778,7 @@ export const runPipeline = async (options: RunOptions): Promise<void> => {
1739
1778
  }
1740
1779
  const rebuilt = buildRuntime(
1741
1780
  options,
1742
- loadedConfig,
1781
+ currentLoadedConfig,
1743
1782
  descriptor.keyCount,
1744
1783
  providers.session.getState() === "locked",
1745
1784
  ).decks
@@ -1788,6 +1827,10 @@ export const runPipeline = async (options: RunOptions): Promise<void> => {
1788
1827
  keyCount: descriptor.keyCount,
1789
1828
  resolverOptions,
1790
1829
  requestDeckRebuild,
1830
+ addonServiceConfigs: buildAddonServiceConfigs(
1831
+ loadedConfig.config.addons ?? [],
1832
+ loadedConfig.addonSpecToName,
1833
+ ),
1791
1834
  ...(mainDeck !== undefined ? { initialDeck: mainDeck } : {}),
1792
1835
  signal: bridgeSignal.signal,
1793
1836
  store,
@@ -1891,6 +1934,8 @@ export const runPipeline = async (options: RunOptions): Promise<void> => {
1891
1934
  })
1892
1935
 
1893
1936
  currentOutputHandle = outputHandle
1937
+ runtimeHealth.setCore("ready")
1938
+ if (options.emulator === true) runtimeHealth.setRenderer("not-applicable")
1894
1939
  let refreshQueue = Promise.resolve()
1895
1940
 
1896
1941
  // Note: do NOT overwrite the accumulated `trackedPids` Set with the initial
@@ -2107,6 +2152,7 @@ export const runPipeline = async (options: RunOptions): Promise<void> => {
2107
2152
 
2108
2153
  await done
2109
2154
  } finally {
2155
+ runtimeHealth.setCore("stopping")
2110
2156
  unsubscribeBrightnessSettings?.()
2111
2157
  settingsStore?.close()
2112
2158
  if (unregisterSignal !== null) unregisterSignal()
@@ -37,10 +37,6 @@ export const refreshStaleUnit = (
37
37
  !exists(currentScript)
38
38
  )
39
39
  return content
40
- const brewUpgrade =
41
- oldScript.includes("/Cellar/sirenodeck/") &&
42
- currentScript.includes("/Cellar/sirenodeck/")
43
- if (exists(oldScript) && !brewUpgrade) return content
44
40
  return content.replace(
45
41
  match[0],
46
42
  `ExecStart="${nodePath}" "${currentScript}" start`,
@@ -210,7 +206,9 @@ export const invokeManager = async (
210
206
  // still holding throws, so go through the retry.
211
207
  await bootstrapWithRetry(uid, plist, DAEMON_NAME)
212
208
  } else if (action === "stop") {
213
- launchctl("bootout", [`gui/${uid}/${DAEMON_NAME}`])
209
+ if (isJobLoaded(uid, DAEMON_NAME)) {
210
+ launchctl("bootout", [`gui/${uid}/${DAEMON_NAME}`])
211
+ }
214
212
  } else if (action === "restart") {
215
213
  try {
216
214
  launchctl("bootout", [`gui/${uid}/${DAEMON_NAME}`])
@@ -3,7 +3,7 @@ import { execFileSync } from "node:child_process"
3
3
  import { dirname, join, resolve as resolvePath } from "node:path"
4
4
  import { fileURLToPath } from "node:url"
5
5
 
6
- import { confirm, isCancel, select } from "@/cli/prompt"
6
+ import { confirm } from "@/cli/prompt"
7
7
  import type pino from "pino"
8
8
 
9
9
  import {
@@ -409,34 +409,6 @@ const killPortListeners = async (
409
409
  await new Promise((r) => setTimeout(r, 500))
410
410
  }
411
411
 
412
- const promptConflict = async (
413
- pid: number | null,
414
- ): Promise<"restart" | "cancel"> => {
415
- const who = pid === null ? "" : ` with pid ${pid}`
416
- if (!process.stdin.isTTY) {
417
- throw new Error(
418
- `Daemon already running${who} (non-interactive: not stopping)`,
419
- )
420
- }
421
- const answer = await select<"restart" | "cancel">({
422
- message: `Daemon already running${who}.`,
423
- options: [
424
- {
425
- value: "restart",
426
- label: "restart",
427
- hint: "Stop the existing daemon and start a new one",
428
- },
429
- {
430
- value: "cancel",
431
- label: "cancel",
432
- hint: "Exit without changes",
433
- },
434
- ],
435
- })
436
- if (isCancel(answer)) return "cancel"
437
- return answer
438
- }
439
-
440
412
  const stopExisting = async (
441
413
  pid: number,
442
414
  logger: pino.Logger,
@@ -449,23 +421,20 @@ const stopExisting = async (
449
421
  removeStartLock()
450
422
  return
451
423
  }
424
+ if (!isOurDaemon(pid))
425
+ throw new Error(`Refusing to stop unverified daemon PID ${pid}`)
452
426
  logger.info({ pid }, "stopping existing daemon")
453
427
  try {
454
428
  process.kill(pid, "SIGTERM")
455
429
  } catch (err) {
456
- logger.warn({ err, pid }, "failed to send SIGTERM to existing daemon")
430
+ throw new Error(`Failed to stop existing daemon ${pid}`, { cause: err })
457
431
  }
458
- const deadline = Date.now() + 5_000
432
+ const deadline = Date.now() + 20_000
459
433
  while (Date.now() < deadline && isRunning(pid)) {
460
434
  await new Promise((r) => setTimeout(r, 100))
461
435
  }
462
436
  if (isRunning(pid)) {
463
- logger.warn({ pid }, "existing daemon did not exit in 5s, sending SIGKILL")
464
- try {
465
- process.kill(pid, "SIGKILL")
466
- } catch (err) {
467
- logger.warn({ err, pid }, "failed to send SIGKILL to existing daemon")
468
- }
437
+ throw new Error(`Existing daemon ${pid} did not exit after SIGTERM`)
469
438
  }
470
439
  await terminateChildren({ logger, timeoutMs: 2_000 })
471
440
  removePidFile()
@@ -982,57 +951,21 @@ const start = async (options: StartOptions): Promise<StartLaunchResult> => {
982
951
  // children as strangers. Asking first also means the answer can come from
983
952
  // the instance lock, which is the one source that cannot be stale: a daemon
984
953
  // holds it for exactly as long as it is alive.
954
+ if (isUnitInstalled()) await invokeManager({ action: "stop", logger })
985
955
  const existing = readPid()
986
956
  const lockHeld = await isSocketLive(instanceLockPath(resolveDaemonPaths()))
987
957
  if (lockHeld || (existing !== null && isRunning(existing))) {
988
- const action = await promptConflict(existing)
989
- if (action === "cancel") {
990
- logger.info("start cancelled")
991
- return "cancelled"
992
- }
993
- // ponytail: a supervised daemon cannot be restarted by killing it. launchd
994
- // with KeepAlive brings it back in about two seconds — measured — and the
995
- // daemon we would spawn here loses the race for the instance lock and dies
996
- // with "another sirenodeck daemon is already running". Before the lock
997
- // existed the same race simply produced TWO daemons, which is how this
998
- // machine ended up with one from 09:39 and another from 16:54 fighting
999
- // over the same ports. The manager owns the process, so the manager is
1000
- // what restarts it; the config and flags go through the state files, the
1001
- // same way `startProduction` hands them over.
1002
- if (isUnitInstalled()) {
1003
- const resolvedRestart = resolveConfigPath(options)
1004
- writeConfigPath(resolvedRestart.path)
1005
- writeFlags(buildRuntimeFlags(options))
1006
- logger.info(
1007
- { configPath: resolvedRestart.path },
1008
- "start: daemon is service-managed — restarting through the service manager",
1009
- )
1010
- await invokeManager({ action: "restart", logger })
1011
- const deadline = Date.now() + 10_000
1012
- let restarted: number | null = null
1013
- while (Date.now() < deadline) {
1014
- await new Promise((r) => setTimeout(r, 200))
1015
- const pid = readPid()
1016
- if (pid !== null && pid !== existing && isRunning(pid)) {
1017
- restarted = pid
1018
- break
1019
- }
1020
- }
1021
- logger.info(
1022
- { pid: restarted },
1023
- restarted === null
1024
- ? "start: service manager restarted the daemon (pid not yet visible)"
1025
- : "start: daemon restarted by the service manager",
958
+ if (lockHeld && (existing === null || !isRunning(existing)))
959
+ throw new Error(
960
+ "A daemon holds the instance lock but has no live PID; refusing to stop an unidentified process",
1026
961
  )
1027
- return "started"
1028
- }
1029
962
  if (existing !== null) await stopExisting(existing, logger)
1030
963
  else
1031
- // The lock is held but nothing wrote a pid file. There is no process to
1032
- // signal by pid, so the port reap below is what clears it.
1033
- logger.warn(
1034
- "start: a daemon holds the instance lock but left no pid file — falling back to the port reap",
964
+ throw new Error(
965
+ "A daemon holds the instance lock but has no PID; refusing to stop an unidentified process",
1035
966
  )
967
+ if (await isSocketLive(instanceLockPath(resolveDaemonPaths())))
968
+ throw new Error("The previous daemon still holds the instance lock")
1036
969
  removePidFile()
1037
970
  removeDaemonControl(resolveDaemonPaths())
1038
971
  removeRuntimeStateFile()
@@ -0,0 +1,126 @@
1
+ import WebSocket from "ws"
2
+ import { PROTOCOL_VERSION } from "@/render/protocol"
3
+
4
+ export type ProbeResult = "responding" | "unreachable" | "unknown"
5
+ export interface BuildIdentity {
6
+ version: string
7
+ buildId: string | null
8
+ }
9
+ const parseIdentity = (value: unknown): BuildIdentity | null => {
10
+ if (!value || typeof value !== "object") return null
11
+ const v = value as Record<string, unknown>
12
+ if (
13
+ typeof v.version !== "string" ||
14
+ !(typeof v.buildId === "string" || v.buildId === null)
15
+ )
16
+ return null
17
+ return { version: v.version, buildId: v.buildId }
18
+ }
19
+
20
+ export const probeWebIdentity = async (
21
+ value: string,
22
+ component: "frontend" | "config-ui",
23
+ ): Promise<BuildIdentity | null> => {
24
+ const base = localUrl(value, ["http:", "https:"])
25
+ if (!base) return null
26
+ try {
27
+ const response = await fetch(
28
+ new URL("/assets/sirenodeck-build.json", base),
29
+ { signal: AbortSignal.timeout(1500), redirect: "manual" },
30
+ )
31
+ if (
32
+ !response.ok ||
33
+ !response.headers.get("content-type")?.includes("application/json")
34
+ )
35
+ return null
36
+ const body: unknown = await response.json()
37
+ if (
38
+ !body ||
39
+ typeof body !== "object" ||
40
+ !("component" in body) ||
41
+ body.component !== component
42
+ )
43
+ return null
44
+ return parseIdentity(body)
45
+ } catch {
46
+ return null
47
+ }
48
+ }
49
+
50
+ // Only contact local endpoints: runtime state may be stale or externally supplied.
51
+ const localUrl = (value: string, protocols: readonly string[]): URL | null => {
52
+ try {
53
+ const url = new URL(value)
54
+ if (!protocols.includes(url.protocol)) return null
55
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) return null
56
+ return url
57
+ } catch {
58
+ return null
59
+ }
60
+ }
61
+
62
+ export const probeHttp = async (value: string): Promise<ProbeResult> => {
63
+ const url = localUrl(value, ["http:", "https:"])
64
+ if (!url) return "unknown"
65
+ try {
66
+ const response = await fetch(url, {
67
+ signal: AbortSignal.timeout(1500),
68
+ redirect: "manual",
69
+ })
70
+ return response.ok ? "responding" : "unreachable"
71
+ } catch {
72
+ return "unreachable"
73
+ }
74
+ }
75
+
76
+ export const probeBridgeInfo = (
77
+ value: string,
78
+ token: string | null,
79
+ ): Promise<{ status: ProbeResult; identity: BuildIdentity | null }> => {
80
+ const url = localUrl(value, ["ws:", "wss:"])
81
+ if (!url || token === null)
82
+ return Promise.resolve({ status: "unknown", identity: null })
83
+ return new Promise((resolve) => {
84
+ const socket = new WebSocket(url)
85
+ const timer = setTimeout(() => finish("unreachable"), 1500)
86
+ let finished = false
87
+ const finish = (
88
+ result: ProbeResult,
89
+ identity: BuildIdentity | null = null,
90
+ ): void => {
91
+ if (finished) return
92
+ finished = true
93
+ clearTimeout(timer)
94
+ socket.terminate()
95
+ resolve({ status: result, identity })
96
+ }
97
+ socket.on("open", () =>
98
+ socket.send(
99
+ JSON.stringify({ type: "hello", version: PROTOCOL_VERSION, token }),
100
+ ),
101
+ )
102
+ socket.on("message", (data) => {
103
+ try {
104
+ const message = JSON.parse(data.toString()) as {
105
+ type?: string
106
+ version?: number
107
+ build?: unknown
108
+ }
109
+ if (message.type === "hello-ack")
110
+ finish(
111
+ message.version === PROTOCOL_VERSION ? "responding" : "unreachable",
112
+ parseIdentity(message.build),
113
+ )
114
+ } catch {
115
+ finish("unreachable")
116
+ }
117
+ })
118
+ socket.on("error", () => finish("unreachable"))
119
+ socket.on("close", () => finish("unreachable"))
120
+ })
121
+ }
122
+
123
+ export const probeBridge = async (
124
+ value: string,
125
+ token: string | null,
126
+ ): Promise<ProbeResult> => (await probeBridgeInfo(value, token)).status