@intentius/behold 0.29.49 → 0.29.51

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 (52) hide show
  1. package/AGENTS.md +155 -4
  2. package/demos.json +15 -0
  3. package/dist/cli.js +2440 -998
  4. package/example-three-cloud/README.md +38 -0
  5. package/example-three-cloud/aws/chant.config.ts +8 -0
  6. package/example-three-cloud/aws/src/site.ts +20 -0
  7. package/example-three-cloud/azure/chant.config.ts +1 -0
  8. package/example-three-cloud/azure/src/site.ts +19 -0
  9. package/example-three-cloud/chant.workspace.json +10 -0
  10. package/example-three-cloud/dns/chant.config.ts +1 -0
  11. package/example-three-cloud/dns/ops/front-door.op.ts +21 -0
  12. package/example-three-cloud/dns/src/route53.ts +54 -0
  13. package/example-three-cloud/gcp/chant.config.ts +1 -0
  14. package/example-three-cloud/gcp/src/site.ts +19 -0
  15. package/example-three-cloud/package-lock.json +715 -0
  16. package/example-three-cloud/package.json +16 -0
  17. package/example-three-cloud/scripts/emulators-up.sh +46 -0
  18. package/example-three-cloud/scripts/front-door.ts +400 -0
  19. package/package.json +4 -2
  20. package/web/app.js +250 -23
  21. package/web/composite-members.js +21 -0
  22. package/web/composite-members.test.js +25 -0
  23. package/web/decision-points.js +70 -0
  24. package/web/decision-points.test.js +87 -0
  25. package/web/dots-kiosk.js +4 -1
  26. package/web/dots-live.test.js +10 -0
  27. package/web/dots.js +41 -4
  28. package/web/export-note.js +35 -0
  29. package/web/export-note.test.js +45 -0
  30. package/web/health-marks.js +146 -0
  31. package/web/health-marks.test.js +67 -0
  32. package/web/index.html +52 -0
  33. package/web/kiosk-runs.js +51 -5
  34. package/web/kiosk-runs.test.js +42 -1
  35. package/web/kiosk-source.js +23 -0
  36. package/web/kiosk-source.test.js +19 -1
  37. package/web/kiosk-track.js +9 -5
  38. package/web/kiosk-track.test.js +12 -2
  39. package/web/kiosk.html +26 -3
  40. package/web/kiosk.js +28 -6
  41. package/web/local-run.js +276 -0
  42. package/web/local-run.test.js +46 -0
  43. package/web/sql-yodeler-lane.js +1 -1
  44. package/web/terragucci-timeline.js +5 -4
  45. package/web/terragucci-timeline.test.js +1 -1
  46. package/web/trunk-lane.js +54 -5
  47. package/web/trunk-lane.test.js +86 -3
  48. package/web/view-url.js +25 -0
  49. package/web/view-url.test.js +24 -1
  50. package/web/why.js +1 -1
  51. package/web/why.test.js +1 -1
  52. package/web/workspace-gates.js +35 -18
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "behold-example-three-cloud",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "A website in three clouds behind Route 53, as a chant workspace on the floci emulators: behold's three-cloud demo and its exported page.",
6
+ "scripts": {
7
+ "emulators": "bash scripts/emulators-up.sh",
8
+ "front-door": "tsx scripts/front-door.ts all --out export"
9
+ },
10
+ "dependencies": {
11
+ "@intentius/chant": "^0.124.34",
12
+ "@intentius/chant-lexicon-aws": "^0.124.34",
13
+ "@intentius/chant-lexicon-azure": "^0.124.34",
14
+ "@intentius/chant-lexicon-gcp": "^0.124.34"
15
+ }
16
+ }
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env bash
2
+ # Boot the three emulators the three-cloud demo runs on: floci (AWS),
3
+ # floci-az (Azure) and floci-gcp (GCP). `behold demo three-cloud` runs this as
4
+ # its setup, then serves the workspace with --local, which finds them running
5
+ # under chant's own container names and reuses them.
6
+ #
7
+ # chant's `chant emulator up` would boot its pinned images, without the Docker
8
+ # socket the emulators need to run the website's containers. So the images
9
+ # here are the builds that probe Route 53 health checks (lex00/floci#259) and
10
+ # serve Container Apps and Cloud Run from real containers, each given the
11
+ # socket, and floci-az is told to run Container Apps for real rather than mock
12
+ # them. A container that is already running is left as it is.
13
+ #
14
+ # Names, ports and images can be overridden, so a second copy can run beside
15
+ # the first: FLOCI_CONTAINER, FLOCI_AZ_CONTAINER, FLOCI_GCP_CONTAINER,
16
+ # FLOCI_PORT, FLOCI_AZ_PORT, FLOCI_GCP_PORT, FLOCI_IMAGE, FLOCI_AZ_IMAGE,
17
+ # FLOCI_GCP_IMAGE.
18
+ set -euo pipefail
19
+
20
+ boot() {
21
+ local name=$1 port=$2 inner=$3 image=$4 health=$5; shift 5
22
+ if [ -n "$(docker ps -q -f "name=^${name}\$")" ]; then
23
+ echo "three-cloud: ${name} already running"
24
+ else
25
+ docker rm -f "$name" >/dev/null 2>&1 || true
26
+ echo "three-cloud: starting ${name} (${image}) on :${port}"
27
+ docker run -d --name "$name" -p "${port}:${inner}" -v /var/run/docker.sock:/var/run/docker.sock "$@" "$image" >/dev/null
28
+ fi
29
+ for _ in $(seq 1 60); do
30
+ if curl -fsS "http://localhost:${port}${health}" >/dev/null 2>&1; then
31
+ echo "three-cloud: ${name} ready on http://localhost:${port}"
32
+ return 0
33
+ fi
34
+ sleep 2
35
+ done
36
+ echo "three-cloud: ${name} did not answer on :${port}${health} within two minutes" >&2
37
+ return 1
38
+ }
39
+
40
+ boot "${FLOCI_CONTAINER:-chant-floci}" "${FLOCI_PORT:-4566}" 4566 \
41
+ "${FLOCI_IMAGE:-ghcr.io/lex00/floci:e9ebdb3}" /_floci/health
42
+ boot "${FLOCI_AZ_CONTAINER:-chant-floci-az}" "${FLOCI_AZ_PORT:-4577}" 4577 \
43
+ "${FLOCI_AZ_IMAGE:-ghcr.io/lex00/floci-az:e1def56}" /_floci/health \
44
+ -e FLOCI_AZ_SERVICES_CONTAINER_APPS_MOCKED=false
45
+ boot "${FLOCI_GCP_CONTAINER:-chant-floci-gcp}" "${FLOCI_GCP_PORT:-4588}" 4588 \
46
+ "${FLOCI_GCP_IMAGE:-ghcr.io/lex00/floci-gcp:4bb6a04}" /_floci-gcp/health
@@ -0,0 +1,400 @@
1
+ /**
2
+ * The front door, rebuilt on the floci emulators: apply the four members,
3
+ * turn Azure off, wait for Route 53 to notice, and export the page.
4
+ *
5
+ * tsx scripts/front-door.ts all --out <dir> every step below, in order
6
+ * tsx scripts/front-door.ts apply build and apply gcp, azure, aws, then dns, and wait
7
+ * until `chant lifecycle health` reads azureCheck healthy
8
+ * tsx scripts/front-door.ts azure-off deactivate the Azure app's active revision
9
+ * tsx scripts/front-door.ts wait until azureCheck reads unhealthy
10
+ * tsx scripts/front-door.ts export --out <dir> behold export, opening on env local at the composites zoom
11
+ *
12
+ * dns/ops/front-door.op.ts runs the same steps as an Op's phases. The emulators
13
+ * are the ones `behold demo three-cloud` boots (chant-floci, chant-floci-az,
14
+ * chant-floci-gcp); FLOCI_CONTAINER, FLOCI_AZ_CONTAINER and FLOCI_GCP_CONTAINER
15
+ * name others, and AWS_ENDPOINT_URL, AZURE_ENDPOINT_URL and GCP_ENDPOINT_URL
16
+ * say where they answer.
17
+ */
18
+ import { execFileSync, spawnSync } from "node:child_process";
19
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
20
+ import { dirname, join, resolve } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { awsApply, awsDelete } from "@intentius/chant-lexicon-aws/op/activities";
23
+ import { azApply } from "@intentius/chant-lexicon-azure/op/activities";
24
+ import { gcpApply } from "@intentius/chant-lexicon-gcp/op/activities";
25
+
26
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
27
+ const WORK = join(ROOT, ".front-door");
28
+ const CHANT = join(ROOT, "node_modules", ".bin", "chant");
29
+
30
+ const ENV = "local";
31
+ // The Azure resource group and the GCP project, as chant's live reads find them:
32
+ // the resource group is named after the environment.
33
+ const RESOURCE_GROUP = ENV;
34
+ const GCP_PROJECT = process.env.GCP_PROJECT_ID ?? "three-cloud";
35
+ const GCP_REGION = process.env.GCP_REGION ?? "asia-northeast1";
36
+ const SUBSCRIPTION = process.env.AZURE_SUBSCRIPTION_ID ?? "00000000-0000-0000-0000-000000000001";
37
+
38
+ const AWS = process.env.AWS_ENDPOINT_URL ?? "http://localhost:4566";
39
+ const AZURE = process.env.AZURE_ENDPOINT_URL ?? "http://localhost:4577";
40
+ const GCP = process.env.GCP_ENDPOINT_URL ?? "http://localhost:4588";
41
+ const CONTAINERS = {
42
+ aws: process.env.FLOCI_CONTAINER ?? "chant-floci",
43
+ azure: process.env.FLOCI_AZ_CONTAINER ?? "chant-floci-az",
44
+ gcp: process.env.FLOCI_GCP_CONTAINER ?? "chant-floci-gcp",
45
+ };
46
+
47
+ /** Everything a chant or behold child needs to reach the emulators. */
48
+ const childEnv: NodeJS.ProcessEnv = {
49
+ ...process.env,
50
+ AWS_ENDPOINT_URL: AWS,
51
+ AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID ?? "test",
52
+ AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY ?? "test",
53
+ AWS_REGION: process.env.AWS_REGION ?? "us-east-1",
54
+ AZURE_ENDPOINT_URL: AZURE,
55
+ AZURE_SUBSCRIPTION_ID: SUBSCRIPTION,
56
+ GCP_ENDPOINT_URL: GCP,
57
+ GCP_PROJECT_ID: GCP_PROJECT,
58
+ GOOGLE_CLOUD_PROJECT: GCP_PROJECT,
59
+ GCP_REGION,
60
+ };
61
+
62
+ const say = (line: string): void => void process.stdout.write(`front-door: ${line}\n`);
63
+
64
+ class Refusal extends Error {}
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Build
68
+
69
+ function build(member: string): string {
70
+ const out = join(WORK, member === "gcp" ? "gcp.yaml" : `${member}.json`);
71
+ mkdirSync(WORK, { recursive: true });
72
+ const r = spawnSync(CHANT, ["build", "src", "-o", out], { cwd: join(ROOT, member), env: childEnv, encoding: "utf8" });
73
+ if (r.status !== 0) throw new Refusal(`chant build failed in ${member}:\n${r.stderr || r.stdout}`);
74
+ return out;
75
+ }
76
+
77
+ /** A copy of a CloudFormation template whose parameters default to `values`,
78
+ * so `awsApply` (which passes no parameters) creates the stack with them. */
79
+ function withDefaults(template: string, values: Record<string, string>): string {
80
+ const doc = JSON.parse(readFileSync(template, "utf8")) as { Parameters?: Record<string, Record<string, unknown>> };
81
+ for (const [name, value] of Object.entries(values)) {
82
+ const p = doc.Parameters?.[name];
83
+ if (!p) throw new Refusal(`${template} declares no parameter ${name}`);
84
+ p.Default = value;
85
+ }
86
+ const out = template.replace(/\.json$/, ".params.json");
87
+ writeFileSync(out, JSON.stringify(doc, null, 2));
88
+ return out;
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // Where the checkers connect
93
+
94
+ /** An emulator container's address on Docker's network, which floci's
95
+ * checkers (in their own container) can reach. */
96
+ function containerAddress(name: string): string {
97
+ let ip = "";
98
+ try {
99
+ ip = execFileSync("docker", ["inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}", name], { encoding: "utf8" }).trim().split(/\s+/)[0] ?? "";
100
+ } catch {
101
+ throw new Refusal(`no container named ${name}: boot the emulators first (behold demo three-cloud does)`);
102
+ }
103
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(ip)) throw new Refusal(`container ${name} has no IPv4 address on a Docker network`);
104
+ return ip;
105
+ }
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // Apply
109
+
110
+ async function applyGcp(): Promise<string> {
111
+ const manifest = build("gcp");
112
+ say(`gcp: applying ${manifest} to ${GCP} (project ${GCP_PROJECT})`);
113
+ await gcpApply({ manifestPath: manifest, endpoint: GCP, project: GCP_PROJECT });
114
+ // Config Connector YAML has no outputs, so the build's `gcpEndpoint` output
115
+ // is not written (chant warns). The URI is read from the service instead.
116
+ // The service's location is the manifest's, or us-central1 where gcpApply
117
+ // puts a service that names none.
118
+ const location = /^\s+location:\s*['"]?([a-z0-9-]+)/m.exec(readFileSync(manifest, "utf8"))?.[1] ?? "us-central1";
119
+ const svc = (await getJson(`${GCP}/v2/projects/${GCP_PROJECT}/locations/${location}/services/web`)) as { uri?: string };
120
+ if (!svc.uri) throw new Refusal(`gcp: the Cloud Run service web has no uri yet (${JSON.stringify(svc).slice(0, 300)})`);
121
+ return new URL(svc.uri).hostname;
122
+ }
123
+
124
+ async function applyAzure(): Promise<string> {
125
+ const template = build("azure");
126
+ say(`azure: applying ${template} to ${AZURE} (resource group ${RESOURCE_GROUP})`);
127
+ await azApply({ templatePath: template, resourceGroup: RESOURCE_GROUP, location: "westeurope", endpoint: AZURE, subscriptionId: SUBSCRIPTION });
128
+ const app = await getJson(`${appUrl()}?api-version=2024-03-01`);
129
+ const fqdn = (app.properties as { configuration?: { ingress?: { fqdn?: string } } } | undefined)?.configuration?.ingress?.fqdn;
130
+ if (!fqdn) throw new Refusal(`azure: the container app web has no ingress fqdn (${JSON.stringify(app).slice(0, 300)})`);
131
+ await azureOn();
132
+ return fqdn;
133
+ }
134
+
135
+ /** A run before this one turned Azure off, and applying the same app again
136
+ * leaves its revision inactive: turn the newest one back on. */
137
+ async function azureOn(): Promise<void> {
138
+ const list = await getJson(`${appUrl()}/revisions?api-version=2024-03-01`);
139
+ const revisions = (list.value ?? []) as Array<{ name: string; properties?: { active?: boolean; createdTime?: string } }>;
140
+ if (!revisions.length || revisions.some((r) => r.properties?.active !== false)) return;
141
+ const newest = [...revisions].sort((a, b) => (a.properties?.createdTime ?? a.name).localeCompare(b.properties?.createdTime ?? b.name)).at(-1)!;
142
+ const res = await fetch(`${appUrl()}/revisions/${newest.name}/activate?api-version=2024-03-01`, { method: "POST" });
143
+ if (!res.ok) throw new Refusal(`azure: activating revision ${newest.name} answered ${res.status}: ${await res.text()}`);
144
+ say(`azure: revision ${newest.name} activated again`);
145
+ }
146
+
147
+ /** The aws member, or why it could not be applied. */
148
+ async function applyAws(): Promise<{ endpoint: string } | { refused: string }> {
149
+ const template = build("aws");
150
+ const subnets = await defaultSubnets();
151
+ const params = withDefaults(template, { vpcId: subnets.vpc, subnetIds: subnets.ids.join(",") });
152
+ // A stack that rolled back on its first create can't be updated; start it again.
153
+ if ((await stackStatus("three-cloud-aws")) === "ROLLBACK_COMPLETE") {
154
+ await awsDelete({ templatePath: params, stackName: "three-cloud-aws", endpoint: AWS, timeoutMs: 180_000 });
155
+ }
156
+ say(`aws: applying ${params} to ${AWS} as stack three-cloud-aws`);
157
+ try {
158
+ await awsApply({ templatePath: params, stackName: "three-cloud-aws", endpoint: AWS, timeoutMs: 180_000 });
159
+ } catch (e) {
160
+ const why = await stackFailure("three-cloud-aws");
161
+ return { refused: `${e instanceof Error ? e.message : String(e)}${why ? `: ${why}` : ""}` };
162
+ }
163
+ const out = await stackOutputs("three-cloud-aws");
164
+ return out.awsEndpoint ? { endpoint: out.awsEndpoint } : { refused: "the stack has no awsEndpoint output" };
165
+ }
166
+
167
+ /** Where floci's checkers connect for one cloud's check, as Route 53 does
168
+ * for a check with an IPAddress: to the address and port given, sending the
169
+ * endpoint as the Host header. */
170
+ interface Probe {
171
+ address: string;
172
+ port: number;
173
+ }
174
+
175
+ /**
176
+ * A copy of the dns template whose checks connect to the emulators. The
177
+ * source declares checks as they are on AWS, where the checkers resolve each
178
+ * endpoint; on the emulators nothing outside Docker resolves a floci-az or
179
+ * floci-gcp hostname, so each check is given the emulator container's address
180
+ * and port (lex00/floci#259). This is the one place the deployed dns stack
181
+ * differs from its source, and behold shows those two fields as drift.
182
+ */
183
+ function withProbes(template: string, probes: Record<string, Probe>): void {
184
+ const doc = JSON.parse(readFileSync(template, "utf8")) as { Resources: Record<string, { Properties: { HealthCheckConfig: Record<string, unknown> } }> };
185
+ for (const [check, probe] of Object.entries(probes)) {
186
+ const cfg = doc.Resources[check]?.Properties?.HealthCheckConfig;
187
+ if (!cfg) throw new Refusal(`${template} declares no health check ${check}`);
188
+ cfg.IPAddress = probe.address;
189
+ cfg.Port = probe.port;
190
+ }
191
+ writeFileSync(template, JSON.stringify(doc, null, 2));
192
+ }
193
+
194
+ async function applyDns(endpoints: Record<string, string>, probes: Record<string, Probe>): Promise<void> {
195
+ const params = withDefaults(build("dns"), endpoints);
196
+ withProbes(params, probes);
197
+ // The stack named after the environment, where chant's live read looks for a single-stack project.
198
+ say(`dns: applying ${params} to ${AWS} as stack ${ENV}`);
199
+ await awsApply({ templatePath: params, stackName: ENV, endpoint: AWS, timeoutMs: 180_000 });
200
+ }
201
+
202
+ export async function apply(): Promise<void> {
203
+ const gcp = await applyGcp();
204
+ say(`gcp: web answers as ${gcp}`);
205
+ const azure = await applyAzure();
206
+ say(`azure: web answers as ${azure}`);
207
+ const aws = await applyAws();
208
+ // An aws stack that doesn't apply leaves its record pointing at a name that
209
+ // doesn't resolve and its check probing an address nothing answers on
210
+ // (192.0.2.1, kept for documentation by RFC 5737), so the page shows AWS
211
+ // failing and the rest still runs.
212
+ if ("refused" in aws) say(`aws: NOT APPLIED, so the aws record has nothing behind it and its check fails: ${aws.refused}`);
213
+ else say(`aws: web answers as ${aws.endpoint}`);
214
+ await applyDns(
215
+ {
216
+ awsEndpoint: "endpoint" in aws ? aws.endpoint : "aws.three-cloud.invalid",
217
+ azureEndpoint: azure,
218
+ gcpEndpoint: gcp,
219
+ },
220
+ {
221
+ // floci runs a load balancer's listener on the listener's own port (80)
222
+ // in its container, not behind :4566.
223
+ awsCheck: { address: "endpoint" in aws ? containerAddress(CONTAINERS.aws) : "192.0.2.1", port: 80 },
224
+ // floci-az serves every app on its own port, by Host header.
225
+ azureCheck: { address: containerAddress(CONTAINERS.azure), port: 4577 },
226
+ // floci-gcp's front door serves Cloud Run services by Host header too.
227
+ gcpCheck: { address: containerAddress(CONTAINERS.gcp), port: 4588 },
228
+ },
229
+ );
230
+ say("dns: applied");
231
+ // Before anything is turned off, the check on Azure has to pass: that is
232
+ // what shows the checkers reach floci-az at all.
233
+ await waitFor("healthy");
234
+ }
235
+
236
+ // ---------------------------------------------------------------------------
237
+ // Turn Azure off
238
+
239
+ function appUrl(): string {
240
+ return `${AZURE}/subscriptions/${SUBSCRIPTION}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.App/containerApps/web`;
241
+ }
242
+
243
+ export async function azureOff(): Promise<void> {
244
+ const list = await getJson(`${appUrl()}/revisions?api-version=2024-03-01`);
245
+ const active = ((list.value ?? []) as Array<{ name: string; properties?: { active?: boolean } }>).filter((r) => r.properties?.active !== false);
246
+ if (!active.length) {
247
+ say("azure: no active revision, already off");
248
+ return;
249
+ }
250
+ for (const r of active) {
251
+ const res = await fetch(`${appUrl()}/revisions/${r.name}/deactivate?api-version=2024-03-01`, { method: "POST" });
252
+ if (!res.ok) throw new Refusal(`azure: deactivating revision ${r.name} answered ${res.status}: ${await res.text()}`);
253
+ say(`azure: revision ${r.name} deactivated`);
254
+ }
255
+ }
256
+
257
+ // ---------------------------------------------------------------------------
258
+ // Wait for Route 53 to notice
259
+
260
+ /** A `chant-health/v1` document, as far as this script reads it. */
261
+ interface HealthDoc {
262
+ lexicons?: Record<string, { entities?: Record<string, { state?: string; detail?: string }> }>;
263
+ }
264
+
265
+ /** azureCheck's state and detail as `chant lifecycle health` reads them. */
266
+ function azureCheckHealth(): { state?: string; detail?: string } {
267
+ const r = spawnSync(CHANT, ["lifecycle", "health", ENV, "--json"], { cwd: join(ROOT, "dns"), env: childEnv, encoding: "utf8" });
268
+ let doc: HealthDoc;
269
+ try {
270
+ doc = JSON.parse(r.stdout) as HealthDoc;
271
+ } catch {
272
+ return { detail: (r.stderr || r.stdout).trim().split("\n")[0] };
273
+ }
274
+ return doc.lexicons?.aws?.entities?.azureCheck ?? {};
275
+ }
276
+
277
+ /** Until azureCheck reads `want`: healthy once the apply has settled (the
278
+ * checkers really reach floci-az), unhealthy once Azure is off. */
279
+ export async function waitFor(want: "healthy" | "unhealthy", timeoutMs = 180_000): Promise<void> {
280
+ const until = Date.now() + timeoutMs;
281
+ let last: { state?: string; detail?: string } = {};
282
+ while (Date.now() < until) {
283
+ last = azureCheckHealth();
284
+ if (last.state === want) {
285
+ say(`dns: azureCheck reads ${want} (${last.detail})${want === "unhealthy" ? "; the azure record is out of rotation" : ""}`);
286
+ return;
287
+ }
288
+ await new Promise((r) => setTimeout(r, 5000));
289
+ }
290
+ throw new Refusal(`dns: azureCheck still reads ${last.state ?? "nothing"}, not ${want}, after ${timeoutMs / 1000}s${last.detail ? ` (${last.detail})` : ""}`);
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // Export
295
+
296
+ export const NOTE = "Run this yourself: `npx @intentius/behold demo three-cloud`";
297
+
298
+ export function exportPage(out: string): void {
299
+ // BEHOLD names the behold to run (a checkout's `tsx src/cli.ts`, say);
300
+ // by default it is the published one.
301
+ const behold = (process.env.BEHOLD ?? "npx --yes @intentius/behold").split(" ");
302
+ const args = [...behold.slice(1), "export", ROOT, "--out", resolve(out), "--open-env", ENV, "--open-zoom", "composites", "--note", NOTE];
303
+ say(`export: ${behold[0]} ${args.join(" ")}`);
304
+ const r = spawnSync(behold[0]!, args, { env: childEnv, stdio: "inherit" });
305
+ if (r.status !== 0) throw new Refusal(`behold export exited ${r.status}`);
306
+ }
307
+
308
+ // ---------------------------------------------------------------------------
309
+ // Small helpers
310
+
311
+ async function getJson(url: string): Promise<Record<string, unknown>> {
312
+ const res = await fetch(url);
313
+ const text = await res.text();
314
+ if (!res.ok) throw new Refusal(`GET ${url} answered ${res.status}: ${text.slice(0, 300)}`);
315
+ return JSON.parse(text) as Record<string, unknown>;
316
+ }
317
+
318
+ async function awsQuery(service: string, form: Record<string, string>): Promise<string> {
319
+ const res = await fetch(`${AWS}/`, {
320
+ method: "POST",
321
+ headers: {
322
+ "content-type": "application/x-www-form-urlencoded",
323
+ authorization: `AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/${service}/aws4_request, SignedHeaders=host, Signature=0`,
324
+ },
325
+ body: new URLSearchParams(form).toString(),
326
+ });
327
+ const text = await res.text();
328
+ if (!res.ok) throw new Refusal(`${service} ${form.Action} answered ${res.status}: ${text.slice(0, 300)}`);
329
+ return text;
330
+ }
331
+
332
+ async function defaultSubnets(): Promise<{ vpc: string; ids: string[] }> {
333
+ const vpcs = await awsQuery("ec2", { Action: "DescribeVpcs", Version: "2016-11-15", "Filter.1.Name": "isDefault", "Filter.1.Value.1": "true" });
334
+ const vpc = /<vpcId>([^<]+)<\/vpcId>/.exec(vpcs)?.[1];
335
+ if (!vpc) throw new Refusal("aws: the emulator has no default VPC");
336
+ const subnets = await awsQuery("ec2", { Action: "DescribeSubnets", Version: "2016-11-15", "Filter.1.Name": "vpc-id", "Filter.1.Value.1": vpc });
337
+ const ids = [...subnets.matchAll(/<subnetId>([^<]+)<\/subnetId>/g)].map((m) => m[1]!).slice(0, 2);
338
+ if (ids.length < 2) throw new Refusal(`aws: the default VPC ${vpc} has fewer than two subnets`);
339
+ return { vpc, ids };
340
+ }
341
+
342
+ async function stackStatus(stack: string): Promise<string | undefined> {
343
+ try {
344
+ const xml = await awsQuery("cloudformation", { Action: "DescribeStacks", Version: "2010-05-15", StackName: stack });
345
+ return /<StackStatus>([^<]+)<\/StackStatus>/.exec(xml)?.[1];
346
+ } catch {
347
+ return undefined;
348
+ }
349
+ }
350
+
351
+ /** The first resource-level reason a stack's events give for failing. */
352
+ async function stackFailure(stack: string): Promise<string | undefined> {
353
+ try {
354
+ const xml = await awsQuery("cloudformation", { Action: "DescribeStackEvents", Version: "2010-05-15", StackName: stack });
355
+ for (const event of xml.split("<member>")) {
356
+ const field = (tag: string) => new RegExp(`<${tag}>([^<]*)</${tag}>`).exec(event)?.[1];
357
+ const id = field("LogicalResourceId");
358
+ const reason = field("ResourceStatusReason");
359
+ if (id && id !== stack && field("ResourceStatus") === "CREATE_FAILED" && reason) {
360
+ return `${id}: ${reason.replace(/&apos;/g, "'").replace(/&quot;/g, '"')}`;
361
+ }
362
+ }
363
+ } catch {
364
+ // no events to read; the applier's own message stands
365
+ }
366
+ return undefined;
367
+ }
368
+
369
+ async function stackOutputs(stack: string): Promise<Record<string, string>> {
370
+ const xml = await awsQuery("cloudformation", { Action: "DescribeStacks", Version: "2010-05-15", StackName: stack });
371
+ const out: Record<string, string> = {};
372
+ for (const m of xml.matchAll(/<OutputKey>([^<]+)<\/OutputKey>\s*<OutputValue>([^<]*)<\/OutputValue>/g)) out[m[1]!] = m[2]!;
373
+ return out;
374
+ }
375
+
376
+ // ---------------------------------------------------------------------------
377
+
378
+ async function main(argv: string[]): Promise<void> {
379
+ const [step, ...rest] = argv;
380
+ const outAt = rest.indexOf("--out");
381
+ const out = outAt >= 0 ? rest[outAt + 1] : undefined;
382
+ if (step === "apply") return apply();
383
+ if (step === "azure-off") return azureOff();
384
+ if (step === "wait") return waitFor("unhealthy");
385
+ if (step === "export" || step === "all") {
386
+ if (!out) throw new Refusal(`${step} needs --out <dir>`);
387
+ if (step === "all") {
388
+ await apply();
389
+ await azureOff();
390
+ await waitFor("unhealthy");
391
+ }
392
+ return exportPage(out);
393
+ }
394
+ throw new Refusal("usage: front-door.ts all|apply|azure-off|wait|export [--out <dir>]");
395
+ }
396
+
397
+ main(process.argv.slice(2)).catch((e: unknown) => {
398
+ process.stderr.write(`front-door: ${e instanceof Error ? e.message : String(e)}\n`);
399
+ process.exit(e instanceof Refusal ? 2 : 1);
400
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/behold",
3
- "version": "0.29.49",
3
+ "version": "0.29.51",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "behold — a live control plane on chant. See your whole estate (every substrate in one graph), coloured by drift; act through delegated, gated Ops.",
@@ -19,6 +19,7 @@
19
19
  "example-terraform-estate",
20
20
  "example-choudoufu-estate",
21
21
  "example-terralith",
22
+ "example-three-cloud",
22
23
  "demos.json",
23
24
  "AGENTS.md",
24
25
  "LICENSE",
@@ -37,6 +38,7 @@
37
38
  "preview:dots": "tsx scripts/dots-preview.ts",
38
39
  "export:carve": "tsx scripts/export-carve.ts",
39
40
  "preview:carve": "tsx scripts/export-carve.ts && node scripts/serve-static.mjs dist-carve 4712",
41
+ "preview:tour": "tsx scripts/tour-preview.ts",
40
42
  "tsc": "tsc --noEmit",
41
43
  "test": "vitest run",
42
44
  "build": "esbuild src/cli.ts --bundle --platform=node --format=esm --external:hono --external:@hono/node-server --external:@intentius/pinhole --external:@kubernetes/client-node --external:ajv --outfile=dist/cli.js && chmod +x dist/cli.js",
@@ -45,7 +47,7 @@
45
47
  },
46
48
  "dependencies": {
47
49
  "@hono/node-server": "^2.0.5",
48
- "@intentius/chant": "^0.124.28",
50
+ "@intentius/chant": "^0.124.34",
49
51
  "@intentius/chant-k8s-client": "^0.124.24",
50
52
  "@intentius/pinhole": "^0.5.0",
51
53
  "ajv": "^8.20.0",