@elumixor/devkit 0.12.3 → 0.12.4

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 (43) hide show
  1. package/README.md +83 -0
  2. package/package.json +26 -2
  3. package/src/bin/devkit.ts +32 -1
  4. package/src/blob/index.ts +169 -0
  5. package/src/build-targets/web.ts +66 -20
  6. package/src/cloud/aws.ts +108 -0
  7. package/src/cloud/bootstrap.ts +114 -0
  8. package/src/cloud/cli.ts +56 -0
  9. package/src/cloud/commands/context.ts +42 -0
  10. package/src/cloud/commands/destroy.ts +43 -0
  11. package/src/cloud/commands/domains.ts +68 -0
  12. package/src/cloud/commands/env.ts +59 -0
  13. package/src/cloud/commands/init.ts +74 -0
  14. package/src/cloud/commands/logs.ts +35 -0
  15. package/src/cloud/commands/rollback.ts +54 -0
  16. package/src/cloud/commands/status.ts +50 -0
  17. package/src/cloud/edge/router.js +86 -0
  18. package/src/cloud/env.ts +93 -0
  19. package/src/cloud/github.ts +92 -0
  20. package/src/cloud/index.ts +9 -0
  21. package/src/cloud/log-events.ts +56 -0
  22. package/src/cloud/mcp.ts +150 -0
  23. package/src/cloud/names.ts +98 -0
  24. package/src/cloud/nitro-build.ts +42 -0
  25. package/src/cloud/overview.ts +105 -0
  26. package/src/cloud/project.ts +143 -0
  27. package/src/cloud/reconcile/acm.ts +97 -0
  28. package/src/cloud/reconcile/cloudflare.ts +103 -0
  29. package/src/cloud/reconcile/edge.ts +97 -0
  30. package/src/cloud/reconcile/guardrails.ts +112 -0
  31. package/src/cloud/reconcile/iam.ts +328 -0
  32. package/src/cloud/reconcile/kvs.ts +98 -0
  33. package/src/cloud/reconcile/lambda.ts +305 -0
  34. package/src/cloud/reconcile/logs.ts +24 -0
  35. package/src/cloud/reconcile/platform.ts +281 -0
  36. package/src/cloud/reconcile/s3.ts +155 -0
  37. package/src/cloud/reconcile/scheduler.ts +100 -0
  38. package/src/cloud/records.ts +129 -0
  39. package/src/cloud/release.ts +268 -0
  40. package/src/cloud/runtime-wrapper.ts +84 -0
  41. package/src/deploy-targets/aws.ts +26 -0
  42. package/src/run-target.ts +2 -0
  43. package/src/runtime/index.ts +50 -0
@@ -0,0 +1,86 @@
1
+ // The Devkit Cloud router: one CloudFront Function (JavaScript runtime 2.0) on the viewer-request
2
+ // event of the shared distribution. It reads the hostname's route record from the KeyValueStore
3
+ // and sends the request to that project's function, its deploy's static files, or its public blobs.
4
+ //
5
+ // Deployed by `devkit cloud bootstrap`; the header and key names are the ones in src/cloud/names.ts.
6
+ import cf from "cloudfront";
7
+
8
+ var routes = cf.kvs();
9
+
10
+ var EDGE_SECRET_KEY = "_edge";
11
+ var EDGE_HEADER = "x-dk-edge";
12
+ var HOST_HEADER = "x-dk-host";
13
+ var PROJECT_HEADER = "x-dk-project";
14
+ var BLOB_PREFIX = "/_blob/";
15
+ var SSR_ASSETS_PREFIX = "/_app/";
16
+ var NO_SITE = {
17
+ statusCode: 404,
18
+ statusDescription: "Not Found",
19
+ headers: { "content-type": { value: "text/plain" } },
20
+ body: "No site is deployed at this hostname.",
21
+ };
22
+
23
+ async function handler(event) {
24
+ var request = event.request;
25
+ var host = request.headers.host ? request.headers.host.value.toLowerCase() : "";
26
+
27
+ // The runtime allows `await` only as a whole statement, never inside another expression.
28
+ var route;
29
+ try {
30
+ var record = await routes.get(host);
31
+ route = JSON.parse(record);
32
+ } catch (e) {
33
+ return NO_SITE;
34
+ }
35
+
36
+ var uri = request.uri;
37
+ // A viewer may not forge the headers the function trusts.
38
+ delete request.headers[EDGE_HEADER];
39
+ delete request.headers[HOST_HEADER];
40
+ request.headers[PROJECT_HEADER] = { value: route.p };
41
+
42
+ if (isApi(uri, route)) {
43
+ var secret = await routes.get(EDGE_SECRET_KEY);
44
+ var customHeaders = {};
45
+ customHeaders[EDGE_HEADER] = secret;
46
+ customHeaders[HOST_HEADER] = host;
47
+ cf.updateRequestOrigin({
48
+ domainName: route.fn,
49
+ originAccessControlConfig: { enabled: false },
50
+ customOriginConfig: { port: 443, protocol: "https", sslProtocols: ["TLSv1.2"] },
51
+ customHeaders: customHeaders,
52
+ originPath: "",
53
+ timeouts: { readTimeout: 60, keepAliveTimeout: 60, connectionTimeout: 10 },
54
+ });
55
+ return request;
56
+ }
57
+
58
+ if (uri.indexOf(BLOB_PREFIX) === 0) {
59
+ cf.selectRequestOriginById("blobs");
60
+ request.uri = "/" + route.p + "/" + route.s + "/public/" + uri.slice(BLOB_PREFIX.length);
61
+ return request;
62
+ }
63
+
64
+ request.uri = "/" + route.p + "/" + route.d + staticPath(uri, route.mode);
65
+ return request;
66
+ }
67
+
68
+ function isApi(uri, route) {
69
+ if (route.mode === "ssr") return uri.indexOf(SSR_ASSETS_PREFIX) !== 0 && uri.indexOf(BLOB_PREFIX) !== 0;
70
+ var prefixes = route.api || [];
71
+ for (var i = 0; i < prefixes.length; i++) {
72
+ var prefix = "/" + prefixes[i];
73
+ if (uri === prefix || uri.indexOf(prefix + "/") === 0) return true;
74
+ }
75
+ return false;
76
+ }
77
+
78
+ // `spa`: any path that doesn't name a file is the app shell. `pages`: a path without a file is a
79
+ // folder holding an index.html. A trailing slash means the folder's index either way.
80
+ function staticPath(uri, mode) {
81
+ if (uri === "" || uri === "/") return "/index.html";
82
+ var last = uri.slice(uri.lastIndexOf("/") + 1);
83
+ if (last.indexOf(".") !== -1) return uri;
84
+ if (mode === "pages") return (uri.slice(-1) === "/" ? uri : uri + "/") + "index.html";
85
+ return "/index.html";
86
+ }
@@ -0,0 +1,93 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import {
3
+ DeleteParameterCommand,
4
+ GetParameterCommand,
5
+ GetParametersByPathCommand,
6
+ PutParameterCommand,
7
+ } from "@aws-sdk/client-ssm";
8
+ import { orUndefined, ssm } from "./aws.ts";
9
+ import type { Target } from "./project.ts";
10
+
11
+ export type Env = Record<string, string>;
12
+
13
+ /** Every variable under a path, decrypted — a stage's env, or the platform's own settings. */
14
+ export async function readEnvAt(prefix: string): Promise<Env> {
15
+ const env: Env = {};
16
+ let NextToken: string | undefined;
17
+ do {
18
+ const page = await ssm().send(
19
+ new GetParametersByPathCommand({ Path: prefix, Recursive: false, WithDecryption: true, NextToken }),
20
+ );
21
+ for (const parameter of page.Parameters ?? []) {
22
+ if (parameter.Name && parameter.Value !== undefined) env[parameter.Name.slice(prefix.length)] = parameter.Value;
23
+ }
24
+ NextToken = page.NextToken;
25
+ } while (NextToken);
26
+ return env;
27
+ }
28
+
29
+ export const readStageEnv = (target: Target) => readEnvAt(target.ssmPrefix);
30
+
31
+ export async function readParameter(name: string) {
32
+ const result = await orUndefined(
33
+ ssm().send(new GetParameterCommand({ Name: name, WithDecryption: true })),
34
+ "ParameterNotFound",
35
+ );
36
+ return result?.Parameter?.Value;
37
+ }
38
+
39
+ /** Every value is a SecureString under the free `aws/ssm` key: nothing to classify, nothing to leak in a listing. */
40
+ export async function writeParameter(name: string, value: string) {
41
+ await ssm().send(
42
+ new PutParameterCommand({ Name: name, Value: value, Type: "SecureString", Overwrite: true, Tier: "Standard" }),
43
+ );
44
+ }
45
+
46
+ export async function writeStageEnv(target: Target, env: Readonly<Env>) {
47
+ for (const [key, value] of Object.entries(env)) await writeParameter(target.ssmPrefix + key, value);
48
+ }
49
+
50
+ export async function deleteStageVariable(target: Target, key: string) {
51
+ await orUndefined(ssm().send(new DeleteParameterCommand({ Name: target.ssmPrefix + key })), "ParameterNotFound");
52
+ }
53
+
54
+ export async function deleteStageEnv(target: Target) {
55
+ for (const key of Object.keys(await readStageEnv(target))) await deleteStageVariable(target, key);
56
+ }
57
+
58
+ /** Reads a parameter, or makes and stores one — for secrets nobody needs to choose. */
59
+ export async function ensureSecret(name: string, bytes = 32) {
60
+ const existing = await readParameter(name);
61
+ if (existing) return existing;
62
+ const secret = randomBytes(bytes).toString("base64url");
63
+ await writeParameter(name, secret);
64
+ return secret;
65
+ }
66
+
67
+ /** `KEY=value` lines; quotes stripped, `#` comments and blanks skipped, `export ` tolerated. */
68
+ export function parseDotenv(text: string): Env {
69
+ const env: Env = {};
70
+ for (const raw of text.split("\n")) {
71
+ const line = raw.trim();
72
+ if (!line || line.startsWith("#")) continue;
73
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
74
+ if (!match) continue;
75
+ const [, key, rest] = match as unknown as [string, string, string];
76
+ env[key] = unquote(rest);
77
+ }
78
+ return env;
79
+ }
80
+
81
+ function unquote(value: string) {
82
+ const trimmed = value.trim();
83
+ if (/^".*"$/.test(trimmed)) return trimmed.slice(1, -1).replace(/\\n/g, "\n").replace(/\\"/g, '"');
84
+ if (/^'.*'$/.test(trimmed)) return trimmed.slice(1, -1);
85
+ return trimmed.replace(/\s+#.*$/, "");
86
+ }
87
+
88
+ export function formatDotenv(env: Readonly<Env>) {
89
+ return `${Object.entries(env)
90
+ .sort(([a], [b]) => a.localeCompare(b))
91
+ .map(([key, value]) => `${key}=${/[\s#"']/.test(value) || value === "" ? JSON.stringify(value) : value}`)
92
+ .join("\n")}\n`;
93
+ }
@@ -0,0 +1,92 @@
1
+ import { $ } from "bun";
2
+ import { log } from "./aws.ts";
3
+
4
+ /**
5
+ * GitHub Deployments: the repo page and each commit show what is live where. Best effort — a
6
+ * deploy never fails because GitHub was unreachable.
7
+ */
8
+ const API = "https://api.github.com";
9
+
10
+ interface Context {
11
+ repo: string;
12
+ token: string;
13
+ }
14
+
15
+ async function context(): Promise<Context | undefined> {
16
+ const repo = process.env.GITHUB_REPOSITORY ?? (await repoFromRemote());
17
+ if (!repo) return undefined;
18
+ const token = process.env.GITHUB_TOKEN ?? (await $`gh auth token`.quiet().nothrow().text()).trim();
19
+ return token ? { repo, token } : undefined;
20
+ }
21
+
22
+ /** GitHub can only record a commit it has; a laptop deploy of unpushed work is left off the repo page. */
23
+ async function isPushed(sha: string) {
24
+ if (process.env.GITHUB_ACTIONS) return true;
25
+ const branches = await $`git branch -r --contains ${sha}`.quiet().nothrow().text();
26
+ return branches.trim().length > 0;
27
+ }
28
+
29
+ async function repoFromRemote() {
30
+ const remote = (await $`git remote get-url origin`.quiet().nothrow().text()).trim();
31
+ const match = /github\.com[:/]([^/]+\/[^/.]+)/.exec(remote);
32
+ return match?.[1];
33
+ }
34
+
35
+ async function call<T>(ctx: Context, method: string, path: string, body: unknown): Promise<T> {
36
+ const response = await fetch(`${API}${path}`, {
37
+ method,
38
+ headers: {
39
+ authorization: `Bearer ${ctx.token}`,
40
+ accept: "application/vnd.github+json",
41
+ "content-type": "application/json",
42
+ "user-agent": "devkit-cloud",
43
+ },
44
+ body: JSON.stringify(body),
45
+ });
46
+ if (!response.ok) throw new Error(`GitHub ${method} ${path}: ${response.status} ${await response.text()}`);
47
+ return (await response.json()) as T;
48
+ }
49
+
50
+ export interface GithubDeployment {
51
+ succeed(url: string): Promise<void>;
52
+ fail(): Promise<void>;
53
+ }
54
+
55
+ /** Opens a deployment for `sha` on `environment`; the result reports how it ended. */
56
+ export async function startGithubDeployment(
57
+ sha: string,
58
+ environment: string,
59
+ description: string,
60
+ ): Promise<GithubDeployment> {
61
+ const quiet: GithubDeployment = { succeed: async () => undefined, fail: async () => undefined };
62
+ const ctx = await context();
63
+ if (!ctx || !(await isPushed(sha))) return quiet;
64
+ try {
65
+ const created = await call<{ id: number }>(ctx, "POST", `/repos/${ctx.repo}/deployments`, {
66
+ ref: sha,
67
+ environment,
68
+ description,
69
+ auto_merge: false,
70
+ required_contexts: [],
71
+ production_environment: environment === "production",
72
+ transient_environment: false,
73
+ });
74
+ const status = async (state: "success" | "failure", environment_url?: string) => {
75
+ try {
76
+ await call(ctx, "POST", `/repos/${ctx.repo}/deployments/${created.id}/statuses`, {
77
+ state,
78
+ environment_url,
79
+ log_url: process.env.GITHUB_SERVER_URL
80
+ ? `${process.env.GITHUB_SERVER_URL}/${ctx.repo}/actions/runs/${process.env.GITHUB_RUN_ID}`
81
+ : undefined,
82
+ });
83
+ } catch (error) {
84
+ log(` GitHub deployment status not posted: ${error instanceof Error ? error.message : error}`);
85
+ }
86
+ };
87
+ return { succeed: (url) => status("success", url), fail: () => status("failure") };
88
+ } catch (error) {
89
+ log(` GitHub deployment not recorded: ${error instanceof Error ? error.message : error}`);
90
+ return quiet;
91
+ }
92
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@elumixor/devkit/cloud`: what an app running on the platform may read about the platform —
3
+ * the dashboard is one. Everything here is read-only; deploys and rollbacks stay with the CLI.
4
+ */
5
+ export { fetchLogEvents, type LogEvent, parseDuration } from "./log-events.ts";
6
+ export { BASE_DOMAIN } from "./names.ts";
7
+ export { age, type Metrics, overview, type ProjectOverview, type StageOverview } from "./overview.ts";
8
+ export { Target } from "./project.ts";
9
+ export { type DeployRecord, listDeploys, readRegistry } from "./records.ts";
@@ -0,0 +1,56 @@
1
+ import { FilterLogEventsCommand } from "@aws-sdk/client-cloudwatch-logs";
2
+ import { CloudError, logs as logsClient } from "./aws.ts";
3
+ import type { Target } from "./project.ts";
4
+
5
+ export interface LogEvent {
6
+ id: string;
7
+ timestamp: number;
8
+ message: string;
9
+ }
10
+
11
+ export interface LogQuery {
12
+ /** Epoch milliseconds to read from. */
13
+ startTime: number;
14
+ /** CloudWatch filter pattern — a word, a phrase in quotes, or `?a ?b`. */
15
+ grep?: string;
16
+ limit?: number;
17
+ }
18
+
19
+ /** One stage's log lines after `startTime`, oldest first. */
20
+ export async function fetchLogEvents(target: Target, query: LogQuery): Promise<LogEvent[]> {
21
+ const events: LogEvent[] = [];
22
+ let nextToken: string | undefined;
23
+ try {
24
+ do {
25
+ const result = await logsClient().send(
26
+ new FilterLogEventsCommand({
27
+ logGroupName: target.logGroup,
28
+ startTime: query.startTime,
29
+ filterPattern: query.grep,
30
+ nextToken,
31
+ interleaved: true,
32
+ limit: query.limit,
33
+ }),
34
+ );
35
+ for (const event of result.events ?? []) {
36
+ if (event.eventId && event.timestamp !== undefined)
37
+ events.push({ id: event.eventId, timestamp: event.timestamp, message: (event.message ?? "").trimEnd() });
38
+ }
39
+ nextToken = result.nextToken;
40
+ } while (nextToken && (!query.limit || events.length < query.limit));
41
+ } catch (error) {
42
+ if (error instanceof Error && error.name === "ResourceNotFoundException")
43
+ throw new CloudError(`No log group ${target.logGroup} — has ${target.project} ${target.stage} been deployed?`);
44
+ throw error;
45
+ }
46
+ return events;
47
+ }
48
+
49
+ /** `30m`, `2h`, `1d` → milliseconds. */
50
+ export function parseDuration(text: string) {
51
+ const match = /^(\d+)\s*([smhd])$/.exec(text.trim());
52
+ if (!match) throw new CloudError(`a duration wants a number and a unit (30m, 2h, 1d), not "${text}"`);
53
+ const [, amount, unit] = match as unknown as [string, string, "s" | "m" | "h" | "d"];
54
+ const seconds = { s: 1, m: 60, h: 3600, d: 86400 }[unit];
55
+ return Number(amount) * seconds * 1000;
56
+ }
@@ -0,0 +1,150 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod";
4
+ import pkg from "../../package.json" with { type: "json" };
5
+ import { targetByName } from "./commands/context.ts";
6
+ import { addDomain, listDomains, removeDomain } from "./commands/domains.ts";
7
+ import { rollback } from "./commands/rollback.ts";
8
+ import { readStageEnv } from "./env.ts";
9
+ import { fetchLogEvents, parseDuration } from "./log-events.ts";
10
+ import { age, overview } from "./overview.ts";
11
+ import { listDeploys } from "./records.ts";
12
+
13
+ /**
14
+ * `devkit mcp`: Devkit Cloud over the Model Context Protocol, so an agent can ask what is live,
15
+ * read a stage's logs and roll a deploy back without a terminal. Stdio transport; the AWS
16
+ * credentials are whatever the environment provides, as for the CLI.
17
+ */
18
+ export async function runMcp() {
19
+ // Stdout carries the protocol; the shared commands' progress lines go to stderr instead.
20
+ console.log = console.error;
21
+ const server = new McpServer({ name: "devkit-cloud", version: pkg.version });
22
+ const text = (value: unknown) => ({
23
+ content: [{ type: "text" as const, text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }],
24
+ });
25
+ const project = z.string().describe("Project name, e.g. `hello`");
26
+ const stage = z.string().optional().describe("Stage name (default `production`)");
27
+
28
+ server.registerTool(
29
+ "cloud_status",
30
+ {
31
+ title: "Devkit Cloud status",
32
+ description:
33
+ "Every deployed project and stage: live deploy, hostnames, and the last 24 h of calls, errors and p95 latency.",
34
+ inputSchema: { project: project.optional() },
35
+ },
36
+ async ({ project }) =>
37
+ text(
38
+ (await overview(project)).map((entry) => ({
39
+ project: entry.project,
40
+ stages: entry.stages.map((s) => ({
41
+ stage: s.stage,
42
+ url: `https://${s.hostnames[0]}`,
43
+ hostnames: s.hostnames,
44
+ deployId: s.current?.deployId,
45
+ liveSince: s.current ? age(s.current.since) : undefined,
46
+ commit: s.live?.commit.slice(0, 7),
47
+ message: s.live?.message,
48
+ last24h: s.metrics,
49
+ })),
50
+ })),
51
+ ),
52
+ );
53
+
54
+ server.registerTool(
55
+ "cloud_deploys",
56
+ {
57
+ title: "Deploy history",
58
+ description: "The last deploys of one stage, newest first, with status, commit, author and any error.",
59
+ inputSchema: { project, stage, limit: z.number().int().min(1).max(50).optional() },
60
+ },
61
+ async ({ project, stage, limit }) => {
62
+ const { target } = await targetByName(project, stage);
63
+ return text(await listDeploys(target, limit ?? 10));
64
+ },
65
+ );
66
+
67
+ server.registerTool(
68
+ "cloud_logs",
69
+ {
70
+ title: "Function logs",
71
+ description: "CloudWatch log lines of a stage's function, oldest first.",
72
+ inputSchema: {
73
+ project,
74
+ stage,
75
+ since: z.string().optional().describe("How far back: 30m, 2h, 1d (default 1h)"),
76
+ grep: z.string().optional().describe("CloudWatch filter pattern: a word, a quoted phrase, or ?a ?b"),
77
+ limit: z.number().int().min(1).max(2000).optional().describe("Most lines to return (default 500)"),
78
+ },
79
+ },
80
+ async ({ project, stage, since, grep, limit }) => {
81
+ const { target } = await targetByName(project, stage);
82
+ const events = await fetchLogEvents(target, {
83
+ startTime: Date.now() - parseDuration(since ?? "1h"),
84
+ grep,
85
+ limit: limit ?? 500,
86
+ });
87
+ return text(
88
+ events.map((event) => `${new Date(event.timestamp).toISOString()} ${event.message}`).join("\n") ||
89
+ "(no log lines)",
90
+ );
91
+ },
92
+ );
93
+
94
+ server.registerTool(
95
+ "cloud_rollback",
96
+ {
97
+ title: "Roll back",
98
+ description:
99
+ "Point a stage back at an earlier deploy (the previous one unless `to` names a deploy id). Takes a few seconds.",
100
+ inputSchema: { project, stage, to: z.string().optional().describe("Deploy id to go back to") },
101
+ },
102
+ async ({ project, stage, to }) => text(await rollback(project, stage, to)),
103
+ );
104
+
105
+ server.registerTool(
106
+ "cloud_env",
107
+ {
108
+ title: "Stage env keys",
109
+ description: "The variable names set on a stage (values are never returned).",
110
+ inputSchema: { project, stage },
111
+ },
112
+ async ({ project, stage }) => {
113
+ const { target } = await targetByName(project, stage);
114
+ return text(Object.keys(await readStageEnv(target)).sort());
115
+ },
116
+ );
117
+
118
+ server.registerTool(
119
+ "cloud_domains",
120
+ {
121
+ title: "Hostnames",
122
+ description: "Every hostname each stage of a project answers on, the primary one first.",
123
+ inputSchema: { project },
124
+ },
125
+ async ({ project }) => text(await listDomains(project)),
126
+ );
127
+
128
+ server.registerTool(
129
+ "cloud_domain_add",
130
+ {
131
+ title: "Add hostname",
132
+ description:
133
+ "Point a hostname at a stage: certificate, CloudFront alias, Cloudflare DNS record and route. Kept by later deploys. A new hostname may need a minute or two (longer when a certificate is issued).",
134
+ inputSchema: { project, host: z.string().describe("Hostname, e.g. app.example.com"), stage },
135
+ },
136
+ async ({ project, host, stage }) => text(await addDomain(project, host, stage)),
137
+ );
138
+
139
+ server.registerTool(
140
+ "cloud_domain_remove",
141
+ {
142
+ title: "Remove hostname",
143
+ description: "Take a hostname off a stage: route, alias and DNS record. The default hostname stays.",
144
+ inputSchema: { project, host: z.string(), stage },
145
+ },
146
+ async ({ project, host, stage }) => text(await removeDomain(project, host, stage)),
147
+ );
148
+
149
+ await server.connect(new StdioServerTransport());
150
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Every resource name and tag Devkit Cloud creates, in one place.
3
+ *
4
+ * The CLI keeps no state file: it finds what it made by these names, so a name is a contract.
5
+ * Renaming one orphans whatever carried the old name.
6
+ */
7
+
8
+ /** Where compute, buckets, parameters and schedules live. */
9
+ export const REGION = "eu-central-1";
10
+ /** CloudFront, its KeyValueStore and the certificates it accepts are global, which AWS spells `us-east-1`. */
11
+ export const GLOBAL_REGION = "us-east-1";
12
+
13
+ /** The apex every default hostname hangs off. */
14
+ export const BASE_DOMAIN = "devkit.atmagaming.com";
15
+ export const WILDCARD_DOMAIN = `*.${BASE_DOMAIN}`;
16
+ /** The aliases the distribution always carries: every default hostname, and the apex the dashboard answers on. */
17
+ export const PLATFORM_ALIASES = [WILDCARD_DOMAIN, BASE_DOMAIN] as const;
18
+
19
+ /** Stage names and the branches that deploy them, matching today's Vercel setup. */
20
+ export const STAGE_BRANCHES: Readonly<Record<string, string>> = { production: "main", development: "develop" };
21
+ export const PRODUCTION = "production";
22
+
23
+ /** Resources that exist once per account. Bucket names are global, so they carry the account id. */
24
+ export const platform = {
25
+ sitesBucket: (account: string) => `dk-sites-${account}`,
26
+ blobsBucket: (account: string) => `dk-blobs-${account}`,
27
+ kvs: "dk-routes",
28
+ routerFunction: "dk-router",
29
+ originAccessControl: "dk-s3",
30
+ cachePolicy: "dk-default",
31
+ /** AWS managed `AllViewerExceptHostHeader`: every header, cookie and query string reaches the origin. */
32
+ originRequestPolicyId: "b689b0a8-53d0-40ab-baf2-68738e2966ac",
33
+ deployRole: "dk-deploy",
34
+ deployPolicy: "dk-deploy",
35
+ localDeployUser: "dk-deploy-local",
36
+ localProfile: "devkit",
37
+ schedulerRole: "dk-scheduler",
38
+ scheduleGroup: "dk",
39
+ ssmPrefix: "/dk/_platform/",
40
+ edgeSecretParameter: "/dk/_platform/EDGE_SECRET",
41
+ cloudflareTokenParameter: "/dk/_platform/CLOUDFLARE_API_TOKEN",
42
+ budgetSmall: "dk-monthly-5",
43
+ budgetLarge: "dk-monthly-20",
44
+ anomalyMonitor: "dk-services",
45
+ tag: { key: "dk", value: "platform" },
46
+ } as const;
47
+
48
+ /** Origin ids inside the one distribution — the router selects them by these names. */
49
+ export const ORIGINS = { sites: "sites", blobs: "blobs" } as const;
50
+
51
+ /** The KVS key whose value is the edge secret, and the header that carries it to the function. */
52
+ export const EDGE_SECRET_KEY = "_edge";
53
+ export const EDGE_HEADER = "x-dk-edge";
54
+ /** The viewer's hostname, carried to the function because the origin request drops `Host`. */
55
+ export const HOST_HEADER = "x-dk-host";
56
+ /** Set by the router per request so two projects' identical API paths never share a cache entry. */
57
+ export const PROJECT_HEADER = "x-dk-project";
58
+
59
+ /** Resources that exist once per project and stage. */
60
+ export const stage = {
61
+ fn: (project: string, stage: string) => `dk-${project}-${stage}`,
62
+ role: (project: string, stage: string) => `dk-${project}-${stage}-role`,
63
+ logGroup: (project: string, stage: string) => `/aws/lambda/dk-${project}-${stage}`,
64
+ schedule: (project: string, stage: string, slug: string) => `dk-${project}-${stage}-${slug}`,
65
+ schedulePrefix: (project: string, stage: string) => `dk-${project}-${stage}-`,
66
+ ssmPrefix: (project: string, stage: string) => `/dk/${project}/${stage}/`,
67
+ defaultHost: (project: string, stage: string) =>
68
+ stage === PRODUCTION ? `${project}.${BASE_DOMAIN}` : `${project}-${shortStage(stage)}.${BASE_DOMAIN}`,
69
+ /** Where one deploy's static files live in the sites bucket; the route record's `d` is the part after the project. */
70
+ deployPrefix: (project: string, stage: string, deployId: string) => `${project}/${stage}/${deployId}/`,
71
+ stagePrefix: (project: string, stage: string) => `${project}/${stage}/`,
72
+ codeKey: (project: string, stage: string, deployId: string) => `_dk/${project}/${stage}/code/${deployId}.zip`,
73
+ deployRecord: (project: string, stage: string, deployId: string) =>
74
+ `_dk/${project}/${stage}/deploys/${deployId}.json`,
75
+ deploysPrefix: (project: string, stage: string) => `_dk/${project}/${stage}/deploys/`,
76
+ current: (project: string, stage: string) => `_dk/${project}/${stage}/current.json`,
77
+ blobPrefix: (project: string, stage: string) => `${project}/${stage}/`,
78
+ } as const;
79
+
80
+ export const registryKey = (project: string) => `_dk/projects/${project}.json`;
81
+
82
+ /** The Lambda alias every Function URL and schedule is bound to; deploys and rollbacks move it. */
83
+ export const LIVE_ALIAS = "live";
84
+
85
+ /** `development` reads as `-dev` in a hostname; any other stage keeps its name. */
86
+ function shortStage(name: string) {
87
+ return name === "development" ? "dev" : name;
88
+ }
89
+
90
+ /** A cron path becomes the tail of its schedule name: `/api/cron/sync-all` → `api-cron-sync-all`. */
91
+ export function cronSlug(path: string) {
92
+ return (
93
+ path
94
+ .replace(/^\/+|\/+$/g, "")
95
+ .replace(/[^a-zA-Z0-9]+/g, "-")
96
+ .toLowerCase() || "root"
97
+ );
98
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Builds a Nitro app for Lambda with response streaming on.
3
+ *
4
+ * Run as its own process (`bun nitro-build.ts <backend dir>`): the project's own `nitropack` is
5
+ * loaded from that directory, and `awsLambda.streaming` is passed as an override — the CLI's
6
+ * `--preset` flag can set the preset but not that option, and the project's config keeps saying
7
+ * `vercel` until the move is over.
8
+ */
9
+ const [, , dir] = process.argv;
10
+ if (!dir) throw new Error("usage: bun nitro-build.ts <backend dir>");
11
+ process.chdir(dir);
12
+
13
+ type NitroModule = {
14
+ createNitro: (config: Record<string, unknown>) => Promise<{ close: () => Promise<void> }>;
15
+ prepare: (nitro: unknown) => Promise<void>;
16
+ copyPublicAssets: (nitro: unknown) => Promise<void>;
17
+ build: (nitro: unknown) => Promise<void>;
18
+ };
19
+
20
+ const nitroModule = (await import(resolveNitro(dir))) as NitroModule;
21
+ const nitro = await nitroModule.createNitro({
22
+ rootDir: dir,
23
+ dev: false,
24
+ preset: "aws-lambda",
25
+ awsLambda: { streaming: true },
26
+ });
27
+ await nitroModule.prepare(nitro);
28
+ await nitroModule.copyPublicAssets(nitro);
29
+ await nitroModule.build(nitro);
30
+ await nitro.close();
31
+
32
+ /** `nitropack` today, `nitro` once projects move to v3. */
33
+ function resolveNitro(from: string) {
34
+ for (const name of ["nitropack", "nitro"]) {
35
+ try {
36
+ return Bun.resolveSync(name, from);
37
+ } catch {
38
+ // not this one — the next name is tried, and the error below names both
39
+ }
40
+ }
41
+ throw new Error(`Neither "nitropack" nor "nitro" is installed in ${from}`);
42
+ }