@tafrahq/wt-tunnel-client 0.0.0-stage → 0.11.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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/dist/bin.js +15 -0
  4. package/dist/bin.js.map +1 -0
  5. package/dist/cli-commands.js +27 -0
  6. package/dist/cli-commands.js.map +1 -0
  7. package/dist/cli-provision.js +25 -0
  8. package/dist/cli-provision.js.map +1 -0
  9. package/dist/cli-status.js +19 -0
  10. package/dist/cli-status.js.map +1 -0
  11. package/dist/cli-workspace.js +38 -0
  12. package/dist/cli-workspace.js.map +1 -0
  13. package/dist/cli-worktree.js +40 -0
  14. package/dist/cli-worktree.js.map +1 -0
  15. package/dist/cli.js +9 -0
  16. package/dist/cli.js.map +1 -0
  17. package/dist/config.js +70 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/domain.js +26 -0
  20. package/dist/domain.js.map +1 -0
  21. package/dist/errno.js +6 -0
  22. package/dist/errno.js.map +1 -0
  23. package/dist/errors.js +7 -0
  24. package/dist/errors.js.map +1 -0
  25. package/dist/exec.js +18 -0
  26. package/dist/exec.js.map +1 -0
  27. package/dist/files.js +18 -0
  28. package/dist/files.js.map +1 -0
  29. package/dist/frpc-binary.js +16 -0
  30. package/dist/frpc-binary.js.map +1 -0
  31. package/dist/frpc-config.js +47 -0
  32. package/dist/frpc-config.js.map +1 -0
  33. package/dist/packages/binaries/src/frp.js +45 -0
  34. package/dist/packages/binaries/src/frp.js.map +1 -0
  35. package/dist/packages/binaries/src/install.js +110 -0
  36. package/dist/packages/binaries/src/install.js.map +1 -0
  37. package/dist/packages/contract/src/bin.js +20 -0
  38. package/dist/packages/contract/src/bin.js.map +1 -0
  39. package/dist/packages/contract/src/index.js +12 -0
  40. package/dist/packages/contract/src/index.js.map +1 -0
  41. package/dist/ports.js +121 -0
  42. package/dist/ports.js.map +1 -0
  43. package/dist/processes.js +118 -0
  44. package/dist/processes.js.map +1 -0
  45. package/dist/provision-frpc.js +100 -0
  46. package/dist/provision-frpc.js.map +1 -0
  47. package/dist/provision-ports.js +75 -0
  48. package/dist/provision-ports.js.map +1 -0
  49. package/dist/provision.js +28 -0
  50. package/dist/provision.js.map +1 -0
  51. package/dist/state.js +53 -0
  52. package/dist/state.js.map +1 -0
  53. package/dist/worktree.js +25 -0
  54. package/dist/worktree.js.map +1 -0
  55. package/llms.txt +33 -0
  56. package/package.json +64 -3
  57. package/src/bin.ts +14 -0
  58. package/src/cli-commands.ts +40 -0
  59. package/src/cli-provision.ts +34 -0
  60. package/src/cli-status.ts +29 -0
  61. package/src/cli-workspace.ts +78 -0
  62. package/src/cli-worktree.ts +62 -0
  63. package/src/cli.ts +15 -0
  64. package/src/config.ts +101 -0
  65. package/src/domain.ts +51 -0
  66. package/src/errno.ts +5 -0
  67. package/src/errors.ts +13 -0
  68. package/src/exec.ts +18 -0
  69. package/src/files.ts +20 -0
  70. package/src/frpc-binary.ts +27 -0
  71. package/src/frpc-config.ts +69 -0
  72. package/src/ports.ts +177 -0
  73. package/src/processes.ts +163 -0
  74. package/src/provision-frpc.ts +152 -0
  75. package/src/provision-ports.ts +116 -0
  76. package/src/provision.ts +41 -0
  77. package/src/resource.ts +28 -0
  78. package/src/state.ts +87 -0
  79. package/src/worktree.ts +52 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tafra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # wt-tunnel-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **wt-tunnel-client is a command-line tool that gives each git worktree its own private HTTPS URLs through a tunnel server you run yourself.** Run `wt-tunnel-client worktree add myproject feat-x` in a worktree and your dev servers open at `https://app.feat-x.dev.example.com` in any browser, after a sign-in (Google, GitHub, Microsoft or Cloudflare Access) that only the people you allow can pass.
4
+
5
+ The URLs have no port, the apps stay plain HTTP on `127.0.0.1`, and the dev machine needs no root access and opens no port. Each worktree runs one `frpc`, which connects out to the server.
6
+
7
+ ```
8
+ browser https://app.feat-x.dev.example.com
9
+ server Caddy :443 ends TLS, asks the auth service, then hands the request to frps
10
+ frps routes by Host to the frpc that registered it
11
+ frpc (this worktree) app.feat-x.dev.example.com → http://127.0.0.1:4123
12
+ ```
13
+
14
+ [docs/server-mode.md](https://github.com/tafrahq/wt-tunnel/blob/main/docs/server-mode.md) describes the design and the sign-in flow. [apps/cli/README.md](https://github.com/tafrahq/wt-tunnel/blob/main/apps/cli/README.md) deploys a server to Fly.io, and [apps/server/README.md](https://github.com/tafrahq/wt-tunnel/blob/main/apps/server/README.md) runs it anywhere else.
15
+
16
+ ## Install
17
+
18
+ The package is published to npm. It needs Node.js 26 or later.
19
+
20
+ ```sh
21
+ npm install -g @tafrahq/wt-tunnel-client # or add it as a devDependency
22
+ ```
23
+
24
+ To install without a GitHub token, build it from a checkout, as the [root README](https://github.com/tafrahq/wt-tunnel#install) shows.
25
+
26
+ Up to 0.4.0 the client was published as `@tafrahq/wt-tunnel`; from 0.5.0 that name is the server setup CLI, so install `@tafrahq/wt-tunnel-client`.
27
+
28
+ Requirements:
29
+
30
+ - Node.js 26 or later.
31
+ - Linux or macOS, on amd64 or arm64, for the machine that runs the worktrees. Windows is not supported.
32
+ - A running wt-tunnel server, and its tunnel token.
33
+
34
+ ## Configure
35
+
36
+ Put `wt-tunnel.json` at the repository root and commit it, so every worktree checks it out:
37
+
38
+ ```json
39
+ {
40
+ "domain": "dev.example.com",
41
+ "server": { "host": "wt-tunnel.example.com" },
42
+ "apps": {
43
+ "app": { "portEnv": "APP_PORT" },
44
+ "api": { "portEnv": "API_PORT" },
45
+ "db": { "portEnv": "DB_PORT", "route": false }
46
+ }
47
+ }
48
+ ```
49
+
50
+ | Field | Default | Meaning |
51
+ | ------------- | -------- | -------------------------------------------------------------------------------------- |
52
+ | `domain` | required | Parent domain of the URLs. It must be one of the server's `domains`. |
53
+ | `server.host` | required | The tunnel server's host name. An IP address also works. |
54
+ | `server.port` | `7000` | The port where the server accepts frpc. |
55
+ | `apps` | required | One entry per service. `portEnv` names the variable that receives its port. See below. |
56
+
57
+ Each entry in `apps` accepts:
58
+
59
+ | Field | Default | Meaning |
60
+ | --------- | -------- | ------------------------------------------------------------------------------------------------------ |
61
+ | `portEnv` | required | Environment variable that receives the service's port, such as `APP_PORT`. |
62
+ | `route` | `true` | `false` for services that need a port but no URL, such as a database. |
63
+ | `port` | reserved | A fixed port, if the service must keep a known one. `worktree add` fails if another worktree holds it. |
64
+
65
+ Each app is served at `https://<label>.<worktree>.<domain>`. An app labelled `root` is served at the bare worktree host, `https://<worktree>.<domain>`, which suits a site with a single app:
66
+
67
+ ```json
68
+ {
69
+ "domain": "dev.example.com",
70
+ "server": { "host": "wt-tunnel.example.com" },
71
+ "apps": { "root": { "portEnv": "PORT" }, "api": { "portEnv": "API_PORT" } }
72
+ }
73
+ ```
74
+
75
+ This gives `https://feat-x.dev.example.com` and `https://api.feat-x.dev.example.com`.
76
+
77
+ Set `WT_TUNNEL_SERVER_TOKEN` to the server's tunnel token (`tunnelToken` in its config). wt-tunnel-client passes it to frpc in the environment and never writes it to disk.
78
+
79
+ ## Trust the server's certificate
80
+
81
+ The server signs its certificates with its own root CA, so no worktree name ever appears in a public Certificate Transparency log. Each device that opens the URLs must trust that root once. It is name-constrained to the dev domains, so it can vouch for nothing else.
82
+
83
+ The easiest way is to open `https://<authHost>/ca` on the device, where `<authHost>` is the server's sign-in host (the host the sign-in page redirects to). The page shows the root's fingerprint and permitted names, downloads the certificate (or, on iPhone and iPad, a profile), and lists the steps for each platform with yours first. To do it by hand with the deployment's `ca.crt`:
84
+
85
+ - **macOS.** `sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ca.crt`.
86
+ - **iOS and iPadOS.** Open the file in Safari, install the profile from **Settings** > **Profile Downloaded**, then turn on full trust in **Settings** > **General** > **About** > **Certificate Trust Settings**.
87
+ - **Linux.** On Debian and Ubuntu, copy it to `/usr/local/share/ca-certificates/wt-tunnel.crt` and run `sudo update-ca-certificates`. On Fedora and RHEL, copy it to `/etc/pki/ca-trust/source/anchors/` and run `sudo update-ca-trust`. Some browsers keep their own certificate store.
88
+ - **Windows.** Open the file, select **Install Certificate**, choose **Current User**, and place it in **Trusted Root Certification Authorities**.
89
+
90
+ ## Commands
91
+
92
+ wt-tunnel-client never runs git and never picks names. Create the git worktree yourself, then name the project and the worktree:
93
+
94
+ ```sh
95
+ git worktree add .worktrees/feat-x && cd .worktrees/feat-x && wt-tunnel-client worktree add myproject feat-x
96
+ ```
97
+
98
+ ```sh
99
+ wt-tunnel-client worktree add <project> <worktree>
100
+ ```
101
+
102
+ Provisions the worktree root, which is the nearest directory at or above the current one that holds `wt-tunnel.json`. It reserves the worktree's ports, writes `.wt-tunnel/frpc.toml` with one HTTP proxy per routed app, starts `frpc`, and waits until the server has accepted every host. It prints the URLs and ports. Both names must be DNS labels (lowercase letters, digits and interior hyphens, at most 63 characters); wt-tunnel-client rejects other names and never rewrites them. Running it again with the same names is safe. If the root is already provisioned under other names, the command fails; run `wt-tunnel-client worktree remove` first.
103
+
104
+ If the server refuses a host, for example because another worktree already serves it, the command stops frpc and fails, naming the host and the reason.
105
+
106
+ ```sh
107
+ wt-tunnel-client worktree remove
108
+ ```
109
+
110
+ Stops frpc, releases the ports, and deletes `.wt-tunnel/`. It reads the names from the root's state. Then remove the checkout yourself with `git worktree remove .worktrees/feat-x`.
111
+
112
+ Run these from inside a provisioned worktree:
113
+
114
+ ```sh
115
+ wt-tunnel-client up # provision and start this worktree, for example after a reboot
116
+ wt-tunnel-client down # stop frpc, keep the ports
117
+ wt-tunnel-client status # server, frpc state (running / stopped / stale), URLs
118
+ eval "$(wt-tunnel-client env)" # export APP_PORT=… for your dev servers
119
+ ```
120
+
121
+ These commands fail with ``run `wt-tunnel-client worktree add <project> <worktree>` first`` in a root that is not provisioned. If the config has not changed, `up` leaves a running frpc alone; otherwise it restarts frpc with the new config.
122
+
123
+ The dev servers must listen on `127.0.0.1` at their allocated ports. For example, a Vite app can use `vite --host 127.0.0.1 --port "$APP_PORT" --strictPort`. Vite must also accept the hostname: add `server.allowedHosts: ['.dev.example.com']` to its config. WebSocket upgrades pass through, so HMR works.
124
+
125
+ ### Ports and URLs between services
126
+
127
+ wt-tunnel-client picks every port at `worktree add`, keeps it for the life of the worktree, and writes it to `.wt-tunnel/env`, together with `WT_TUNNEL_HOST=<worktree>.<domain>`.
128
+
129
+ Ports are reserved per user in `~/.local/state/wt-tunnel/ports/`, one file per port naming the worktree that owns it. A stopped worktree keeps its ports, so another worktree is never handed them. Reserved ports come from 20000-29999, below the range Linux uses for outgoing connections. `worktree remove` releases them, and reservations of a worktree deleted without `remove` are reclaimed automatically.
130
+
131
+ Write service URLs once in `mise.toml`. mise fills in the ports from the env file, in every worktree:
132
+
133
+ ```toml
134
+ [env]
135
+ _.file = { path = ".wt-tunnel/env", tools = false }
136
+ DATABASE_URL = "postgres://127.0.0.1:{{ env.DB_PORT | default(value='') }}/app"
137
+ API_URL = "http://127.0.0.1:{{ env.API_PORT | default(value='') }}"
138
+ VITE_API_URL = "https://api.{{ env.WT_TUNNEL_HOST | default(value='localhost') }}"
139
+ ```
140
+
141
+ Services on the dev machine talk to each other over `127.0.0.1`. The browser uses the `https://<app>.<worktree>.<domain>` names.
142
+
143
+ ## The frpc binary
144
+
145
+ On first use, wt-tunnel-client downloads frp v0.71.1 for the platform from GitHub. It checks the download against a SHA-256 pinned in the source, then installs frpc in `$XDG_CACHE_HOME/wt-tunnel/frp/0.71.1/` (by default `~/.cache` on Linux and `~/Library/Caches` on macOS). To use your own frpc binary, set `WT_TUNNEL_FRPC`.
146
+
147
+ ## Local state
148
+
149
+ Local state lives in `<worktree root>/.wt-tunnel/`, which ignores itself in git. It contains:
150
+
151
+ - `state.json`, with the project and worktree names and the reserved ports
152
+ - `env`
153
+ - `frpc.toml`, without the token
154
+ - `frpc.pid` and `frpc.log`
155
+
156
+ The frpc log records each host the server accepted or refused. It is the first place to look when a URL does not load.
157
+
158
+ ## Limits
159
+
160
+ - Two projects that share a `domain` cannot use the same worktree name at the same time. The server refuses the second worktree's hosts. Projects with different domains can use the same worktree name.
161
+ - Every URL is reachable from the internet, behind the sign-in. The server admits only the emails and email domains in its `allow` list.
162
+
163
+ ## Development
164
+
165
+ This package is `apps/client` in the [wt-tunnel monorepo](https://github.com/tafrahq/wt-tunnel/blob/main/README.md), which describes how to install, check and build it. `nub run build` here runs tsdown unbundled: one dist file per source file, with the dependencies external. The workspace-only `@tafrahq/wt-tunnel-contract` package is compiled into `dist/`, so it is not a dependency of the published package.
166
+
167
+ The package ships the built `dist/`, the TypeScript sources in `src/` (source maps point at them), and `llms.txt`, the same layout Effect uses for its packages.
168
+
169
+ Releases publish this package together with the server and the `wt-tunnel` CLI, at one version. [CONTRIBUTING.md](https://github.com/tafrahq/wt-tunnel/blob/main/CONTRIBUTING.md#releasing) describes how.
package/dist/bin.js ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { binProgram } from "./packages/contract/src/bin.js";
3
+ import { run } from "./cli.js";
4
+ import { NodeRuntime, NodeServices } from "@effect/platform-node";
5
+ import { Effect } from "effect";
6
+ // src/bin.ts
7
+ const program = binProgram({
8
+ expected: "WtTunnelError",
9
+ name: "wt-tunnel-client",
10
+ url: import.meta.url
11
+ }, run);
12
+ NodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)));
13
+ export {};
14
+
15
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\n// fallow-ignore-file coverage-gaps -- only hands cli.ts's run to NodeRuntime; cli.test.ts runs run in-process, and packages/contract/src/bin.test.ts tests binProgram\nimport { NodeRuntime, NodeServices } from '@effect/platform-node';\nimport { binProgram } from '@tafrahq/wt-tunnel-contract/bin';\nimport { Effect } from 'effect';\n\nimport { run } from './cli.ts';\n\nconst program = binProgram(\n { expected: 'WtTunnelError', name: 'wt-tunnel-client', url: import.meta.url },\n run,\n);\n\nNodeRuntime.runMain(program.pipe(Effect.provide(NodeServices.layer)));\n"],"mappings":";;;;;;AAQA,MAAM,UAAU,WACd;CAAE,UAAU;CAAiB,MAAM;CAAoB,KAAK,YAAY;AAAI,GAC5E,GACF;AAEA,YAAY,QAAQ,QAAQ,KAAK,OAAO,QAAQ,aAAa,KAAK,CAAC,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { WtTunnelError } from "./errors.js";
2
+ import { pathExists } from "./files.js";
3
+ import { currentWorktreeCommand, envLines } from "./cli-workspace.js";
4
+ import { stopProcess } from "./processes.js";
5
+ import { provisionUp } from "./cli-provision.js";
6
+ import { status } from "./cli-status.js";
7
+ import { Console, Effect } from "effect";
8
+ // src/cli-commands.ts
9
+ const up = currentWorktreeCommand("up", "Provision and start this worktree (for example after a reboot)", ({ config, state, worktree }) => provisionUp({
10
+ config,
11
+ worktree
12
+ }, state));
13
+ const down = currentWorktreeCommand("down", "Stop this worktree's frpc, keep its ports", ({ worktree }) => stopProcess(worktree.stateDir, "frpc").pipe(Effect.andThen(Console.log("Stopped frpc. Run wt-tunnel-client up to start again."))));
14
+ const env = currentWorktreeCommand("env", "Print shell exports for the allocated ports: eval \"$(wt-tunnel-client env)\"", ({ worktree }) => Effect.gen(function* printExports() {
15
+ if (!(yield* Effect.promise(() => pathExists(worktree.envFile)))) yield* new WtTunnelError({ message: "No ports allocated yet. Run wt-tunnel-client up." });
16
+ const lines = yield* envLines(worktree);
17
+ yield* Effect.all(lines.map((line) => Console.log(`export ${line}`)));
18
+ }));
19
+ const worktreeCommands = [
20
+ up,
21
+ down,
22
+ status,
23
+ env
24
+ ];
25
+ export { worktreeCommands };
26
+
27
+ //# sourceMappingURL=cli-commands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-commands.js","names":[],"sources":["../src/cli-commands.ts"],"sourcesContent":["import { Console, Effect } from 'effect';\n\nimport { provisionUp } from './cli-provision.ts';\nimport { status } from './cli-status.ts';\nimport { currentWorktreeCommand, envLines } from './cli-workspace.ts';\nimport { WtTunnelError } from './errors.ts';\nimport { pathExists } from './files.ts';\nimport { stopProcess } from './processes.ts';\n\nconst up = currentWorktreeCommand(\n 'up',\n 'Provision and start this worktree (for example after a reboot)',\n ({ config, state, worktree }) => provisionUp({ config, worktree }, state),\n);\n\nconst down = currentWorktreeCommand(\n 'down',\n \"Stop this worktree's frpc, keep its ports\",\n ({ worktree }) =>\n stopProcess(worktree.stateDir, 'frpc').pipe(\n Effect.andThen(Console.log('Stopped frpc. Run wt-tunnel-client up to start again.')),\n ),\n);\n\nconst env = currentWorktreeCommand(\n 'env',\n 'Print shell exports for the allocated ports: eval \"$(wt-tunnel-client env)\"',\n ({ worktree }) =>\n Effect.gen(function* printExports() {\n if (!(yield* Effect.promise(() => pathExists(worktree.envFile)))) {\n yield* new WtTunnelError({ message: 'No ports allocated yet. Run wt-tunnel-client up.' });\n }\n const lines = yield* envLines(worktree);\n yield* Effect.all(lines.map((line) => Console.log(`export ${line}`)));\n }),\n);\n\nconst worktreeCommands = [up, down, status, env] as const;\n\nexport { worktreeCommands };\n"],"mappings":";;;;;;;;AASA,MAAM,KAAK,uBACT,MACA,mEACC,EAAE,QAAQ,OAAO,eAAe,YAAY;CAAE;CAAQ;AAAS,GAAG,KAAK,CAC1E;AAEA,MAAM,OAAO,uBACX,QACA,8CACC,EAAE,eACD,YAAY,SAAS,UAAU,MAAM,CAAC,CAAC,KACrC,OAAO,QAAQ,QAAQ,IAAI,uDAAuD,CAAC,CACrF,CACJ;AAEA,MAAM,MAAM,uBACV,OACA,kFACC,EAAE,eACD,OAAO,IAAI,UAAU,eAAe;CAClC,IAAI,EAAE,OAAO,OAAO,cAAc,WAAW,SAAS,OAAO,CAAC,IAC5D,OAAO,IAAI,cAAc,EAAE,SAAS,mDAAmD,CAAC;CAE1F,MAAM,QAAQ,OAAO,SAAS,QAAQ;CACtC,OAAO,OAAO,IAAI,MAAM,KAAK,SAAS,QAAQ,IAAI,UAAU,MAAM,CAAC,CAAC;AACtE,CAAC,CACL;AAEA,MAAM,mBAAmB;CAAC;CAAI;CAAM;CAAQ;AAAG"}
@@ -0,0 +1,25 @@
1
+ import { writeState } from "./state.js";
2
+ import { envLines, prepareStateDir, urls } from "./cli-workspace.js";
3
+ import { serverEndpoint } from "./frpc-config.js";
4
+ import { frpcLaunch } from "./provision-frpc.js";
5
+ import { ensureAll } from "./provision.js";
6
+ import { Console, Effect } from "effect";
7
+ // src/cli-provision.ts
8
+ const printSummary = (context, state) => Effect.gen(function* printUrlsAndPorts() {
9
+ const { config, worktree } = context;
10
+ yield* Console.log(`\nWorktree ${state.worktree}, frpc to ${serverEndpoint(config.server)}`);
11
+ yield* Effect.all(urls(context, state).map(({ url, port }) => Console.log(` ${url} → http://127.0.0.1:${port}`)));
12
+ yield* Console.log(`\nStart your dev servers with these ports (also in ${worktree.envFile}):`);
13
+ const lines = yield* envLines(worktree);
14
+ yield* Effect.all(lines.map((line) => Console.log(` ${line}`)));
15
+ });
16
+ /** Checks for the token and frpc before anything of the worktree is created. */
17
+ const provisionUp = (context, initial) => Effect.gen(function* checkProvisionPrint() {
18
+ yield* frpcLaunch;
19
+ yield* prepareStateDir(context.worktree);
20
+ yield* writeState(context.worktree.stateFile, initial);
21
+ yield* printSummary(context, yield* ensureAll(context, initial));
22
+ });
23
+ export { provisionUp };
24
+
25
+ //# sourceMappingURL=cli-provision.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-provision.js","names":[],"sources":["../src/cli-provision.ts"],"sourcesContent":["import { Console, Effect } from 'effect';\n\nimport { envLines, prepareStateDir, urls } from './cli-workspace.ts';\nimport { serverEndpoint } from './frpc-config.ts';\nimport { frpcLaunch } from './provision-frpc.ts';\nimport { ensureAll } from './provision.ts';\nimport type { ProvisionContext } from './resource.ts';\nimport { writeState } from './state.ts';\nimport type { WorktreeState } from './state.ts';\n\nconst printSummary = (context: ProvisionContext, state: WorktreeState) =>\n Effect.gen(function* printUrlsAndPorts() {\n const { config, worktree } = context;\n yield* Console.log(`\\nWorktree ${state.worktree}, frpc to ${serverEndpoint(config.server)}`);\n yield* Effect.all(\n urls(context, state).map(({ url, port }) =>\n Console.log(` ${url} → http://127.0.0.1:${port}`),\n ),\n );\n yield* Console.log(`\\nStart your dev servers with these ports (also in ${worktree.envFile}):`);\n const lines = yield* envLines(worktree);\n yield* Effect.all(lines.map((line) => Console.log(` ${line}`)));\n });\n\n/** Checks for the token and frpc before anything of the worktree is created. */\nconst provisionUp = (context: ProvisionContext, initial: WorktreeState) =>\n Effect.gen(function* checkProvisionPrint() {\n yield* frpcLaunch;\n yield* prepareStateDir(context.worktree);\n yield* writeState(context.worktree.stateFile, initial);\n yield* printSummary(context, yield* ensureAll(context, initial));\n });\n\nexport { provisionUp };\n"],"mappings":";;;;;;;AAUA,MAAM,gBAAgB,SAA2B,UAC/C,OAAO,IAAI,UAAU,oBAAoB;CACvC,MAAM,EAAE,QAAQ,aAAa;CAC7B,OAAO,QAAQ,IAAI,cAAc,MAAM,SAAS,YAAY,eAAe,OAAO,MAAM,GAAG;CAC3F,OAAO,OAAO,IACZ,KAAK,SAAS,KAAK,CAAC,CAAC,KAAK,EAAE,KAAK,WAC/B,QAAQ,IAAI,KAAK,IAAI,wBAAwB,MAAM,CACrD,CACF;CACA,OAAO,QAAQ,IAAI,sDAAsD,SAAS,QAAQ,GAAG;CAC7F,MAAM,QAAQ,OAAO,SAAS,QAAQ;CACtC,OAAO,OAAO,IAAI,MAAM,KAAK,SAAS,QAAQ,IAAI,KAAK,MAAM,CAAC,CAAC;AACjE,CAAC;;AAGH,MAAM,eAAe,SAA2B,YAC9C,OAAO,IAAI,UAAU,sBAAsB;CACzC,OAAO;CACP,OAAO,gBAAgB,QAAQ,QAAQ;CACvC,OAAO,WAAW,QAAQ,SAAS,WAAW,OAAO;CACrD,OAAO,aAAa,SAAS,OAAO,UAAU,SAAS,OAAO,CAAC;AACjE,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { currentWorktreeCommand, urls } from "./cli-workspace.js";
2
+ import { serverEndpoint } from "./frpc-config.js";
3
+ import { processStatus } from "./processes.js";
4
+ import { Console, Effect } from "effect";
5
+ // src/cli-status.ts
6
+ const printStatus = ({ config, worktree, state }) => Effect.gen(function* printEndpointProcessUrls() {
7
+ yield* Console.log(`${state.project} ${state.worktree}, frpc to ${serverEndpoint(config.server)}`);
8
+ const frpc = yield* processStatus(worktree.stateDir, "frpc");
9
+ const pid = frpc._tag === "stopped" ? "" : ` (pid ${frpc.pid})`;
10
+ yield* Console.log(` frpc ${frpc._tag}${pid}`);
11
+ yield* Effect.all(urls({
12
+ config,
13
+ worktree
14
+ }, state).map(({ url, port }) => Console.log(` ${url} → :${port}`)));
15
+ });
16
+ const status = currentWorktreeCommand("status", "Show this worktree's tunnel server, frpc and URLs", printStatus);
17
+ export { status };
18
+
19
+ //# sourceMappingURL=cli-status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-status.js","names":[],"sources":["../src/cli-status.ts"],"sourcesContent":["import { Console, Effect } from 'effect';\n\nimport { currentWorktreeCommand, urls } from './cli-workspace.ts';\nimport type { CurrentWorktree } from './cli-workspace.ts';\nimport { serverEndpoint } from './frpc-config.ts';\nimport { processStatus } from './processes.ts';\n\nconst printStatus = ({ config, worktree, state }: CurrentWorktree) =>\n Effect.gen(function* printEndpointProcessUrls() {\n yield* Console.log(\n `${state.project} ${state.worktree}, frpc to ${serverEndpoint(config.server)}`,\n );\n const frpc = yield* processStatus(worktree.stateDir, 'frpc');\n const pid = frpc._tag === 'stopped' ? '' : ` (pid ${frpc.pid})`;\n yield* Console.log(` frpc ${frpc._tag}${pid}`);\n yield* Effect.all(\n urls({ config, worktree }, state).map(({ url, port }) =>\n Console.log(` ${url} → :${port}`),\n ),\n );\n });\n\nconst status = currentWorktreeCommand(\n 'status',\n \"Show this worktree's tunnel server, frpc and URLs\",\n printStatus,\n);\n\nexport { status };\n"],"mappings":";;;;;AAOA,MAAM,eAAe,EAAE,QAAQ,UAAU,YACvC,OAAO,IAAI,UAAU,2BAA2B;CAC9C,OAAO,QAAQ,IACb,GAAG,MAAM,QAAQ,GAAG,MAAM,SAAS,YAAY,eAAe,OAAO,MAAM,GAC7E;CACA,MAAM,OAAO,OAAO,cAAc,SAAS,UAAU,MAAM;CAC3D,MAAM,MAAM,KAAK,SAAS,YAAY,KAAK,SAAS,KAAK,IAAI;CAC7D,OAAO,QAAQ,IAAI,UAAU,KAAK,OAAO,KAAK;CAC9C,OAAO,OAAO,IACZ,KAAK;EAAE;EAAQ;CAAS,GAAG,KAAK,CAAC,CAAC,KAAK,EAAE,KAAK,WAC5C,QAAQ,IAAI,KAAK,IAAI,QAAQ,MAAM,CACrC,CACF;AACF,CAAC;AAEH,MAAM,SAAS,uBACb,UACA,qDACA,WACF"}
@@ -0,0 +1,38 @@
1
+ import { WtTunnelError } from "./errors.js";
2
+ import { loadWorkspace } from "./config.js";
3
+ import { routedApps } from "./provision-ports.js";
4
+ import { readState } from "./state.js";
5
+ import { stateFileOf, worktreeAt } from "./worktree.js";
6
+ import { Effect } from "effect";
7
+ import { Command } from "effect/cli";
8
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ // src/cli-workspace.ts
11
+ /** The worktree root containing the current directory, and its config. */
12
+ const workspace = Effect.suspend(() => loadWorkspace(process.cwd()));
13
+ /** The provisioned worktree root containing the current directory; its names come from state. */
14
+ const currentWorktree = Effect.gen(function* worktreeOfCwd() {
15
+ const { root, config } = yield* workspace;
16
+ const state = yield* readState(stateFileOf(root));
17
+ if (state === void 0) return yield* new WtTunnelError({ message: `${root} is not provisioned. Run \`wt-tunnel-client worktree add <project> <worktree>\` first.` });
18
+ return {
19
+ config,
20
+ state,
21
+ worktree: worktreeAt(root, state.project, state.worktree)
22
+ };
23
+ });
24
+ /** A command without arguments that acts on the worktree containing the current directory. */
25
+ const currentWorktreeCommand = (name, description, action) => Command.make(name, {}, () => currentWorktree.pipe(Effect.flatMap((current) => action(current)))).pipe(Command.withDescription(description));
26
+ const prepareStateDir = (worktree) => Effect.promise(async () => {
27
+ await mkdir(worktree.stateDir, { recursive: true });
28
+ await writeFile(join(worktree.stateDir, ".gitignore"), "*\n");
29
+ });
30
+ /** The `NAME=value` lines of the worktree's env file. */
31
+ const envLines = (worktree) => Effect.promise(() => readFile(worktree.envFile, "utf8")).pipe(Effect.map((text) => text.split("\n").filter(Boolean)));
32
+ const urls = (context, state) => routedApps(context, state.ports).map(({ hostname, port }) => ({
33
+ port,
34
+ url: `https://${hostname}`
35
+ }));
36
+ export { currentWorktree, currentWorktreeCommand, envLines, prepareStateDir, urls, workspace };
37
+
38
+ //# sourceMappingURL=cli-workspace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-workspace.js","names":[],"sources":["../src/cli-workspace.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { Effect } from 'effect';\nimport { Command } from 'effect/cli';\n\nimport { loadWorkspace } from './config.ts';\nimport type { WtTunnelConfig } from './config.ts';\nimport { WtTunnelError } from './errors.ts';\nimport { routedApps } from './provision-ports.ts';\nimport type { ProvisionContext } from './resource.ts';\nimport { readState } from './state.ts';\nimport type { WorktreeState } from './state.ts';\nimport { stateFileOf, worktreeAt } from './worktree.ts';\nimport type { Worktree } from './worktree.ts';\n\n/** The worktree root containing the current directory, and its config. */\nconst workspace = Effect.suspend(() => loadWorkspace(process.cwd()));\n\ninterface CurrentWorktree {\n readonly config: WtTunnelConfig;\n readonly state: WorktreeState;\n readonly worktree: Worktree;\n}\n\n/** The provisioned worktree root containing the current directory; its names come from state. */\nconst currentWorktree = Effect.gen(function* worktreeOfCwd() {\n const { root, config } = yield* workspace;\n const state = yield* readState(stateFileOf(root));\n if (state === undefined) {\n return yield* new WtTunnelError({\n message: `${root} is not provisioned. Run \\`wt-tunnel-client worktree add <project> <worktree>\\` first.`,\n });\n }\n const current: CurrentWorktree = {\n config,\n state,\n worktree: worktreeAt(root, state.project, state.worktree),\n };\n return current;\n});\n\n/** A command without arguments that acts on the worktree containing the current directory. */\nconst currentWorktreeCommand = <Failure, Requirements>(\n name: string,\n description: string,\n action: (current: CurrentWorktree) => Effect.Effect<void, Failure, Requirements>,\n) =>\n Command.make(name, {}, () =>\n currentWorktree.pipe(Effect.flatMap((current) => action(current))),\n ).pipe(Command.withDescription(description));\n\nconst prepareStateDir = (worktree: Worktree) =>\n Effect.promise(async () => {\n await mkdir(worktree.stateDir, { recursive: true });\n // Self-ignoring, so the user's repo needs no .gitignore entry.\n await writeFile(join(worktree.stateDir, '.gitignore'), '*\\n');\n });\n\n/** The `NAME=value` lines of the worktree's env file. */\nconst envLines = (worktree: Worktree) =>\n Effect.promise(() => readFile(worktree.envFile, 'utf8')).pipe(\n Effect.map((text) => text.split('\\n').filter(Boolean)),\n );\n\ninterface AppUrl {\n readonly port: number;\n readonly url: string;\n}\n\nconst urls = (context: ProvisionContext, state: WorktreeState) =>\n routedApps(context, state.ports).map(({ hostname, port }): AppUrl => ({\n port,\n url: `https://${hostname}`,\n }));\n\nexport { currentWorktree, currentWorktreeCommand, envLines, prepareStateDir, urls, workspace };\nexport type { CurrentWorktree };\n"],"mappings":";;;;;;;;;;;AAiBA,MAAM,YAAY,OAAO,cAAc,cAAc,QAAQ,IAAI,CAAC,CAAC;;AASnE,MAAM,kBAAkB,OAAO,IAAI,UAAU,gBAAgB;CAC3D,MAAM,EAAE,MAAM,WAAW,OAAO;CAChC,MAAM,QAAQ,OAAO,UAAU,YAAY,IAAI,CAAC;CAChD,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO,IAAI,cAAc,EAC9B,SAAS,GAAG,KAAK,wFACnB,CAAC;CAOH,OAAO;EAJL;EACA;EACA,UAAU,WAAW,MAAM,MAAM,SAAS,MAAM,QAAQ;CAE7C;AACf,CAAC;;AAGD,MAAM,0BACJ,MACA,aACA,WAEA,QAAQ,KAAK,MAAM,CAAC,SAClB,gBAAgB,KAAK,OAAO,SAAS,YAAY,OAAO,OAAO,CAAC,CAAC,CACnE,CAAC,CAAC,KAAK,QAAQ,gBAAgB,WAAW,CAAC;AAE7C,MAAM,mBAAmB,aACvB,OAAO,QAAQ,YAAY;CACzB,MAAM,MAAM,SAAS,UAAU,EAAE,WAAW,KAAK,CAAC;CAElD,MAAM,UAAU,KAAK,SAAS,UAAU,YAAY,GAAG,KAAK;AAC9D,CAAC;;AAGH,MAAM,YAAY,aAChB,OAAO,cAAc,SAAS,SAAS,SAAS,MAAM,CAAC,CAAC,CAAC,KACvD,OAAO,KAAK,SAAS,KAAK,MAAM,IAAI,CAAC,CAAC,OAAO,OAAO,CAAC,CACvD;AAOF,MAAM,QAAQ,SAA2B,UACvC,WAAW,SAAS,MAAM,KAAK,CAAC,CAAC,KAAK,EAAE,UAAU,YAAoB;CACpE;CACA,KAAK,WAAW;AAClB,EAAE"}
@@ -0,0 +1,40 @@
1
+ import { startingState } from "./state.js";
2
+ import { parseProjectName, parseWorktreeName, worktreeAt } from "./worktree.js";
3
+ import { currentWorktree, workspace } from "./cli-workspace.js";
4
+ import { removeAll, worktreeResources } from "./provision.js";
5
+ import { provisionUp } from "./cli-provision.js";
6
+ import { Console, Effect } from "effect";
7
+ import { Argument, Command } from "effect/cli";
8
+ import { rm } from "node:fs/promises";
9
+ // src/cli-worktree.ts
10
+ const add = Command.make("add", {
11
+ project: Argument.String("project").pipe(Argument.withDescription("Project name, a DNS label. The tunnel server knows the worktree as <project>.<worktree>.")),
12
+ worktree: Argument.String("worktree").pipe(Argument.withDescription("Worktree name, a DNS label. URLs are https://<app>.<worktree>.<domain>."))
13
+ }, (input) => Effect.gen(function* addWorktree() {
14
+ const { root, config } = yield* workspace;
15
+ const project = yield* parseProjectName(input.project);
16
+ const name = yield* parseWorktreeName(input.worktree);
17
+ const worktree = worktreeAt(root, project, name);
18
+ const state = yield* startingState(worktree, config.domain);
19
+ return yield* provisionUp({
20
+ config,
21
+ worktree
22
+ }, state);
23
+ })).pipe(Command.withDescription("Give the directory holding wt-tunnel.json (the worktree root) its private URLs"));
24
+ const remove = Command.make("remove", {}, () => Effect.gen(function* removeWorktree() {
25
+ const { config, state, worktree } = yield* currentWorktree;
26
+ yield* removeAll({
27
+ config,
28
+ worktree
29
+ }, state);
30
+ const removed = worktreeResources.map((resource) => resource.name);
31
+ yield* Effect.promise(() => rm(worktree.stateDir, {
32
+ force: true,
33
+ recursive: true
34
+ }));
35
+ yield* Console.log(`Removed ${state.project} ${state.worktree}: its ${removed.join(", ")} and ${worktree.stateDir} are gone.`);
36
+ })).pipe(Command.withDescription("Stop this worktree's frpc, release its ports and delete its .wt-tunnel directory"));
37
+ const worktreeCommand = Command.make("worktree").pipe(Command.withDescription("Provision and remove worktree roots"), Command.withSubcommands([add, remove]));
38
+ export { worktreeCommand };
39
+
40
+ //# sourceMappingURL=cli-worktree.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-worktree.js","names":[],"sources":["../src/cli-worktree.ts"],"sourcesContent":["import { rm } from 'node:fs/promises';\n\nimport { Console, Effect } from 'effect';\nimport { Argument, Command } from 'effect/cli';\n\nimport { provisionUp } from './cli-provision.ts';\nimport { currentWorktree, workspace } from './cli-workspace.ts';\nimport { removeAll, worktreeResources } from './provision.ts';\nimport { startingState } from './state.ts';\nimport { parseProjectName, parseWorktreeName, worktreeAt } from './worktree.ts';\n\nconst add = Command.make(\n 'add',\n {\n project: Argument.String('project').pipe(\n Argument.withDescription(\n 'Project name, a DNS label. The tunnel server knows the worktree as <project>.<worktree>.',\n ),\n ),\n worktree: Argument.String('worktree').pipe(\n Argument.withDescription(\n 'Worktree name, a DNS label. URLs are https://<app>.<worktree>.<domain>.',\n ),\n ),\n },\n (input) =>\n Effect.gen(function* addWorktree() {\n const { root, config } = yield* workspace;\n const project = yield* parseProjectName(input.project);\n const name = yield* parseWorktreeName(input.worktree);\n const worktree = worktreeAt(root, project, name);\n const state = yield* startingState(worktree, config.domain);\n return yield* provisionUp({ config, worktree }, state);\n }),\n).pipe(\n Command.withDescription(\n 'Give the directory holding wt-tunnel.json (the worktree root) its private URLs',\n ),\n);\n\nconst remove = Command.make('remove', {}, () =>\n Effect.gen(function* removeWorktree() {\n const { config, state, worktree } = yield* currentWorktree;\n yield* removeAll({ config, worktree }, state);\n const removed = worktreeResources.map((resource) => resource.name);\n yield* Effect.promise(() => rm(worktree.stateDir, { force: true, recursive: true }));\n yield* Console.log(\n `Removed ${state.project} ${state.worktree}: its ${removed.join(', ')} and ${worktree.stateDir} are gone.`,\n );\n }),\n).pipe(\n Command.withDescription(\n \"Stop this worktree's frpc, release its ports and delete its .wt-tunnel directory\",\n ),\n);\n\nconst worktreeCommand = Command.make('worktree').pipe(\n Command.withDescription('Provision and remove worktree roots'),\n Command.withSubcommands([add, remove]),\n);\n\nexport { worktreeCommand };\n"],"mappings":";;;;;;;;;AAWA,MAAM,MAAM,QAAQ,KAClB,OACA;CACE,SAAS,SAAS,OAAO,SAAS,CAAC,CAAC,KAClC,SAAS,gBACP,0FACF,CACF;CACA,UAAU,SAAS,OAAO,UAAU,CAAC,CAAC,KACpC,SAAS,gBACP,yEACF,CACF;AACF,IACC,UACC,OAAO,IAAI,UAAU,cAAc;CACjC,MAAM,EAAE,MAAM,WAAW,OAAO;CAChC,MAAM,UAAU,OAAO,iBAAiB,MAAM,OAAO;CACrD,MAAM,OAAO,OAAO,kBAAkB,MAAM,QAAQ;CACpD,MAAM,WAAW,WAAW,MAAM,SAAS,IAAI;CAC/C,MAAM,QAAQ,OAAO,cAAc,UAAU,OAAO,MAAM;CAC1D,OAAO,OAAO,YAAY;EAAE;EAAQ;CAAS,GAAG,KAAK;AACvD,CAAC,CACL,CAAC,CAAC,KACA,QAAQ,gBACN,gFACF,CACF;AAEA,MAAM,SAAS,QAAQ,KAAK,UAAU,CAAC,SACrC,OAAO,IAAI,UAAU,iBAAiB;CACpC,MAAM,EAAE,QAAQ,OAAO,aAAa,OAAO;CAC3C,OAAO,UAAU;EAAE;EAAQ;CAAS,GAAG,KAAK;CAC5C,MAAM,UAAU,kBAAkB,KAAK,aAAa,SAAS,IAAI;CACjE,OAAO,OAAO,cAAc,GAAG,SAAS,UAAU;EAAE,OAAO;EAAM,WAAW;CAAK,CAAC,CAAC;CACnF,OAAO,QAAQ,IACb,WAAW,MAAM,QAAQ,GAAG,MAAM,SAAS,QAAQ,QAAQ,KAAK,IAAI,EAAE,OAAO,SAAS,SAAS,WACjG;AACF,CAAC,CACH,CAAC,CAAC,KACA,QAAQ,gBACN,kFACF,CACF;AAEA,MAAM,kBAAkB,QAAQ,KAAK,UAAU,CAAC,CAAC,KAC/C,QAAQ,gBAAgB,qCAAqC,GAC7D,QAAQ,gBAAgB,CAAC,KAAK,MAAM,CAAC,CACvC"}
package/dist/cli.js ADDED
@@ -0,0 +1,9 @@
1
+ import { worktreeCommands } from "./cli-commands.js";
2
+ import { worktreeCommand } from "./cli-worktree.js";
3
+ import { Command } from "effect/cli";
4
+ // src/cli.ts
5
+ const cli = Command.make("wt-tunnel-client").pipe(Command.withDescription("Private HTTPS URLs for every git worktree, through your own tunnel server"), Command.withSubcommands([worktreeCommand, ...worktreeCommands]));
6
+ const run = (version) => Command.run(cli, { version });
7
+ export { run };
8
+
9
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { Command } from 'effect/cli';\n\nimport { worktreeCommands } from './cli-commands.ts';\nimport { worktreeCommand } from './cli-worktree.ts';\n\nconst cli = Command.make('wt-tunnel-client').pipe(\n Command.withDescription(\n 'Private HTTPS URLs for every git worktree, through your own tunnel server',\n ),\n Command.withSubcommands([worktreeCommand, ...worktreeCommands]),\n);\n\nconst run = (version: string) => Command.run(cli, { version });\n\nexport { run };\n"],"mappings":";;;;AAKA,MAAM,MAAM,QAAQ,KAAK,kBAAkB,CAAC,CAAC,KAC3C,QAAQ,gBACN,2EACF,GACA,QAAQ,gBAAgB,CAAC,iBAAiB,GAAG,gBAAgB,CAAC,CAChE;AAEA,MAAM,OAAO,YAAoB,QAAQ,IAAI,KAAK,EAAE,QAAQ,CAAC"}
package/dist/config.js ADDED
@@ -0,0 +1,70 @@
1
+ import { Hostname } from "./packages/contract/src/index.js";
2
+ import { AppLabel, EnvName, Port, ServerHost } from "./domain.js";
3
+ import { WtTunnelError } from "./errors.js";
4
+ import { Array, Effect, FileSystem, Path, Schema } from "effect";
5
+ // src/config.ts
6
+ const configFileName = "wt-tunnel.json";
7
+ const AppConfig = Schema.Struct({
8
+ /** Pin the port instead of letting wt-tunnel reserve one. */
9
+ port: Schema.optionalKey(Port),
10
+ portEnv: EnvName,
11
+ /** `false` for services that only need a port, such as a database. */
12
+ route: Schema.optionalKey(Schema.Boolean)
13
+ });
14
+ /** The tunnel server that every worktree's frpc connects to (docs/server-mode.md). */
15
+ const ServerConfig = Schema.Struct({
16
+ host: ServerHost,
17
+ port: Schema.optionalKey(Port)
18
+ });
19
+ const WtTunnelConfig = Schema.Struct({
20
+ apps: Schema.Record(AppLabel, AppConfig),
21
+ domain: Hostname,
22
+ server: ServerConfig
23
+ });
24
+ const ConfigJson = Schema.fromJsonString(WtTunnelConfig);
25
+ const firstDuplicate = (values) => values.find((value, index) => values.indexOf(value) !== index);
26
+ /** What the schema cannot express: at least one app, and no port variable or pin used twice. */
27
+ const appsProblem = (apps, source) => {
28
+ const envs = Object.values(apps).map((app) => app.portEnv);
29
+ if (!Array.isReadonlyArrayNonEmpty(envs)) return `${source} must define at least one app`;
30
+ const duplicate = firstDuplicate(envs);
31
+ if (duplicate !== void 0) return `${source} uses portEnv ${duplicate} twice`;
32
+ const clash = firstDuplicate(Object.values(apps).flatMap((app) => app.port === void 0 ? [] : [app.port]));
33
+ return clash === void 0 ? void 0 : `${source} pins port ${clash} twice`;
34
+ };
35
+ const decodeConfig = (text, source) => Effect.gen(function* decodeAndCheck() {
36
+ const config = yield* Schema.decodeUnknownEffect(ConfigJson)(text).pipe(Effect.mapError((schemaError) => new WtTunnelError({ message: `${source} is not a valid config: ${schemaError.message}` })));
37
+ const problem = appsProblem(config.apps, source);
38
+ if (problem !== void 0) return yield* new WtTunnelError({ message: problem });
39
+ return config;
40
+ });
41
+ /**
42
+ * The worktree root: the nearest directory at or above `start` that holds wt-tunnel.json. Its
43
+ * `.wt-tunnel/` holds the state of what it serves.
44
+ */
45
+ const findRoot = (start) => Effect.gen(function* walkUp() {
46
+ const fs = yield* FileSystem.FileSystem;
47
+ const path = yield* Path.Path;
48
+ let dir = path.resolve(start);
49
+ while (!(yield* fs.exists(path.join(dir, configFileName)).pipe(Effect.orDie))) {
50
+ const parent = path.dirname(dir);
51
+ if (parent === dir) return yield* new WtTunnelError({ message: `No ${configFileName} in ${start} or any directory above it. Run wt-tunnel-client from inside a checkout that has one.` });
52
+ dir = parent;
53
+ }
54
+ return dir;
55
+ });
56
+ /** The root containing `start` and the config in it. */
57
+ const loadWorkspace = (start) => Effect.gen(function* readConfigFile() {
58
+ const fs = yield* FileSystem.FileSystem;
59
+ const path = yield* Path.Path;
60
+ const root = yield* findRoot(start);
61
+ const file = path.join(root, configFileName);
62
+ const text = yield* fs.readFileString(file).pipe(Effect.orDie);
63
+ return {
64
+ config: yield* decodeConfig(text, file),
65
+ root
66
+ };
67
+ });
68
+ export { decodeConfig, loadWorkspace };
69
+
70
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport { Array, Effect, FileSystem, Path, Schema } from 'effect';\n\nimport { AppLabel, EnvName, Port, ServerHost } from './domain.ts';\nimport { WtTunnelError } from './errors.ts';\n\nconst configFileName = 'wt-tunnel.json';\n\nconst AppConfig = Schema.Struct({\n /** Pin the port instead of letting wt-tunnel reserve one. */\n port: Schema.optionalKey(Port),\n portEnv: EnvName,\n /** `false` for services that only need a port, such as a database. */\n route: Schema.optionalKey(Schema.Boolean),\n});\n\n/** The tunnel server that every worktree's frpc connects to (docs/server-mode.md). */\nconst ServerConfig = Schema.Struct({\n host: ServerHost,\n port: Schema.optionalKey(Port),\n});\ntype ServerConfig = typeof ServerConfig.Type;\n\nconst WtTunnelConfig = Schema.Struct({\n apps: Schema.Record(AppLabel, AppConfig),\n domain: Hostname,\n server: ServerConfig,\n});\ntype WtTunnelConfig = typeof WtTunnelConfig.Type;\n\nconst ConfigJson = Schema.fromJsonString(WtTunnelConfig);\n\nconst firstDuplicate = <Value>(values: readonly Value[]) =>\n values.find((value, index) => values.indexOf(value) !== index);\n\n/** What the schema cannot express: at least one app, and no port variable or pin used twice. */\nconst appsProblem = (apps: WtTunnelConfig['apps'], source: string): string | undefined => {\n const envs = Object.values(apps).map((app) => app.portEnv);\n if (!Array.isReadonlyArrayNonEmpty(envs)) {\n return `${source} must define at least one app`;\n }\n const duplicate = firstDuplicate(envs);\n if (duplicate !== undefined) {\n return `${source} uses portEnv ${duplicate} twice`;\n }\n const clash = firstDuplicate(\n Object.values(apps).flatMap((app) => (app.port === undefined ? [] : [app.port])),\n );\n return clash === undefined ? undefined : `${source} pins port ${clash} twice`;\n};\n\nconst decodeConfig = (text: string, source: string) =>\n Effect.gen(function* decodeAndCheck() {\n const config = yield* Schema.decodeUnknownEffect(ConfigJson)(text).pipe(\n Effect.mapError(\n (schemaError) =>\n new WtTunnelError({ message: `${source} is not a valid config: ${schemaError.message}` }),\n ),\n );\n const problem = appsProblem(config.apps, source);\n if (problem !== undefined) {\n return yield* new WtTunnelError({ message: problem });\n }\n return config;\n });\n\n/**\n * The worktree root: the nearest directory at or above `start` that holds wt-tunnel.json. Its\n * `.wt-tunnel/` holds the state of what it serves.\n */\nconst findRoot = (start: string) =>\n Effect.gen(function* walkUp() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n let dir = path.resolve(start);\n while (!(yield* fs.exists(path.join(dir, configFileName)).pipe(Effect.orDie))) {\n const parent = path.dirname(dir);\n if (parent === dir) {\n return yield* new WtTunnelError({\n message: `No ${configFileName} in ${start} or any directory above it. Run wt-tunnel-client from inside a checkout that has one.`,\n });\n }\n dir = parent;\n }\n return dir;\n });\n\n/** The root containing `start` and the config in it. */\nconst loadWorkspace = (start: string) =>\n Effect.gen(function* readConfigFile() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const root = yield* findRoot(start);\n const file = path.join(root, configFileName);\n const text = yield* fs.readFileString(file).pipe(Effect.orDie);\n const config = yield* decodeConfig(text, file);\n return { config, root };\n });\n\nexport { decodeConfig, loadWorkspace };\nexport type { ServerConfig, WtTunnelConfig };\n"],"mappings":";;;;;AAMA,MAAM,iBAAiB;AAEvB,MAAM,YAAY,OAAO,OAAO;;CAE9B,MAAM,OAAO,YAAY,IAAI;CAC7B,SAAS;;CAET,OAAO,OAAO,YAAY,OAAO,OAAO;AAC1C,CAAC;;AAGD,MAAM,eAAe,OAAO,OAAO;CACjC,MAAM;CACN,MAAM,OAAO,YAAY,IAAI;AAC/B,CAAC;AAGD,MAAM,iBAAiB,OAAO,OAAO;CACnC,MAAM,OAAO,OAAO,UAAU,SAAS;CACvC,QAAQ;CACR,QAAQ;AACV,CAAC;AAGD,MAAM,aAAa,OAAO,eAAe,cAAc;AAEvD,MAAM,kBAAyB,WAC7B,OAAO,MAAM,OAAO,UAAU,OAAO,QAAQ,KAAK,MAAM,KAAK;;AAG/D,MAAM,eAAe,MAA8B,WAAuC;CACxF,MAAM,OAAO,OAAO,OAAO,IAAI,CAAC,CAAC,KAAK,QAAQ,IAAI,OAAO;CACzD,IAAI,CAAC,MAAM,wBAAwB,IAAI,GACrC,OAAO,GAAG,OAAO;CAEnB,MAAM,YAAY,eAAe,IAAI;CACrC,IAAI,cAAc,KAAA,GAChB,OAAO,GAAG,OAAO,gBAAgB,UAAU;CAE7C,MAAM,QAAQ,eACZ,OAAO,OAAO,IAAI,CAAC,CAAC,SAAS,QAAS,IAAI,SAAS,KAAA,IAAY,CAAC,IAAI,CAAC,IAAI,IAAI,CAAE,CACjF;CACA,OAAO,UAAU,KAAA,IAAY,KAAA,IAAY,GAAG,OAAO,aAAa,MAAM;AACxE;AAEA,MAAM,gBAAgB,MAAc,WAClC,OAAO,IAAI,UAAU,iBAAiB;CACpC,MAAM,SAAS,OAAO,OAAO,oBAAoB,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,KACjE,OAAO,UACJ,gBACC,IAAI,cAAc,EAAE,SAAS,GAAG,OAAO,0BAA0B,YAAY,UAAU,CAAC,CAC5F,CACF;CACA,MAAM,UAAU,YAAY,OAAO,MAAM,MAAM;CAC/C,IAAI,YAAY,KAAA,GACd,OAAO,OAAO,IAAI,cAAc,EAAE,SAAS,QAAQ,CAAC;CAEtD,OAAO;AACT,CAAC;;;;;AAMH,MAAM,YAAY,UAChB,OAAO,IAAI,UAAU,SAAS;CAC5B,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,OAAO,EAAE,OAAO,GAAG,OAAO,KAAK,KAAK,KAAK,cAAc,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK,IAAI;EAC7E,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KACb,OAAO,OAAO,IAAI,cAAc,EAC9B,SAAS,MAAM,eAAe,MAAM,MAAM,uFAC5C,CAAC;EAEH,MAAM;CACR;CACA,OAAO;AACT,CAAC;;AAGH,MAAM,iBAAiB,UACrB,OAAO,IAAI,UAAU,iBAAiB;CACpC,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,OAAO,OAAO,SAAS,KAAK;CAClC,MAAM,OAAO,KAAK,KAAK,MAAM,cAAc;CAC3C,MAAM,OAAO,OAAO,GAAG,eAAe,IAAI,CAAC,CAAC,KAAK,OAAO,KAAK;CAE7D,OAAO;EAAE,QAAA,OADa,aAAa,MAAM,IAAI;EAC5B;CAAK;AACxB,CAAC"}
package/dist/domain.js ADDED
@@ -0,0 +1,26 @@
1
+ import { Hostname } from "./packages/contract/src/index.js";
2
+ import { Brand, Schema } from "effect";
3
+ import { isIP } from "node:net";
4
+ // src/domain.ts
5
+ const dnsLabel = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
6
+ const portMin = 1;
7
+ const portMax = 65535;
8
+ const DnsLabel = Schema.String.check(Schema.isPattern(dnsLabel));
9
+ const WorktreeName = DnsLabel.pipe(Schema.brand("WorktreeName"));
10
+ const ProjectName = DnsLabel.pipe(Schema.brand("ProjectName"));
11
+ const AppLabel = DnsLabel.pipe(Schema.brand("AppLabel"));
12
+ const Port = Schema.Int.check(Schema.isBetween({
13
+ maximum: portMax,
14
+ minimum: portMin
15
+ })).pipe(Schema.brand("Port"));
16
+ const isHostname = Schema.is(Hostname);
17
+ const isIpOrHostname = (value) => isIP(value) !== 0 || isHostname(value) || "expected an IP address or a host name";
18
+ const ServerHost = Schema.String.check(Schema.makeFilter(isIpOrHostname));
19
+ const EnvName = Schema.String.check(Schema.isPattern(/^[A-Z_][A-Z0-9_]*$/u));
20
+ /** Brands host names this module builds from already valid parts, without re-validating them. */
21
+ const trustedHostname = Brand.nominal();
22
+ const worktreeZone = (worktree, domain) => trustedHostname(`${worktree}.${domain}`);
23
+ const hostnameFor = (app, worktree, domain) => trustedHostname(`${app}.${worktreeZone(worktree, domain)}`);
24
+ export { AppLabel, EnvName, Port, ProjectName, ServerHost, WorktreeName, hostnameFor, worktreeZone };
25
+
26
+ //# sourceMappingURL=domain.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"domain.js","names":[],"sources":["../src/domain.ts"],"sourcesContent":["import { isIP } from 'node:net';\n\nimport { Hostname } from '@tafrahq/wt-tunnel-contract';\nimport { Brand, Schema } from 'effect';\n\nconst dnsLabel = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\nconst portMin = 1;\nconst portMax = 65_535;\n\nconst DnsLabel = Schema.String.check(Schema.isPattern(dnsLabel));\n\nconst WorktreeName = DnsLabel.pipe(Schema.brand('WorktreeName'));\ntype WorktreeName = typeof WorktreeName.Type;\n\nconst ProjectName = DnsLabel.pipe(Schema.brand('ProjectName'));\ntype ProjectName = typeof ProjectName.Type;\n\nconst AppLabel = DnsLabel.pipe(Schema.brand('AppLabel'));\ntype AppLabel = typeof AppLabel.Type;\n\nconst Port = Schema.Int.check(Schema.isBetween({ maximum: portMax, minimum: portMin })).pipe(\n Schema.brand('Port'),\n);\ntype Port = typeof Port.Type;\n\nconst isHostname = Schema.is(Hostname);\nconst isIpOrHostname = (value: string) =>\n isIP(value) !== 0 || isHostname(value) || 'expected an IP address or a host name';\nconst ServerHost = Schema.String.check(Schema.makeFilter(isIpOrHostname));\n\nconst EnvName = Schema.String.check(Schema.isPattern(/^[A-Z_][A-Z0-9_]*$/u));\n\n/** Brands host names this module builds from already valid parts, without re-validating them. */\nconst trustedHostname = Brand.nominal<Hostname>();\n\nconst worktreeZone = (worktree: WorktreeName, domain: Hostname): Hostname =>\n trustedHostname(`${worktree}.${domain}`);\n\nconst hostnameFor = (app: AppLabel, worktree: WorktreeName, domain: Hostname): Hostname =>\n trustedHostname(`${app}.${worktreeZone(worktree, domain)}`);\n\nexport {\n AppLabel,\n EnvName,\n hostnameFor,\n Port,\n ProjectName,\n ServerHost,\n WorktreeName,\n worktreeZone,\n};\n"],"mappings":";;;;AAKA,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,UAAU;AAEhB,MAAM,WAAW,OAAO,OAAO,MAAM,OAAO,UAAU,QAAQ,CAAC;AAE/D,MAAM,eAAe,SAAS,KAAK,OAAO,MAAM,cAAc,CAAC;AAG/D,MAAM,cAAc,SAAS,KAAK,OAAO,MAAM,aAAa,CAAC;AAG7D,MAAM,WAAW,SAAS,KAAK,OAAO,MAAM,UAAU,CAAC;AAGvD,MAAM,OAAO,OAAO,IAAI,MAAM,OAAO,UAAU;CAAE,SAAS;CAAS,SAAS;AAAQ,CAAC,CAAC,CAAC,CAAC,KACtF,OAAO,MAAM,MAAM,CACrB;AAGA,MAAM,aAAa,OAAO,GAAG,QAAQ;AACrC,MAAM,kBAAkB,UACtB,KAAK,KAAK,MAAM,KAAK,WAAW,KAAK,KAAK;AAC5C,MAAM,aAAa,OAAO,OAAO,MAAM,OAAO,WAAW,cAAc,CAAC;AAExE,MAAM,UAAU,OAAO,OAAO,MAAM,OAAO,UAAU,qBAAqB,CAAC;;AAG3E,MAAM,kBAAkB,MAAM,QAAkB;AAEhD,MAAM,gBAAgB,UAAwB,WAC5C,gBAAgB,GAAG,SAAS,GAAG,QAAQ;AAEzC,MAAM,eAAe,KAAe,UAAwB,WAC1D,gBAAgB,GAAG,IAAI,GAAG,aAAa,UAAU,MAAM,GAAG"}
package/dist/errno.js ADDED
@@ -0,0 +1,6 @@
1
+ // src/errno.ts
2
+ /** The `code` of a Node system error (`EEXIST`, `EADDRINUSE`, ...), if it has one. */
3
+ const errorCode = (error) => error instanceof Error && "code" in error ? error.code : void 0;
4
+ export { errorCode };
5
+
6
+ //# sourceMappingURL=errno.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errno.js","names":[],"sources":["../src/errno.ts"],"sourcesContent":["/** The `code` of a Node system error (`EEXIST`, `EADDRINUSE`, ...), if it has one. */\nconst errorCode = (error: unknown): unknown =>\n error instanceof Error && 'code' in error ? error.code : undefined;\n\nexport { errorCode };\n"],"mappings":";;AACA,MAAM,aAAa,UACjB,iBAAiB,SAAS,UAAU,QAAQ,MAAM,OAAO,KAAA"}
package/dist/errors.js ADDED
@@ -0,0 +1,7 @@
1
+ import { Schema } from "effect";
2
+ // src/errors.ts
3
+ const { TaggedError: taggedErrorClass } = Schema;
4
+ var WtTunnelError = class extends taggedErrorClass()("WtTunnelError", { message: Schema.String }) {};
5
+ export { WtTunnelError };
6
+
7
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { Schema } from 'effect';\n\n/*\n * The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in\n * `Error`, as an error thrown without `new`.\n */\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass WtTunnelError extends taggedErrorClass<WtTunnelError>()('WtTunnelError', {\n message: Schema.String,\n}) {}\n\nexport { WtTunnelError };\n"],"mappings":";;AAMA,MAAM,EAAE,aAAa,qBAAqB;AAE1C,IAAM,gBAAN,cAA4B,iBAAgC,CAAC,CAAC,iBAAiB,EAC7E,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC"}
package/dist/exec.js ADDED
@@ -0,0 +1,18 @@
1
+ import { Effect } from "effect";
2
+ import { execFile } from "node:child_process";
3
+ // src/exec.ts
4
+ /** Runs a program to completion and yields its stdout; a non-zero exit fails with its stderr. */
5
+ const execFileText = (file, args, cwd) => Effect.callback((resume) => {
6
+ execFile(file, [...args], {
7
+ cwd,
8
+ encoding: "utf8"
9
+ }, (failure, stdout, stderr) => {
10
+ resume(failure === null ? Effect.succeed(stdout) : Effect.fail({
11
+ cause: failure,
12
+ stderr
13
+ }));
14
+ });
15
+ });
16
+ export { execFileText };
17
+
18
+ //# sourceMappingURL=exec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exec.js","names":[],"sources":["../src/exec.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\n\nimport { Effect } from 'effect';\n\ninterface ExecFailure {\n readonly cause: unknown;\n readonly stderr: string;\n}\n\n/** Runs a program to completion and yields its stdout; a non-zero exit fails with its stderr. */\nconst execFileText = (file: string, args: readonly string[], cwd?: string) =>\n Effect.callback<string, ExecFailure>((resume) => {\n execFile(file, [...args], { cwd, encoding: 'utf8' }, (failure: unknown, stdout, stderr) => {\n resume(failure === null ? Effect.succeed(stdout) : Effect.fail({ cause: failure, stderr }));\n });\n });\n\nexport { execFileText };\n"],"mappings":";;;;AAUA,MAAM,gBAAgB,MAAc,MAAyB,QAC3D,OAAO,UAA+B,WAAW;CAC/C,SAAS,MAAM,CAAC,GAAG,IAAI,GAAG;EAAE;EAAK,UAAU;CAAO,IAAI,SAAkB,QAAQ,WAAW;EACzF,OAAO,YAAY,OAAO,OAAO,QAAQ,MAAM,IAAI,OAAO,KAAK;GAAE,OAAO;GAAS;EAAO,CAAC,CAAC;CAC5F,CAAC;AACH,CAAC"}
package/dist/files.js ADDED
@@ -0,0 +1,18 @@
1
+ import { access, readFile } from "node:fs/promises";
2
+ // src/files.ts
3
+ /** Like `existsSync`: false for any path that cannot be accessed. */
4
+ const pathExists = async (path) => {
5
+ try {
6
+ await access(path);
7
+ return true;
8
+ } catch {
9
+ return false;
10
+ }
11
+ };
12
+ const readTextIfExists = async (file) => {
13
+ if (!await pathExists(file)) return;
14
+ return readFile(file, "utf8");
15
+ };
16
+ export { pathExists, readTextIfExists };
17
+
18
+ //# sourceMappingURL=files.js.map