@blinkhost/cli 2.6.0 → 2.8.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.
- package/CHANGELOG.md +13 -0
- package/README.md +534 -2
- package/dist/api.d.ts +2 -2
- package/dist/api.js +57 -8
- package/dist/assistant.js +6 -1
- package/dist/cli.js +162 -9
- package/dist/design.d.ts +5 -0
- package/dist/design.js +82 -0
- package/dist/guidance.d.ts +1 -1
- package/dist/guidance.js +55 -12
- package/dist/javascript-runtime/resource-limits.js +3 -0
- package/dist/javascript-runtime/resource-profiles.js +2 -0
- package/dist/local-dev.d.ts +3 -0
- package/dist/local-dev.js +145 -0
- package/dist/local-development/README.md +410 -0
- package/dist/local-development/artifact-watch.mjs +36 -0
- package/dist/local-development/blinkhost.local.example.json +15 -0
- package/dist/local-development/frontend-proxy.mjs +189 -0
- package/dist/local-development/hello.rs +24 -0
- package/dist/local-development/local-stack.mjs +511 -0
- package/dist/local-development/native-database.mjs +37 -0
- package/dist/local-development/provider-fixtures.example.json +36 -0
- package/dist/local-development/provider-fixtures.mjs +203 -0
- package/dist/local-development/provider-grants.mjs +36 -0
- package/dist/local-development/test-provider-example.mjs +74 -0
- package/dist/local-source-build.d.ts +39 -0
- package/dist/local-source-build.js +225 -0
- package/dist/local-source-watch.d.ts +24 -0
- package/dist/local-source-watch.js +87 -0
- package/dist/local-test-command.d.ts +49 -0
- package/dist/local-test-command.js +128 -0
- package/dist/local-test-config.d.ts +37 -0
- package/dist/local-test-config.js +174 -0
- package/dist/local-test-gates.d.ts +71 -0
- package/dist/local-test-gates.js +247 -0
- package/dist/local-test-go-runner.d.ts +27 -0
- package/dist/local-test-go-runner.js +209 -0
- package/dist/local-test-node-arguments.d.ts +2 -0
- package/dist/local-test-node-arguments.js +14 -0
- package/dist/local-test-node-reporter.d.ts +7 -0
- package/dist/local-test-node-reporter.js +159 -0
- package/dist/local-test-results.d.ts +65 -0
- package/dist/local-test-results.js +163 -0
- package/dist/local-test-rust-runner.d.ts +18 -0
- package/dist/local-test-rust-runner.js +252 -0
- package/dist/local-test-starters.d.ts +3 -0
- package/dist/local-test-starters.js +157 -0
- package/dist/logs.d.ts +43 -0
- package/dist/logs.js +417 -0
- package/dist/module-build-diagnostics.d.ts +10 -0
- package/dist/module-build-diagnostics.js +208 -0
- package/dist/module-build.js +4 -0
- package/dist/release-preparation-diagnostics.d.ts +38 -0
- package/dist/release-preparation-diagnostics.js +204 -0
- package/dist/remote.js +14 -0
- package/dist/templates.d.ts +1 -0
- package/dist/templates.js +4 -1
- package/dist/test-credentials.d.ts +7 -0
- package/dist/test-credentials.js +236 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workflows.d.ts +39 -2
- package/dist/workflows.js +241 -14
- package/package.json +4 -3
- package/test-runners/python-unittest.py +266 -0
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
# Run your application with a local backend and libSQL
|
|
2
|
+
|
|
3
|
+
The Linux local stack serves your built frontend, runs your portable backend module in WasmEdge, and connects it to a fresh libSQL database. You can also run scripted email, payment and AI providers alongside your app. It uses loopback listeners and requires no BlinkHost login.
|
|
4
|
+
|
|
5
|
+
## Install the development tools
|
|
6
|
+
|
|
7
|
+
Use 64-bit x86 Ubuntu 24.04 with OpenSSL 3, the Ubuntu `ca-certificates` package and Node.js 22.12 or later. The local libSQL server loads the system certificate store during startup. Download `blinkhost-local-runtime-2.8.0-linux-x86_64.tar.gz` from the runtime release. Download `local-runtime.SHA256SUMS` and `local-runtime.SHA256SUMS.sigstore.json` from the CLI v2.8.0 release. [BlinkHost local runtime](https://github.com/blinkhost-ltd/blinkhost-cli/releases/tag/local-runtime-v2.8.0) · [CLI v2.8.0 signed checksums](https://github.com/blinkhost-ltd/blinkhost-cli/releases/tag/v2.8.0)
|
|
8
|
+
|
|
9
|
+
In your application directory, verify the checksum list's signature using Cosign, then verify the archive before extracting the runtime and its matching WasmEdge 0.18.1 library.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
archive=blinkhost-local-runtime-2.8.0-linux-x86_64.tar.gz
|
|
13
|
+
cosign verify-blob \
|
|
14
|
+
--bundle local-runtime.SHA256SUMS.sigstore.json \
|
|
15
|
+
--certificate-identity https://github.com/blinkhost-ltd/blinkhost-cli/.github/workflows/release.yml@refs/tags/v2.8.0 \
|
|
16
|
+
--certificate-oidc-issuer https://token.actions.githubusercontent.com \
|
|
17
|
+
local-runtime.SHA256SUMS &&
|
|
18
|
+
awk -v name="$archive" '$2 == name' local-runtime.SHA256SUMS | sha256sum --strict --check - &&
|
|
19
|
+
printf '%s %s\n' 852962e6c1bd4a66bb1dff66e16818cd2980a5e3dcb41316f6568db174b4134f "$archive" | sha256sum --strict --check - &&
|
|
20
|
+
mkdir -p tools && tar -xzf "$archive" -C tools
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The CLI package contains the launcher and configuration examples. The backend stack requires the separate runtime and engine. You can use native application tests with `blinkhost test .` and run your frontend's configured development command with `blinkhost dev .` independently.
|
|
24
|
+
|
|
25
|
+
Install upstream `sqld` 0.24.32 for Linux x86-64, verify its published asset checksum and put the executable in `tools/sqld`. [libSQL server 0.24.32 downloads](https://github.com/tursodatabase/libsql/releases/tag/libsql-server-v0.24.32)
|
|
26
|
+
|
|
27
|
+
Copy the configuration example from your installation to your application. For a globally installed CLI, run the following from the project directory.
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
cli_tools="$(npm root -g)/@blinkhost/cli/dist/local-development"
|
|
31
|
+
cp "$cli_tools/blinkhost.local.example.json" blinkhost.local.json
|
|
32
|
+
mkdir -p local-data
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
For a project-local installation, the examples are under `node_modules/@blinkhost/cli/dist/local-development/`. Set `runtime.path`, `engine.path`, `database.executable.path`, `artifact.path` and `frontend` to your files. The engine path must use the shared library name `libwasmedge.so`. Use `sha256sum` on each of the four input files to fill its matching `sha256` field. The runtime and engine digests must match the verified distribution. Relative paths resolve against the configuration file. Build your frontend into the public directory that you set as `frontend`.
|
|
36
|
+
|
|
37
|
+
## Build your first portable backend module
|
|
38
|
+
|
|
39
|
+
The package includes a complete Rust HTTP handler that returns `Hello from BlinkHost!`. It compiles with stock Rust and uses the runtime's response function directly. You can edit its status, headers and body. From your application directory, use `cli_tools` from above or set it to `node_modules/@blinkhost/cli/dist/local-development` for a project-local install.
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
rustup toolchain install 1.98.0 --profile minimal --target wasm32-unknown-unknown
|
|
43
|
+
cp "$cli_tools/hello.rs" hello.rs
|
|
44
|
+
rustc +1.98.0 --edition=2024 --target wasm32-unknown-unknown \
|
|
45
|
+
-C opt-level=s -C panic=abort -C strip=symbols hello.rs -o artifact.wasm
|
|
46
|
+
sha256sum artifact.wasm
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Copy that digest into `artifact.sha256` in `blinkhost.local.json`. For a new project you can start with `blinkhost create hello --template html --no-install`. In that project's directory, `mkdir -p frontend && cp index.html script.js style.css frontend/` prepares the static frontend for the example configuration. After the stack prints its frontend origin, open `/api/hello` at that origin to see the handler's response.
|
|
50
|
+
|
|
51
|
+
For your own language toolchain, you can also supply an executable compiler wrapper as described below. The dashboard's **Build** action compiles a saved module on BlinkHost and reports its build status and artifact digest. Local execution requires a portable module on disk. The generated JavaScript and TypeScript handlers use BlinkHost's request and response adapter during compilation. Building those handlers for local use requires a compiler with that adapter. Stock Javy alone can emit a module that starts and returns an empty body.
|
|
52
|
+
|
|
53
|
+
## Start and stop the stack together
|
|
54
|
+
|
|
55
|
+
The launcher starts `sqld`, applies your setup statements, starts the runtime, verifies its health and connects the frontend. It checks the runtime contract, engine version and the hashes of your configured inputs.
|
|
56
|
+
|
|
57
|
+
Choose a **new** state directory whose parent already exists, outside the served
|
|
58
|
+
frontend directory:
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
blinkhost dev . --local-config ./blinkhost.local.json --state-dir ./local-data/run-001 --json
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The installed CLI packages this tool and validates `blinkhost.yaml` before
|
|
65
|
+
startup. Both local options are required; it makes no account/update API requests.
|
|
66
|
+
It emits a JSON readiness record followed by the final shutdown result. Ctrl-C
|
|
67
|
+
or SIGTERM after readiness exits zero; interrupted startup and child failures
|
|
68
|
+
exit nonzero. Readiness output waits at most three seconds, final output one
|
|
69
|
+
second; incomplete output fails after stopping owned processes. An idle closed
|
|
70
|
+
pipe may be detected only on the next write.
|
|
71
|
+
|
|
72
|
+
The JSON output contains the actual frontend, runtime and database origins.
|
|
73
|
+
Listeners bind to `127.0.0.1` on operating-system-selected ports, discovered from
|
|
74
|
+
sockets owned by each child through Linux `/proc`. Open the printed frontend URL.
|
|
75
|
+
You can also use those origins in the browser test configuration below. Run a
|
|
76
|
+
second stack with another state directory to test isolated projects.
|
|
77
|
+
|
|
78
|
+
Ctrl-C or SIGTERM stops the owned module, database and frontend. A startup or
|
|
79
|
+
child-process failure stops its companions. The state directory retains the
|
|
80
|
+
database, bounded process logs and private `ready.json`/`stopped.json` evidence;
|
|
81
|
+
the tool never deletes data or resumes/resets an existing directory. Logs retain
|
|
82
|
+
at most 1 MiB per process; stop evidence reports dropped bytes. A new run with
|
|
83
|
+
the same setup gives a fresh fixture without erasing the previous run. Setup
|
|
84
|
+
uses real Hrana results, and an SQL error fails startup even with HTTP 200.
|
|
85
|
+
Setup SQL is customer-controlled privileged development code; review it as you
|
|
86
|
+
would an ordinary migration. Bound Hrana null/integer/float/text/blob arguments
|
|
87
|
+
are supported. Configuration is limited to 64 KiB and 128 setup statements.
|
|
88
|
+
|
|
89
|
+
The child environment supplies only explicit tool/library/temp paths and locale,
|
|
90
|
+
without inheriting cloud/account/libSQL credentials or service configuration.
|
|
91
|
+
This entry point defaults to the read-only Free local profile described below.
|
|
92
|
+
Native database operations and guest provider access require the separate
|
|
93
|
+
explicit grants described below. Compile
|
|
94
|
+
your artifact separately; `--watch-artifact` can replace that compiled artifact
|
|
95
|
+
as described below. Source compilation and coverage use separate tooling. This
|
|
96
|
+
entry point grants no deployment authority. The local profile has a 20,000,000-byte portable artifact limit and a 128 MiB guest memory limit. Set `limits.max_concurrent` from 1 to 10 (default 4). Request and response bodies are each bounded to 5,000,000 bytes. The request budget includes upload, preparation and execution. Set `limits.request_timeout_ms` from 1 to 30,000 milliseconds (default 30,000). Expiry returns HTTP 504, and the separate five-second upload limit returns HTTP 408. A disconnected request may occupy its slot until guest execution stops.
|
|
97
|
+
|
|
98
|
+
## Reload a separately compiled artifact
|
|
99
|
+
|
|
100
|
+
Add `--watch-artifact` to the installed CLI's explicit local stack command:
|
|
101
|
+
|
|
102
|
+
```sh
|
|
103
|
+
blinkhost dev . --local-config ./blinkhost.local.json --state-dir ./local-data/run-002 --watch-artifact --json
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
After compiling a new portable WASM module, update `artifact.path` and
|
|
107
|
+
`artifact.sha256` together in the configuration. Atomic file replacement is
|
|
108
|
+
supported. The watcher polls every 500 milliseconds; it does not watch source
|
|
109
|
+
files or invoke a compiler. An identical artifact digest starts no new runtime.
|
|
110
|
+
Tools, setup SQL, limits, frontend, native permissions and provider declarations
|
|
111
|
+
must stay unchanged. Change those by starting a fresh stack instead.
|
|
112
|
+
|
|
113
|
+
The owner captures verified private artifact bytes, starts a candidate and
|
|
114
|
+
checks its engine, digest, memory, limits, database scope and provider grant.
|
|
115
|
+
It pauses new frontend API work with HTTP 503 and `Retry-After: 1`, waits for
|
|
116
|
+
in-flight frontend work and old execution slots to drain, then stops the old
|
|
117
|
+
runtime before publishing the candidate. It checks the configuration again
|
|
118
|
+
after draining. The frontend URL, physical database, native scope, provider
|
|
119
|
+
listeners and scripted provider sequences survive replacement; setup SQL is
|
|
120
|
+
not replayed. Static frontend files remain available during the pause.
|
|
121
|
+
|
|
122
|
+
JSON output emits `reloaded` or `reload_failed`. Invalid configurations, artifacts
|
|
123
|
+
or candidates keep the previous runtime running if it has not begun retirement.
|
|
124
|
+
A failure once retirement begins, or a candidate that cannot be stopped, fails
|
|
125
|
+
and stops the whole owned stack. Shutdown aborts pending reloads. Every real
|
|
126
|
+
candidate attempt retains private `reload-NNN.wasm`, `.log` and `.json` evidence;
|
|
127
|
+
validation errors before candidate creation are reported in the CLI event.
|
|
128
|
+
At most 32 real candidate attempts are allowed per stack. Start a fresh stack
|
|
129
|
+
to continue after that limit. Event output has a three-second bound; failed
|
|
130
|
+
output stops owned resources. An idle closed pipe may be detected on the next
|
|
131
|
+
write.
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
## Compile selected source files before starting
|
|
136
|
+
|
|
137
|
+
The installed CLI can invoke an explicitly configured compiler once before
|
|
138
|
+
starting the owned stack:
|
|
139
|
+
|
|
140
|
+
```sh
|
|
141
|
+
blinkhost dev . --local-config blinkhost.local.json --local-build-config blinkhost.build.json --state-dir local-data/run-002 --json
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
For example, a customer-prepared compiler wrapper can use this build config:
|
|
145
|
+
|
|
146
|
+
```json
|
|
147
|
+
{
|
|
148
|
+
"schema": "blinkhost.local-source-build/v1",
|
|
149
|
+
"source_root": "backend",
|
|
150
|
+
"files": ["Cargo.toml", "Cargo.lock", "src/main.rs"],
|
|
151
|
+
"command": { "path": "tools/compile-backend", "sha256": "REPLACE_WITH_VERIFIED_SHA256" },
|
|
152
|
+
"args": [],
|
|
153
|
+
"artifact": "module.wasm",
|
|
154
|
+
"timeout_ms": 300000
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Source roots/files stay inside the project and reject existing symlinks. Include
|
|
159
|
+
every application source file and build manifest the compiler needs. The config
|
|
160
|
+
is limited to 64 KiB, 1,024 explicit files and 64 MiB total source. Arguments are
|
|
161
|
+
literal; no shell expands them. A matching executable digest is required. The
|
|
162
|
+
wrapper is **trusted customer code**, with the local user's authority; this
|
|
163
|
+
command runner supplies bounds and process-group cleanup, rather than a security
|
|
164
|
+
sandbox. A wrapper using Docker or another service must isolate and stop its own
|
|
165
|
+
service resources, including cancellation. Use the pinned matching compiler,
|
|
166
|
+
SDK and offline dependencies for a production-like portable build.
|
|
167
|
+
|
|
168
|
+
The compiler runs in a fresh source snapshot. Its screened environment supplies
|
|
169
|
+
`BLINKHOST_LOCAL_BUILD_SOURCE`, `BLINKHOST_LOCAL_BUILD_OUTPUT` and
|
|
170
|
+
`BLINKHOST_LOCAL_BUILD_ARTIFACT`, along with a private `TMPDIR`, executable/system
|
|
171
|
+
`PATH` and locale/timezone. It does not inherit account/cloud credentials or
|
|
172
|
+
service configuration. Write the selected `.wasm` file to the supplied artifact
|
|
173
|
+
path. The default wall deadline is five minutes and the maximum is 15 minutes;
|
|
174
|
+
combined compiler output is bounded to 1 MiB. Native child-process groups stop
|
|
175
|
+
on failure, cancellation or output overflow.
|
|
176
|
+
|
|
177
|
+
After compilation, the CLI checks the executable, configuration and both the
|
|
178
|
+
original/copied source bytes again. It copies a regular portable artifact of at
|
|
179
|
+
most 20,000,000 bytes into private retained state. This build envelope checks the
|
|
180
|
+
portable header; the local WasmEdge runner subsequently performs its actual
|
|
181
|
+
artifact/resource/ABI admission before readiness. Compilation alone certifies
|
|
182
|
+
neither successful runtime admission nor application tests or coverage.
|
|
183
|
+
|
|
184
|
+
Use a new state directory outside both the served frontend and `source_root`.
|
|
185
|
+
It retains `build-001/build-result.json`, screened compiler output, source/output
|
|
186
|
+
files and `compiled-stack.json`; the running stack lives in `stack/`. Failed
|
|
187
|
+
builds retain their result and never start libSQL, runtime or frontend listeners.
|
|
188
|
+
The original stack/build configuration is preserved. Without `--watch-source`,
|
|
189
|
+
the source-build workflow runs once. It cannot be combined with
|
|
190
|
+
`--watch-artifact` in the same run.
|
|
191
|
+
|
|
192
|
+
## Watch declared source files
|
|
193
|
+
|
|
194
|
+
```sh
|
|
195
|
+
blinkhost dev . --local-config blinkhost.local.json --local-build-config blinkhost.build.json --state-dir local-data/run-003 --watch-source --json
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
The watcher checks the content of the initially declared source files once per
|
|
199
|
+
second. List every source/build input in the build configuration; it does not
|
|
200
|
+
discover new files or install dependencies. Rebuilds run serially in private
|
|
201
|
+
snapshots retained as `build-002/`, `build-003/` and so on. A successful compiled
|
|
202
|
+
candidate passes the same runtime admission and request draining used by
|
|
203
|
+
artifact reload. The database, native scope and provider response sequence stay
|
|
204
|
+
in place, and provider grants bind to the replacement artifact digest.
|
|
205
|
+
|
|
206
|
+
Compiler failures and invalid candidates retain the working module. Source and
|
|
207
|
+
configuration checks reject candidates whose inputs change before publication.
|
|
208
|
+
Another source edit triggers another attempt. The original stack configuration,
|
|
209
|
+
build configuration, source list, compiler and permissions must stay fixed;
|
|
210
|
+
configuration changes require a fresh development run.
|
|
211
|
+
|
|
212
|
+
JSON output adds `reloaded`, `build_unchanged` or `build_failed` events, also
|
|
213
|
+
retained in private `source-rebuild-NNN.json` records. At most 32 rebuilds and 64
|
|
214
|
+
normal events are allowed; a further change emits a final `build_failed` event
|
|
215
|
+
with `watching_stopped: true`. The running module remains available until you
|
|
216
|
+
stop the stack. Shutdown aborts and awaits the active compiler/reload. The final
|
|
217
|
+
command result includes the last successfully published build receipt. This
|
|
218
|
+
workflow supports portable artifacts; it does not certify AOT, native/WASM
|
|
219
|
+
coverage or production latency.
|
|
220
|
+
|
|
221
|
+
## Grant native DEFAULT database operations locally
|
|
222
|
+
|
|
223
|
+
Use a local runtime built with `customer-local-database`. Add a `native` object inside `database` alongside `executable` and your `setup` statements.
|
|
224
|
+
|
|
225
|
+
```json
|
|
226
|
+
"native": { "read": true, "write": true, "transaction": true }
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
All three booleans are required, and at least one must be true. Omission retains
|
|
230
|
+
the default denial of native operations. A build without the feature rejects
|
|
231
|
+
the grant. Choose the permissions needed by your application: a transaction
|
|
232
|
+
grant does not implicitly grant reads or writes. The compatibility DEFAULT read
|
|
233
|
+
binding remains separately available in this local profile.
|
|
234
|
+
|
|
235
|
+
The stack creates a new owned database, applies your privileged setup, then
|
|
236
|
+
installs protected receipt and database-state tables. It generates fresh database
|
|
237
|
+
and generation identifiers; it never adopts an existing state directory. The
|
|
238
|
+
readiness record's `native_database_scope` supplies those identifiers for SDK
|
|
239
|
+
calls, with environment `development` and namespace `customer-local`.
|
|
240
|
+
`native_database_permissions` records the selected grant. SDK writes require a
|
|
241
|
+
stable operation UUID and the current scope. Retry the same payload with the
|
|
242
|
+
same UUID, or reconcile its receipt before issuing a replacement operation.
|
|
243
|
+
Changed-payload replay fails. Write-only reconciliation reports commit status
|
|
244
|
+
while withholding receipt results with `receipt_results_require_read`.
|
|
245
|
+
|
|
246
|
+
Native calls use the existing gateway's SQL restrictions, permissions, budgets,
|
|
247
|
+
deadlines, scope checks, receipts and transaction cleanup. Guest SQL cannot alter
|
|
248
|
+
the protected tables, attach another database or perform schema administration.
|
|
249
|
+
Apply migrations and seeds explicitly through `database.setup` or owned local
|
|
250
|
+
Hrana tooling. Failed assertions roll back atomically; an abandoned interactive
|
|
251
|
+
transaction is rolled back before execution admission is released. Excess HTTP
|
|
252
|
+
concurrency returns 503 and does not create additional execution slots.
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
## Test customer email, payments and AI providers locally
|
|
257
|
+
|
|
258
|
+
When native transactions and provider grants are both enabled, outgoing HTTP
|
|
259
|
+
calls are blocked while an interactive database transaction is open. The SDK
|
|
260
|
+
reports `not_sent` with `external_effect_in_transaction`; the provider fixture
|
|
261
|
+
receives no request. Finish or roll back the transaction before calling a
|
|
262
|
+
provider. An abandoned transaction rolls back at guest exit, and its token
|
|
263
|
+
cannot be reused by another invocation.
|
|
264
|
+
|
|
265
|
+
A provider call after a database commit cannot undo that commit. A declined
|
|
266
|
+
payment, denied route, provider timeout, browser disconnect or local shutdown
|
|
267
|
+
may leave the earlier write committed. Reconcile the database receipt and the
|
|
268
|
+
provider's own outcome separately. Replaying a committed database operation
|
|
269
|
+
does not deduplicate a later HTTP call: use the customer's provider idempotency
|
|
270
|
+
key or a durable outbox for effects that must survive retries. An HTTP timeout
|
|
271
|
+
does not prove the provider rejected or failed to process the request.
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
Add optional `providers` to your local configuration. Each named fixture owns an
|
|
276
|
+
ephemeral loopback listener and matches an exact HTTP method and path. This
|
|
277
|
+
example returns a rate limit, then a successful email result:
|
|
278
|
+
|
|
279
|
+
```json
|
|
280
|
+
{
|
|
281
|
+
"providers": {
|
|
282
|
+
"email": {
|
|
283
|
+
"routes": [{
|
|
284
|
+
"method": "POST",
|
|
285
|
+
"path": "/send",
|
|
286
|
+
"responses": [
|
|
287
|
+
{ "status": 429, "headers": { "retry-after": "1" }, "body": "{\"error\":\"limited\"}" },
|
|
288
|
+
{ "status": 202, "body": "{\"id\":\"local-send\"}" }
|
|
289
|
+
]
|
|
290
|
+
}]
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
Read `provider_fixtures.email` from the readiness record, and give that URL to
|
|
297
|
+
your application's native integration test or replaceable provider adapter.
|
|
298
|
+
These fixtures serve only their scripted responses: they never forward to a
|
|
299
|
+
real provider or use BlinkHost's internal email, payment, AI or identity systems.
|
|
300
|
+
They require no provider credentials. Declaring a fixture alone does not grant
|
|
301
|
+
the WASM guest outbound access. Browsers must use the exact fixture origin; cross-origin browser
|
|
302
|
+
requests are rejected.
|
|
303
|
+
|
|
304
|
+
To let your compiled module call selected fixtures, use a local runtime with `customer-local-providers` enabled. Include `customer-local-database` as well when testing native database operations. Add this top-level field beside `providers`.
|
|
305
|
+
|
|
306
|
+
```json
|
|
307
|
+
"provider_permissions": { "module": "customer-local", "fixtures": ["email"] }
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
Select only the declared fixtures your module needs. The stack generates a
|
|
311
|
+
grant from its newly started listeners, exact route methods/paths and the
|
|
312
|
+
compiled artifact digest. Read the origins from `provider_fixtures` in the
|
|
313
|
+
readiness record and pass them to your own replaceable application adapters.
|
|
314
|
+
The normal SDK structured, binary and streaming HTTP calls use those grants;
|
|
315
|
+
omission retains `outbound_http_disabled`. A binary without the development
|
|
316
|
+
feature rejects the grant before startup.
|
|
317
|
+
|
|
318
|
+
The guest can call only the selected owned IPv4 loopback origins and exact
|
|
319
|
+
methods/paths. Other projects' fixtures, unrelated local listeners, external
|
|
320
|
+
hosts, redirects, query strings and normalized or encoded paths are denied.
|
|
321
|
+
Do not include routing, framing or proxy headers in customer requests. The
|
|
322
|
+
runtime preserves its request/response byte bounds, invocation-owned stream
|
|
323
|
+
handles, deadlines and cancellation. Failed calls never retry automatically;
|
|
324
|
+
your adapter decides whether an explicit retry is safe. The readiness record's
|
|
325
|
+
`provider_permissions` and `provider_grant` show the selected local capability.
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
Binary and streaming response metadata includes valid `retry-after` hints:
|
|
329
|
+
up to ten decimal digits or a canonical GMT HTTP date. Other private/custom
|
|
330
|
+
provider headers remain filtered. A stalled provider can return
|
|
331
|
+
`outcome: "unknown"` with `error: "header_timeout"` inside your application's
|
|
332
|
+
HTTP 200 response before the whole module request deadline expires. This means
|
|
333
|
+
delivery is uncertain; do not treat it as confirmation that no effect occurred.
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
Each matched request consumes the next response after its body is received.
|
|
338
|
+
Parallel requests claim distinct steps in admission order. Exhaustion returns
|
|
339
|
+
409 unless the route sets `repeat_last: true`. A disconnected admitted request
|
|
340
|
+
still consumes its step, so tests can model retries without assuming an external
|
|
341
|
+
side effect happened exactly once. An optional `request_sha256` requires an exact
|
|
342
|
+
body digest; a mismatch returns 422 without consuming a step. Unexpected paths
|
|
343
|
+
return 404. Redirects and remote destinations are forbidden.
|
|
344
|
+
|
|
345
|
+
For streaming AI tests, replace `body` with `chunks` and use the SSE content type:
|
|
346
|
+
|
|
347
|
+
```json
|
|
348
|
+
{
|
|
349
|
+
"status": 200,
|
|
350
|
+
"headers": { "content-type": "text/event-stream" },
|
|
351
|
+
"chunks": [
|
|
352
|
+
{ "body": "data: {\"token\":\"hello\"}\n\n" },
|
|
353
|
+
{ "body": "data: [DONE]\n\n", "delay_ms": 20 }
|
|
354
|
+
]
|
|
355
|
+
}
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
Response/chunk delays total at most 30 seconds. Definitions allow eight providers,
|
|
359
|
+
32 routes per provider, 32 responses per route and 64 chunks per response.
|
|
360
|
+
Request and response bodies are each limited to 64 KiB; fixture definitions have
|
|
361
|
+
a conservatively counted 1 MiB aggregate ceiling, within the existing 64 KiB
|
|
362
|
+
local configuration-file limit. Each listener admits 16 requests and 32 sockets;
|
|
363
|
+
excess admitted capacity returns 503. Incomplete headers and uploads expire after
|
|
364
|
+
five seconds. Only `content-type` and numeric `retry-after` response headers are
|
|
365
|
+
configurable.
|
|
366
|
+
|
|
367
|
+
Stopping the stack cancels fixture work and retains private
|
|
368
|
+
`provider-fixtures.json` beside the database evidence. It records route counters,
|
|
369
|
+
outcomes and request sizes/digests, without request payloads or headers. Each
|
|
370
|
+
provider retains 256 events and counts overflow. A fixture reporting a scripted
|
|
371
|
+
success proves only the local test behavior. It does not certify provider
|
|
372
|
+
delivery, billing, production availability or the guest provider path.
|
|
373
|
+
|
|
374
|
+
For a runnable example, merge the `providers` from
|
|
375
|
+
`provider-fixtures.example.json` into your local configuration and copy
|
|
376
|
+
`test-provider-example.mjs` into your application's root. Both files ship in the
|
|
377
|
+
CLI's `dist/local-development/` directory. Add this object to the `checks` array in
|
|
378
|
+
your `blinkhost.tests.json`.
|
|
379
|
+
|
|
380
|
+
```json
|
|
381
|
+
{
|
|
382
|
+
"id": "customer-providers",
|
|
383
|
+
"target": "project",
|
|
384
|
+
"cwd": ".",
|
|
385
|
+
"command": "node",
|
|
386
|
+
"args": ["test-provider-example.mjs"],
|
|
387
|
+
"kind": "integration",
|
|
388
|
+
"profile": "native",
|
|
389
|
+
"results": { "format": "blinkhost/v1" }
|
|
390
|
+
}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Set `BLINKHOST_LOCAL_PROVIDER_FIXTURES` to the readiness record's
|
|
394
|
+
`provider_fixtures` JSON object, then run `blinkhost test . --json`. The example
|
|
395
|
+
reports eight assertions and their durations, including body mismatch, retry,
|
|
396
|
+
declined payment and streaming AI responses. It uses the native profile because
|
|
397
|
+
these calls come from Node. Tests stop at the first failure and do not count
|
|
398
|
+
unexecuted assertions. Coverage remains `not_collected`. Start a fresh owned
|
|
399
|
+
stack for each run: the example consumes its scripted steps. Adapt the tests and
|
|
400
|
+
replaceable provider adapters to your application's behavior.
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
## Connect a browser and run integration checks
|
|
405
|
+
|
|
406
|
+
Open the exact frontend URL in the readiness record. The included proxy serves the configured public directory, forwarding `/api/PATH` to `/PATH` on your backend, with its original method, content type and body. It checks the browser origin and Host header. Cookies and authorization headers are omitted. The proxy also limits body sizes and rejects dotfiles, path traversal and symlinks escaping the public directory.
|
|
407
|
+
|
|
408
|
+
With a framework development server, configure its `/api/` proxy to the loopback runtime in the readiness record and enforce its own Host and Origin checks. Keep your listeners and database on loopback.
|
|
409
|
+
|
|
410
|
+
Run unit or integration checks with `blinkhost test .`. For a custom browser check that writes a structured report, add a check with `kind: integration`, `profile: browser` and `results: { "format": "blinkhost/v1" }` in `blinkhost.tests.json`. Supply the printed loopback origins to your own test code. Each state directory retains its database and private logs after Ctrl-C. Keep or remove those files according to the needs of your application.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Poll one explicit local config; builds and cloud actions are not inferred. */
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { configurationDigest } from './local-stack.mjs';
|
|
4
|
+
|
|
5
|
+
export async function watchLocalArtifacts(stack, filename, onEvent, { signal } = {}) {
|
|
6
|
+
let seen = stack.manifest.config_sha256;
|
|
7
|
+
while (!signal?.aborted) {
|
|
8
|
+
try { await delay(500, undefined, { signal }); }
|
|
9
|
+
catch (error) { if (signal?.aborted) return; throw error; }
|
|
10
|
+
if (signal?.aborted) return;
|
|
11
|
+
let digest, event;
|
|
12
|
+
try { digest = await configurationDigest(filename); }
|
|
13
|
+
catch {
|
|
14
|
+
if (seen === 'unavailable') continue;
|
|
15
|
+
seen = 'unavailable';
|
|
16
|
+
event = { schema: 'blinkhost.local-artifact-reload/v1', status: 'rejected',
|
|
17
|
+
error: 'local_stack_configuration_unavailable', previous_runtime_retained: stack.runtimeAvailable === true,
|
|
18
|
+
production_authority: false };
|
|
19
|
+
}
|
|
20
|
+
if (!event) {
|
|
21
|
+
if (digest === seen) continue;
|
|
22
|
+
seen = digest;
|
|
23
|
+
try { event = await stack.reload(); }
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (signal?.aborted) return;
|
|
26
|
+
event = { schema: 'blinkhost.local-artifact-reload/v1', status: 'rejected', config_sha256: digest,
|
|
27
|
+
error: error instanceof Error && /^[a-z_]{1,96}$/.test(error.message)
|
|
28
|
+
? error.message : 'local_stack_reload_failed',
|
|
29
|
+
previous_runtime_retained: stack.runtimeAvailable === true, production_authority: false };
|
|
30
|
+
}
|
|
31
|
+
if (event.status === 'unchanged') continue;
|
|
32
|
+
}
|
|
33
|
+
if (signal?.aborted) return;
|
|
34
|
+
await onEvent(event);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": "blinkhost.local-stack/v1",
|
|
3
|
+
"runtime": { "path": "./tools/local_backend_module", "sha256": "REPLACE_WITH_VERIFIED_RUNTIME_SHA256" },
|
|
4
|
+
"engine": { "path": "./tools/wasmedge/lib64/libwasmedge.so", "sha256": "REPLACE_WITH_VERIFIED_ENGINE_SHA256" },
|
|
5
|
+
"database": {
|
|
6
|
+
"executable": { "path": "./tools/sqld", "sha256": "REPLACE_WITH_VERIFIED_SQLD_SHA256" },
|
|
7
|
+
"setup": [
|
|
8
|
+
{ "sql": "CREATE TABLE local_customer(id INTEGER PRIMARY KEY, value TEXT NOT NULL)" },
|
|
9
|
+
{ "sql": "INSERT INTO local_customer(id,value) VALUES(1,?1)", "args": [{ "type": "text", "value": "tenant-a-original" }] }
|
|
10
|
+
]
|
|
11
|
+
},
|
|
12
|
+
"artifact": { "path": "./artifact.wasm", "sha256": "REPLACE_WITH_VERIFIED_PORTABLE_ARTIFACT_SHA256" },
|
|
13
|
+
"frontend": "./frontend",
|
|
14
|
+
"limits": { "max_concurrent": 4, "request_timeout_ms": 30000 }
|
|
15
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/** Static customer-local frontend with an owner-selected loopback WASM origin. */
|
|
2
|
+
import { createServer, request as requestHttp } from 'node:http';
|
|
3
|
+
import { isIP } from 'node:net';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { open, realpath, stat } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { BASELINE_REQUEST_BYTES, BASELINE_RESPONSE_BYTES } from '../javascript-runtime/resource-limits.js';
|
|
9
|
+
|
|
10
|
+
const loopback = value => isIP(value) === 4 ? value.split('.')[0] === '127' : value === '::1';
|
|
11
|
+
const addressHost = url => url.hostname.replace(/^\[|\]$/g, '');
|
|
12
|
+
const countHeader = (request, name) => request.rawHeaders.filter((_, index) => index % 2 === 0)
|
|
13
|
+
.filter(key => key.toLowerCase() === name).length;
|
|
14
|
+
|
|
15
|
+
export function localOrigin(value, allowZeroPort = false) {
|
|
16
|
+
const url = new URL(value);
|
|
17
|
+
if (url.protocol !== 'http:' || !loopback(addressHost(url)) || url.username || url.password
|
|
18
|
+
|| url.pathname !== '/' || url.search || url.hash || (!allowZeroPort && url.port === '0')) {
|
|
19
|
+
throw new Error('Use an HTTP loopback IP origin without credentials, path, query or fragment.');
|
|
20
|
+
}
|
|
21
|
+
return url;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function options(arguments_) {
|
|
25
|
+
const values = new Map();
|
|
26
|
+
for (let index = 0; index < arguments_.length; index += 2) {
|
|
27
|
+
const key = arguments_[index], value = arguments_[index + 1];
|
|
28
|
+
if (!['--frontend', '--runtime-url', '--listen'].includes(key) || !value || values.has(key)) {
|
|
29
|
+
throw new Error('Expected --frontend DIRECTORY --runtime-url HTTP_LOOPBACK_ORIGIN [--listen LOOPBACK_IP:PORT].');
|
|
30
|
+
}
|
|
31
|
+
values.set(key, value);
|
|
32
|
+
}
|
|
33
|
+
if (!values.has('--frontend') || !values.has('--runtime-url')) throw new Error('--frontend and --runtime-url are required.');
|
|
34
|
+
const listen = localOrigin('http://' + (values.get('--listen') ?? '127.0.0.1:3000'), true);
|
|
35
|
+
return { frontend: values.get('--frontend'), runtime: localOrigin(values.get('--runtime-url')),
|
|
36
|
+
host: addressHost(listen), port: listen.port ? Number(listen.port) : 80 };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
40
|
+
'.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
|
|
41
|
+
'.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
|
|
42
|
+
'.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.wasm': 'application/wasm' };
|
|
43
|
+
|
|
44
|
+
export async function createLocalFrontendServer({ frontend, runtime: runtimeValue }) {
|
|
45
|
+
let runtime = localOrigin(String(runtimeValue)), runtimePaused = false, activeRuntimeRequests = 0;
|
|
46
|
+
const root = await realpath(frontend);
|
|
47
|
+
if (!(await stat(root)).isDirectory()) throw new Error('The frontend must be a directory.');
|
|
48
|
+
let server;
|
|
49
|
+
const reply = (response, status, text) => {
|
|
50
|
+
if (response.writableEnded || response.destroyed) return;
|
|
51
|
+
if (response.headersSent) { response.destroy(); return; }
|
|
52
|
+
response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' }); response.end(text);
|
|
53
|
+
};
|
|
54
|
+
server = createServer(async (request, response) => {
|
|
55
|
+
const bound = server.address();
|
|
56
|
+
const host = `${bound.address.includes(':') ? '[' + bound.address + ']' : bound.address}:${bound.port}`;
|
|
57
|
+
const origin = `http://${host}`;
|
|
58
|
+
response.setHeader('cache-control', 'no-store');
|
|
59
|
+
response.setHeader('x-content-type-options', 'nosniff');
|
|
60
|
+
if (!loopback(request.socket.remoteAddress) || countHeader(request, 'host') !== 1
|
|
61
|
+
|| countHeader(request, 'origin') > 1 || request.headers.host !== host
|
|
62
|
+
|| (request.headers.origin !== undefined && request.headers.origin !== origin)) {
|
|
63
|
+
return reply(response, 403, 'local origin rejected');
|
|
64
|
+
}
|
|
65
|
+
if (!request.url?.startsWith('/') || request.url.startsWith('//') || request.url.includes('\\')
|
|
66
|
+
|| request.url.length > 4096) return reply(response, 400, 'invalid local request');
|
|
67
|
+
if (request.url.startsWith('/api/')) {
|
|
68
|
+
if (runtimePaused) {
|
|
69
|
+
response.setHeader('retry-after', '1');
|
|
70
|
+
request.resume();
|
|
71
|
+
return reply(response, 503, 'local module reload in progress');
|
|
72
|
+
}
|
|
73
|
+
// Capture one target for the entire request, including its headers. Only
|
|
74
|
+
// the local stack owner can change the target; HTTP exposes no controls.
|
|
75
|
+
const target = runtime;
|
|
76
|
+
activeRuntimeRequests += 1;
|
|
77
|
+
response.once('close', () => { activeRuntimeRequests -= 1; });
|
|
78
|
+
// Never forward ambient cookies, account grants, custom Host or redirect a
|
|
79
|
+
// request to a provider-selected address. Credentials belong to the app.
|
|
80
|
+
const headers = { host: target.host, origin: target.origin };
|
|
81
|
+
if (request.headers['content-type']) headers['content-type'] = request.headers['content-type'];
|
|
82
|
+
const upstream = requestHttp({ hostname: addressHost(target), port: target.port || 80,
|
|
83
|
+
method: request.method, path: request.url.slice(4), headers, agent: false }, incoming => {
|
|
84
|
+
const responseHeaders = { 'content-type': incoming.headers['content-type'] ?? 'application/octet-stream' };
|
|
85
|
+
if (incoming.headers['retry-after']) responseHeaders['retry-after'] = incoming.headers['retry-after'];
|
|
86
|
+
// Buffer within the ABI response limit before emitting success. This
|
|
87
|
+
// prevents an oversized or truncated upstream reply appearing complete.
|
|
88
|
+
const chunks = []; let size = 0;
|
|
89
|
+
incoming.on('data', chunk => {
|
|
90
|
+
size += chunk.length;
|
|
91
|
+
if (size > BASELINE_RESPONSE_BYTES) {
|
|
92
|
+
incoming.destroy(); upstream.destroy(); reply(response, 502, 'local response limit exceeded');
|
|
93
|
+
} else chunks.push(chunk);
|
|
94
|
+
});
|
|
95
|
+
incoming.on('end', () => {
|
|
96
|
+
if (!response.writableEnded && !response.destroyed) {
|
|
97
|
+
response.writeHead(incoming.statusCode, responseHeaders); response.end(Buffer.concat(chunks));
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
incoming.on('error', () => reply(response, 502, 'local runtime response unavailable'));
|
|
101
|
+
});
|
|
102
|
+
const deadline = setTimeout(() => {
|
|
103
|
+
upstream.destroy(); reply(response, 504, 'local runtime request timed out');
|
|
104
|
+
}, 35_000);
|
|
105
|
+
const bodyDeadline = setTimeout(() => {
|
|
106
|
+
upstream.destroy(); reply(response, 408, 'local request body timed out');
|
|
107
|
+
}, 5000);
|
|
108
|
+
request.on('end', () => clearTimeout(bodyDeadline));
|
|
109
|
+
let received = 0;
|
|
110
|
+
request.on('data', chunk => {
|
|
111
|
+
received += chunk.length;
|
|
112
|
+
if (received > BASELINE_REQUEST_BYTES) {
|
|
113
|
+
upstream.destroy(); reply(response, 413, 'local request limit exceeded');
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
request.on('aborted', () => upstream.destroy());
|
|
117
|
+
response.on('close', () => { clearTimeout(deadline); clearTimeout(bodyDeadline); upstream.destroy(); });
|
|
118
|
+
upstream.on('error', () => reply(response, 502, 'local runtime unavailable'));
|
|
119
|
+
request.pipe(upstream);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (!['GET', 'HEAD'].includes(request.method)) return reply(response, 405, 'static files require GET or HEAD');
|
|
123
|
+
let file;
|
|
124
|
+
try {
|
|
125
|
+
const pathname = decodeURIComponent(request.url.split('?')[0]);
|
|
126
|
+
const segments = pathname.split('/');
|
|
127
|
+
if (segments.some(part => part === '..' || part.startsWith('.') || part.includes('\0') || part.includes('\\'))) {
|
|
128
|
+
return reply(response, 404, 'local file unavailable');
|
|
129
|
+
}
|
|
130
|
+
const requested = path.join(root, pathname === '/' ? 'index.html' : pathname);
|
|
131
|
+
const resolved = await realpath(requested);
|
|
132
|
+
if (!resolved.startsWith(root + path.sep)) return reply(response, 404, 'local file unavailable');
|
|
133
|
+
file = await open(requested, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
134
|
+
const metadata = await file.stat();
|
|
135
|
+
const type = mime[path.extname(resolved).toLowerCase()];
|
|
136
|
+
if (!metadata.isFile() || !type || metadata.size > BASELINE_RESPONSE_BYTES) {
|
|
137
|
+
return reply(response, 404, 'local file unavailable');
|
|
138
|
+
}
|
|
139
|
+
// Read through the already checked descriptor, with one extra byte to
|
|
140
|
+
// reject growth during the read. Allocation never exceeds the file cap.
|
|
141
|
+
let contents;
|
|
142
|
+
if (request.method !== 'HEAD') {
|
|
143
|
+
contents = Buffer.alloc(metadata.size + 1);
|
|
144
|
+
let size = 0;
|
|
145
|
+
while (size < contents.length) {
|
|
146
|
+
const { bytesRead } = await file.read(contents, size, contents.length - size, size);
|
|
147
|
+
if (!bytesRead) break;
|
|
148
|
+
size += bytesRead;
|
|
149
|
+
}
|
|
150
|
+
if (size !== metadata.size) return reply(response, 404, 'local file changed');
|
|
151
|
+
contents = contents.subarray(0, size);
|
|
152
|
+
}
|
|
153
|
+
response.setHeader('content-type', type);
|
|
154
|
+
response.setHeader('content-length', metadata.size);
|
|
155
|
+
response.setHeader('content-security-policy', "default-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'");
|
|
156
|
+
response.end(contents);
|
|
157
|
+
} catch { reply(response, 404, 'local file unavailable'); }
|
|
158
|
+
finally { if (file) await file.close(); }
|
|
159
|
+
});
|
|
160
|
+
server.requestTimeout = 5000;
|
|
161
|
+
server.headersTimeout = 5000;
|
|
162
|
+
server.on('clientError', (_, socket) => socket.destroy());
|
|
163
|
+
Object.defineProperties(server, {
|
|
164
|
+
setRuntime: { value: value => { runtime = localOrigin(String(value)); } },
|
|
165
|
+
setRuntimePaused: { value: value => {
|
|
166
|
+
if (typeof value !== 'boolean') throw new Error('invalid_local_runtime_pause');
|
|
167
|
+
runtimePaused = value;
|
|
168
|
+
} },
|
|
169
|
+
activeRuntimeRequests: { get: () => activeRuntimeRequests },
|
|
170
|
+
});
|
|
171
|
+
return server;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
|
175
|
+
try {
|
|
176
|
+
const configuration = options(process.argv.slice(2));
|
|
177
|
+
const server = await createLocalFrontendServer(configuration);
|
|
178
|
+
server.on('error', () => { console.error('Local frontend listener unavailable.'); process.exitCode = 1; });
|
|
179
|
+
server.listen(configuration.port, configuration.host, () => {
|
|
180
|
+
const address = server.address();
|
|
181
|
+
console.log(JSON.stringify({ schema: 'blinkhost.local-frontend/v1',
|
|
182
|
+
url: `http://${address.address.includes(':') ? '[' + address.address + ']' : address.address}:${address.port}`,
|
|
183
|
+
runtime: configuration.runtime.origin, production_authority: false }));
|
|
184
|
+
});
|
|
185
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => {
|
|
186
|
+
server.close(); server.closeAllConnections();
|
|
187
|
+
});
|
|
188
|
+
} catch { console.error('Invalid local frontend configuration. See local-development/README.md.'); process.exitCode = 2; }
|
|
189
|
+
}
|