@crvouga/mockingbird-preview 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +355 -2
- package/dist/chunk-WAMTSUKW.js +400 -0
- package/dist/chunk-WAMTSUKW.js.map +7 -0
- package/dist/dev-proxy.d.ts +176 -0
- package/dist/dev-proxy.js +15 -0
- package/dist/dev-proxy.js.map +7 -0
- package/dist/index.d.ts +229 -0
- package/dist/index.js +1008 -0
- package/dist/index.js.map +7 -0
- package/dist/node.d.ts +14 -0
- package/dist/node.js +76 -0
- package/dist/node.js.map +7 -0
- package/dist/types-CQYnWD6z.d.ts +27 -0
- package/package.json +57 -4
package/README.md
CHANGED
|
@@ -1,3 +1,356 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @crvouga/mockingbird-preview
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Local emulators. Real API contracts. Part of [Mockingbird](https://github.com/crvouga-organization/mockingbird).
|
|
4
|
+
|
|
5
|
+
Reusable infrastructure for static application previews: a streaming Fetch bridge over MessagePort,
|
|
6
|
+
shared worker lifecycle, verified compressed assets, a Node test adapter, and Cloudflare named
|
|
7
|
+
Worker Preview deployment. App entrypoints, schemas, synthetic fixtures, credentials acquisition,
|
|
8
|
+
cloud identities and organization CI policy remain in the consuming application.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @crvouga/mockingbird-preview
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
A module worker creates its application once, and attaches each visiting page to that same system:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createPreviewHost, installPreviewWorkerHost } from "@crvouga/mockingbird-preview"
|
|
22
|
+
|
|
23
|
+
const host = createPreviewHost({
|
|
24
|
+
artifact: "sha256:the-build-identity",
|
|
25
|
+
boot: async ({ generation, signal }) => ({
|
|
26
|
+
fetch: (request) => Response.json({ generation, path: new URL(request.url).pathname }),
|
|
27
|
+
dispose: async () => {},
|
|
28
|
+
}),
|
|
29
|
+
allow: (url) => url.hostname === "app.preview",
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
installPreviewWorkerHost(host, self)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The page uses `connectSharedPreviewWorker("/worker.js", { application: "demo", artifact:
|
|
36
|
+
"sha256:the-build-identity", generation: 0 })` and its returned `fetch`. The browser's normal
|
|
37
|
+
same-origin restrictions apply to the worker URL. Each connected page has isolated in-flight
|
|
38
|
+
requests. Disconnecting a page does not dispose the shared system. Call `host.reset()` to abort
|
|
39
|
+
connections, dispose state and boot the next generation; reconnect clients afterwards. A failed
|
|
40
|
+
boot is visible through `status()` and returns HTTP 503. Calling `dispose()` terminates the host.
|
|
41
|
+
The application must honor the boot/request AbortSignals to terminate work it started.
|
|
42
|
+
|
|
43
|
+
## API
|
|
44
|
+
|
|
45
|
+
- `createPreviewClient(port, options)` exposes `fetch`, `dispose()` and the number of pending
|
|
46
|
+
requests. `timeoutMs` covers response headers and the complete response stream (30 seconds by
|
|
47
|
+
default); configure it for intentionally long-lived streams. Worker death without a port error
|
|
48
|
+
is detected by this deadline. `allow(url)` optionally restricts destinations at the client.
|
|
49
|
+
- `servePreviewPort(port, fetch, options)` handles requests through the application's Fetch
|
|
50
|
+
handler. Responses use transferable ArrayBuffers and one chunk per consumer pull; cancellation
|
|
51
|
+
aborts the handler's signal and reader. Pre-header failures reject fetch and post-header failures
|
|
52
|
+
error its body. Error messages are opaque to avoid leaking server details. `maxRequests`
|
|
53
|
+
bounds concurrent requests per port, default 128. `onClose` supports connection accounting.
|
|
54
|
+
- `createPreviewHost({ artifact, boot, allow })` serializes boot/reset/dispose and exposes
|
|
55
|
+
`connect`, `fetch`, `status`, `ready`, `reset` and `dispose`. It owns no emulator-specific state:
|
|
56
|
+
use a fleet's lifecycle inside the boot/dispose callbacks.
|
|
57
|
+
- `sharedPreviewWorkerName({ application, artifact, generation })` creates an unambiguous worker
|
|
58
|
+
identity; changing artifact or generation creates a distinct SharedWorker.
|
|
59
|
+
- `connectSharedPreviewWorker(url, options)` opens a module SharedWorker and connects its port.
|
|
60
|
+
`connectDedicatedPreviewWorker(url, options)` uses a dedicated module Worker and transferred
|
|
61
|
+
MessageChannel. Both expose `fetch`, `pending`, `worker` and `dispose`; worker errors reject
|
|
62
|
+
pending requests. Dedicated disposal also terminates its worker.
|
|
63
|
+
- `installPreviewWorkerHost(host, scope)` accepts SharedWorker connection events and dedicated
|
|
64
|
+
worker MessagePort handshakes. Returns an async disposer.
|
|
65
|
+
- `createPreviewArtifact(bytes, { commit, url, encoding })` records format version, source commit,
|
|
66
|
+
exact packed byte count and SHA-256. `parsePreviewArtifact(value)` validates this manifest.
|
|
67
|
+
`digestPreviewBytes(bytes)` returns a lowercase SHA-256 digest.
|
|
68
|
+
- `loadPreviewArtifact(manifest, options)` fetches with `no-store`, no credentials and redirect
|
|
69
|
+
refusal; checks expected commit, size and hash before optional gzip decompression. Packed and
|
|
70
|
+
decompressed sizes are bounded by `maximumBytes` (128 MiB default). The result is bytes; the
|
|
71
|
+
caller deliberately chooses how to execute or persist trusted application code. It never evals
|
|
72
|
+
arbitrary fetched source.
|
|
73
|
+
- `selectPreviewAction(currentFacts, builtCommit)` chooses deploy/remove/skip from current PR
|
|
74
|
+
state. Closed PRs select removal; forks and stale build heads cannot deploy.
|
|
75
|
+
- `planPreviewSweep({ previews, openNames, owns, now, retentionMs, capacity })` is a pure plan
|
|
76
|
+
listing managed names removed for orphaning, expiry or capacity. It never removes unmanaged
|
|
77
|
+
names or performs cloud operations. Capacity eviction retains the newest managed previews.
|
|
78
|
+
- `createCloudflarePreviews({ accountId, workerName, token, fetch })` returns `deploy`, `list` and
|
|
79
|
+
`remove`. `deploy` takes explicit static files, source commit, a name and a `currentPullRequest`
|
|
80
|
+
callback. It checks current facts before upload and immediately before deployment, sends only
|
|
81
|
+
missing assets, preserves optional `_headers` text and uses content identity to avoid repeating
|
|
82
|
+
an already identical deployment. `list` follows pages and throws on API failures; `remove`
|
|
83
|
+
treats HTTP 404 as success. No production Worker deployment is changed.
|
|
84
|
+
- `previewNodeHandler(fetch)` and `listenPreview(fetch, { port, hostname })`, from the `/node`
|
|
85
|
+
export, expose the same Fetch handler or browser bridge to a Node HTTP test runner. The default
|
|
86
|
+
listener is loopback on an ephemeral port. Responses are always `Cache-Control: no-store` to
|
|
87
|
+
avoid browser worker-asset cache failures. Stream errors destroy the response instead of
|
|
88
|
+
creating a successful EOF. Call the returned `close()` to release the listener.
|
|
89
|
+
- `createDevProxy({ providers, env, allow, basePath?, allowOrigins?, trustNonBrowser?, fetch? })`, from
|
|
90
|
+
the `/dev-proxy` export (also re-exported from the package root), is the dev proxy's Fetch
|
|
91
|
+
handler; `devProxyWorker(options)` wraps it as a Cloudflare Worker `{ fetch(request, env) }`.
|
|
92
|
+
`allow` is required: an anchored pattern per env value a provider reads, checked default-deny.
|
|
93
|
+
`devProviders` holds the Stripe, Junction, Resend, Slack, Twilio and FCM providers;
|
|
94
|
+
`NON_PROD_PATTERNS` the vendor formats that by themselves prove a non-production credential;
|
|
95
|
+
and `devBaseUrlName(id)` the `<ID>_BASE_URL` override name. See [Dev resources](#dev-resources).
|
|
96
|
+
- `createDevResources({ proxyUrl?, storage?, fetch? })` is the browser side: `upstream(id)` for an
|
|
97
|
+
emulator's `createRuntime({ upstream })` and `controls(services)` for the System screen.
|
|
98
|
+
`DEV_MESSAGES` holds its status sentences and `DEV_STORAGE_KEYS` its storage keys.
|
|
99
|
+
|
|
100
|
+
## Cookies, redirects and trust
|
|
101
|
+
|
|
102
|
+
The bridge defaults to removing Cookie and Set-Cookie headers. It does not borrow browser cookies
|
|
103
|
+
or impersonate the page origin. For a fully virtual application, both bridge ends may opt into
|
|
104
|
+
`cookies: true`; that carries explicitly supplied cookie headers, but supplies no cookie jar and
|
|
105
|
+
never writes `document.cookie`. The host must own a jar per intended user/session if needed.
|
|
106
|
+
Responses preserve redirect statuses and Location; redirects are always manual, including when a
|
|
107
|
+
Request uses its usual `follow` default. Follow redirects explicitly through the same allowlisted
|
|
108
|
+
Fetch boundary. Do not forward authorization/cookies to a new origin. These deliberate rules avoid
|
|
109
|
+
silently following an allowed virtual request into a real production host.
|
|
110
|
+
|
|
111
|
+
Request bodies are buffered before transfer; response bodies stream with backpressure. This is
|
|
112
|
+
not a streaming request-upload implementation. Ports are trusted capabilities, not an untrusted
|
|
113
|
+
RPC/authentication boundary. Browser-delivered code, environment values and files remain visible
|
|
114
|
+
and editable by the visitor. Never put production or shared secret values in these artifacts.
|
|
115
|
+
|
|
116
|
+
Cloudflare helpers require an existing parent Worker and explicit account credentials on the
|
|
117
|
+
trusted CI/server side. They create named Preview resources with base-config inheritance disabled,
|
|
118
|
+
no environment bindings, and assets-only deployments. Existing organization ownership/naming
|
|
119
|
+
rules remain the caller's responsibility. Per-PR deployment jobs must be serialized externally:
|
|
120
|
+
the final head re-read narrows, but cannot eliminate, races without a provider compare-and-swap.
|
|
121
|
+
A retry after an ambiguous create response should re-read the named preview before retrying.
|
|
122
|
+
No live cloud credentials were used for the package's acceptance tests.
|
|
123
|
+
|
|
124
|
+
Cloudflare protocol references:
|
|
125
|
+
[official Preview API implementation](https://github.com/cloudflare/workers-sdk/blob/main/packages/deploy-helpers/src/preview/api.ts),
|
|
126
|
+
[asset upload documentation](https://developers.cloudflare.com/workers/static-assets/direct-upload/),
|
|
127
|
+
[Worker Previews](https://developers.cloudflare.com/workers/previews/).
|
|
128
|
+
|
|
129
|
+
## Dev resources
|
|
130
|
+
|
|
131
|
+
A preview runs every third-party service as an in-browser emulator. Dev resources let a viewer
|
|
132
|
+
flip one service at a time from **Emulated** to **Dev**: that emulator's runtime switches to
|
|
133
|
+
forward mode (`PUT /__admin/upstream {"mode":"forward"}`) and sends the app's API calls to a real
|
|
134
|
+
**non-production** resource the app's dev instance uses: a Stripe account in test mode,
|
|
135
|
+
Junction's sandbox, a dev Resend account, a dev Slack workspace, a self-hosted dev instance. The
|
|
136
|
+
browser never holds a credential. A small Fetch handler, the **dev proxy**
|
|
137
|
+
(`@crvouga/mockingbird-preview/dev-proxy`), sits next to the static preview, holds the secrets in
|
|
138
|
+
its environment and attaches them per request, and only after checking that every one of them is
|
|
139
|
+
allowed. It is mounted on the dev app's own origin and trusts that app: there is no access key,
|
|
140
|
+
and the client never handles a credential.
|
|
141
|
+
|
|
142
|
+
```mermaid
|
|
143
|
+
sequenceDiagram
|
|
144
|
+
participant App as App code (browser)
|
|
145
|
+
participant Emu as Emulator runtime (browser)
|
|
146
|
+
participant Proxy as Dev proxy (Worker / server)
|
|
147
|
+
participant Vendor as Non-prod resource (e.g. Stripe test mode)
|
|
148
|
+
App->>Emu: POST /v1/customers (Authorization: Bearer sk_test_fake)
|
|
149
|
+
Note over Emu: mode = forward (System screen chose "Dev")
|
|
150
|
+
Emu->>Proxy: POST /__dev/stripe/v1/customers<br/>Sec-Fetch-Site: same-origin<br/>(Authorization dropped)
|
|
151
|
+
Note over Proxy: same origin? else 403 cross_origin<br/>STRIPE_SECRET_KEY must match allow (sk_test_/rk_test_)<br/>and not deny (sk_live_/rk_live_), else 403<br/>strip cookie, origin, x-mockingbird-*, ...
|
|
152
|
+
Proxy->>Vendor: POST https://api.stripe.com/v1/customers<br/>Authorization: Bearer STRIPE_SECRET_KEY
|
|
153
|
+
Vendor-->>Proxy: 200 {"id": "cus_..."}
|
|
154
|
+
Proxy-->>Emu: 200 (set-cookie dropped, secrets redacted)
|
|
155
|
+
Emu-->>App: 200 {"id": "cus_..."}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Safety model: default deny
|
|
159
|
+
|
|
160
|
+
Nothing is reachable until you say, in code, what a non-production value looks like.
|
|
161
|
+
|
|
162
|
+
- **`allow` is required.** For every env value a provider reads (its secrets, its identifiers and
|
|
163
|
+
any `<ID>_BASE_URL` override) `allow` names the pattern it must match. A provider with an env
|
|
164
|
+
value that has no entry, or does not match it, is **blocked**: the manifest reports why and
|
|
165
|
+
every relay answers `403 { "error": { "code": "not_allowed", "message" } }` without sending
|
|
166
|
+
anything. Patterns must be anchored (`/^…$/`, no `m` flag) or `createDevProxy()` /
|
|
167
|
+
`devProxyWorker()` throws; each is matched against the whole value. They live in code so they
|
|
168
|
+
are reviewed, never in the environment.
|
|
169
|
+
- **Known production formats always lose.** A provider can declare `deny` patterns that win over
|
|
170
|
+
`allow`: Stripe refuses `sk_live_` and `rk_live_` keys even under `allow: { STRIPE_SECRET_KEY: /^.+$/ }`.
|
|
171
|
+
- **`NON_PROD_PATTERNS`** holds the vendor formats that by themselves prove a non-production
|
|
172
|
+
credential (`STRIPE_SECRET_KEY: /^(sk|rk)_test_[A-Za-z0-9]+$/`,
|
|
173
|
+
`JUNCTION_API_KEY: /^sk_(us|eu)_[A-Za-z0-9_-]+$/`). Resend, Slack, Twilio and FCM credentials
|
|
174
|
+
look the same in production and development, so there is no entry for them: pin an identifier
|
|
175
|
+
(`TWILIO_ACCOUNT_SID: /^AC0123…$/`, `FCM_PROJECT_ID: /^my-app-dev$/`) or write a pattern that
|
|
176
|
+
only your dev credential matches.
|
|
177
|
+
- **Reasons never echo values.** `blocked` reads "No allow-list pattern for RESEND_API_KEY",
|
|
178
|
+
"STRIPE_SECRET_KEY does not match its allow-list pattern" or "STRIPE_SECRET_KEY is a production
|
|
179
|
+
credential"; the System screen shows it as the service's reason.
|
|
180
|
+
- **Base URL overrides are allow-listed too.** Each provider has a default host. An env value
|
|
181
|
+
`<ID>_BASE_URL` (`RESEND_BASE_URL`, `JUNCTION_BASE_URL`, ...; `devBaseUrlName(id)`) replaces it
|
|
182
|
+
only when `allow` has a matching entry for that name and the value is an `https:` URL without
|
|
183
|
+
query or credentials; a path prefix is kept. Otherwise the provider is blocked. This is how a
|
|
184
|
+
self-hosted dev instance is reached.
|
|
185
|
+
|
|
186
|
+
| id | Reaches by default | Secrets | Identifiers | `allow` entry |
|
|
187
|
+
| --- | --- | --- | --- | --- |
|
|
188
|
+
| `stripe` | `api.stripe.com` (`/v1/*`) | `STRIPE_SECRET_KEY` | | `NON_PROD_PATTERNS` (test-mode keys; live keys are denied) |
|
|
189
|
+
| `junction` | Junction's sandbox `api.sandbox.tryvital.io` (`api.sandbox.eu.tryvital.io` for `sk_eu_` keys; `/v<n>/*`) | `JUNCTION_API_KEY` | | `NON_PROD_PATTERNS` |
|
|
190
|
+
| `resend` | `api.resend.com` | `RESEND_API_KEY` | | pin your dev key, or reach a dev instance via `RESEND_BASE_URL` |
|
|
191
|
+
| `slack` | `slack.com` (`/api/*`) | `SLACK_BOT_TOKEN` | | pin your dev workspace's bot token |
|
|
192
|
+
| `twilio` | `api.twilio.com`, `verify.twilio.com`, `lookups.twilio.com`, `messaging.twilio.com` (by path) | `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN` | `TWILIO_ACCOUNT_SID` | pin an identifier: `TWILIO_ACCOUNT_SID` (test credentials or a dev subaccount) |
|
|
193
|
+
| `fcm` | `fcm.googleapis.com` (`POST /v1/projects/*/messages:send`) | `FCM_ACCESS_TOKEN`, `FCM_PROJECT_ID` | `FCM_PROJECT_ID` | pin an identifier: `FCM_PROJECT_ID` (your dev project) |
|
|
194
|
+
|
|
195
|
+
Every value in the Secrets column needs an `allow` entry, including the token next to a pinned
|
|
196
|
+
identifier (a loose `/^.+$/` is fine there: the pin is what proves non-prod).
|
|
197
|
+
|
|
198
|
+
Provider notes: Stripe prices, products, coupons and webhook endpoints the app names must exist in
|
|
199
|
+
the test-mode account. Junction lab test ids and users must exist in Junction's sandbox team; a
|
|
200
|
+
`JUNCTION_BASE_URL` override replaces the EU host switch. Resend really sends email: use a sending
|
|
201
|
+
domain and recipients you own. Slack channels and users must exist in the bot's workspace. Twilio
|
|
202
|
+
rewrites any `/Accounts/<sid>/` to the configured SID; sender numbers and Messaging / Verify
|
|
203
|
+
Service SIDs must exist in that account; `/v1/Services` always goes to Messaging, so Conversations'
|
|
204
|
+
`/v1/Services` is not reachable; a `TWILIO_BASE_URL` override replaces only the default API host
|
|
205
|
+
(`/2010-04-01/*`), Verify, Lookups and Messaging keep their vendor hosts. FCM rewrites the project
|
|
206
|
+
id to `FCM_PROJECT_ID`; the access token is a short-lived OAuth token (about an hour), refresh it
|
|
207
|
+
out of band.
|
|
208
|
+
|
|
209
|
+
For every provider: vendor webhooks are **not** relayed back to the browser emulator, and
|
|
210
|
+
forwarded responses are relayed as-is (emulators with a forwarded-response hook, such as Resend,
|
|
211
|
+
FCM and Twilio, record a receipt; Stripe and Junction do not mirror remote objects into their
|
|
212
|
+
state). A path a provider does not map answers `501`.
|
|
213
|
+
|
|
214
|
+
### Trust and transport
|
|
215
|
+
|
|
216
|
+
- **Same-origin only.** The proxy answers a request only when the browser marks it
|
|
217
|
+
`Sec-Fetch-Site: same-origin` and its `Origin`, when sent, is the proxy's own origin (or listed
|
|
218
|
+
in `allowOrigins`, which also turns on CORS for exactly those origins). Cross-site, same-site and
|
|
219
|
+
navigation requests, and a foreign `Origin`, get `403 { "error": { "code": "cross_origin" } }`
|
|
220
|
+
with nothing sent. A request without `Sec-Fetch-Site` (curl, a server, a test) is refused too
|
|
221
|
+
unless the proxy is built with `trustNonBrowser: true`.
|
|
222
|
+
- **Who can open the preview is the preview host's job.** Anyone who can load the page can use its
|
|
223
|
+
dev resources, so restrict the preview itself, e.g. with
|
|
224
|
+
[Cloudflare Access](https://developers.cloudflare.com/cloudflare-one/policies/access/) in front
|
|
225
|
+
of the Worker. The allow-list above is what keeps those resources non-production.
|
|
226
|
+
- **Fixed hosts only.** Each provider builds the URL on its fixed (or allow-listed override)
|
|
227
|
+
base from the path; a crafted path cannot change the host, and unmapped paths answer `501`.
|
|
228
|
+
Redirects are returned, never followed.
|
|
229
|
+
- **Secrets never reach the browser.** The proxy drops the caller's `authorization`, `cookie`,
|
|
230
|
+
`origin`, `referer`, `x-mockingbird-*`, `cf-*`, `x-forwarded-*` and `forwarded` headers,
|
|
231
|
+
attaches the credential itself, drops `set-cookie` from the answer, and redacts every secret
|
|
232
|
+
value from its own errors and from text responses (account identifiers such as the Twilio
|
|
233
|
+
Account SID stay). Errors are `{ "error": { "code", "message" } }`.
|
|
234
|
+
- **Modes per viewer.** The browser keeps only the chosen modes in its own `localStorage`.
|
|
235
|
+
|
|
236
|
+
### Mounting the proxy
|
|
237
|
+
|
|
238
|
+
A Cloudflare Worker that serves the static preview and the proxy on one origin (set the secrets
|
|
239
|
+
with `wrangler secret put STRIPE_SECRET_KEY`, ...):
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
import {
|
|
243
|
+
devProviders,
|
|
244
|
+
devProxyWorker,
|
|
245
|
+
NON_PROD_PATTERNS,
|
|
246
|
+
} from "@crvouga/mockingbird-preview/dev-proxy"
|
|
247
|
+
|
|
248
|
+
const proxy = devProxyWorker({
|
|
249
|
+
basePath: "/__dev",
|
|
250
|
+
providers: [devProviders.stripe, devProviders.junction, devProviders.twilio],
|
|
251
|
+
allow: {
|
|
252
|
+
...NON_PROD_PATTERNS,
|
|
253
|
+
TWILIO_ACCOUNT_SID: /^AC_YOUR_DEV_ACCOUNT_SID$/, // the dev account, pinned
|
|
254
|
+
TWILIO_AUTH_TOKEN: /^[0-9a-f]{32}$/,
|
|
255
|
+
},
|
|
256
|
+
})
|
|
257
|
+
|
|
258
|
+
export default {
|
|
259
|
+
fetch(request: Request, env: Record<string, string | undefined> & { ASSETS: { fetch(request: Request): Promise<Response> } }) {
|
|
260
|
+
const { pathname } = new URL(request.url)
|
|
261
|
+
if (pathname === "/__dev" || pathname.startsWith("/__dev/")) {
|
|
262
|
+
const { ASSETS: _assets, ...secrets } = env
|
|
263
|
+
return proxy.fetch(request, secrets)
|
|
264
|
+
}
|
|
265
|
+
return env.ASSETS.fetch(request)
|
|
266
|
+
},
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
A Bun server (Node 18+ and Deno work the same with any Fetch-handler server), secrets from
|
|
271
|
+
`.env.local` / the process environment, reaching a self-hosted dev Resend-compatible instance:
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { createDevProxy, devProviders, NON_PROD_PATTERNS } from "@crvouga/mockingbird-preview/dev-proxy"
|
|
275
|
+
|
|
276
|
+
const dev = createDevProxy({
|
|
277
|
+
basePath: "/__dev",
|
|
278
|
+
providers: [devProviders.stripe, devProviders.resend],
|
|
279
|
+
env: process.env,
|
|
280
|
+
allow: {
|
|
281
|
+
...NON_PROD_PATTERNS,
|
|
282
|
+
RESEND_API_KEY: /^re_dev_[A-Za-z0-9_]+$/,
|
|
283
|
+
RESEND_BASE_URL: /^https:\/\/mail\.dev\.example\.com$/,
|
|
284
|
+
},
|
|
285
|
+
allowOrigins: ["http://localhost:5173"], // only when the page is served from another origin
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
Bun.serve({
|
|
289
|
+
port: 8787,
|
|
290
|
+
fetch: (request) =>
|
|
291
|
+
new URL(request.url).pathname.startsWith("/__dev")
|
|
292
|
+
? dev(request)
|
|
293
|
+
: new Response("Not found", { status: 404 }),
|
|
294
|
+
})
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
`GET /__dev/` answers the manifest:
|
|
298
|
+
`{ providers: [{ id, label, configured, missing, blocked? }] }`.
|
|
299
|
+
|
|
300
|
+
### Browser wiring
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
import { createDevResources } from "@crvouga/mockingbird-preview"
|
|
304
|
+
import { createRuntime as createStripe } from "@crvouga/mockingbird-service-stripe"
|
|
305
|
+
import { createRuntime as createResend } from "@crvouga/mockingbird-service-resend"
|
|
306
|
+
|
|
307
|
+
const dev = createDevResources({ proxyUrl: "/__dev" }) // omit proxyUrl: dev resources not offered
|
|
308
|
+
|
|
309
|
+
// Each emulator forwards through the proxy when switched to Dev; it boots emulated.
|
|
310
|
+
const stripe = createStripe({ upstream: dev.upstream("stripe") })
|
|
311
|
+
const resend = createResend({ upstream: dev.upstream("resend") })
|
|
312
|
+
|
|
313
|
+
// The System screen's service list (`mountSystemHarness(host, surfaces, { services })`).
|
|
314
|
+
const services = dev.controls([
|
|
315
|
+
{ id: "stripe", label: "Stripe", category: "Payments", admin: (r) => stripe.fetch(r) },
|
|
316
|
+
{ id: "resend", label: "Resend", category: "Email", admin: (r) => resend.fetch(r) },
|
|
317
|
+
{
|
|
318
|
+
id: "keycloak",
|
|
319
|
+
label: "Keycloak",
|
|
320
|
+
admin: async () => Response.json({ mode: "emulated" }),
|
|
321
|
+
unsupported: "Runs in this browser; there is no remote dev resource",
|
|
322
|
+
},
|
|
323
|
+
])
|
|
324
|
+
|
|
325
|
+
await services.setMode("stripe", "dev") // throws a readable reason when unavailable
|
|
326
|
+
const { dev: status, services: rows } = await services.list()
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
`upstream(id)` gives `{ baseUrl: "<proxy>/<id>", fetch, rewriteAuth }`: `fetch` sends the request
|
|
330
|
+
to the proxy as-is (the browser adds `Sec-Fetch-Site`), `rewriteAuth` drops the app's fake
|
|
331
|
+
`authorization` and any cookie. `controls()` reads each
|
|
332
|
+
emulator's mode from `GET /__admin/upstream`, and its `unavailable` reason follows this order:
|
|
333
|
+
the spec's `unsupported`, no proxy configured, proxy unreachable or refusing the page
|
|
334
|
+
(`cross_origin`), provider secrets missing, the provider's `blocked` reason. Chosen modes persist per viewer; because emulator state resets on reload, the
|
|
335
|
+
first `list()` re-applies stored Dev choices that are still available.
|
|
336
|
+
|
|
337
|
+
## Validation
|
|
338
|
+
|
|
339
|
+
Tests exercise concurrent requests, first-chunk delivery, cancellation, deadlines, failures on
|
|
340
|
+
both sides of response headers, target restrictions, two virtual apps sharing a real Chromium
|
|
341
|
+
SharedWorker, reset/disconnect, compressed integrity/size limits, the Node HTTP adapter, and injected
|
|
342
|
+
Cloudflare upload/pagination/stale-head/deletion failures. Cloudflare behavior is based on official
|
|
343
|
+
API source and documentation, not a live-account parity claim.
|
|
344
|
+
|
|
345
|
+
## Runtime compatibility
|
|
346
|
+
|
|
347
|
+
`@crvouga/mockingbird-runtime/preview/*` delegates to this package, preserving its legacy signatures.
|
|
348
|
+
`loadPreviewArtifact` also accepts `LegacyPreviewArtifact` (`version: 1`, `sha256`, `url`, optional
|
|
349
|
+
`compression: "gzip"`), whose hash covers decoded bytes. Legacy downloads still enforce the same
|
|
350
|
+
bounded loading, no-store and redirect policy; they cannot satisfy `expectedCommit` because they
|
|
351
|
+
carry no commit. New manifests cover packed bytes, size and source commit.
|
|
352
|
+
|
|
353
|
+
The bridge's `exposeErrors: true` option on both ends exists for trusted legacy compatibility.
|
|
354
|
+
It forwards original error messages and must not be enabled on a boundary that needs opaque
|
|
355
|
+
errors. Both ends must also opt into `cookies: true` to transport explicit virtual cookie headers.
|
|
356
|
+
These options do not create a browser cookie jar or expose server-held credentials.
|