Skip to content
386 linesCodeBlameRaw
1#!/usr/bin/env node
2// Writes the Wrangler configs a self-hosted g1t runs with, derived from the
3// hosted ones, so the two never drift apart.
4//
5// Each hosted service's wrangler.jsonc is read and changed only where
6// Cloudflare-only things live:
7//
8// - account, routes, placement, observability and builds are dropped;
9// - ARTIFACTS (git storage) becomes a service binding to workers/artifacts,
10// which keeps repositories in the git store (gitstore/server.mjs);
11// - EMAIL (Email Sending) becomes a service binding to workers/mail;
12// - the packages service keeps files in S3-compatible storage (RustFS)
13// instead of R2, and the repos service its nightly backups (a bucket of
14// their own, BACKUP_S3_BUCKET);
15// - services that are off in this phase (agents, the context hub, the
16// g1t.page dispatcher, model proxy) are bound to workers/off instead, and
17// events stop queueing work for them;
18// - URLs that name g1t.sh name PUBLIC_URL instead, and billing is free.
19//
20// Usage: node configs.mjs [outDir]
21// Environment: PUBLIC_URL, GITSTORE_URL, GITSTORE_SECRET, MAIL_URL,
22// ACTIONS_KEY, INTEGRATIONS_KEY, WEBHOOKS_KEY, IDENTITY_KEY, USERCONTENT_KEY,
23// USERCONTENT_URL,
24// PACKAGES_TOKEN_SECRET, S3_ENDPOINT, S3_BUCKET, BACKUP_S3_BUCKET, S3_REGION,
25// S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_PUBLIC_ENDPOINT, and optionally
26// your own GitHub App: GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID,
27// GITHUB_APP_CLIENT_SECRET, GITHUB_APP_PRIVATE_KEY, GITHUB_APP_WEBHOOK_SECRET.
28//
29// The output is for `wrangler dev` (see start.sh): every Worker in one
30// workerd, the site first, with D1, KV and Queues kept on disk.
31
32import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
33import { dirname, join, relative, resolve } from "node:path";
34import { fileURLToPath } from "node:url";
35
36const here = dirname(fileURLToPath(import.meta.url));
37const root = resolve(here, "../..");
38const out = resolve(process.argv[2] ?? join(here, ".generated"));
39mkdirSync(out, { recursive: true });
40
41const PUBLIC_URL = (process.env.PUBLIC_URL ?? "http://localhost:8787").replace(/\/$/, "");
42
43/**
44 * Where the API (REST, OAuth) is reached: API_URL, or PUBLIC_URL's host on
45 * API_PORT (8789). The MCP server is a path on it: MCP_URL, or
46 * `<API_URL>/mcp`. The API's OAuth issuer is API_URL.
47 */
48export function apiAddresses(env = process.env, publicUrl = PUBLIC_URL) {
49 let api = (env.API_URL ?? "").trim().replace(/\/$/, "");
50 if (!api) {
51 const url = new URL(publicUrl);
52 url.port = env.API_PORT || "8789";
53 api = url.origin;
54 }
55 const mcp = (env.MCP_URL ?? "").trim().replace(/\/$/, "") || `${api}/mcp`;
56 return { api, mcp };
57}
58const { api: API_URL, mcp: MCP_URL } = apiAddresses();
59
60// What runs, and what is off, is each unit's `self_host` in
61// deploy/stack.jsonc: the list hosted g1t deploys from.
62const STACK = Object.values(parseJsonc(readFileSync(join(root, "deploy/stack.jsonc"), "utf8")).units);
63
64/** Services that run, in the order Wrangler is given them (the site first). */
65export const RUNNING = STACK.filter((unit) => unit.self_host === "run")
66 .map((unit) => ({ name: unit.worker, dir: unit.path, web: unit.kind === "react-router" }))
67 .sort((a, b) => Number(b.web) - Number(a.web));
68
69/** What the off Worker calls each service that is off in phase 1. */
70const OFF_NAMES = {
71 "g1t-runner": "Agents",
72 "g1t-context": "Context search and memory",
73};
74const OFF = Object.fromEntries(
75 STACK.filter((unit) => unit.self_host === "off").map((unit) => [unit.worker, OFF_NAMES[unit.worker] ?? unit.worker]),
76);
77
78/** Sealing keys, by the service that holds each (hosted: Wrangler secrets). */
79const SECRETS = {
80 g1t: "USERCONTENT_KEY",
81 "g1t-actions": "ACTIONS_KEY",
82 "g1t-integrations": "INTEGRATIONS_KEY",
83 "g1t-webhooks": "WEBHOOKS_KEY",
84};
85
86/**
87 * g1t.sh's GitHub App is its own: an installation registers one of its
88 * own, or has none, and then no GitHub buttons appear. Its public settings
89 * replace the hosted vars; its secrets go only to the service that uses each.
90 */
91const GITHUB_VARS = ["GITHUB_APP_ID", "GITHUB_APP_SLUG", "GITHUB_APP_CLIENT_ID"];
92const GITHUB_SECRETS = {
93 "g1t-identity": ["GITHUB_APP_CLIENT_SECRET", "IDENTITY_KEY", "REGISTRATION_MODE"],
94 "g1t-integrations": ["GITHUB_APP_PRIVATE_KEY", "GITHUB_APP_WEBHOOK_SECRET"],
95};
96
97/**
98 * Services whose cron triggers scheduler.mjs runs here: sweeps and
99 * reminders that need nothing self-hosting lacks. Not run: actions (its
100 * minute would start scheduled workflows with no runner to take them),
101 * billing (reconciles against Cloudflare and Stripe), deployments (calls
102 * Cloudflare's API) and the services that are off.
103 */
104const SELF_HOST_CRONS = new Set(["g1t-repos", "g1t-events", "g1t-identity", "g1t-security", "g1t-webhooks", "g1t-packages"]);
105
106/** Queues whose consumers are off: events stops sending to them. */
107const OFF_QUEUES = new Set(["g1t-events-runner", "g1t-events-context"]);
108
109/** Strips comments and trailing commas from JSONC. Strings are respected. */
110function parseJsonc(text) {
111 let result = "";
112 let inString = false;
113 for (let i = 0; i < text.length; i++) {
114 const char = text[i];
115 if (inString) {
116 result += char;
117 if (char === "\\") result += text[++i];
118 else if (char === '"') inString = false;
119 } else if (char === '"') {
120 inString = true;
121 result += char;
122 } else if (char === "/" && text[i + 1] === "/") {
123 while (i < text.length && text[i] !== "\n") i++;
124 result += "\n";
125 } else if (char === "/" && text[i + 1] === "*") {
126 i = text.indexOf("*/", i + 2) + 1;
127 } else {
128 result += char;
129 }
130 }
131 return JSON.parse(result.replace(/,(\s*[}\]])/g, "$1"));
132}
133
134const rel = (path) => relative(out, resolve(root, path)).replaceAll("\\", "/");
135
136function hostedUrl(value) {
137 return typeof value === "string"
138 ? value.replace(/https:\/\/api\.g1t\.sh/g, API_URL).replace(/https:\/\/g1t\.sh/g, PUBLIC_URL)
139 : value;
140}
141
142function selfHosted(service) {
143 const hosted = parseJsonc(readFileSync(join(root, service.dir, "wrangler.jsonc"), "utf8"));
144 const config = {
145 name: hosted.name,
146 compatibility_date: hosted.compatibility_date,
147 compatibility_flags: hosted.compatibility_flags,
148 rules: hosted.rules,
149 vars: {},
150 };
151
152 if (service.web) {
153 // The site as React Router built it (apps/web/build), not its sources.
154 config.main = rel(`${service.dir}/build/server/index.js`);
155 config.no_bundle = true;
156 config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
157 config.assets = { directory: rel(`${service.dir}/build/client`) };
158 } else {
159 config.main = rel(join(service.dir, hosted.main));
160 }
161
162 for (const [key, value] of Object.entries(hosted.vars ?? {})) config.vars[key] = hostedUrl(value);
163
164 if (hosted.d1_databases) {
165 config.d1_databases = hosted.d1_databases.map((db) => ({
166 binding: db.binding,
167 database_name: db.database_name,
168 database_id: db.database_id,
169 migrations_dir: rel(join(service.dir, db.migrations_dir ?? "migrations")),
170 }));
171 }
172 if (hosted.kv_namespaces) config.kv_namespaces = hosted.kv_namespaces.map(({ binding, id }) => ({ binding, id }));
173 if (hosted.triggers) config.triggers = hosted.triggers;
174
175 if (hosted.queues) {
176 config.queues = {};
177 if (hosted.queues.producers) {
178 config.queues.producers = hosted.queues.producers.filter((producer) => !OFF_QUEUES.has(producer.queue));
179 }
180 if (hosted.queues.consumers) config.queues.consumers = hosted.queues.consumers;
181 }
182
183 config.services = (hosted.services ?? []).map((binding) =>
184 OFF[binding.service] ? { binding: binding.binding, service: offName(binding.service) } : binding,
185 );
186
187 // Cloudflare-only bindings, and what stands in for them.
188 if (hosted.artifacts) {
189 for (const artifacts of hosted.artifacts) {
190 config.services.push({ binding: artifacts.binding, service: "g1t-artifacts" });
191 }
192 }
193 if (hosted.send_email) {
194 for (const email of hosted.send_email) config.services.push({ binding: email.name, service: "g1t-mail" });
195 }
196
197 // Secrets the hosted services hold, given here from the environment, each
198 // only to the service that uses it.
199 const secret = SECRETS[hosted.name];
200 if (secret && process.env[secret]) config.vars[secret] = process.env[secret];
201 for (const name of GITHUB_VARS) {
202 if (name in config.vars) config.vars[name] = process.env[name] ?? "";
203 }
204 for (const name of GITHUB_SECRETS[hosted.name] ?? []) {
205 if (process.env[name]) config.vars[name] = process.env[name];
206 }
207
208 // Self-hosted g1t charges nothing: billing records usage at cost and never
209 // stops work for it.
210 if (hosted.name === "g1t-billing") config.vars.FREE_WHILE_BUILDING = "true";
211 // Anyone may register on an installation of your own unless you set
212 // REGISTRATION_MODE=invite; invites then work as on g1t.sh, and the owners
213 // of INVITE_STAFF_WORKSPACES (yours, not g1t.sh's) invite without limit.
214 if (hosted.name === "g1t-identity") {
215 config.vars.REGISTRATION_MODE = process.env.REGISTRATION_MODE || "open";
216 config.vars.INVITE_STAFF_WORKSPACES = process.env.INVITE_STAFF_WORKSPACES ?? "";
217 if (process.env.INVITES_PER_USER) config.vars.INVITES_PER_USER = process.env.INVITES_PER_USER;
218 // Access requests are summarised to your own address, not g1t.sh's.
219 config.vars.WAITLIST_NOTIFY_EMAIL = process.env.WAITLIST_NOTIFY_EMAIL ?? "";
220 }
221 // Packages' files go to the compose file's RustFS (or any S3-compatible
222 // store) instead of R2, with no request size limit, and package
223 // addresses start with this installation's host.
224 if (hosted.name === "g1t-packages") {
225 Object.assign(config.vars, {
226 BLOB_STORE: "s3",
227 S3_ENDPOINT: process.env.S3_ENDPOINT ?? "http://rustfs:9000",
228 S3_BUCKET: process.env.S3_BUCKET ?? "g1t-packages",
229 S3_REGION: process.env.S3_REGION ?? "us-east-1",
230 S3_ACCESS_KEY_ID: process.env.S3_ACCESS_KEY_ID ?? "",
231 S3_SECRET_ACCESS_KEY: process.env.S3_SECRET_ACCESS_KEY ?? "",
232 S3_PUBLIC_ENDPOINT: process.env.S3_PUBLIC_ENDPOINT ?? "",
233 MAX_REQUEST_BYTES: "0",
234 STORAGE_LIMITS: "off",
235 REGISTRY_HOST: new URL(PUBLIC_URL).host,
236 PACKAGES_TOKEN_SECRET: process.env.PACKAGES_TOKEN_SECRET ?? "",
237 });
238 delete config.vars.R2_ACCOUNT_ID;
239 delete config.vars.R2_BUCKET;
240 }
241 // Where this installation is reached, for the links and addresses each
242 // shows: the site's clone URLs, meta tags and agent setup, the API's
243 // OAuth issuer and MCP server, and identity's mail. No social cards: the
244 // card service (services/og) is not run here.
245 // Repository files and avatars: USERCONTENT_URL, a host of its own that
246 // reaches this same site, or, empty, a path on it (PUBLIC_URL/-/usercontent).
247 if (service.web) {
248 Object.assign(config.vars, { SITE_URL: PUBLIC_URL, API_URL, MCP_URL, OG_URL: "", USERCONTENT_URL: (process.env.USERCONTENT_URL ?? "").trim() });
249 }
250 if (hosted.name === "g1t-api") Object.assign(config.vars, { SITE_URL: PUBLIC_URL, API_URL, MCP_URL });
251 if (hosted.name === "g1t-identity") config.vars.SITE_URL = PUBLIC_URL;
252 // Nightly backups' bundles go to a bucket of their own on the same
253 // S3-compatible store, instead of the BACKUPS R2 bucket, and so do the
254 // packs kept for fresh clones (src/pack_cache.rs), instead of GIT_PACKS.
255 if (hosted.name === "g1t-repos") {
256 Object.assign(config.vars, {
257 BACKUP_STORE: "s3",
258 BACKUP_S3_BUCKET: process.env.BACKUP_S3_BUCKET ?? "g1t-backups",
259 PACK_STORE: "s3",
260 PACK_S3_BUCKET: process.env.PACK_S3_BUCKET ?? "g1t-git-packs",
261 S3_ENDPOINT: process.env.S3_ENDPOINT ?? "http://rustfs:9000",
262 S3_REGION: process.env.S3_REGION ?? "us-east-1",
263 S3_ACCESS_KEY_ID: process.env.S3_ACCESS_KEY_ID ?? "",
264 S3_SECRET_ACCESS_KEY: process.env.S3_SECRET_ACCESS_KEY ?? "",
265 });
266 }
267 // Nothing to deploy to: deployments are off (no Cloudflare API token).
268 if (hosted.name === "g1t-deployments") delete config.vars.CUSTOM_HOSTNAMES_ZONE_ID;
269
270 return config;
271}
272
273function offName(service) {
274 return `${service}-off`;
275}
276
277function write(name, config) {
278 const path = join(out, `${name}.json`);
279 writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);
280 return path;
281}
282
283const files = [];
284for (const service of RUNNING) files.push(write(service.name, selfHosted(service)));
285
286const compatibility_date = "2026-09-26";
287files.push(
288 write("g1t-artifacts", {
289 name: "g1t-artifacts",
290 main: rel("deploy/self-host/workers/artifacts/index.js"),
291 compatibility_date,
292 vars: {
293 GITSTORE_URL: process.env.GITSTORE_URL ?? "http://gitstore:8080",
294 GITSTORE_SECRET: process.env.GITSTORE_SECRET ?? "",
295 },
296 }),
297);
298files.push(
299 write("g1t-mail", {
300 name: "g1t-mail",
301 main: rel("deploy/self-host/workers/mail/index.js"),
302 compatibility_date,
303 vars: {
304 PUBLIC_URL,
305 MAIL_URL: process.env.MAIL_URL ?? "",
306 MAIL_FROM: process.env.MAIL_FROM ?? "",
307 },
308 }),
309);
310for (const [service, feature] of Object.entries(OFF)) {
311 files.push(
312 write(offName(service), {
313 name: offName(service),
314 main: rel("deploy/self-host/workers/off/index.js"),
315 compatibility_date,
316 vars: { OFF_NAME: feature },
317 }),
318 );
319}
320
321// The order Wrangler takes them in: the site first, as the one that serves.
322writeFileSync(join(out, "workers.txt"), `${files.map((file) => relative(out, file)).join("\n")}\n`);
323
324// The API (REST, MCP and OAuth) is served on a port of its own (API_PORT),
325// by a second `wrangler dev` (start.sh): not in workers.txt. Its service
326// bindings reach the Workers above through Wrangler's dev registry, as
327// any two `wrangler dev` sessions on one machine do.
328{
329 const api = STACK.find((unit) => unit.worker === "g1t-api");
330 write("g1t-api", selfHosted({ name: api.worker, dir: api.path, web: false }));
331 writeFileSync(join(out, "api.json"), `${JSON.stringify({ api: API_URL, mcp: MCP_URL }, null, 2)}\n`);
332}
333
334// What scheduler.mjs runs: each service's own crons, as hosted g1t's Cron
335// Triggers run them, for the services in SELF_HOST_CRONS.
336const schedules = RUNNING.filter((service) => SELF_HOST_CRONS.has(service.name))
337 .map((service) => ({
338 worker: service.name,
339 crons: parseJsonc(readFileSync(join(root, service.dir, "wrangler.jsonc"), "utf8")).triggers?.crons ?? [],
340 }))
341 .filter((schedule) => schedule.crons.length > 0);
342writeFileSync(join(out, "schedules.json"), `${JSON.stringify(schedules, null, 2)}\n`);
343
344// The status page runs in a workerd of its own (status.sh, the `status`
345// service in docker-compose.yml), so it stays up when the site does not:
346// not in workers.txt. It checks the site from inside Compose
347// (STATUS_CHECK_URL) and links to it at PUBLIC_URL. Parts this
348// installation does not run (the API, MCP, docs, g1t.page, the model
349// proxy, billing) are left off its page; a public repository of yours in
350// STATUS_PROBE_REPO adds the git check.
351{
352 const hosted = parseJsonc(readFileSync(join(root, "apps/status/wrangler.jsonc"), "utf8"));
353 const db = hosted.d1_databases[0];
354 write("g1t-status", {
355 name: hosted.name,
356 main: rel(join("apps/status", hosted.main)),
357 compatibility_date: hosted.compatibility_date,
358 rules: hosted.rules,
359 triggers: hosted.triggers,
360 d1_databases: [
361 {
362 binding: db.binding,
363 database_name: db.database_name,
364 database_id: db.database_id,
365 migrations_dir: rel(join("apps/status", db.migrations_dir)),
366 },
367 ],
368 vars: {
369 SITE_URL: (process.env.STATUS_CHECK_URL ?? "http://g1t:8787").replace(/\/$/, ""),
370 PUBLIC_SITE_URL: PUBLIC_URL,
371 API_URL: "",
372 MCP_URL: "",
373 DOCS_URL: "",
374 PAGES_URL: "",
375 MODELS_URL: "",
376 PROBE_REPO: process.env.STATUS_PROBE_REPO ?? "",
377 SUPPORT_URL: `${PUBLIC_URL}/support`,
378 OG_IMAGE: "",
379 // Its own address, for links made outside a request. No email
380 // binding here: subscribing by email is off, the feeds work.
381 STATUS_URL: `http://localhost:${process.env.STATUS_PORT ?? "8788"}`,
382 STATUS_ALERT_EMAIL: "",
383 },
384 });
385}
386console.log(`Wrote ${files.length} configs to ${out}`);