@blinkhost/cli 2.7.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.
Files changed (63) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +514 -2
  3. package/dist/api.d.ts +2 -2
  4. package/dist/api.js +57 -8
  5. package/dist/assistant.js +6 -1
  6. package/dist/cli.js +157 -9
  7. package/dist/guidance.d.ts +1 -1
  8. package/dist/guidance.js +43 -11
  9. package/dist/javascript-runtime/resource-limits.js +3 -0
  10. package/dist/javascript-runtime/resource-profiles.js +2 -0
  11. package/dist/local-dev.d.ts +3 -0
  12. package/dist/local-dev.js +145 -0
  13. package/dist/local-development/README.md +410 -0
  14. package/dist/local-development/artifact-watch.mjs +36 -0
  15. package/dist/local-development/blinkhost.local.example.json +15 -0
  16. package/dist/local-development/frontend-proxy.mjs +189 -0
  17. package/dist/local-development/hello.rs +24 -0
  18. package/dist/local-development/local-stack.mjs +511 -0
  19. package/dist/local-development/native-database.mjs +37 -0
  20. package/dist/local-development/provider-fixtures.example.json +36 -0
  21. package/dist/local-development/provider-fixtures.mjs +203 -0
  22. package/dist/local-development/provider-grants.mjs +36 -0
  23. package/dist/local-development/test-provider-example.mjs +74 -0
  24. package/dist/local-source-build.d.ts +39 -0
  25. package/dist/local-source-build.js +225 -0
  26. package/dist/local-source-watch.d.ts +24 -0
  27. package/dist/local-source-watch.js +87 -0
  28. package/dist/local-test-command.d.ts +49 -0
  29. package/dist/local-test-command.js +128 -0
  30. package/dist/local-test-config.d.ts +37 -0
  31. package/dist/local-test-config.js +174 -0
  32. package/dist/local-test-gates.d.ts +71 -0
  33. package/dist/local-test-gates.js +247 -0
  34. package/dist/local-test-go-runner.d.ts +27 -0
  35. package/dist/local-test-go-runner.js +209 -0
  36. package/dist/local-test-node-arguments.d.ts +2 -0
  37. package/dist/local-test-node-arguments.js +14 -0
  38. package/dist/local-test-node-reporter.d.ts +7 -0
  39. package/dist/local-test-node-reporter.js +159 -0
  40. package/dist/local-test-results.d.ts +65 -0
  41. package/dist/local-test-results.js +163 -0
  42. package/dist/local-test-rust-runner.d.ts +18 -0
  43. package/dist/local-test-rust-runner.js +252 -0
  44. package/dist/local-test-starters.d.ts +3 -0
  45. package/dist/local-test-starters.js +157 -0
  46. package/dist/logs.d.ts +43 -0
  47. package/dist/logs.js +417 -0
  48. package/dist/module-build-diagnostics.d.ts +10 -0
  49. package/dist/module-build-diagnostics.js +208 -0
  50. package/dist/module-build.js +4 -0
  51. package/dist/release-preparation-diagnostics.d.ts +38 -0
  52. package/dist/release-preparation-diagnostics.js +204 -0
  53. package/dist/remote.js +14 -0
  54. package/dist/templates.d.ts +1 -0
  55. package/dist/templates.js +4 -1
  56. package/dist/test-credentials.d.ts +7 -0
  57. package/dist/test-credentials.js +236 -0
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/dist/workflows.d.ts +39 -2
  61. package/dist/workflows.js +241 -14
  62. package/package.json +4 -3
  63. package/test-runners/python-unittest.py +266 -0
@@ -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
+ }
@@ -0,0 +1,24 @@
1
+ #![no_std]
2
+ #![no_main]
3
+
4
+ use core::panic::PanicInfo;
5
+
6
+ #[link(wasm_import_module = "blinkhost_system")]
7
+ unsafe extern "C" {
8
+ fn write_response(bytes: *const u8, len: usize) -> i32;
9
+ }
10
+
11
+ #[unsafe(no_mangle)]
12
+ pub extern "C" fn _start() {
13
+ let response = br#"{"status":200,"headers":{"content-type":"text/plain"},"body":"Hello from BlinkHost!"}"#;
14
+ // The host returns the number of response bytes it accepted.
15
+ let written = unsafe { write_response(response.as_ptr(), response.len()) };
16
+ if written != response.len() as i32 {
17
+ core::arch::wasm32::unreachable();
18
+ }
19
+ }
20
+
21
+ #[panic_handler]
22
+ fn panic(_: &PanicInfo) -> ! {
23
+ core::arch::wasm32::unreachable()
24
+ }