everything-dev 1.35.2 → 1.35.3

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.
@@ -45,31 +45,62 @@ function getSecretGroups(runtimeConfig) {
45
45
  }
46
46
  return groups;
47
47
  }
48
- function buildGeneratedInfraSpec(runtimeConfig) {
48
+ function buildGeneratedInfraSpec(runtimeConfig, configDir) {
49
49
  const groups = getSecretGroups(runtimeConfig);
50
+ const originMap = configDir ? buildOriginMap(configDir, runtimeConfig) : /* @__PURE__ */ new Map();
50
51
  return {
51
52
  groups,
52
- databases: buildDatabaseConfigs(groups.flatMap((group) => group.secrets))
53
+ databases: buildDatabaseConfigs(groups.flatMap((group) => group.secrets), originMap)
53
54
  };
54
55
  }
55
56
  function normalizeDatabaseSlug(secret) {
56
57
  return secret.replace(/_DATABASE_URL$/, "").toLowerCase();
57
58
  }
58
- function buildDatabaseConfigs(secrets) {
59
+ function buildOriginMap(configDir, runtimeConfig) {
60
+ const configPath = (0, node_path.join)(configDir, "bos.config.json");
61
+ const originMap = /* @__PURE__ */ new Map();
62
+ const account = runtimeConfig.account;
63
+ const resolveOrigin = (extendsRef) => {
64
+ if (typeof extendsRef === "string") return extendsRef.match(/^bos:\/\/([^/]+)\//)?.[1] ?? null;
65
+ return null;
66
+ };
67
+ const rawConfig = (0, node_fs.existsSync)(configPath) ? JSON.parse((0, node_fs.readFileSync)(configPath, "utf-8")) : null;
68
+ const rawPlugins = rawConfig?.plugins;
69
+ for (const secret of runtimeConfig.api.secrets ?? []) if (!originMap.has(secret)) originMap.set(secret, account);
70
+ const authExtends = ((rawConfig?.app)?.auth)?.extends;
71
+ const authOrigin = resolveOrigin(authExtends) ?? account;
72
+ for (const secret of runtimeConfig.auth?.secrets ?? []) if (!originMap.has(secret)) originMap.set(secret, authOrigin);
73
+ for (const [pluginKey, pluginEntry] of Object.entries(runtimeConfig.plugins ?? {})) {
74
+ const rawPlugin = rawPlugins?.[pluginKey];
75
+ let pluginOrigin;
76
+ if (typeof rawPlugin === "string") pluginOrigin = resolveOrigin(rawPlugin) ?? account;
77
+ else if (rawPlugin && typeof rawPlugin === "object") pluginOrigin = resolveOrigin(rawPlugin.extends) ?? account;
78
+ else pluginOrigin = account;
79
+ for (const secret of pluginEntry.secrets ?? []) if (!originMap.has(secret)) originMap.set(secret, pluginOrigin);
80
+ }
81
+ for (const secret of runtimeConfig.host.secrets ?? []) if (!originMap.has(secret)) originMap.set(secret, account);
82
+ return originMap;
83
+ }
84
+ function buildDatabaseConfigs(secrets, originMap) {
59
85
  return [
60
86
  API_DATABASE_SECRET,
61
87
  AUTH_DATABASE_SECRET,
62
88
  ...uniqueSecrets(secrets.filter((secret) => secret.endsWith("_DATABASE_URL"))).filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET).sort((a, b) => a.localeCompare(b))
63
89
  ].map((secret, index) => {
64
90
  const slug = normalizeDatabaseSlug(secret);
91
+ const fromKey = originMap.get(secret) ?? "";
65
92
  const port = secret === API_DATABASE_SECRET ? 5432 : secret === AUTH_DATABASE_SECRET ? 5433 : BASE_DATABASE_PORT + index - 2;
93
+ const volumeName = fromKey ? `${fromKey.replace(/\./g, "_")}_postgres_${slug}_data` : `postgres_${slug}_data`;
94
+ const containerName = fromKey ? `${fromKey}-postgres-${slug}` : `postgres-${slug}`;
66
95
  return {
67
96
  secret,
68
97
  slug,
98
+ fromKey,
69
99
  port,
70
100
  serviceName: `postgres-${slug.replace(/_/g, "-")}`,
101
+ containerName,
71
102
  databaseName: `${slug}_db`,
72
- volumeName: `postgres_${slug}_data`,
103
+ volumeName,
73
104
  url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`
74
105
  };
75
106
  });
@@ -93,8 +124,10 @@ function renderEnvFile(groups, databases, options) {
93
124
  }
94
125
  return `${lines.join("\n")}\n`;
95
126
  }
96
- function renderDockerCompose(databases) {
127
+ function renderDockerCompose(databases, projectName) {
97
128
  const lines = [
129
+ `name: ${projectName}`,
130
+ "",
98
131
  "x-pg-common: &pg-common",
99
132
  " image: postgres:17-alpine",
100
133
  " environment: &pg-env",
@@ -111,6 +144,7 @@ function renderDockerCompose(databases) {
111
144
  for (const database of databases) {
112
145
  lines.push(` ${database.serviceName}:`);
113
146
  lines.push(" <<: *pg-common");
147
+ lines.push(` container_name: ${database.containerName}`);
114
148
  lines.push(" environment:");
115
149
  lines.push(" <<: *pg-env");
116
150
  lines.push(` POSTGRES_DB: ${database.databaseName}`);
@@ -121,7 +155,10 @@ function renderDockerCompose(databases) {
121
155
  lines.push("");
122
156
  }
123
157
  lines.push("volumes:");
124
- for (const database of databases) lines.push(` ${database.volumeName}:`);
158
+ for (const database of databases) {
159
+ lines.push(` ${database.volumeName}:`);
160
+ lines.push(` name: ${database.volumeName}`);
161
+ }
125
162
  return `${lines.join("\n")}\n`;
126
163
  }
127
164
  function syncTextFile(filePath, nextContent) {
@@ -133,10 +170,10 @@ function writeGeneratedInfra(configDir, runtimeConfig) {
133
170
  return syncGeneratedInfra(configDir, runtimeConfig).secrets;
134
171
  }
135
172
  function syncGeneratedInfra(configDir, runtimeConfig) {
136
- const spec = buildGeneratedInfraSpec(runtimeConfig);
173
+ const spec = buildGeneratedInfraSpec(runtimeConfig, configDir);
137
174
  const secrets = spec.groups.flatMap((group) => group.secrets);
138
175
  const newEnvContent = renderEnvFile(spec.groups, spec.databases, { forExample: true });
139
- const newDockerContent = renderDockerCompose(spec.databases);
176
+ const newDockerContent = renderDockerCompose(spec.databases, runtimeConfig.account);
140
177
  const envExamplePath = (0, node_path.join)(configDir, ".env.example");
141
178
  const dockerComposePath = (0, node_path.join)(configDir, "docker-compose.yml");
142
179
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"infra.cjs","names":[],"sources":["../../src/cli/infra.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport { config as loadDotenv } from \"dotenv\";\nimport type { RuntimeConfig } from \"../types\";\n\nconst POSTGRES_USER = \"everythingdev\";\nconst POSTGRES_PASSWORD = \"everythingdev\";\nconst API_DATABASE_SECRET = \"API_DATABASE_URL\";\nconst AUTH_DATABASE_SECRET = \"AUTH_DATABASE_URL\";\nconst HOST_SECRET = \"CORS_ORIGIN\";\nconst BASE_DATABASE_PORT = 5434;\n\ninterface DatabaseSecretConfig {\n secret: string;\n slug: string;\n port: number;\n serviceName: string;\n databaseName: string;\n volumeName: string;\n url: string;\n}\n\ninterface SecretGroup {\n section: string;\n secrets: string[];\n}\n\ninterface GeneratedInfraSpec {\n groups: SecretGroup[];\n databases: DatabaseSecretConfig[];\n}\n\ninterface SyncGeneratedInfraResult {\n secrets: string[];\n envExampleChanged: boolean;\n dockerComposeChanged: boolean;\n}\n\nfunction uniqueSecrets(values: Array<string | undefined>): string[] {\n const secrets: string[] = [];\n const seen = new Set<string>();\n\n for (const value of values) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n secrets.push(value);\n }\n\n return secrets;\n}\n\nfunction getSecretGroups(runtimeConfig: RuntimeConfig): SecretGroup[] {\n const groups: SecretGroup[] = [];\n const seen = new Set<string>();\n\n const addGroup = (section: string, secrets: string[]) => {\n const filtered = secrets.filter((s) => {\n if (seen.has(s)) return false;\n seen.add(s);\n return true;\n });\n if (filtered.length > 0) {\n groups.push({ section, secrets: filtered });\n }\n };\n\n addGroup(\"app.host\", uniqueSecrets([...(runtimeConfig.host.secrets ?? []), HOST_SECRET]));\n\n addGroup(\"app.api\", uniqueSecrets(runtimeConfig.api.secrets ?? []));\n\n if (runtimeConfig.auth) {\n addGroup(\"app.auth\", uniqueSecrets(runtimeConfig.auth.secrets ?? []));\n }\n\n if (runtimeConfig.plugins) {\n for (const [pluginKey, plugin] of Object.entries(runtimeConfig.plugins)) {\n if (plugin.secrets && plugin.secrets.length > 0) {\n addGroup(`plugins.${pluginKey}`, plugin.secrets);\n }\n }\n }\n\n return groups;\n}\n\nfunction buildGeneratedInfraSpec(runtimeConfig: RuntimeConfig): GeneratedInfraSpec {\n const groups = getSecretGroups(runtimeConfig);\n const databases = buildDatabaseConfigs(groups.flatMap((group) => group.secrets));\n return { groups, databases };\n}\n\nfunction normalizeDatabaseSlug(secret: string): string {\n return secret.replace(/_DATABASE_URL$/, \"\").toLowerCase();\n}\n\nfunction buildDatabaseConfigs(secrets: string[]): DatabaseSecretConfig[] {\n const databaseSecrets = uniqueSecrets(\n secrets.filter((secret) => secret.endsWith(\"_DATABASE_URL\")),\n );\n\n const additionalSecrets = databaseSecrets\n .filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET)\n .sort((a, b) => a.localeCompare(b));\n\n const orderedSecrets = [API_DATABASE_SECRET, AUTH_DATABASE_SECRET, ...additionalSecrets];\n\n return orderedSecrets.map((secret, index) => {\n const slug = normalizeDatabaseSlug(secret);\n const port =\n secret === API_DATABASE_SECRET\n ? 5432\n : secret === AUTH_DATABASE_SECRET\n ? 5433\n : BASE_DATABASE_PORT + index - 2;\n\n return {\n secret,\n slug,\n port,\n serviceName: `postgres-${slug.replace(/_/g, \"-\")}`,\n databaseName: `${slug}_db`,\n volumeName: `postgres_${slug}_data`,\n url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`,\n };\n });\n}\n\nfunction defaultSecretValue(\n secret: string,\n databases: Map<string, DatabaseSecretConfig>,\n options: { forExample: boolean },\n): string {\n if (secret === \"BETTER_AUTH_SECRET\") {\n return options.forExample ? \"\" : randomBytes(32).toString(\"base64url\");\n }\n\n if (secret === \"CORS_ORIGIN\") {\n return \"http://localhost:3000\";\n }\n\n return databases.get(secret)?.url ?? \"\";\n}\n\nfunction renderEnvFile(\n groups: SecretGroup[],\n databases: DatabaseSecretConfig[],\n options: { forExample: boolean },\n): string {\n const databaseMap = new Map(databases.map((entry) => [entry.secret, entry]));\n const lines: string[] = [\n \"# Generated from configured bos secrets\",\n \"# Update values as needed for your local environment\",\n \"\",\n ];\n\n for (const group of groups) {\n lines.push(`# ${group.section}`);\n for (const secret of group.secrets) {\n lines.push(`${secret}=${defaultSecretValue(secret, databaseMap, options)}`);\n }\n lines.push(\"\");\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderDockerCompose(databases: DatabaseSecretConfig[]): string {\n const lines = [\n \"x-pg-common: &pg-common\",\n \" image: postgres:17-alpine\",\n \" environment: &pg-env\",\n ` POSTGRES_USER: ${POSTGRES_USER}`,\n ` POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}`,\n \" healthcheck:\",\n ' test: [\"CMD-SHELL\", \"pg_isready -U everythingdev\"]',\n \" interval: 3s\",\n \" timeout: 3s\",\n \" retries: 5\",\n \"\",\n \"services:\",\n ];\n\n for (const database of databases) {\n lines.push(` ${database.serviceName}:`);\n lines.push(\" <<: *pg-common\");\n lines.push(\" environment:\");\n lines.push(\" <<: *pg-env\");\n lines.push(` POSTGRES_DB: ${database.databaseName}`);\n lines.push(\" ports:\");\n lines.push(` - \"${database.port}:5432\"`);\n lines.push(\" volumes:\");\n lines.push(` - ${database.volumeName}:/var/lib/postgresql/data`);\n lines.push(\"\");\n }\n\n lines.push(\"volumes:\");\n for (const database of databases) {\n lines.push(` ${database.volumeName}:`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction syncTextFile(filePath: string, nextContent: string): boolean {\n if (existsSync(filePath) && readFileSync(filePath, \"utf-8\") === nextContent) {\n return false;\n }\n\n writeFileSync(filePath, nextContent);\n return true;\n}\n\nexport function writeGeneratedInfra(configDir: string, runtimeConfig: RuntimeConfig): string[] {\n return syncGeneratedInfra(configDir, runtimeConfig).secrets;\n}\n\nexport function syncGeneratedInfra(\n configDir: string,\n runtimeConfig: RuntimeConfig,\n): SyncGeneratedInfraResult {\n const spec = buildGeneratedInfraSpec(runtimeConfig);\n const secrets = spec.groups.flatMap((group) => group.secrets);\n const newEnvContent = renderEnvFile(spec.groups, spec.databases, { forExample: true });\n const newDockerContent = renderDockerCompose(spec.databases);\n\n const envExamplePath = join(configDir, \".env.example\");\n const dockerComposePath = join(configDir, \"docker-compose.yml\");\n\n return {\n secrets,\n envExampleChanged: syncTextFile(envExamplePath, newEnvContent),\n dockerComposeChanged: syncTextFile(dockerComposePath, newDockerContent),\n };\n}\n\nexport function ensureEnvFile(configDir: string): void {\n const envPath = join(configDir, \".env\");\n const examplePath = join(configDir, \".env.example\");\n\n if (existsSync(envPath) || !existsSync(examplePath)) return;\n\n const content = readFileSync(examplePath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const secret = randomBytes(32).toString(\"base64url\");\n const updated = lines\n .map((line) => {\n if (/^BETTER_AUTH_SECRET=/.test(line)) {\n return `BETTER_AUTH_SECRET=${secret}`;\n }\n return line;\n })\n .join(\"\\n\");\n\n writeFileSync(envPath, updated);\n p.log.info(\"Created .env from generated .env.example with generated BETTER_AUTH_SECRET\");\n}\n\nexport function loadProjectEnv(configDir: string): void {\n const envPath = join(configDir, \".env\");\n if (!existsSync(envPath)) return;\n\n loadDotenv({ path: envPath, processEnv: process.env, quiet: true });\n}\n"],"mappings":";;;;;;;;;AAOA,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAC7B,MAAM,cAAc;AACpB,MAAM,qBAAqB;AA4B3B,SAAS,cAAc,QAA6C;CAClE,MAAM,UAAoB,EAAE;CAC5B,MAAM,uBAAO,IAAI,KAAa;AAE9B,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,CAAC,SAAS,KAAK,IAAI,MAAM,CAAE;AAC/B,OAAK,IAAI,MAAM;AACf,UAAQ,KAAK,MAAM;;AAGrB,QAAO;;AAGT,SAAS,gBAAgB,eAA6C;CACpE,MAAM,SAAwB,EAAE;CAChC,MAAM,uBAAO,IAAI,KAAa;CAE9B,MAAM,YAAY,SAAiB,YAAsB;EACvD,MAAM,W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AAM;EAAS,YAAY,QAAQ;EAAK,OAAO;EAAM,CAAC"}
1
+ {"version":3,"file":"infra.cjs","names":[],"sources":["../../src/cli/infra.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport { config as loadDotenv } from \"dotenv\";\nimport type { RuntimeConfig } from \"../types\";\n\nconst POSTGRES_USER = \"everythingdev\";\nconst POSTGRES_PASSWORD = \"everythingdev\";\nconst API_DATABASE_SECRET = \"API_DATABASE_URL\";\nconst AUTH_DATABASE_SECRET = \"AUTH_DATABASE_URL\";\nconst HOST_SECRET = \"CORS_ORIGIN\";\nconst BASE_DATABASE_PORT = 5434;\n\ninterface DatabaseSecretConfig {\n secret: string;\n slug: string;\n fromKey: string;\n port: number;\n serviceName: string;\n containerName: string;\n databaseName: string;\n volumeName: string;\n url: string;\n}\n\ninterface SecretGroup {\n section: string;\n secrets: string[];\n}\n\ninterface GeneratedInfraSpec {\n groups: SecretGroup[];\n databases: DatabaseSecretConfig[];\n}\n\ninterface SyncGeneratedInfraResult {\n secrets: string[];\n envExampleChanged: boolean;\n dockerComposeChanged: boolean;\n}\n\nfunction uniqueSecrets(values: Array<string | undefined>): string[] {\n const secrets: string[] = [];\n const seen = new Set<string>();\n\n for (const value of values) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n secrets.push(value);\n }\n\n return secrets;\n}\n\nfunction getSecretGroups(runtimeConfig: RuntimeConfig): SecretGroup[] {\n const groups: SecretGroup[] = [];\n const seen = new Set<string>();\n\n const addGroup = (section: string, secrets: string[]) => {\n const filtered = secrets.filter((s) => {\n if (seen.has(s)) return false;\n seen.add(s);\n return true;\n });\n if (filtered.length > 0) {\n groups.push({ section, secrets: filtered });\n }\n };\n\n addGroup(\"app.host\", uniqueSecrets([...(runtimeConfig.host.secrets ?? []), HOST_SECRET]));\n\n addGroup(\"app.api\", uniqueSecrets(runtimeConfig.api.secrets ?? []));\n\n if (runtimeConfig.auth) {\n addGroup(\"app.auth\", uniqueSecrets(runtimeConfig.auth.secrets ?? []));\n }\n\n if (runtimeConfig.plugins) {\n for (const [pluginKey, plugin] of Object.entries(runtimeConfig.plugins)) {\n if (plugin.secrets && plugin.secrets.length > 0) {\n addGroup(`plugins.${pluginKey}`, plugin.secrets);\n }\n }\n }\n\n return groups;\n}\n\nfunction buildGeneratedInfraSpec(\n runtimeConfig: RuntimeConfig,\n configDir?: string,\n): GeneratedInfraSpec {\n const groups = getSecretGroups(runtimeConfig);\n const originMap = configDir ? buildOriginMap(configDir, runtimeConfig) : new Map();\n const databases = buildDatabaseConfigs(\n groups.flatMap((group) => group.secrets),\n originMap,\n );\n return { groups, databases };\n}\n\nfunction normalizeDatabaseSlug(secret: string): string {\n return secret.replace(/_DATABASE_URL$/, \"\").toLowerCase();\n}\n\nfunction buildOriginMap(configDir: string, runtimeConfig: RuntimeConfig): Map<string, string> {\n const configPath = join(configDir, \"bos.config.json\");\n\n const originMap = new Map<string, string>();\n const account = runtimeConfig.account;\n\n const resolveOrigin = (extendsRef: unknown): string | null => {\n if (typeof extendsRef === \"string\") {\n const match = extendsRef.match(/^bos:\\/\\/([^/]+)\\//);\n return match?.[1] ?? null;\n }\n return null;\n };\n\n const rawConfig = existsSync(configPath)\n ? (JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>)\n : null;\n const rawPlugins = rawConfig?.plugins as Record<string, unknown> | undefined;\n\n for (const secret of runtimeConfig.api.secrets ?? []) {\n if (!originMap.has(secret)) originMap.set(secret, account);\n }\n\n const rawApp = rawConfig?.app as Record<string, unknown> | undefined;\n const authExtends = (rawApp?.auth as Record<string, unknown> | undefined)?.extends;\n const authOrigin = resolveOrigin(authExtends) ?? account;\n for (const secret of runtimeConfig.auth?.secrets ?? []) {\n if (!originMap.has(secret)) originMap.set(secret, authOrigin);\n }\n\n for (const [pluginKey, pluginEntry] of Object.entries(runtimeConfig.plugins ?? {})) {\n const rawPlugin = rawPlugins?.[pluginKey];\n let pluginOrigin: string;\n if (typeof rawPlugin === \"string\") {\n pluginOrigin = resolveOrigin(rawPlugin) ?? account;\n } else if (rawPlugin && typeof rawPlugin === \"object\") {\n pluginOrigin = resolveOrigin((rawPlugin as Record<string, unknown>).extends) ?? account;\n } else {\n pluginOrigin = account;\n }\n for (const secret of pluginEntry.secrets ?? []) {\n if (!originMap.has(secret)) originMap.set(secret, pluginOrigin);\n }\n }\n\n for (const secret of runtimeConfig.host.secrets ?? []) {\n if (!originMap.has(secret)) originMap.set(secret, account);\n }\n\n return originMap;\n}\n\nfunction buildDatabaseConfigs(\n secrets: string[],\n originMap: Map<string, string>,\n): DatabaseSecretConfig[] {\n const databaseSecrets = uniqueSecrets(\n secrets.filter((secret) => secret.endsWith(\"_DATABASE_URL\")),\n );\n\n const additionalSecrets = databaseSecrets\n .filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET)\n .sort((a, b) => a.localeCompare(b));\n\n const orderedSecrets = [API_DATABASE_SECRET, AUTH_DATABASE_SECRET, ...additionalSecrets];\n\n return orderedSecrets.map((secret, index) => {\n const slug = normalizeDatabaseSlug(secret);\n const fromKey = originMap.get(secret) ?? \"\";\n const port =\n secret === API_DATABASE_SECRET\n ? 5432\n : secret === AUTH_DATABASE_SECRET\n ? 5433\n : BASE_DATABASE_PORT + index - 2;\n\n const volumeName = fromKey\n ? `${fromKey.replace(/\\./g, \"_\")}_postgres_${slug}_data`\n : `postgres_${slug}_data`;\n\n const containerName = fromKey ? `${fromKey}-postgres-${slug}` : `postgres-${slug}`;\n\n return {\n secret,\n slug,\n fromKey,\n port,\n serviceName: `postgres-${slug.replace(/_/g, \"-\")}`,\n containerName,\n databaseName: `${slug}_db`,\n volumeName,\n url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`,\n };\n });\n}\n\nfunction defaultSecretValue(\n secret: string,\n databases: Map<string, DatabaseSecretConfig>,\n options: { forExample: boolean },\n): string {\n if (secret === \"BETTER_AUTH_SECRET\") {\n return options.forExample ? \"\" : randomBytes(32).toString(\"base64url\");\n }\n\n if (secret === \"CORS_ORIGIN\") {\n return \"http://localhost:3000\";\n }\n\n return databases.get(secret)?.url ?? \"\";\n}\n\nfunction renderEnvFile(\n groups: SecretGroup[],\n databases: DatabaseSecretConfig[],\n options: { forExample: boolean },\n): string {\n const databaseMap = new Map(databases.map((entry) => [entry.secret, entry]));\n const lines: string[] = [\n \"# Generated from configured bos secrets\",\n \"# Update values as needed for your local environment\",\n \"\",\n ];\n\n for (const group of groups) {\n lines.push(`# ${group.section}`);\n for (const secret of group.secrets) {\n lines.push(`${secret}=${defaultSecretValue(secret, databaseMap, options)}`);\n }\n lines.push(\"\");\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderDockerCompose(databases: DatabaseSecretConfig[], projectName: string): string {\n const lines = [\n `name: ${projectName}`,\n \"\",\n \"x-pg-common: &pg-common\",\n \" image: postgres:17-alpine\",\n \" environment: &pg-env\",\n ` POSTGRES_USER: ${POSTGRES_USER}`,\n ` POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}`,\n \" healthcheck:\",\n ' test: [\"CMD-SHELL\", \"pg_isready -U everythingdev\"]',\n \" interval: 3s\",\n \" timeout: 3s\",\n \" retries: 5\",\n \"\",\n \"services:\",\n ];\n\n for (const database of databases) {\n lines.push(` ${database.serviceName}:`);\n lines.push(\" <<: *pg-common\");\n lines.push(` container_name: ${database.containerName}`);\n lines.push(\" environment:\");\n lines.push(\" <<: *pg-env\");\n lines.push(` POSTGRES_DB: ${database.databaseName}`);\n lines.push(\" ports:\");\n lines.push(` - \"${database.port}:5432\"`);\n lines.push(\" volumes:\");\n lines.push(` - ${database.volumeName}:/var/lib/postgresql/data`);\n lines.push(\"\");\n }\n\n lines.push(\"volumes:\");\n for (const database of databases) {\n lines.push(` ${database.volumeName}:`);\n lines.push(` name: ${database.volumeName}`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction syncTextFile(filePath: string, nextContent: string): boolean {\n if (existsSync(filePath) && readFileSync(filePath, \"utf-8\") === nextContent) {\n return false;\n }\n\n writeFileSync(filePath, nextContent);\n return true;\n}\n\nexport function writeGeneratedInfra(configDir: string, runtimeConfig: RuntimeConfig): string[] {\n return syncGeneratedInfra(configDir, runtimeConfig).secrets;\n}\n\nexport function syncGeneratedInfra(\n configDir: string,\n runtimeConfig: RuntimeConfig,\n): SyncGeneratedInfraResult {\n const spec = buildGeneratedInfraSpec(runtimeConfig, configDir);\n const secrets = spec.groups.flatMap((group) => group.secrets);\n const newEnvContent = renderEnvFile(spec.groups, spec.databases, { forExample: true });\n const newDockerContent = renderDockerCompose(spec.databases, runtimeConfig.account);\n\n const envExamplePath = join(configDir, \".env.example\");\n const dockerComposePath = join(configDir, \"docker-compose.yml\");\n\n return {\n secrets,\n envExampleChanged: syncTextFile(envExamplePath, newEnvContent),\n dockerComposeChanged: syncTextFile(dockerComposePath, newDockerContent),\n };\n}\n\nexport function ensureEnvFile(configDir: string): void {\n const envPath = join(configDir, \".env\");\n const examplePath = join(configDir, \".env.example\");\n\n if (existsSync(envPath) || !existsSync(examplePath)) return;\n\n const content = readFileSync(examplePath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const secret = randomBytes(32).toString(\"base64url\");\n const updated = lines\n .map((line) => {\n if (/^BETTER_AUTH_SECRET=/.test(line)) {\n return `BETTER_AUTH_SECRET=${secret}`;\n }\n return line;\n })\n .join(\"\\n\");\n\n writeFileSync(envPath, updated);\n p.log.info(\"Created .env from generated .env.example with generated BETTER_AUTH_SECRET\");\n}\n\nexport function loadProjectEnv(configDir: string): void {\n const envPath = join(configDir, \".env\");\n if (!existsSync(envPath)) return;\n\n loadDotenv({ path: envPath, processEnv: process.env, quiet: true });\n}\n"],"mappings":";;;;;;;;;AAOA,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5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B,oBAAoB,KAAK,WAAW,cAAc,QAAQ;CAEnF,MAAM,qCAAsB,WAAW,eAAe;CACtD,MAAM,wCAAyB,WAAW,qBAAqB;AAE/D,QAAO;EACL;EACA,mBAAmB,aAAa,gBAAgB,cAAc;EAC9D,sBAAsB,aAAa,mBAAmB,iBAAiB;EACxE;;AAGH,SAAgB,cAAc,WAAyB;CACrD,MAAM,8BAAe,WAAW,OAAO;CACvC,MAAM,kCAAmB,WAAW,eAAe;AAEnD,6BAAe,QAAQ,IAAI,yBAAY,YAAY,CAAE;CAGrD,MAAM,kCADuB,aAAa,QACrB,CAAC,MAAM,KAAK;CACjC,MAAM,sCAAqB,GAAG,CAAC,SAAS,YAAY;AAUpD,4BAAc,SATE,MACb,KAAK,SAAS;AACb,MAAI,uBAAuB,KAAK,KAAK,CACnC,QAAO,sBAAsB;AAE/B,SAAO;GACP,CACD,KAAK,KAEsB,CAAC;AAC/B,gBAAE,IAAI,KAAK,6EAA6E;;AAG1F,SAAgB,eAAe,WAAyB;CACtD,MAAM,8BAAe,WAAW,OAAO;AACvC,KAAI,yBAAY,QAAQ,CAAE;AAE1B,oBAAW;EAAE,MAAM;EAAS,YAAY,QAAQ;EAAK,OAAO;EAAM,CAAC"}
@@ -43,31 +43,62 @@ function getSecretGroups(runtimeConfig) {
43
43
  }
44
44
  return groups;
45
45
  }
46
- function buildGeneratedInfraSpec(runtimeConfig) {
46
+ function buildGeneratedInfraSpec(runtimeConfig, configDir) {
47
47
  const groups = getSecretGroups(runtimeConfig);
48
+ const originMap = configDir ? buildOriginMap(configDir, runtimeConfig) : /* @__PURE__ */ new Map();
48
49
  return {
49
50
  groups,
50
- databases: buildDatabaseConfigs(groups.flatMap((group) => group.secrets))
51
+ databases: buildDatabaseConfigs(groups.flatMap((group) => group.secrets), originMap)
51
52
  };
52
53
  }
53
54
  function normalizeDatabaseSlug(secret) {
54
55
  return secret.replace(/_DATABASE_URL$/, "").toLowerCase();
55
56
  }
56
- function buildDatabaseConfigs(secrets) {
57
+ function buildOriginMap(configDir, runtimeConfig) {
58
+ const configPath = join(configDir, "bos.config.json");
59
+ const originMap = /* @__PURE__ */ new Map();
60
+ const account = runtimeConfig.account;
61
+ const resolveOrigin = (extendsRef) => {
62
+ if (typeof extendsRef === "string") return extendsRef.match(/^bos:\/\/([^/]+)\//)?.[1] ?? null;
63
+ return null;
64
+ };
65
+ const rawConfig = existsSync(configPath) ? JSON.parse(readFileSync(configPath, "utf-8")) : null;
66
+ const rawPlugins = rawConfig?.plugins;
67
+ for (const secret of runtimeConfig.api.secrets ?? []) if (!originMap.has(secret)) originMap.set(secret, account);
68
+ const authExtends = ((rawConfig?.app)?.auth)?.extends;
69
+ const authOrigin = resolveOrigin(authExtends) ?? account;
70
+ for (const secret of runtimeConfig.auth?.secrets ?? []) if (!originMap.has(secret)) originMap.set(secret, authOrigin);
71
+ for (const [pluginKey, pluginEntry] of Object.entries(runtimeConfig.plugins ?? {})) {
72
+ const rawPlugin = rawPlugins?.[pluginKey];
73
+ let pluginOrigin;
74
+ if (typeof rawPlugin === "string") pluginOrigin = resolveOrigin(rawPlugin) ?? account;
75
+ else if (rawPlugin && typeof rawPlugin === "object") pluginOrigin = resolveOrigin(rawPlugin.extends) ?? account;
76
+ else pluginOrigin = account;
77
+ for (const secret of pluginEntry.secrets ?? []) if (!originMap.has(secret)) originMap.set(secret, pluginOrigin);
78
+ }
79
+ for (const secret of runtimeConfig.host.secrets ?? []) if (!originMap.has(secret)) originMap.set(secret, account);
80
+ return originMap;
81
+ }
82
+ function buildDatabaseConfigs(secrets, originMap) {
57
83
  return [
58
84
  API_DATABASE_SECRET,
59
85
  AUTH_DATABASE_SECRET,
60
86
  ...uniqueSecrets(secrets.filter((secret) => secret.endsWith("_DATABASE_URL"))).filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET).sort((a, b) => a.localeCompare(b))
61
87
  ].map((secret, index) => {
62
88
  const slug = normalizeDatabaseSlug(secret);
89
+ const fromKey = originMap.get(secret) ?? "";
63
90
  const port = secret === API_DATABASE_SECRET ? 5432 : secret === AUTH_DATABASE_SECRET ? 5433 : BASE_DATABASE_PORT + index - 2;
91
+ const volumeName = fromKey ? `${fromKey.replace(/\./g, "_")}_postgres_${slug}_data` : `postgres_${slug}_data`;
92
+ const containerName = fromKey ? `${fromKey}-postgres-${slug}` : `postgres-${slug}`;
64
93
  return {
65
94
  secret,
66
95
  slug,
96
+ fromKey,
67
97
  port,
68
98
  serviceName: `postgres-${slug.replace(/_/g, "-")}`,
99
+ containerName,
69
100
  databaseName: `${slug}_db`,
70
- volumeName: `postgres_${slug}_data`,
101
+ volumeName,
71
102
  url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`
72
103
  };
73
104
  });
@@ -91,8 +122,10 @@ function renderEnvFile(groups, databases, options) {
91
122
  }
92
123
  return `${lines.join("\n")}\n`;
93
124
  }
94
- function renderDockerCompose(databases) {
125
+ function renderDockerCompose(databases, projectName) {
95
126
  const lines = [
127
+ `name: ${projectName}`,
128
+ "",
96
129
  "x-pg-common: &pg-common",
97
130
  " image: postgres:17-alpine",
98
131
  " environment: &pg-env",
@@ -109,6 +142,7 @@ function renderDockerCompose(databases) {
109
142
  for (const database of databases) {
110
143
  lines.push(` ${database.serviceName}:`);
111
144
  lines.push(" <<: *pg-common");
145
+ lines.push(` container_name: ${database.containerName}`);
112
146
  lines.push(" environment:");
113
147
  lines.push(" <<: *pg-env");
114
148
  lines.push(` POSTGRES_DB: ${database.databaseName}`);
@@ -119,7 +153,10 @@ function renderDockerCompose(databases) {
119
153
  lines.push("");
120
154
  }
121
155
  lines.push("volumes:");
122
- for (const database of databases) lines.push(` ${database.volumeName}:`);
156
+ for (const database of databases) {
157
+ lines.push(` ${database.volumeName}:`);
158
+ lines.push(` name: ${database.volumeName}`);
159
+ }
123
160
  return `${lines.join("\n")}\n`;
124
161
  }
125
162
  function syncTextFile(filePath, nextContent) {
@@ -131,10 +168,10 @@ function writeGeneratedInfra(configDir, runtimeConfig) {
131
168
  return syncGeneratedInfra(configDir, runtimeConfig).secrets;
132
169
  }
133
170
  function syncGeneratedInfra(configDir, runtimeConfig) {
134
- const spec = buildGeneratedInfraSpec(runtimeConfig);
171
+ const spec = buildGeneratedInfraSpec(runtimeConfig, configDir);
135
172
  const secrets = spec.groups.flatMap((group) => group.secrets);
136
173
  const newEnvContent = renderEnvFile(spec.groups, spec.databases, { forExample: true });
137
- const newDockerContent = renderDockerCompose(spec.databases);
174
+ const newDockerContent = renderDockerCompose(spec.databases, runtimeConfig.account);
138
175
  const envExamplePath = join(configDir, ".env.example");
139
176
  const dockerComposePath = join(configDir, "docker-compose.yml");
140
177
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"infra.mjs","names":[],"sources":["../../src/cli/infra.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport { config as loadDotenv } from \"dotenv\";\nimport type { RuntimeConfig } from \"../types\";\n\nconst POSTGRES_USER = \"everythingdev\";\nconst POSTGRES_PASSWORD = \"everythingdev\";\nconst API_DATABASE_SECRET = \"API_DATABASE_URL\";\nconst AUTH_DATABASE_SECRET = \"AUTH_DATABASE_URL\";\nconst HOST_SECRET = \"CORS_ORIGIN\";\nconst BASE_DATABASE_PORT = 5434;\n\ninterface DatabaseSecretConfig {\n secret: string;\n slug: string;\n port: number;\n serviceName: string;\n databaseName: string;\n volumeName: string;\n url: string;\n}\n\ninterface SecretGroup {\n section: string;\n secrets: string[];\n}\n\ninterface GeneratedInfraSpec {\n groups: SecretGroup[];\n databases: DatabaseSecretConfig[];\n}\n\ninterface SyncGeneratedInfraResult {\n secrets: string[];\n envExampleChanged: boolean;\n dockerComposeChanged: boolean;\n}\n\nfunction uniqueSecrets(values: Array<string | undefined>): string[] {\n const secrets: string[] = [];\n const seen = new Set<string>();\n\n for (const value of values) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n secrets.push(value);\n }\n\n return secrets;\n}\n\nfunction getSecretGroups(runtimeConfig: RuntimeConfig): SecretGroup[] {\n const groups: SecretGroup[] = [];\n const seen = new Set<string>();\n\n const addGroup = (section: string, secrets: string[]) => {\n const filtered = secrets.filter((s) => {\n if (seen.has(s)) return false;\n seen.add(s);\n return true;\n });\n if (filtered.length > 0) {\n groups.push({ section, secrets: filtered });\n }\n };\n\n addGroup(\"app.host\", uniqueSecrets([...(runtimeConfig.host.secrets ?? []), HOST_SECRET]));\n\n addGroup(\"app.api\", uniqueSecrets(runtimeConfig.api.secrets ?? []));\n\n if (runtimeConfig.auth) {\n addGroup(\"app.auth\", uniqueSecrets(runtimeConfig.auth.secrets ?? []));\n }\n\n if (runtimeConfig.plugins) {\n for (const [pluginKey, plugin] of Object.entries(runtimeConfig.plugins)) {\n if (plugin.secrets && plugin.secrets.length > 0) {\n addGroup(`plugins.${pluginKey}`, plugin.secrets);\n }\n }\n }\n\n return groups;\n}\n\nfunction buildGeneratedInfraSpec(runtimeConfig: RuntimeConfig): GeneratedInfraSpec {\n const groups = getSecretGroups(runtimeConfig);\n const databases = buildDatabaseConfigs(groups.flatMap((group) => group.secrets));\n return { groups, databases };\n}\n\nfunction normalizeDatabaseSlug(secret: string): string {\n return secret.replace(/_DATABASE_URL$/, \"\").toLowerCase();\n}\n\nfunction buildDatabaseConfigs(secrets: string[]): DatabaseSecretConfig[] {\n const databaseSecrets = uniqueSecrets(\n secrets.filter((secret) => secret.endsWith(\"_DATABASE_URL\")),\n );\n\n const additionalSecrets = databaseSecrets\n .filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET)\n .sort((a, b) => a.localeCompare(b));\n\n const orderedSecrets = [API_DATABASE_SECRET, AUTH_DATABASE_SECRET, ...additionalSecrets];\n\n return orderedSecrets.map((secret, index) => {\n const slug = normalizeDatabaseSlug(secret);\n const port =\n secret === API_DATABASE_SECRET\n ? 5432\n : secret === AUTH_DATABASE_SECRET\n ? 5433\n : BASE_DATABASE_PORT + index - 2;\n\n return {\n secret,\n slug,\n port,\n serviceName: `postgres-${slug.replace(/_/g, \"-\")}`,\n databaseName: `${slug}_db`,\n volumeName: `postgres_${slug}_data`,\n url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`,\n };\n });\n}\n\nfunction defaultSecretValue(\n secret: string,\n databases: Map<string, DatabaseSecretConfig>,\n options: { forExample: boolean },\n): string {\n if (secret === \"BETTER_AUTH_SECRET\") {\n return options.forExample ? \"\" : randomBytes(32).toString(\"base64url\");\n }\n\n if (secret === \"CORS_ORIGIN\") {\n return \"http://localhost:3000\";\n }\n\n return databases.get(secret)?.url ?? \"\";\n}\n\nfunction renderEnvFile(\n groups: SecretGroup[],\n databases: DatabaseSecretConfig[],\n options: { forExample: boolean },\n): string {\n const databaseMap = new Map(databases.map((entry) => [entry.secret, entry]));\n const lines: string[] = [\n \"# Generated from configured bos secrets\",\n \"# Update values as needed for your local environment\",\n \"\",\n ];\n\n for (const group of groups) {\n lines.push(`# ${group.section}`);\n for (const secret of group.secrets) {\n lines.push(`${secret}=${defaultSecretValue(secret, databaseMap, options)}`);\n }\n lines.push(\"\");\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderDockerCompose(databases: DatabaseSecretConfig[]): string {\n const lines = [\n \"x-pg-common: &pg-common\",\n \" image: postgres:17-alpine\",\n \" environment: &pg-env\",\n ` POSTGRES_USER: ${POSTGRES_USER}`,\n ` POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}`,\n \" healthcheck:\",\n ' test: [\"CMD-SHELL\", \"pg_isready -U everythingdev\"]',\n \" interval: 3s\",\n \" timeout: 3s\",\n \" retries: 5\",\n \"\",\n \"services:\",\n ];\n\n for (const database of databases) {\n lines.push(` ${database.serviceName}:`);\n lines.push(\" <<: *pg-common\");\n lines.push(\" environment:\");\n lines.push(\" <<: *pg-env\");\n lines.push(` POSTGRES_DB: ${database.databaseName}`);\n lines.push(\" ports:\");\n lines.push(` - \"${database.port}:5432\"`);\n lines.push(\" volumes:\");\n lines.push(` - ${database.volumeName}:/var/lib/postgresql/data`);\n lines.push(\"\");\n }\n\n lines.push(\"volumes:\");\n for (const database of databases) {\n lines.push(` ${database.volumeName}:`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction syncTextFile(filePath: string, nextContent: string): boolean {\n if (existsSync(filePath) && readFileSync(filePath, \"utf-8\") === nextContent) {\n return false;\n }\n\n writeFileSync(filePath, nextContent);\n return true;\n}\n\nexport function writeGeneratedInfra(configDir: string, runtimeConfig: RuntimeConfig): string[] {\n return syncGeneratedInfra(configDir, runtimeConfig).secrets;\n}\n\nexport function syncGeneratedInfra(\n configDir: string,\n runtimeConfig: RuntimeConfig,\n): SyncGeneratedInfraResult {\n const spec = buildGeneratedInfraSpec(runtimeConfig);\n const secrets = spec.groups.flatMap((group) => group.secrets);\n const newEnvContent = renderEnvFile(spec.groups, spec.databases, { forExample: true });\n const newDockerContent = renderDockerCompose(spec.databases);\n\n const envExamplePath = join(configDir, \".env.example\");\n const dockerComposePath = join(configDir, \"docker-compose.yml\");\n\n return {\n secrets,\n envExampleChanged: syncTextFile(envExamplePath, newEnvContent),\n dockerComposeChanged: syncTextFile(dockerComposePath, newDockerContent),\n };\n}\n\nexport function ensureEnvFile(configDir: string): void {\n const envPath = join(configDir, \".env\");\n const examplePath = join(configDir, \".env.example\");\n\n if (existsSync(envPath) || !existsSync(examplePath)) return;\n\n const content = readFileSync(examplePath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const secret = randomBytes(32).toString(\"base64url\");\n const updated = lines\n .map((line) => {\n if (/^BETTER_AUTH_SECRET=/.test(line)) {\n return `BETTER_AUTH_SECRET=${secret}`;\n }\n return line;\n })\n .join(\"\\n\");\n\n writeFileSync(envPath, updated);\n p.log.info(\"Created .env from generated .env.example with generated BETTER_AUTH_SECRET\");\n}\n\nexport function loadProjectEnv(configDir: string): void {\n const envPath = join(configDir, \".env\");\n if (!existsSync(envPath)) return;\n\n loadDotenv({ path: envPath, processEnv: process.env, quiet: true });\n}\n"],"mappings":";;;;;;;AAOA,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAC7B,MAAM,cAAc;AACpB,MAAM,qBAAqB;AA4B3B,SAAS,cAAc,QAA6C;CAClE,MAAM,UAAoB,EAAE;CAC5B,MAAM,uBAAO,IAAI,KAAa;AAE9B,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,CAAC,SAAS,KAAK,IAAI,MAAM,CAAE;AAC/B,OAAK,IAAI,MAAM;AACf,UAAQ,KAAK,MAAM;;AAGrB,QAAO;;AAGT,SAAS,gBAAgB,eAA6C;CACpE,MAAM,SAAwB,EAAE;CAChC,MAAM,uBAAO,IAAI,KAAa;CAE9B,MAAM,YAAY,SAAiB,YAAsB;EACvD,MAAM,WAAW,QAAQ,QAAQ,MAAM;AACrC,OAAI,KAAK,IAAI,EAAE,CAAE,QAAO;AACxB,QAAK,IAAI,EAAE;AACX,UAAO;IACP;AACF,MAAI,SAAS,SAAS,EACpB,QAAO,KAAK;GAAE;GAAS,SAAS;GAAU,CAAC;;AAI/C,UAAS,YAAY,cAAc,CAAC,GAAI,cAAc,KAAK,WAAW,EAAE,EAAG,YAAY,CAAC,CAAC;AAEzF,UAAS,WAAW,cAAc,cAAc,IAAI,WAAW,EAAE,CAAC,CAAC;AAEnE,KAAI,cAAc,KAChB,UAAS,YAAY,cAAc,cAAc,KAAK,WAAW,EAAE,CAAC,CAAC;AAGvE,KAAI,cAAc,SAChB;OAAK,MAAM,CAAC,WAAW,WAAW,OAAO,QAAQ,cAAc,QAAQ,CACrE,KAAI,OAAO,WAAW,OAAO,QAAQ,SAAS,EAC5C,UAAS,WAAW,aAAa,OAAO,QAAQ;;AAKtD,QAAO;;AAGT,SAAS,wBAAwB,eAAkD;CACjF,MAAM,SA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AAK,WAAW,qBAAqB;AAE/D,QAAO;EACL;EACA,mBAAmB,aAAa,gBAAgB,cAAc;EAC9D,sBAAsB,aAAa,mBAAmB,iBAAiB;EACxE;;AAGH,SAAgB,cAAc,WAAyB;CACrD,MAAM,UAAU,KAAK,WAAW,OAAO;CACvC,MAAM,cAAc,KAAK,WAAW,eAAe;AAEnD,KAAI,WAAW,QAAQ,IAAI,CAAC,WAAW,YAAY,CAAE;CAGrD,MAAM,QADU,aAAa,aAAa,QACrB,CAAC,MAAM,KAAK;CACjC,MAAM,SAAS,YAAY,GAAG,CAAC,SAAS,YAAY;AAUpD,eAAc,SATE,MACb,KAAK,SAAS;AACb,MAAI,uBAAuB,KAAK,KAAK,CACnC,QAAO,sBAAsB;AAE/B,SAAO;GACP,CACD,KAAK,KAEsB,CAAC;AAC/B,GAAE,IAAI,KAAK,6EAA6E;;AAG1F,SAAgB,eAAe,WAAyB;CACtD,MAAM,UAAU,KAAK,WAAW,OAAO;AACvC,KAAI,CAAC,WAAW,QAAQ,CAAE;AAE1B,QAAW;EAAE,MAAM;EAAS,YAAY,QAAQ;EAAK,OAAO;EAAM,CAAC"}
1
+ {"version":3,"file":"infra.mjs","names":[],"sources":["../../src/cli/infra.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport { config as loadDotenv } from \"dotenv\";\nimport type { RuntimeConfig } from \"../types\";\n\nconst POSTGRES_USER = \"everythingdev\";\nconst POSTGRES_PASSWORD = \"everythingdev\";\nconst API_DATABASE_SECRET = \"API_DATABASE_URL\";\nconst AUTH_DATABASE_SECRET = \"AUTH_DATABASE_URL\";\nconst HOST_SECRET = \"CORS_ORIGIN\";\nconst BASE_DATABASE_PORT = 5434;\n\ninterface DatabaseSecretConfig {\n secret: string;\n slug: string;\n fromKey: string;\n port: number;\n serviceName: string;\n containerName: string;\n databaseName: string;\n volumeName: string;\n url: string;\n}\n\ninterface SecretGroup {\n section: string;\n secrets: string[];\n}\n\ninterface GeneratedInfraSpec {\n groups: SecretGroup[];\n databases: DatabaseSecretConfig[];\n}\n\ninterface SyncGeneratedInfraResult {\n secrets: string[];\n envExampleChanged: boolean;\n dockerComposeChanged: boolean;\n}\n\nfunction uniqueSecrets(values: Array<string | undefined>): string[] {\n const secrets: string[] = [];\n const seen = new Set<string>();\n\n for (const value of values) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n secrets.push(value);\n }\n\n return secrets;\n}\n\nfunction getSecretGroups(runtimeConfig: RuntimeConfig): SecretGroup[] {\n const groups: SecretGroup[] = [];\n const seen = new Set<string>();\n\n const addGroup = (section: string, secrets: string[]) => {\n const filtered = secrets.filter((s) => {\n if (seen.has(s)) return false;\n seen.add(s);\n return true;\n });\n if (filtered.length > 0) {\n groups.push({ section, secrets: filtered });\n }\n };\n\n addGroup(\"app.host\", uniqueSecrets([...(runtimeConfig.host.secrets ?? []), HOST_SECRET]));\n\n addGroup(\"app.api\", uniqueSecrets(runtimeConfig.api.secrets ?? []));\n\n if (runtimeConfig.auth) {\n addGroup(\"app.auth\", uniqueSecrets(runtimeConfig.auth.secrets ?? []));\n }\n\n if (runtimeConfig.plugins) {\n for (const [pluginKey, plugin] of Object.entries(runtimeConfig.plugins)) {\n if (plugin.secrets && plugin.secrets.length > 0) {\n addGroup(`plugins.${pluginKey}`, plugin.secrets);\n }\n }\n }\n\n return groups;\n}\n\nfunction buildGeneratedInfraSpec(\n runtimeConfig: RuntimeConfig,\n configDir?: string,\n): GeneratedInfraSpec {\n const groups = getSecretGroups(runtimeConfig);\n const originMap = configDir ? buildOriginMap(configDir, runtimeConfig) : new Map();\n const databases = buildDatabaseConfigs(\n groups.flatMap((group) => group.secrets),\n originMap,\n );\n return { groups, databases };\n}\n\nfunction normalizeDatabaseSlug(secret: string): string {\n return secret.replace(/_DATABASE_URL$/, \"\").toLowerCase();\n}\n\nfunction buildOriginMap(configDir: string, runtimeConfig: RuntimeConfig): Map<string, string> {\n const configPath = join(configDir, \"bos.config.json\");\n\n const originMap = new Map<string, string>();\n const account = runtimeConfig.account;\n\n const resolveOrigin = (extendsRef: unknown): string | null => {\n if (typeof extendsRef === \"string\") {\n const match = extendsRef.match(/^bos:\\/\\/([^/]+)\\//);\n return match?.[1] ?? null;\n }\n return null;\n };\n\n const rawConfig = existsSync(configPath)\n ? (JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>)\n : null;\n const rawPlugins = rawConfig?.plugins as Record<string, unknown> | undefined;\n\n for (const secret of runtimeConfig.api.secrets ?? []) {\n if (!originMap.has(secret)) originMap.set(secret, account);\n }\n\n const rawApp = rawConfig?.app as Record<string, unknown> | undefined;\n const authExtends = (rawApp?.auth as Record<string, unknown> | undefined)?.extends;\n const authOrigin = resolveOrigin(authExtends) ?? account;\n for (const secret of runtimeConfig.auth?.secrets ?? []) {\n if (!originMap.has(secret)) originMap.set(secret, authOrigin);\n }\n\n for (const [pluginKey, pluginEntry] of Object.entries(runtimeConfig.plugins ?? {})) {\n const rawPlugin = rawPlugins?.[pluginKey];\n let pluginOrigin: string;\n if (typeof rawPlugin === \"string\") {\n pluginOrigin = resolveOrigin(rawPlugin) ?? account;\n } else if (rawPlugin && typeof rawPlugin === \"object\") {\n pluginOrigin = resolveOrigin((rawPlugin as Record<string, unknown>).extends) ?? account;\n } else {\n pluginOrigin = account;\n }\n for (const secret of pluginEntry.secrets ?? []) {\n if (!originMap.has(secret)) originMap.set(secret, pluginOrigin);\n }\n }\n\n for (const secret of runtimeConfig.host.secrets ?? []) {\n if (!originMap.has(secret)) originMap.set(secret, account);\n }\n\n return originMap;\n}\n\nfunction buildDatabaseConfigs(\n secrets: string[],\n originMap: Map<string, string>,\n): DatabaseSecretConfig[] {\n const databaseSecrets = uniqueSecrets(\n secrets.filter((secret) => secret.endsWith(\"_DATABASE_URL\")),\n );\n\n const additionalSecrets = databaseSecrets\n .filter((secret) => secret !== API_DATABASE_SECRET && secret !== AUTH_DATABASE_SECRET)\n .sort((a, b) => a.localeCompare(b));\n\n const orderedSecrets = [API_DATABASE_SECRET, AUTH_DATABASE_SECRET, ...additionalSecrets];\n\n return orderedSecrets.map((secret, index) => {\n const slug = normalizeDatabaseSlug(secret);\n const fromKey = originMap.get(secret) ?? \"\";\n const port =\n secret === API_DATABASE_SECRET\n ? 5432\n : secret === AUTH_DATABASE_SECRET\n ? 5433\n : BASE_DATABASE_PORT + index - 2;\n\n const volumeName = fromKey\n ? `${fromKey.replace(/\\./g, \"_\")}_postgres_${slug}_data`\n : `postgres_${slug}_data`;\n\n const containerName = fromKey ? `${fromKey}-postgres-${slug}` : `postgres-${slug}`;\n\n return {\n secret,\n slug,\n fromKey,\n port,\n serviceName: `postgres-${slug.replace(/_/g, \"-\")}`,\n containerName,\n databaseName: `${slug}_db`,\n volumeName,\n url: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${port}/${slug}_db`,\n };\n });\n}\n\nfunction defaultSecretValue(\n secret: string,\n databases: Map<string, DatabaseSecretConfig>,\n options: { forExample: boolean },\n): string {\n if (secret === \"BETTER_AUTH_SECRET\") {\n return options.forExample ? \"\" : randomBytes(32).toString(\"base64url\");\n }\n\n if (secret === \"CORS_ORIGIN\") {\n return \"http://localhost:3000\";\n }\n\n return databases.get(secret)?.url ?? \"\";\n}\n\nfunction renderEnvFile(\n groups: SecretGroup[],\n databases: DatabaseSecretConfig[],\n options: { forExample: boolean },\n): string {\n const databaseMap = new Map(databases.map((entry) => [entry.secret, entry]));\n const lines: string[] = [\n \"# Generated from configured bos secrets\",\n \"# Update values as needed for your local environment\",\n \"\",\n ];\n\n for (const group of groups) {\n lines.push(`# ${group.section}`);\n for (const secret of group.secrets) {\n lines.push(`${secret}=${defaultSecretValue(secret, databaseMap, options)}`);\n }\n lines.push(\"\");\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction renderDockerCompose(databases: DatabaseSecretConfig[], projectName: string): string {\n const lines = [\n `name: ${projectName}`,\n \"\",\n \"x-pg-common: &pg-common\",\n \" image: postgres:17-alpine\",\n \" environment: &pg-env\",\n ` POSTGRES_USER: ${POSTGRES_USER}`,\n ` POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}`,\n \" healthcheck:\",\n ' test: [\"CMD-SHELL\", \"pg_isready -U everythingdev\"]',\n \" interval: 3s\",\n \" timeout: 3s\",\n \" retries: 5\",\n \"\",\n \"services:\",\n ];\n\n for (const database of databases) {\n lines.push(` ${database.serviceName}:`);\n lines.push(\" <<: *pg-common\");\n lines.push(` container_name: ${database.containerName}`);\n lines.push(\" environment:\");\n lines.push(\" <<: *pg-env\");\n lines.push(` POSTGRES_DB: ${database.databaseName}`);\n lines.push(\" ports:\");\n lines.push(` - \"${database.port}:5432\"`);\n lines.push(\" volumes:\");\n lines.push(` - ${database.volumeName}:/var/lib/postgresql/data`);\n lines.push(\"\");\n }\n\n lines.push(\"volumes:\");\n for (const database of databases) {\n lines.push(` ${database.volumeName}:`);\n lines.push(` name: ${database.volumeName}`);\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction syncTextFile(filePath: string, nextContent: string): boolean {\n if (existsSync(filePath) && readFileSync(filePath, \"utf-8\") === nextContent) {\n return false;\n }\n\n writeFileSync(filePath, nextContent);\n return true;\n}\n\nexport function writeGeneratedInfra(configDir: string, runtimeConfig: RuntimeConfig): string[] {\n return syncGeneratedInfra(configDir, runtimeConfig).secrets;\n}\n\nexport function syncGeneratedInfra(\n configDir: string,\n runtimeConfig: RuntimeConfig,\n): SyncGeneratedInfraResult {\n const spec = buildGeneratedInfraSpec(runtimeConfig, configDir);\n const secrets = spec.groups.flatMap((group) => group.secrets);\n const newEnvContent = renderEnvFile(spec.groups, spec.databases, { forExample: true });\n const newDockerContent = renderDockerCompose(spec.databases, runtimeConfig.account);\n\n const envExamplePath = join(configDir, \".env.example\");\n const dockerComposePath = join(configDir, \"docker-compose.yml\");\n\n return {\n secrets,\n envExampleChanged: syncTextFile(envExamplePath, newEnvContent),\n dockerComposeChanged: syncTextFile(dockerComposePath, newDockerContent),\n };\n}\n\nexport function ensureEnvFile(configDir: string): void {\n const envPath = join(configDir, \".env\");\n const examplePath = join(configDir, \".env.example\");\n\n if (existsSync(envPath) || !existsSync(examplePath)) return;\n\n const content = readFileSync(examplePath, \"utf-8\");\n const lines = content.split(\"\\n\");\n const secret = randomBytes(32).toString(\"base64url\");\n const updated = lines\n .map((line) => {\n if (/^BETTER_AUTH_SECRET=/.test(line)) {\n return `BETTER_AUTH_SECRET=${secret}`;\n }\n return line;\n })\n .join(\"\\n\");\n\n writeFileSync(envPath, updated);\n p.log.info(\"Created .env from generated .env.example with generated BETTER_AUTH_SECRET\");\n}\n\nexport function loadProjectEnv(configDir: string): void {\n const envPath = join(configDir, \".env\");\n if (!existsSync(envPath)) return;\n\n loadDotenv({ path: envPath, processEnv: process.env, quiet: true });\n}\n"],"mappings":";;;;;;;AAOA,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAC7B,MAAM,cAAc;AACpB,MAAM,qBAAqB;AA8B3B,SAAS,cAAc,QAA6C;CAClE,MAAM,UAAoB,EAAE;CAC5B,MAAM,uBAAO,IAAI,KAAa;AAE9B,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,CAAC,SAAS,KAAK,IAAI,MAAM,CAAE;AAC/B,OAAK,IAAI,MAAM;AACf,UAAQ,KAAK,MAAM;;AAGrB,QAAO;;AAGT,SAAS,gBAAgB,eAA6C;CACpE,MAAM,SAAwB,EAAE;CAChC,MAAM,uBAAO,IAAI,KAAa;CAE9B,MAAM,YAAY,SAAiB,YAAsB;EACvD,MAAM,WAAW,QAAQ,QAAQ,MAAM;AACrC,OAAI,KAAK,IAAI,EAAE,CAAE,QAAO;AACxB,QAAK,IAAI,EAAE;AACX,UAAO;IACP;AACF,MAAI,SAAS,SAAS,EACpB,QAAO,KAAK;GAAE;G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AsB;AAE/B,SAAO;GACP,CACD,KAAK,KAEsB,CAAC;AAC/B,GAAE,IAAI,KAAK,6EAA6E;;AAG1F,SAAgB,eAAe,WAAyB;CACtD,MAAM,UAAU,KAAK,WAAW,OAAO;AACvC,KAAI,CAAC,WAAW,QAAQ,CAAE;AAE1B,QAAW;EAAE,MAAM;EAAS,YAAY,QAAQ;EAAK,OAAO;EAAM,CAAC"}
package/dist/cli/init.cjs CHANGED
@@ -322,7 +322,7 @@ function buildRootTypecheckScript(sections) {
322
322
  }
323
323
  function buildChildRootScripts(sections) {
324
324
  const scripts = {
325
- dev: "node_modules/.bin/bos dev --host remote",
325
+ dev: "node_modules/.bin/bos dev",
326
326
  "dev:proxy": "node_modules/.bin/bos dev --proxy",
327
327
  build: "node_modules/.bin/bos build",
328
328
  deploy: "node_modules/.bin/bos build --deploy",
@@ -864,6 +864,7 @@ function generateGitignore() {
864
864
  dist/
865
865
  .env
866
866
  .bos/
867
+ docker-compose.yml
867
868
  *.gen.ts
868
869
  *.gen.tsx
869
870
  `;
@@ -1 +1 @@
1
- {"version":3,"file":"init.cjs","names":["require","resolveExtendsRef","fetchBosConfigFromFastKv","saveBosConfig","loadManifestNormalizationSpec","normalizePackageManifestsInTree","writeSnapshot"],"sources":["../../src/cli/init.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { execa } from \"execa\";\nimport { glob } from \"glob\";\nimport type { OverrideSection } from \"../contract\";\nimport { fetchBosConfigFromFastKv } from \"../fastkv\";\nimport {\n loadManifestNormalizationSpec,\n normalizePackageManifestsInTree,\n} from \"../internal/manifest-normalizer\";\nimport { resolveExtendsRef } from \"../merge\";\nimport type { BosConfig, BosConfigInput } from \"../types\";\nimport { saveBosConfig } from \"../utils/save-config\";\nimport { writeSnapshot } from \"./snapshot\";\n\nconst require = createRequire(import.meta.url);\n\nexport const INIT_ROOT_PATTERNS = [\n \"bos.config.json\",\n \"package.json\",\n \".env.example\",\n \".gitignore\",\n \"biome.json\",\n \"bunfig.toml\",\n \"Dockerfile\",\n \"railway.json\",\n \"railway.toml\",\n \"AGENTS.md\",\n \".changeset/config.json\",\n \".changeset/README.md\",\n \"README.md\",\n \"CONTRIBUTING.md\",\n \".github/templates/**\",\n] as const;\n\nconst OVERRIDE_WORKSPACE_MAP: Record<OverrideSection, string[]> = {\n ui: [\"ui\"],\n api: [\"api\"],\n host: [\"host\"],\n plugins: [],\n};\n\ninterface SourceResult {\n sourceDir: string;\n parentConfig: BosConfig;\n cleanup: () => Promise<void>;\n}\n\nexport interface CatalogChainSource {\n catalog: Record<string, string>;\n repository?: string;\n extendsChain: string[];\n}\n\nfunction getExtendsRef(config: Record<string, unknown>): string | undefined {\n if (typeof config.extends === \"string\") {\n return config.extends;\n }\n\n if (config.extends && typeof config.extends === \"object\") {\n return resolveExtendsRef(config.extends as Record<string, string>, \"production\");\n }\n\n return undefined;\n}\n\nfunction parseBosRef(ref: string): { account: string; gateway: string } | null {\n const match = ref.match(/^bos:\\/\\/([^/]+)\\/(.+)$/);\n if (!match?.[1] || !match[2]) return null;\n return { account: match[1], gateway: match[2] };\n}\n\nfunction readWorkspaceCatalog(sourceDir: string): Record<string, string> {\n const pkgPath = join(sourceDir, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n\n const pkg = readJsonFile<{ workspaces?: { catalog?: Record<string, string> } }>(pkgPath);\n return { ...(pkg.workspaces?.catalog ?? {}) };\n}\n\nexport async function resolveCatalogChainSource(opts: {\n extendsAccount: string;\n extendsGateway: string;\n sourceDir?: string;\n}): Promise<CatalogChainSource> {\n const catalogs: Record<string, string>[] = [];\n const cleanups: Array<() => Promise<void>> = [];\n const extendsChain: string[] = [];\n const visited = new Set<string>();\n let repository: string | undefined;\n let currentRef = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n let sourceDir = opts.sourceDir ? resolve(opts.sourceDir) : undefined;\n let configPath = sourceDir ? join(sourceDir, \"bos.config.json\") : undefined;\n\n try {\n while (true) {\n if (visited.has(currentRef)) {\n throw new Error(`Circular extends detected while resolving catalog source: ${currentRef}`);\n }\n\n visited.add(currentRef);\n extendsChain.push(currentRef);\n\n let config: Record<string, unknown>;\n let currentSourceDir = sourceDir;\n let cleanup: () => Promise<void> = async () => {};\n\n if (configPath) {\n config = readJsonFile<Record<string, unknown>>(configPath);\n currentSourceDir = dirname(configPath);\n } else {\n const parsed = parseBosRef(currentRef);\n if (!parsed) {\n break;\n }\n const sourceResult = await resolveSourceDir({\n extendsAccount: parsed.account,\n extendsGateway: parsed.gateway,\n });\n config = sourceResult.parentConfig as Record<string, unknown>;\n currentSourceDir = sourceResult.sourceDir || undefined;\n cleanup = sourceResult.cleanup;\n }\n\n cleanups.push(cleanup);\n catalogs.push(currentSourceDir ? readWorkspaceCatalog(currentSourceDir) : {});\n\n if (typeof config.repository === \"string\") {\n repository = config.repository;\n }\n\n const nextExtendsRef = getExtendsRef(config);\n if (!nextExtendsRef) {\n break;\n }\n\n if (nextExtendsRef.startsWith(\"bos://\")) {\n currentRef = nextExtendsRef;\n sourceDir = undefined;\n configPath = undefined;\n continue;\n }\n\n if (!currentSourceDir) {\n break;\n }\n\n const nextConfigPath = resolve(currentSourceDir, nextExtendsRef);\n if (!existsSync(nextConfigPath)) {\n break;\n }\n\n currentRef = nextConfigPath;\n sourceDir = dirname(nextConfigPath);\n configPath = nextConfigPath;\n }\n } finally {\n for (const cleanup of cleanups.reverse()) {\n await cleanup();\n }\n }\n\n return {\n catalog: Object.assign({}, ...catalogs.reverse()),\n repository,\n extendsChain,\n };\n}\n\nexport async function resolveSourceDir(opts: {\n extendsAccount: string;\n extendsGateway: string;\n source?: string;\n}): Promise<SourceResult> {\n if (opts.source) {\n const sourceDir = resolve(opts.source);\n if (!existsSync(join(sourceDir, \"bos.config.json\"))) {\n throw new Error(`No bos.config.json found in source directory: ${sourceDir}`);\n }\n const parentConfig = JSON.parse(\n readFileSync(join(sourceDir, \"bos.config.json\"), \"utf-8\"),\n ) as BosConfig;\n return { sourceDir, parentConfig, cleanup: async () => {} };\n }\n\n const parentConfig = await fetchParentConfig(opts.extendsAccount, opts.extendsGateway);\n\n if (parentConfig.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(parentConfig.repository);\n return { sourceDir, parentConfig, cleanup };\n }\n\n const chainResult = await resolveRepositoryViaExtendsChain(\n opts.extendsAccount,\n opts.extendsGateway,\n );\n if (chainResult?.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(chainResult.repository);\n return { sourceDir, parentConfig: chainResult.config, cleanup };\n }\n\n return {\n sourceDir: \"\",\n parentConfig,\n cleanup: async () => {},\n };\n}\n\nexport function buildInitPatterns(overrides: OverrideSection[], plugins?: string[]): string[] {\n const has = (section: OverrideSection) => overrides.includes(section);\n const patterns: string[] = [...INIT_ROOT_PATTERNS];\n\n if (has(\"ui\")) patterns.push(\"ui/**\");\n if (has(\"api\")) patterns.push(\"api/**\");\n if (has(\"host\")) patterns.push(\"host/**\");\n if (has(\"plugins\")) {\n for (const plugin of plugins ?? []) {\n patterns.push(`plugins/${plugin}/**`);\n }\n }\n\n return patterns;\n}\n\nexport function sourcePathToDestinationPath(filePath: string): string {\n return filePath.startsWith(\".github/templates/\")\n ? filePath.replace(/^\\.github\\/templates\\//, \".github/\")\n : filePath;\n}\n\nexport async function fetchParentConfig(\n extendsAccount: string,\n extendsGateway: string,\n): Promise<BosConfig> {\n const bosUrl = `bos://${extendsAccount}/${extendsGateway}`;\n return fetchBosConfigFromFastKv<BosConfig>(bosUrl);\n}\n\nexport async function resolveRepositoryViaExtendsChain(\n extendsAccount: string,\n extendsGateway: string,\n visited = new Set<string>(),\n): Promise<{ repository: string; config: BosConfig } | null> {\n const key = `bos://${extendsAccount}/${extendsGateway}`;\n if (visited.has(key)) return null;\n visited.add(key);\n\n try {\n const config = await fetchParentConfig(extendsAccount, extendsGateway);\n if (config.repository) {\n return { repository: config.repository, config };\n }\n\n const extendsRef = getExtendsRef(config as Record<string, unknown>);\n if (extendsRef) {\n const normalized = extendsRef.startsWith(\"bos://\") ? extendsRef : `bos://${extendsRef}`;\n const parsed = parseBosRef(normalized);\n if (parsed) {\n const result = await resolveRepositoryViaExtendsChain(\n parsed.account,\n parsed.gateway,\n visited,\n );\n if (result) return result;\n }\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function detectGitRemoteUrl(directory: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd: directory,\n stdio: \"pipe\",\n });\n const url = stdout.trim();\n if (!url) return undefined;\n return normalizeGitUrl(url);\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeGitUrl(url: string): string | undefined {\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;\n }\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;\n }\n return url.endsWith(\".git\") ? url.slice(0, -4) : url;\n}\n\nexport async function downloadTarball(\n repoUrl: string,\n): Promise<{ dir: string; cleanup: () => Promise<void> }> {\n const parsed = parseGitHubUrl(repoUrl);\n if (!parsed) {\n throw new Error(`Cannot parse repository URL: ${repoUrl}`);\n }\n\n const { owner, repo } = parsed;\n let response: Response | null = null;\n\n for (const branch of [\"main\", \"master\"]) {\n const candidate = await fetch(\n `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`,\n {\n headers: { \"User-Agent\": \"everything-dev\" },\n redirect: \"follow\",\n },\n );\n if (candidate.ok) {\n response = candidate;\n break;\n }\n if (candidate.status !== 404) {\n throw new Error(\n `GitHub tarball download failed: ${candidate.status} ${candidate.statusText}`,\n );\n }\n }\n\n if (!response) {\n throw new Error(`GitHub tarball download failed for ${repoUrl}: tried main and master`);\n }\n\n if (!response.body) {\n throw new Error(\"GitHub tarball download returned empty body\");\n }\n\n const tmpDir = mkTmpDir(\"bos-init-tarball-\");\n const tarballPath = join(tmpDir, \"source.tar.gz\");\n\n const fileStream = createWriteStream(tarballPath);\n const reader = response.body as unknown as NodeJS.ReadableStream;\n await pipeline(reader, fileStream);\n\n const extractDir = mkTmpDir(\"bos-init-extract-\");\n try {\n const tar = require(\"tar\") as {\n extract: (opts: { cwd: string; file: string; strip: number }) => Promise<void>;\n };\n await tar.extract({ cwd: extractDir, file: tarballPath, strip: 1 });\n } catch {\n await execCommand(\"tar\", [\"-xzf\", tarballPath, \"--strip-components=1\", \"-C\", extractDir]);\n }\n\n rmSync(tmpDir, { recursive: true, force: true });\n\n return {\n dir: extractDir,\n cleanup: async () => {\n rmSync(extractDir, { recursive: true, force: true });\n },\n };\n}\n\nfunction parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return { owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return { owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n return null;\n}\n\nexport async function copyFilteredFiles(\n sourceDir: string,\n destination: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<number> {\n if (patterns.length === 0) {\n return 0;\n }\n\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n mkdirSync(destination, { recursive: true });\n\n let count = 0;\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n\n const destPath = sourcePathToDestinationPath(filePath);\n const dest = join(destination, destPath);\n mkdirSync(dirname(dest), { recursive: true });\n const content = readFileSync(src);\n writeFileSync(dest, content);\n count++;\n }\n\n return count;\n}\n\nfunction stripProductionFields(entry: Record<string, unknown>): void {\n delete entry.production;\n delete entry.integrity;\n delete entry.ssr;\n delete entry.ssrIntegrity;\n}\n\nfunction buildRootTypecheckScript(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): string {\n const commands = [\"bun run types:gen\"];\n\n if (sections.ui) {\n commands.push(\"if [ -d ui ]; then bun run --cwd ui typecheck; fi\");\n }\n if (sections.api) {\n commands.push(\"if [ -d api ]; then bun run --cwd api typecheck; fi\");\n }\n if (sections.host) {\n commands.push(\"if [ -d host ]; then bun run --cwd host typecheck; fi\");\n }\n if (sections.plugins) {\n commands.push(\n 'if [ -d plugins ]; then for dir in plugins/*; do if [ -f \"$dir/package.json\" ]; then bun run --cwd \"$dir\" typecheck; fi; done; fi',\n );\n }\n\n return commands.join(\" && \");\n}\n\nexport function buildChildRootScripts(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): Record<string, string> {\n const scripts: Record<string, string> = {\n dev: \"node_modules/.bin/bos dev --host remote\",\n \"dev:proxy\": \"node_modules/.bin/bos dev --proxy\",\n build: \"node_modules/.bin/bos build\",\n deploy: \"node_modules/.bin/bos build --deploy\",\n publish: \"node_modules/.bin/bos publish\",\n start: \"node_modules/.bin/bos start\",\n typecheck: buildRootTypecheckScript(sections),\n lint: \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n format: \"biome format --write .\",\n \"format:check\": \"biome format .\",\n changeset: \"changeset\",\n version: \"changeset version\",\n release: \"echo 'Packages versioned - app release handled by workflow'\",\n postinstall: \"node_modules/.bin/bos types gen || true\",\n \"types:gen\": \"node_modules/.bin/bos types gen\",\n bos: \"node_modules/.bin/bos\",\n };\n\n if (sections.api) {\n scripts[\"db:push\"] = \"bun run --cwd api drizzle-kit push\";\n scripts[\"db:studio\"] = \"bun run --cwd api drizzle-kit studio\";\n scripts[\"db:generate\"] = \"bun run --cwd api drizzle-kit generate\";\n scripts[\"db:migrate\"] = \"bun run --cwd api drizzle-kit migrate\";\n scripts[\"test:api\"] = \"cd api && bun run test tests/integration/ tests/unit/\";\n scripts[\"test:integration\"] = \"cd api && bun run test tests/integration/\";\n }\n\n if (sections.host) {\n scripts[\"test:e2e\"] = \"bun run --cwd host test:e2e\";\n }\n\n if (sections.api && sections.host) {\n scripts.test = \"bun run test:api && bun run test:e2e\";\n } else if (sections.api) {\n scripts.test = \"bun run test:api\";\n } else if (sections.host) {\n scripts.test = \"bun run test:e2e\";\n }\n\n if (sections.api || sections.host) {\n scripts[\"dev:postgres\"] = \"docker compose up -d --wait && bun run dev\";\n scripts[\"dev:postgres:down\"] = \"docker compose down\";\n scripts[\"dev:postgres:reset\"] = \"docker compose down -v && docker compose up -d --wait\";\n }\n\n if (sections.ui) {\n scripts[\"dev:ui\"] = \"node_modules/.bin/bos dev --ui local --api remote\";\n }\n if (sections.api) {\n scripts[\"dev:api\"] = \"node_modules/.bin/bos dev --ui remote --api local\";\n }\n\n return scripts;\n}\n\nexport async function personalizeConfig(\n destination: string,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n pluginRoutes?: Record<string, string[]>;\n workspaceOpts?: { localOverrides?: boolean; sourceDir?: string };\n mode?: \"init\" | \"sync\";\n existingConfig?: Record<string, unknown>;\n repository?: string;\n title?: string;\n description?: string;\n testnet?: string;\n staging?: unknown;\n },\n): Promise<void> {\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n const existingApp =\n opts.mode === \"sync\" && opts.existingConfig?.app && typeof opts.existingConfig.app === \"object\"\n ? (opts.existingConfig.app as Record<string, unknown>)\n : undefined;\n const preservedAuth = existingApp?.auth;\n\n const explicitRootKeys = new Set(\n Object.entries(opts)\n .filter(\n ([key, value]) =>\n value !== undefined &&\n ![\n \"extendsAccount\",\n \"extendsGateway\",\n \"plugins\",\n \"overrides\",\n \"pluginRoutes\",\n \"workspaceOpts\",\n \"mode\",\n \"existingConfig\",\n ].includes(key),\n )\n .map(([key]) => key),\n );\n\n const configPath = join(destination, \"bos.config.json\");\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>;\n\n config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n if (opts.account) {\n config.account = opts.account;\n }\n if (opts.domain) {\n config.domain = opts.domain;\n }\n if (opts.repository) {\n config.repository = opts.repository;\n } else {\n delete config.repository;\n }\n\n const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n for (const field of inheritableFields) {\n if (!(field in opts)) {\n delete config[field];\n }\n }\n\n if (config.app && typeof config.app === \"object\") {\n const app = config.app as Record<string, unknown>;\n\n for (const entryKey of Object.keys(app)) {\n if (\n !has(entryKey as OverrideSection) &&\n (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n ) {\n delete app[entryKey];\n continue;\n }\n if (entryKey === \"auth\") {\n delete app[entryKey];\n continue;\n }\n const entry = app[entryKey];\n if (entry && typeof entry === \"object\") {\n stripProductionFields(entry as Record<string, unknown>);\n }\n }\n\n if (preservedAuth !== undefined) {\n app.auth = preservedAuth;\n }\n\n if (Object.keys(app).length === 0) {\n delete config.app;\n }\n }\n\n if (has(\"plugins\")) {\n if (config.plugins && typeof config.plugins === \"object\") {\n const plugins = config.plugins as Record<string, unknown>;\n\n if (opts.plugins !== undefined) {\n for (const pluginKey of Object.keys(plugins)) {\n if (!opts.plugins.includes(pluginKey)) {\n delete plugins[pluginKey];\n }\n }\n }\n\n for (const pluginKey of Object.keys(plugins)) {\n const plugin = plugins[pluginKey];\n let pluginObj: Record<string, unknown>;\n\n if (typeof plugin === \"string\") {\n pluginObj = { extends: plugin };\n plugins[pluginKey] = pluginObj;\n } else if (plugin && typeof plugin === \"object\") {\n pluginObj = { ...(plugin as Record<string, unknown>) };\n plugins[pluginKey] = pluginObj;\n } else {\n continue;\n }\n\n stripProductionFields(pluginObj);\n }\n\n if (Object.keys(plugins).length === 0) {\n config.plugins = {};\n }\n }\n } else {\n config.plugins = {};\n }\n\n if (opts.mode === \"sync\" && opts.existingConfig) {\n const managedRootKeys = new Set([\"extends\", \"account\", \"domain\", \"app\", \"plugins\"]);\n const preservedRootKeys = new Set([\n ...managedRootKeys,\n ...Object.keys(opts.existingConfig),\n ...explicitRootKeys,\n ]);\n\n for (const key of Object.keys(config)) {\n if (!preservedRootKeys.has(key)) {\n delete config[key];\n }\n }\n\n for (const [key, value] of Object.entries(opts.existingConfig)) {\n if (!(key in config) && !managedRootKeys.has(key) && !explicitRootKeys.has(key)) {\n config[key] = value;\n }\n }\n }\n\n await saveBosConfig(destination, config);\n }\n\n const pkgPath = join(destination, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const childScripts = buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n });\n\n if (typeof pkg.name !== \"string\" || pkg.name.length === 0) {\n pkg.name = \"monorepo\";\n }\n pkg.private = true;\n pkg.type = \"module\";\n delete pkg.module;\n delete pkg.peerDependencies;\n\n if (pkg.workspaces && typeof pkg.workspaces === \"object\") {\n const ws = pkg.workspaces as { packages?: string[] };\n if (Array.isArray(ws.packages)) {\n ws.packages = ws.packages.filter((p: string) => {\n if (p.startsWith(\"packages/\")) return false;\n if (p === \"ui\") return has(\"ui\");\n if (p === \"api\") return has(\"api\");\n if (p === \"host\") return has(\"host\");\n if (p.startsWith(\"plugins/\")) return false;\n return true;\n });\n\n if (has(\"plugins\")) {\n if (!ws.packages.includes(\"plugins/*\")) {\n ws.packages.push(\"plugins/*\");\n }\n }\n }\n }\n\n if (!pkg.scripts || typeof pkg.scripts !== \"object\") {\n pkg.scripts = {};\n }\n const scripts = pkg.scripts as Record<string, string>;\n for (const [key, value] of Object.entries(childScripts)) {\n scripts[key] = value;\n }\n for (const obsoleteScript of [\n \"init\",\n \"sync-catalog\",\n \"db:push\",\n \"db:studio\",\n \"db:generate\",\n \"db:migrate\",\n \"test\",\n \"test:api\",\n \"test:integration\",\n \"test:e2e\",\n \"dev:postgres\",\n \"dev:postgres:down\",\n \"dev:postgres:reset\",\n \"dev:ui\",\n \"dev:api\",\n ]) {\n if (!(obsoleteScript in childScripts)) {\n delete scripts[obsoleteScript];\n }\n }\n\n if (pkg.devDependencies && typeof pkg.devDependencies === \"object\") {\n const deps = pkg.devDependencies as Record<string, string>;\n delete deps[\"every-plugin\"];\n delete deps[\"everything-dev\"];\n }\n\n if (!pkg.workspaces || typeof pkg.workspaces !== \"object\") {\n pkg.workspaces = { packages: [], catalog: {} };\n }\n const workspaces = pkg.workspaces as { packages?: string[]; catalog?: Record<string, string> };\n if (!workspaces.catalog || typeof workspaces.catalog !== \"object\") {\n workspaces.catalog = {};\n }\n\n if (!pkg.dependencies) pkg.dependencies = {};\n const deps = pkg.dependencies as Record<string, string>;\n const spec = opts.workspaceOpts?.sourceDir\n ? loadManifestNormalizationSpec(opts.workspaceOpts.sourceDir)\n : null;\n if (spec) {\n workspaces.catalog[\"everything-dev\"] = spec.rootCatalog[\"everything-dev\"];\n workspaces.catalog[\"every-plugin\"] = spec.rootCatalog[\"every-plugin\"];\n }\n const frameworkCatalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n sourceDir: opts.workspaceOpts?.sourceDir,\n })\n ).catalog;\n for (const [name, version] of Object.entries(frameworkCatalog)) {\n workspaces.catalog[name] = version;\n }\n if (!deps[\"everything-dev\"]) deps[\"everything-dev\"] = \"catalog:\";\n if (!deps[\"every-plugin\"]) deps[\"every-plugin\"] = \"catalog:\";\n\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n }\n\n const apiTsConfigPath = join(destination, \"api\", \"tsconfig.json\");\n if (existsSync(apiTsConfigPath)) {\n const apiTsConfig = JSON.parse(readFileSync(apiTsConfigPath, \"utf-8\")) as {\n files?: string[];\n [key: string]: unknown;\n };\n if (apiTsConfig.files) {\n const validFiles = apiTsConfig.files.filter((f) => existsSync(join(destination, \"api\", f)));\n if (validFiles.length !== apiTsConfig.files.length) {\n if (validFiles.length === 0) {\n delete apiTsConfig.files;\n } else {\n apiTsConfig.files = validFiles;\n }\n writeFileSync(apiTsConfigPath, `${JSON.stringify(apiTsConfig, null, 2)}\\n`);\n }\n }\n }\n\n await resolveWorkspaceRefs(destination, opts.workspaceOpts);\n\n if (has(\"ui\")) {\n const genContractPath = join(destination, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n if (!existsSync(genContractPath)) {\n mkdirSync(dirname(genContractPath), { recursive: true });\n writeFileSync(genContractPath, `export type ApiContract = Record<string, never>;\\n`);\n }\n }\n\n if (has(\"api\")) {\n const pluginsClientGenPath = join(destination, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n if (!existsSync(pluginsClientGenPath)) {\n mkdirSync(dirname(pluginsClientGenPath), { recursive: true });\n writeFileSync(\n pluginsClientGenPath,\n `import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";\\ntype ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\\nexport type PluginsClient = Record<string, never>;\\n`,\n );\n }\n }\n\n const authTypesPaths: string[] = [];\n if (has(\"ui\")) {\n authTypesPaths.push(join(destination, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"api\")) {\n authTypesPaths.push(join(destination, \"api\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"host\") && existsSync(join(destination, \"host\", \"src\"))) {\n authTypesPaths.push(join(destination, \"host\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n for (const authTypesGenPath of authTypesPaths) {\n if (!existsSync(authTypesGenPath)) {\n mkdirSync(dirname(authTypesGenPath), { recursive: true });\n writeFileSync(authTypesGenPath, generateAuthTypesContent(authTypesGenPath, destination));\n }\n }\n\n if (authTypesPaths.length > 0) {\n const authDir = join(destination, \".bos\", \"generated\", \"auth\");\n if (!existsSync(authDir)) {\n mkdirSync(authDir, { recursive: true });\n }\n const authExportStubPath = join(authDir, \"auth-export.d.ts\");\n if (!existsSync(authExportStubPath)) {\n writeFileSync(\n authExportStubPath,\n `export type Auth = any;\nexport type AuthOrganizationContext = any;\nexport type AuthOrganization = any;\nexport type AuthOrganizationSummary = any;\nexport type AuthOrganizationMember = any;\nexport type AuthApiKey = any;\nexport type AuthInvitation = any;\nexport type GetActiveMemberInput = any;\nexport type GetOrganizationInput = any;\nexport type ListMembersInput = any;\nexport type ListInvitationsInput = any;\nexport type ListApiKeysInput = any;\nexport type AuthServices = any;\nexport type createAuthInstance = any;\n`,\n );\n }\n const contractStubPath = join(authDir, \"contract.d.ts\");\n if (!existsSync(contractStubPath)) {\n writeFileSync(\n contractStubPath,\n `export type ContractType = any;\nexport type InferOutput<_TRoute extends string> = any;\n`,\n );\n }\n }\n\n if (has(\"plugins\")) {\n for (const plugin of opts.plugins ?? []) {\n const pluginSrcDir = join(destination, \"plugins\", plugin, \"src\");\n const pluginIndexPath = join(pluginSrcDir, \"index.ts\");\n const pluginClientGenPath = join(pluginSrcDir, \"plugins-client.gen.ts\");\n if (!existsSync(pluginIndexPath) || existsSync(pluginClientGenPath)) {\n continue;\n }\n const pluginIndex = readFileSync(pluginIndexPath, \"utf-8\");\n if (!pluginIndex.includes(\"./plugins-client.gen\")) {\n continue;\n }\n writeFileSync(pluginClientGenPath, \"export type PluginsClient = Record<string, never>;\\n\");\n }\n }\n}\n\nfunction generateAuthTypesContent(targetPath: string, configDir: string): string {\n const authExportRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"auth-export.d.ts\"),\n targetPath,\n );\n const contractRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"contract.d.ts\"),\n targetPath,\n );\n\n return `export type {\n Auth,\n AuthOrganizationContext,\n AuthOrganization,\n AuthOrganizationSummary,\n AuthOrganizationMember,\n AuthApiKey,\n AuthInvitation,\n GetActiveMemberInput,\n GetOrganizationInput,\n ListMembersInput,\n ListInvitationsInput,\n ListApiKeysInput,\n AuthServices,\n createAuthInstance,\n} from \"${authExportRel}\";\nimport type { InferOutput, ContractType as AuthContract } from \"${contractRel}\";\nimport type { Auth as BaseAuth } from \"${authExportRel}\";\n\ntype RawAuthSession = InferOutput<\"getSession\">;\ntype RawAuthRequestContext = InferOutput<\"getContext\">;\ntype RawAuthActiveMember = InferOutput<\"getActiveMember\">;\n\nexport type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {\n role?: string | null;\n isAnonymous?: boolean | null;\n walletAddress?: string | null;\n banned?: boolean | null;\n};\nexport type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {\n activeOrganizationId?: string | null;\n};\nexport type AuthSession = {\n user: AuthSessionUser | null;\n session: AuthSessionData | null;\n};\nexport type AuthRequestContext = RawAuthRequestContext & {\n organization?: { activeOrganizationId?: string | null } | null;\n apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;\n};\nexport type AuthActiveMember = RawAuthActiveMember;\nexport type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];\nexport type AuthContractType = AuthContract;\n`;\n}\n\nfunction toRelativeImportPath(fromPath: string, toPath: string): string {\n const rel = relative(dirname(toPath), fromPath);\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport async function runBunInstall(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--ignore-scripts\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runBunInstallForUpgrade(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--force\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runTypesGen(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n const localBosBin = join(destination, \"node_modules\", \".bin\", \"bos\");\n if (existsSync(localBosBin)) {\n await runWithProgress(\n \"node_modules/.bin/bos\",\n [\"types\", \"gen\"],\n destination,\n spinner,\n \"Generating types\",\n );\n return;\n }\n\n throw new Error(\"Unable to locate bos CLI for types generation\");\n}\n\nexport async function runDockerComposeUp(destination: string): Promise<void> {\n await execCommand(\"docker\", [\"compose\", \"up\", \"-d\", \"--wait\"], destination, { stdio: \"inherit\" });\n}\n\nasync function runWithProgress(\n command: string,\n args: string[],\n cwd: string,\n spinner: { message: (msg: string) => void } | undefined,\n label: string,\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n const child = execa(command, args, { cwd, stdio: \"inherit\", timeout });\n\n if (spinner) {\n const start = Date.now();\n const interval = setInterval(() => {\n const elapsed = Math.round((Date.now() - start) / 1000);\n spinner.message(`${label}... (${elapsed}s)`);\n }, 2000);\n try {\n await child;\n } finally {\n clearInterval(interval);\n }\n } else {\n await child;\n }\n}\n\nexport function stripOrphanedWorkspacesFromLockfile(\n lockfilePath: string,\n allowedWorkspaces: string[],\n): void {\n if (!existsSync(lockfilePath)) return;\n\n const content = readFileSync(lockfilePath, \"utf-8\");\n let lockfile: Record<string, unknown>;\n try {\n lockfile = JSON.parse(content) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const workspaces = lockfile.workspaces;\n if (!workspaces || typeof workspaces !== \"object\") return;\n\n const workspaceMap = workspaces as Record<string, unknown>;\n const allowed = new Set([\"\", ...allowedWorkspaces]);\n\n const keys = Object.keys(workspaceMap);\n let changed = false;\n for (const key of keys) {\n if (allowed.has(key)) continue;\n if (\n allowedWorkspaces.some(\n (pattern) => pattern.endsWith(\"/*\") && key.startsWith(pattern.slice(0, -1)),\n )\n )\n continue;\n delete workspaceMap[key];\n changed = true;\n }\n\n if (changed) {\n writeFileSync(lockfilePath, `${JSON.stringify(lockfile, null, 2)}\\n`);\n }\n}\n\nexport function removeInitLockfile(lockfilePath: string): void {\n if (!existsSync(lockfilePath)) return;\n rmSync(lockfilePath, { force: true });\n}\n\nfunction readJsonFile<T>(filePath: string): T {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n}\n\nexport async function scaffoldMinimalProject(\n destination: string,\n parentConfig: BosConfigInput,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n repository?: string;\n title?: string;\n description?: string;\n },\n): Promise<number> {\n mkdirSync(destination, { recursive: true });\n\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n\n const config: Record<string, unknown> = {\n extends: `bos://${opts.extendsAccount}/${opts.extendsGateway}`,\n account: opts.account || opts.extendsAccount,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.repository ? { repository: opts.repository } : {}),\n ...(opts.title ? { title: opts.title } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n };\n\n if (parentConfig.app && typeof parentConfig.app === \"object\") {\n const app: Record<string, unknown> = {};\n const parentApp = parentConfig.app as Record<string, Record<string, unknown>>;\n\n if (has(\"host\") && parentApp.host) {\n app.host = { ...parentApp.host };\n stripProductionFields(app.host as Record<string, unknown>);\n }\n\n if (has(\"ui\") && parentApp.ui) {\n app.ui = { ...parentApp.ui };\n stripProductionFields(app.ui as Record<string, unknown>);\n }\n\n if (has(\"api\") && parentApp.api) {\n app.api = { ...parentApp.api };\n stripProductionFields(app.api as Record<string, unknown>);\n }\n\n if (Object.keys(app).length > 0) {\n config.app = app;\n }\n }\n\n if (has(\"plugins\") && opts.plugins && opts.plugins.length > 0 && parentConfig.plugins) {\n const plugins: Record<string, unknown> = {};\n for (const key of opts.plugins) {\n const parentPlugin = (parentConfig.plugins as Record<string, unknown>)?.[key];\n if (parentPlugin) {\n if (typeof parentPlugin === \"string\") {\n plugins[key] = { extends: parentPlugin };\n } else {\n const pluginCopy = { ...(parentPlugin as Record<string, unknown>) };\n stripProductionFields(pluginCopy);\n plugins[key] = pluginCopy;\n }\n }\n }\n config.plugins = plugins;\n } else if (has(\"plugins\")) {\n config.plugins = {};\n }\n\n await saveBosConfig(destination, config);\n\n const workspacePackages: string[] = [];\n for (const section of opts.overrides) {\n workspacePackages.push(...OVERRIDE_WORKSPACE_MAP[section]);\n }\n if (has(\"plugins\")) {\n workspacePackages.push(\"plugins/*\");\n }\n\n const catalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n })\n ).catalog;\n\n const pkg: Record<string, unknown> = {\n name: \"monorepo\",\n private: true,\n type: \"module\",\n scripts: buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n }),\n dependencies: {\n \"everything-dev\": \"catalog:\",\n \"every-plugin\": \"catalog:\",\n },\n devDependencies: {},\n workspaces: {\n packages: workspacePackages,\n catalog,\n },\n };\n writeFileSync(join(destination, \"package.json\"), `${JSON.stringify(pkg, null, 2)}\\n`);\n\n writeFileSync(join(destination, \".gitignore\"), generateGitignore());\n\n return 4;\n}\n\nasync function resolveWorkspaceRefs(\n destination: string,\n options?: { localOverrides?: boolean; sourceDir?: string },\n): Promise<void> {\n await normalizePackageManifestsInTree({\n sourceRootDir: options?.sourceDir ?? destination,\n targetDir: destination,\n resolveCatalogRefs: false,\n preserveCatalogRefs: true,\n removeWorkspaceDeps: [\"host\"],\n });\n}\n\nexport async function writeInitSnapshot(\n destination: string,\n extendsAccount: string,\n extendsGateway: string,\n sourceDir: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<void> {\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n const fileHashes: Record<string, string> = {};\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n const content = readFileSync(src);\n const destPath = sourcePathToDestinationPath(filePath);\n fileHashes[destPath] = computeHash(content);\n }\n\n await writeSnapshot(destination, {\n parentRef: `bos://${extendsAccount}/${extendsGateway}`,\n files: fileHashes,\n });\n}\n\nfunction computeHash(data: Uint8Array): string {\n return createHash(\"sha256\").update(data).digest(\"hex\").substring(0, 16);\n}\n\nfunction mkTmpDir(prefix: string): string {\n return mkdtempSync(join(tmpdir(), `${prefix}-`));\n}\n\nexport async function generateDatabaseMigrations(destination: string): Promise<void> {\n const drizzleConfigs = await glob(\"**/drizzle.config.ts\", {\n cwd: destination,\n nodir: true,\n dot: false,\n absolute: false,\n ignore: [\"**/node_modules/**\"],\n });\n\n for (const configPath of drizzleConfigs) {\n const workspaceDir = dirname(configPath);\n const pkgPath = join(destination, workspaceDir, \"package.json\");\n if (!existsSync(pkgPath)) continue;\n\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const scripts = pkg.scripts as Record<string, string> | undefined;\n if (!scripts?.[\"db:generate\"]) continue;\n\n const cwd = join(destination, workspaceDir);\n await execCommand(\"bun\", [\"run\", \"db:generate\"], cwd);\n }\n}\n\nconst COMMAND_TIMEOUTS: Record<string, number> = {\n bun: 5 * 60_000,\n docker: 5 * 60_000,\n node_modules: 2 * 60_000,\n tar: 60_000,\n};\n\nexport async function execCommand(\n command: string,\n args: string[],\n cwd?: string,\n options?: { stdio?: \"pipe\" | \"inherit\" },\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n await execa(command, args, { cwd, stdio: options?.stdio ?? \"pipe\", timeout });\n}\n\nfunction generateGitignore(): string {\n return `node_modules/\ndist/\n.env\n.bos/\n*.gen.ts\n*.gen.tsx\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAMA,yFAAwC;AAE9C,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,yBAA4D;CAChE,IAAI,CAAC,KAAK;CACV,KAAK,CAAC,MAAM;CACZ,MAAM,CAAC,OAAO;CACd,SAAS,EAAE;CACZ;AAcD,SAAS,cAAc,QAAqD;AAC1E,KAAI,OAAO,OAAO,YAAY,SAC5B,QAAO,OAAO;AAGhB,KAAI,OAAO,WAAW,OAAO,OAAO,YAAY,SAC9C,QAAOC,gCAAkB,OAAO,SAAmC,aAAa;;AAMpF,SAAS,YAAY,KAA0D;CAC7E,MAAM,QAAQ,IAAI,MAAM,0BAA0B;AAClD,KAAI,CAAC,QAAQ,MAAM,CAAC,MAAM,GAAI,QAAO;AACrC,QAAO;EAAE,SAAS,MAAM;EAAI,SAAS,MAAM;EAAI;;AAGjD,SAAS,qBAAqB,WAA2C;CACvE,MAAM,8BAAe,WAAW,eAAe;AAC/C,KAAI,yBAAY,QAAQ,CACtB,QAAO,EAAE;AAIX,QAAO,EAAE,GADG,aAAoE,QAChE,CAAC,YAAY,WAAW,EAAE,EAAG;;AAG/C,eAAsB,0BAA0B,MAIhB;CAC9B,MAAM,WAAqC,EAAE;CAC7C,MAAM,WAAuC,EAAE;CAC/C,MAAM,eAAyB,EAAE;CACjC,MAAM,0BAAU,IAAI,KAAa;CACjC,IAAI;CACJ,IAAI,aAAa,SAAS,KAAK,eAAe,GAAG,KA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AM,8BAAe,aAAa,cAAc,eAAe;AAC/D,MAAI,yBAAY,QAAQ,CAAE;AAI1B,MAAI,CAFQ,KAAK,gCAAmB,SAAS,QAAQ,CAClC,CAAC,UACL,eAAgB;AAG/B,QAAM,YAAY,OAAO,CAAC,OAAO,cAAc,sBAD9B,aAAa,aACsB,CAAC;;;AAIzD,MAAM,mBAA2C;CAC/C,KAAK,IAAI;CACT,QAAQ,IAAI;CACZ,cAAc,IAAI;CAClB,KAAK;CACN;AAED,eAAsB,YACpB,SACA,MACA,KACA,SACe;CACf,MAAM,UAAU,iBAAiB,YAAY,IAAI;AACjD,wBAAY,SAAS,MAAM;EAAE;EAAK,OAAO,SAAS,SAAS;EAAQ;EAAS,CAAC;;AAG/E,SAAS,oBAA4B;AACnC,QAAO"}
1
+ {"version":3,"file":"init.cjs","names":["require","resolveExtendsRef","fetchBosConfigFromFastKv","saveBosConfig","loadManifestNormalizationSpec","normalizePackageManifestsInTree","writeSnapshot"],"sources":["../../src/cli/init.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { execa } from \"execa\";\nimport { glob } from \"glob\";\nimport type { OverrideSection } from \"../contract\";\nimport { fetchBosConfigFromFastKv } from \"../fastkv\";\nimport {\n loadManifestNormalizationSpec,\n normalizePackageManifestsInTree,\n} from \"../internal/manifest-normalizer\";\nimport { resolveExtendsRef } from \"../merge\";\nimport type { BosConfig, BosConfigInput } from \"../types\";\nimport { saveBosConfig } from \"../utils/save-config\";\nimport { writeSnapshot } from \"./snapshot\";\n\nconst require = createRequire(import.meta.url);\n\nexport const INIT_ROOT_PATTERNS = [\n \"bos.config.json\",\n \"package.json\",\n \".env.example\",\n \".gitignore\",\n \"biome.json\",\n \"bunfig.toml\",\n \"Dockerfile\",\n \"railway.json\",\n \"railway.toml\",\n \"AGENTS.md\",\n \".changeset/config.json\",\n \".changeset/README.md\",\n \"README.md\",\n \"CONTRIBUTING.md\",\n \".github/templates/**\",\n] as const;\n\nconst OVERRIDE_WORKSPACE_MAP: Record<OverrideSection, string[]> = {\n ui: [\"ui\"],\n api: [\"api\"],\n host: [\"host\"],\n plugins: [],\n};\n\ninterface SourceResult {\n sourceDir: string;\n parentConfig: BosConfig;\n cleanup: () => Promise<void>;\n}\n\nexport interface CatalogChainSource {\n catalog: Record<string, string>;\n repository?: string;\n extendsChain: string[];\n}\n\nfunction getExtendsRef(config: Record<string, unknown>): string | undefined {\n if (typeof config.extends === \"string\") {\n return config.extends;\n }\n\n if (config.extends && typeof config.extends === \"object\") {\n return resolveExtendsRef(config.extends as Record<string, string>, \"production\");\n }\n\n return undefined;\n}\n\nfunction parseBosRef(ref: string): { account: string; gateway: string } | null {\n const match = ref.match(/^bos:\\/\\/([^/]+)\\/(.+)$/);\n if (!match?.[1] || !match[2]) return null;\n return { account: match[1], gateway: match[2] };\n}\n\nfunction readWorkspaceCatalog(sourceDir: string): Record<string, string> {\n const pkgPath = join(sourceDir, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n\n const pkg = readJsonFile<{ workspaces?: { catalog?: Record<string, string> } }>(pkgPath);\n return { ...(pkg.workspaces?.catalog ?? {}) };\n}\n\nexport async function resolveCatalogChainSource(opts: {\n extendsAccount: string;\n extendsGateway: string;\n sourceDir?: string;\n}): Promise<CatalogChainSource> {\n const catalogs: Record<string, string>[] = [];\n const cleanups: Array<() => Promise<void>> = [];\n const extendsChain: string[] = [];\n const visited = new Set<string>();\n let repository: string | undefined;\n let currentRef = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n let sourceDir = opts.sourceDir ? resolve(opts.sourceDir) : undefined;\n let configPath = sourceDir ? join(sourceDir, \"bos.config.json\") : undefined;\n\n try {\n while (true) {\n if (visited.has(currentRef)) {\n throw new Error(`Circular extends detected while resolving catalog source: ${currentRef}`);\n }\n\n visited.add(currentRef);\n extendsChain.push(currentRef);\n\n let config: Record<string, unknown>;\n let currentSourceDir = sourceDir;\n let cleanup: () => Promise<void> = async () => {};\n\n if (configPath) {\n config = readJsonFile<Record<string, unknown>>(configPath);\n currentSourceDir = dirname(configPath);\n } else {\n const parsed = parseBosRef(currentRef);\n if (!parsed) {\n break;\n }\n const sourceResult = await resolveSourceDir({\n extendsAccount: parsed.account,\n extendsGateway: parsed.gateway,\n });\n config = sourceResult.parentConfig as Record<string, unknown>;\n currentSourceDir = sourceResult.sourceDir || undefined;\n cleanup = sourceResult.cleanup;\n }\n\n cleanups.push(cleanup);\n catalogs.push(currentSourceDir ? readWorkspaceCatalog(currentSourceDir) : {});\n\n if (typeof config.repository === \"string\") {\n repository = config.repository;\n }\n\n const nextExtendsRef = getExtendsRef(config);\n if (!nextExtendsRef) {\n break;\n }\n\n if (nextExtendsRef.startsWith(\"bos://\")) {\n currentRef = nextExtendsRef;\n sourceDir = undefined;\n configPath = undefined;\n continue;\n }\n\n if (!currentSourceDir) {\n break;\n }\n\n const nextConfigPath = resolve(currentSourceDir, nextExtendsRef);\n if (!existsSync(nextConfigPath)) {\n break;\n }\n\n currentRef = nextConfigPath;\n sourceDir = dirname(nextConfigPath);\n configPath = nextConfigPath;\n }\n } finally {\n for (const cleanup of cleanups.reverse()) {\n await cleanup();\n }\n }\n\n return {\n catalog: Object.assign({}, ...catalogs.reverse()),\n repository,\n extendsChain,\n };\n}\n\nexport async function resolveSourceDir(opts: {\n extendsAccount: string;\n extendsGateway: string;\n source?: string;\n}): Promise<SourceResult> {\n if (opts.source) {\n const sourceDir = resolve(opts.source);\n if (!existsSync(join(sourceDir, \"bos.config.json\"))) {\n throw new Error(`No bos.config.json found in source directory: ${sourceDir}`);\n }\n const parentConfig = JSON.parse(\n readFileSync(join(sourceDir, \"bos.config.json\"), \"utf-8\"),\n ) as BosConfig;\n return { sourceDir, parentConfig, cleanup: async () => {} };\n }\n\n const parentConfig = await fetchParentConfig(opts.extendsAccount, opts.extendsGateway);\n\n if (parentConfig.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(parentConfig.repository);\n return { sourceDir, parentConfig, cleanup };\n }\n\n const chainResult = await resolveRepositoryViaExtendsChain(\n opts.extendsAccount,\n opts.extendsGateway,\n );\n if (chainResult?.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(chainResult.repository);\n return { sourceDir, parentConfig: chainResult.config, cleanup };\n }\n\n return {\n sourceDir: \"\",\n parentConfig,\n cleanup: async () => {},\n };\n}\n\nexport function buildInitPatterns(overrides: OverrideSection[], plugins?: string[]): string[] {\n const has = (section: OverrideSection) => overrides.includes(section);\n const patterns: string[] = [...INIT_ROOT_PATTERNS];\n\n if (has(\"ui\")) patterns.push(\"ui/**\");\n if (has(\"api\")) patterns.push(\"api/**\");\n if (has(\"host\")) patterns.push(\"host/**\");\n if (has(\"plugins\")) {\n for (const plugin of plugins ?? []) {\n patterns.push(`plugins/${plugin}/**`);\n }\n }\n\n return patterns;\n}\n\nexport function sourcePathToDestinationPath(filePath: string): string {\n return filePath.startsWith(\".github/templates/\")\n ? filePath.replace(/^\\.github\\/templates\\//, \".github/\")\n : filePath;\n}\n\nexport async function fetchParentConfig(\n extendsAccount: string,\n extendsGateway: string,\n): Promise<BosConfig> {\n const bosUrl = `bos://${extendsAccount}/${extendsGateway}`;\n return fetchBosConfigFromFastKv<BosConfig>(bosUrl);\n}\n\nexport async function resolveRepositoryViaExtendsChain(\n extendsAccount: string,\n extendsGateway: string,\n visited = new Set<string>(),\n): Promise<{ repository: string; config: BosConfig } | null> {\n const key = `bos://${extendsAccount}/${extendsGateway}`;\n if (visited.has(key)) return null;\n visited.add(key);\n\n try {\n const config = await fetchParentConfig(extendsAccount, extendsGateway);\n if (config.repository) {\n return { repository: config.repository, config };\n }\n\n const extendsRef = getExtendsRef(config as Record<string, unknown>);\n if (extendsRef) {\n const normalized = extendsRef.startsWith(\"bos://\") ? extendsRef : `bos://${extendsRef}`;\n const parsed = parseBosRef(normalized);\n if (parsed) {\n const result = await resolveRepositoryViaExtendsChain(\n parsed.account,\n parsed.gateway,\n visited,\n );\n if (result) return result;\n }\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function detectGitRemoteUrl(directory: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd: directory,\n stdio: \"pipe\",\n });\n const url = stdout.trim();\n if (!url) return undefined;\n return normalizeGitUrl(url);\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeGitUrl(url: string): string | undefined {\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;\n }\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;\n }\n return url.endsWith(\".git\") ? url.slice(0, -4) : url;\n}\n\nexport async function downloadTarball(\n repoUrl: string,\n): Promise<{ dir: string; cleanup: () => Promise<void> }> {\n const parsed = parseGitHubUrl(repoUrl);\n if (!parsed) {\n throw new Error(`Cannot parse repository URL: ${repoUrl}`);\n }\n\n const { owner, repo } = parsed;\n let response: Response | null = null;\n\n for (const branch of [\"main\", \"master\"]) {\n const candidate = await fetch(\n `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`,\n {\n headers: { \"User-Agent\": \"everything-dev\" },\n redirect: \"follow\",\n },\n );\n if (candidate.ok) {\n response = candidate;\n break;\n }\n if (candidate.status !== 404) {\n throw new Error(\n `GitHub tarball download failed: ${candidate.status} ${candidate.statusText}`,\n );\n }\n }\n\n if (!response) {\n throw new Error(`GitHub tarball download failed for ${repoUrl}: tried main and master`);\n }\n\n if (!response.body) {\n throw new Error(\"GitHub tarball download returned empty body\");\n }\n\n const tmpDir = mkTmpDir(\"bos-init-tarball-\");\n const tarballPath = join(tmpDir, \"source.tar.gz\");\n\n const fileStream = createWriteStream(tarballPath);\n const reader = response.body as unknown as NodeJS.ReadableStream;\n await pipeline(reader, fileStream);\n\n const extractDir = mkTmpDir(\"bos-init-extract-\");\n try {\n const tar = require(\"tar\") as {\n extract: (opts: { cwd: string; file: string; strip: number }) => Promise<void>;\n };\n await tar.extract({ cwd: extractDir, file: tarballPath, strip: 1 });\n } catch {\n await execCommand(\"tar\", [\"-xzf\", tarballPath, \"--strip-components=1\", \"-C\", extractDir]);\n }\n\n rmSync(tmpDir, { recursive: true, force: true });\n\n return {\n dir: extractDir,\n cleanup: async () => {\n rmSync(extractDir, { recursive: true, force: true });\n },\n };\n}\n\nfunction parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return { owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return { owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n return null;\n}\n\nexport async function copyFilteredFiles(\n sourceDir: string,\n destination: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<number> {\n if (patterns.length === 0) {\n return 0;\n }\n\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n mkdirSync(destination, { recursive: true });\n\n let count = 0;\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n\n const destPath = sourcePathToDestinationPath(filePath);\n const dest = join(destination, destPath);\n mkdirSync(dirname(dest), { recursive: true });\n const content = readFileSync(src);\n writeFileSync(dest, content);\n count++;\n }\n\n return count;\n}\n\nfunction stripProductionFields(entry: Record<string, unknown>): void {\n delete entry.production;\n delete entry.integrity;\n delete entry.ssr;\n delete entry.ssrIntegrity;\n}\n\nfunction buildRootTypecheckScript(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): string {\n const commands = [\"bun run types:gen\"];\n\n if (sections.ui) {\n commands.push(\"if [ -d ui ]; then bun run --cwd ui typecheck; fi\");\n }\n if (sections.api) {\n commands.push(\"if [ -d api ]; then bun run --cwd api typecheck; fi\");\n }\n if (sections.host) {\n commands.push(\"if [ -d host ]; then bun run --cwd host typecheck; fi\");\n }\n if (sections.plugins) {\n commands.push(\n 'if [ -d plugins ]; then for dir in plugins/*; do if [ -f \"$dir/package.json\" ]; then bun run --cwd \"$dir\" typecheck; fi; done; fi',\n );\n }\n\n return commands.join(\" && \");\n}\n\nexport function buildChildRootScripts(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): Record<string, string> {\n const scripts: Record<string, string> = {\n dev: \"node_modules/.bin/bos dev\",\n \"dev:proxy\": \"node_modules/.bin/bos dev --proxy\",\n build: \"node_modules/.bin/bos build\",\n deploy: \"node_modules/.bin/bos build --deploy\",\n publish: \"node_modules/.bin/bos publish\",\n start: \"node_modules/.bin/bos start\",\n typecheck: buildRootTypecheckScript(sections),\n lint: \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n format: \"biome format --write .\",\n \"format:check\": \"biome format .\",\n changeset: \"changeset\",\n version: \"changeset version\",\n release: \"echo 'Packages versioned - app release handled by workflow'\",\n postinstall: \"node_modules/.bin/bos types gen || true\",\n \"types:gen\": \"node_modules/.bin/bos types gen\",\n bos: \"node_modules/.bin/bos\",\n };\n\n if (sections.api) {\n scripts[\"db:push\"] = \"bun run --cwd api drizzle-kit push\";\n scripts[\"db:studio\"] = \"bun run --cwd api drizzle-kit studio\";\n scripts[\"db:generate\"] = \"bun run --cwd api drizzle-kit generate\";\n scripts[\"db:migrate\"] = \"bun run --cwd api drizzle-kit migrate\";\n scripts[\"test:api\"] = \"cd api && bun run test tests/integration/ tests/unit/\";\n scripts[\"test:integration\"] = \"cd api && bun run test tests/integration/\";\n }\n\n if (sections.host) {\n scripts[\"test:e2e\"] = \"bun run --cwd host test:e2e\";\n }\n\n if (sections.api && sections.host) {\n scripts.test = \"bun run test:api && bun run test:e2e\";\n } else if (sections.api) {\n scripts.test = \"bun run test:api\";\n } else if (sections.host) {\n scripts.test = \"bun run test:e2e\";\n }\n\n if (sections.api || sections.host) {\n scripts[\"dev:postgres\"] = \"docker compose up -d --wait && bun run dev\";\n scripts[\"dev:postgres:down\"] = \"docker compose down\";\n scripts[\"dev:postgres:reset\"] = \"docker compose down -v && docker compose up -d --wait\";\n }\n\n if (sections.ui) {\n scripts[\"dev:ui\"] = \"node_modules/.bin/bos dev --ui local --api remote\";\n }\n if (sections.api) {\n scripts[\"dev:api\"] = \"node_modules/.bin/bos dev --ui remote --api local\";\n }\n\n return scripts;\n}\n\nexport async function personalizeConfig(\n destination: string,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n pluginRoutes?: Record<string, string[]>;\n workspaceOpts?: { localOverrides?: boolean; sourceDir?: string };\n mode?: \"init\" | \"sync\";\n existingConfig?: Record<string, unknown>;\n repository?: string;\n title?: string;\n description?: string;\n testnet?: string;\n staging?: unknown;\n },\n): Promise<void> {\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n const existingApp =\n opts.mode === \"sync\" && opts.existingConfig?.app && typeof opts.existingConfig.app === \"object\"\n ? (opts.existingConfig.app as Record<string, unknown>)\n : undefined;\n const preservedAuth = existingApp?.auth;\n\n const explicitRootKeys = new Set(\n Object.entries(opts)\n .filter(\n ([key, value]) =>\n value !== undefined &&\n ![\n \"extendsAccount\",\n \"extendsGateway\",\n \"plugins\",\n \"overrides\",\n \"pluginRoutes\",\n \"workspaceOpts\",\n \"mode\",\n \"existingConfig\",\n ].includes(key),\n )\n .map(([key]) => key),\n );\n\n const configPath = join(destination, \"bos.config.json\");\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>;\n\n config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n if (opts.account) {\n config.account = opts.account;\n }\n if (opts.domain) {\n config.domain = opts.domain;\n }\n if (opts.repository) {\n config.repository = opts.repository;\n } else {\n delete config.repository;\n }\n\n const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n for (const field of inheritableFields) {\n if (!(field in opts)) {\n delete config[field];\n }\n }\n\n if (config.app && typeof config.app === \"object\") {\n const app = config.app as Record<string, unknown>;\n\n for (const entryKey of Object.keys(app)) {\n if (\n !has(entryKey as OverrideSection) &&\n (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n ) {\n delete app[entryKey];\n continue;\n }\n if (entryKey === \"auth\") {\n delete app[entryKey];\n continue;\n }\n const entry = app[entryKey];\n if (entry && typeof entry === \"object\") {\n stripProductionFields(entry as Record<string, unknown>);\n }\n }\n\n if (preservedAuth !== undefined) {\n app.auth = preservedAuth;\n }\n\n if (Object.keys(app).length === 0) {\n delete config.app;\n }\n }\n\n if (has(\"plugins\")) {\n if (config.plugins && typeof config.plugins === \"object\") {\n const plugins = config.plugins as Record<string, unknown>;\n\n if (opts.plugins !== undefined) {\n for (const pluginKey of Object.keys(plugins)) {\n if (!opts.plugins.includes(pluginKey)) {\n delete plugins[pluginKey];\n }\n }\n }\n\n for (const pluginKey of Object.keys(plugins)) {\n const plugin = plugins[pluginKey];\n let pluginObj: Record<string, unknown>;\n\n if (typeof plugin === \"string\") {\n pluginObj = { extends: plugin };\n plugins[pluginKey] = pluginObj;\n } else if (plugin && typeof plugin === \"object\") {\n pluginObj = { ...(plugin as Record<string, unknown>) };\n plugins[pluginKey] = pluginObj;\n } else {\n continue;\n }\n\n stripProductionFields(pluginObj);\n }\n\n if (Object.keys(plugins).length === 0) {\n config.plugins = {};\n }\n }\n } else {\n config.plugins = {};\n }\n\n if (opts.mode === \"sync\" && opts.existingConfig) {\n const managedRootKeys = new Set([\"extends\", \"account\", \"domain\", \"app\", \"plugins\"]);\n const preservedRootKeys = new Set([\n ...managedRootKeys,\n ...Object.keys(opts.existingConfig),\n ...explicitRootKeys,\n ]);\n\n for (const key of Object.keys(config)) {\n if (!preservedRootKeys.has(key)) {\n delete config[key];\n }\n }\n\n for (const [key, value] of Object.entries(opts.existingConfig)) {\n if (!(key in config) && !managedRootKeys.has(key) && !explicitRootKeys.has(key)) {\n config[key] = value;\n }\n }\n }\n\n await saveBosConfig(destination, config);\n }\n\n const pkgPath = join(destination, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const childScripts = buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n });\n\n if (typeof pkg.name !== \"string\" || pkg.name.length === 0) {\n pkg.name = \"monorepo\";\n }\n pkg.private = true;\n pkg.type = \"module\";\n delete pkg.module;\n delete pkg.peerDependencies;\n\n if (pkg.workspaces && typeof pkg.workspaces === \"object\") {\n const ws = pkg.workspaces as { packages?: string[] };\n if (Array.isArray(ws.packages)) {\n ws.packages = ws.packages.filter((p: string) => {\n if (p.startsWith(\"packages/\")) return false;\n if (p === \"ui\") return has(\"ui\");\n if (p === \"api\") return has(\"api\");\n if (p === \"host\") return has(\"host\");\n if (p.startsWith(\"plugins/\")) return false;\n return true;\n });\n\n if (has(\"plugins\")) {\n if (!ws.packages.includes(\"plugins/*\")) {\n ws.packages.push(\"plugins/*\");\n }\n }\n }\n }\n\n if (!pkg.scripts || typeof pkg.scripts !== \"object\") {\n pkg.scripts = {};\n }\n const scripts = pkg.scripts as Record<string, string>;\n for (const [key, value] of Object.entries(childScripts)) {\n scripts[key] = value;\n }\n for (const obsoleteScript of [\n \"init\",\n \"sync-catalog\",\n \"db:push\",\n \"db:studio\",\n \"db:generate\",\n \"db:migrate\",\n \"test\",\n \"test:api\",\n \"test:integration\",\n \"test:e2e\",\n \"dev:postgres\",\n \"dev:postgres:down\",\n \"dev:postgres:reset\",\n \"dev:ui\",\n \"dev:api\",\n ]) {\n if (!(obsoleteScript in childScripts)) {\n delete scripts[obsoleteScript];\n }\n }\n\n if (pkg.devDependencies && typeof pkg.devDependencies === \"object\") {\n const deps = pkg.devDependencies as Record<string, string>;\n delete deps[\"every-plugin\"];\n delete deps[\"everything-dev\"];\n }\n\n if (!pkg.workspaces || typeof pkg.workspaces !== \"object\") {\n pkg.workspaces = { packages: [], catalog: {} };\n }\n const workspaces = pkg.workspaces as { packages?: string[]; catalog?: Record<string, string> };\n if (!workspaces.catalog || typeof workspaces.catalog !== \"object\") {\n workspaces.catalog = {};\n }\n\n if (!pkg.dependencies) pkg.dependencies = {};\n const deps = pkg.dependencies as Record<string, string>;\n const spec = opts.workspaceOpts?.sourceDir\n ? loadManifestNormalizationSpec(opts.workspaceOpts.sourceDir)\n : null;\n if (spec) {\n workspaces.catalog[\"everything-dev\"] = spec.rootCatalog[\"everything-dev\"];\n workspaces.catalog[\"every-plugin\"] = spec.rootCatalog[\"every-plugin\"];\n }\n const frameworkCatalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n sourceDir: opts.workspaceOpts?.sourceDir,\n })\n ).catalog;\n for (const [name, version] of Object.entries(frameworkCatalog)) {\n workspaces.catalog[name] = version;\n }\n if (!deps[\"everything-dev\"]) deps[\"everything-dev\"] = \"catalog:\";\n if (!deps[\"every-plugin\"]) deps[\"every-plugin\"] = \"catalog:\";\n\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n }\n\n const apiTsConfigPath = join(destination, \"api\", \"tsconfig.json\");\n if (existsSync(apiTsConfigPath)) {\n const apiTsConfig = JSON.parse(readFileSync(apiTsConfigPath, \"utf-8\")) as {\n files?: string[];\n [key: string]: unknown;\n };\n if (apiTsConfig.files) {\n const validFiles = apiTsConfig.files.filter((f) => existsSync(join(destination, \"api\", f)));\n if (validFiles.length !== apiTsConfig.files.length) {\n if (validFiles.length === 0) {\n delete apiTsConfig.files;\n } else {\n apiTsConfig.files = validFiles;\n }\n writeFileSync(apiTsConfigPath, `${JSON.stringify(apiTsConfig, null, 2)}\\n`);\n }\n }\n }\n\n await resolveWorkspaceRefs(destination, opts.workspaceOpts);\n\n if (has(\"ui\")) {\n const genContractPath = join(destination, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n if (!existsSync(genContractPath)) {\n mkdirSync(dirname(genContractPath), { recursive: true });\n writeFileSync(genContractPath, `export type ApiContract = Record<string, never>;\\n`);\n }\n }\n\n if (has(\"api\")) {\n const pluginsClientGenPath = join(destination, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n if (!existsSync(pluginsClientGenPath)) {\n mkdirSync(dirname(pluginsClientGenPath), { recursive: true });\n writeFileSync(\n pluginsClientGenPath,\n `import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";\\ntype ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\\nexport type PluginsClient = Record<string, never>;\\n`,\n );\n }\n }\n\n const authTypesPaths: string[] = [];\n if (has(\"ui\")) {\n authTypesPaths.push(join(destination, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"api\")) {\n authTypesPaths.push(join(destination, \"api\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"host\") && existsSync(join(destination, \"host\", \"src\"))) {\n authTypesPaths.push(join(destination, \"host\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n for (const authTypesGenPath of authTypesPaths) {\n if (!existsSync(authTypesGenPath)) {\n mkdirSync(dirname(authTypesGenPath), { recursive: true });\n writeFileSync(authTypesGenPath, generateAuthTypesContent(authTypesGenPath, destination));\n }\n }\n\n if (authTypesPaths.length > 0) {\n const authDir = join(destination, \".bos\", \"generated\", \"auth\");\n if (!existsSync(authDir)) {\n mkdirSync(authDir, { recursive: true });\n }\n const authExportStubPath = join(authDir, \"auth-export.d.ts\");\n if (!existsSync(authExportStubPath)) {\n writeFileSync(\n authExportStubPath,\n `export type Auth = any;\nexport type AuthOrganizationContext = any;\nexport type AuthOrganization = any;\nexport type AuthOrganizationSummary = any;\nexport type AuthOrganizationMember = any;\nexport type AuthApiKey = any;\nexport type AuthInvitation = any;\nexport type GetActiveMemberInput = any;\nexport type GetOrganizationInput = any;\nexport type ListMembersInput = any;\nexport type ListInvitationsInput = any;\nexport type ListApiKeysInput = any;\nexport type AuthServices = any;\nexport type createAuthInstance = any;\n`,\n );\n }\n const contractStubPath = join(authDir, \"contract.d.ts\");\n if (!existsSync(contractStubPath)) {\n writeFileSync(\n contractStubPath,\n `export type ContractType = any;\nexport type InferOutput<_TRoute extends string> = any;\n`,\n );\n }\n }\n\n if (has(\"plugins\")) {\n for (const plugin of opts.plugins ?? []) {\n const pluginSrcDir = join(destination, \"plugins\", plugin, \"src\");\n const pluginIndexPath = join(pluginSrcDir, \"index.ts\");\n const pluginClientGenPath = join(pluginSrcDir, \"plugins-client.gen.ts\");\n if (!existsSync(pluginIndexPath) || existsSync(pluginClientGenPath)) {\n continue;\n }\n const pluginIndex = readFileSync(pluginIndexPath, \"utf-8\");\n if (!pluginIndex.includes(\"./plugins-client.gen\")) {\n continue;\n }\n writeFileSync(pluginClientGenPath, \"export type PluginsClient = Record<string, never>;\\n\");\n }\n }\n}\n\nfunction generateAuthTypesContent(targetPath: string, configDir: string): string {\n const authExportRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"auth-export.d.ts\"),\n targetPath,\n );\n const contractRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"contract.d.ts\"),\n targetPath,\n );\n\n return `export type {\n Auth,\n AuthOrganizationContext,\n AuthOrganization,\n AuthOrganizationSummary,\n AuthOrganizationMember,\n AuthApiKey,\n AuthInvitation,\n GetActiveMemberInput,\n GetOrganizationInput,\n ListMembersInput,\n ListInvitationsInput,\n ListApiKeysInput,\n AuthServices,\n createAuthInstance,\n} from \"${authExportRel}\";\nimport type { InferOutput, ContractType as AuthContract } from \"${contractRel}\";\nimport type { Auth as BaseAuth } from \"${authExportRel}\";\n\ntype RawAuthSession = InferOutput<\"getSession\">;\ntype RawAuthRequestContext = InferOutput<\"getContext\">;\ntype RawAuthActiveMember = InferOutput<\"getActiveMember\">;\n\nexport type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {\n role?: string | null;\n isAnonymous?: boolean | null;\n walletAddress?: string | null;\n banned?: boolean | null;\n};\nexport type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {\n activeOrganizationId?: string | null;\n};\nexport type AuthSession = {\n user: AuthSessionUser | null;\n session: AuthSessionData | null;\n};\nexport type AuthRequestContext = RawAuthRequestContext & {\n organization?: { activeOrganizationId?: string | null } | null;\n apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;\n};\nexport type AuthActiveMember = RawAuthActiveMember;\nexport type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];\nexport type AuthContractType = AuthContract;\n`;\n}\n\nfunction toRelativeImportPath(fromPath: string, toPath: string): string {\n const rel = relative(dirname(toPath), fromPath);\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport async function runBunInstall(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--ignore-scripts\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runBunInstallForUpgrade(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--force\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runTypesGen(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n const localBosBin = join(destination, \"node_modules\", \".bin\", \"bos\");\n if (existsSync(localBosBin)) {\n await runWithProgress(\n \"node_modules/.bin/bos\",\n [\"types\", \"gen\"],\n destination,\n spinner,\n \"Generating types\",\n );\n return;\n }\n\n throw new Error(\"Unable to locate bos CLI for types generation\");\n}\n\nexport async function runDockerComposeUp(destination: string): Promise<void> {\n await execCommand(\"docker\", [\"compose\", \"up\", \"-d\", \"--wait\"], destination, { stdio: \"inherit\" });\n}\n\nasync function runWithProgress(\n command: string,\n args: string[],\n cwd: string,\n spinner: { message: (msg: string) => void } | undefined,\n label: string,\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n const child = execa(command, args, { cwd, stdio: \"inherit\", timeout });\n\n if (spinner) {\n const start = Date.now();\n const interval = setInterval(() => {\n const elapsed = Math.round((Date.now() - start) / 1000);\n spinner.message(`${label}... (${elapsed}s)`);\n }, 2000);\n try {\n await child;\n } finally {\n clearInterval(interval);\n }\n } else {\n await child;\n }\n}\n\nexport function stripOrphanedWorkspacesFromLockfile(\n lockfilePath: string,\n allowedWorkspaces: string[],\n): void {\n if (!existsSync(lockfilePath)) return;\n\n const content = readFileSync(lockfilePath, \"utf-8\");\n let lockfile: Record<string, unknown>;\n try {\n lockfile = JSON.parse(content) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const workspaces = lockfile.workspaces;\n if (!workspaces || typeof workspaces !== \"object\") return;\n\n const workspaceMap = workspaces as Record<string, unknown>;\n const allowed = new Set([\"\", ...allowedWorkspaces]);\n\n const keys = Object.keys(workspaceMap);\n let changed = false;\n for (const key of keys) {\n if (allowed.has(key)) continue;\n if (\n allowedWorkspaces.some(\n (pattern) => pattern.endsWith(\"/*\") && key.startsWith(pattern.slice(0, -1)),\n )\n )\n continue;\n delete workspaceMap[key];\n changed = true;\n }\n\n if (changed) {\n writeFileSync(lockfilePath, `${JSON.stringify(lockfile, null, 2)}\\n`);\n }\n}\n\nexport function removeInitLockfile(lockfilePath: string): void {\n if (!existsSync(lockfilePath)) return;\n rmSync(lockfilePath, { force: true });\n}\n\nfunction readJsonFile<T>(filePath: string): T {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n}\n\nexport async function scaffoldMinimalProject(\n destination: string,\n parentConfig: BosConfigInput,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n repository?: string;\n title?: string;\n description?: string;\n },\n): Promise<number> {\n mkdirSync(destination, { recursive: true });\n\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n\n const config: Record<string, unknown> = {\n extends: `bos://${opts.extendsAccount}/${opts.extendsGateway}`,\n account: opts.account || opts.extendsAccount,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.repository ? { repository: opts.repository } : {}),\n ...(opts.title ? { title: opts.title } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n };\n\n if (parentConfig.app && typeof parentConfig.app === \"object\") {\n const app: Record<string, unknown> = {};\n const parentApp = parentConfig.app as Record<string, Record<string, unknown>>;\n\n if (has(\"host\") && parentApp.host) {\n app.host = { ...parentApp.host };\n stripProductionFields(app.host as Record<string, unknown>);\n }\n\n if (has(\"ui\") && parentApp.ui) {\n app.ui = { ...parentApp.ui };\n stripProductionFields(app.ui as Record<string, unknown>);\n }\n\n if (has(\"api\") && parentApp.api) {\n app.api = { ...parentApp.api };\n stripProductionFields(app.api as Record<string, unknown>);\n }\n\n if (Object.keys(app).length > 0) {\n config.app = app;\n }\n }\n\n if (has(\"plugins\") && opts.plugins && opts.plugins.length > 0 && parentConfig.plugins) {\n const plugins: Record<string, unknown> = {};\n for (const key of opts.plugins) {\n const parentPlugin = (parentConfig.plugins as Record<string, unknown>)?.[key];\n if (parentPlugin) {\n if (typeof parentPlugin === \"string\") {\n plugins[key] = { extends: parentPlugin };\n } else {\n const pluginCopy = { ...(parentPlugin as Record<string, unknown>) };\n stripProductionFields(pluginCopy);\n plugins[key] = pluginCopy;\n }\n }\n }\n config.plugins = plugins;\n } else if (has(\"plugins\")) {\n config.plugins = {};\n }\n\n await saveBosConfig(destination, config);\n\n const workspacePackages: string[] = [];\n for (const section of opts.overrides) {\n workspacePackages.push(...OVERRIDE_WORKSPACE_MAP[section]);\n }\n if (has(\"plugins\")) {\n workspacePackages.push(\"plugins/*\");\n }\n\n const catalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n })\n ).catalog;\n\n const pkg: Record<string, unknown> = {\n name: \"monorepo\",\n private: true,\n type: \"module\",\n scripts: buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n }),\n dependencies: {\n \"everything-dev\": \"catalog:\",\n \"every-plugin\": \"catalog:\",\n },\n devDependencies: {},\n workspaces: {\n packages: workspacePackages,\n catalog,\n },\n };\n writeFileSync(join(destination, \"package.json\"), `${JSON.stringify(pkg, null, 2)}\\n`);\n\n writeFileSync(join(destination, \".gitignore\"), generateGitignore());\n\n return 4;\n}\n\nasync function resolveWorkspaceRefs(\n destination: string,\n options?: { localOverrides?: boolean; sourceDir?: string },\n): Promise<void> {\n await normalizePackageManifestsInTree({\n sourceRootDir: options?.sourceDir ?? destination,\n targetDir: destination,\n resolveCatalogRefs: false,\n preserveCatalogRefs: true,\n removeWorkspaceDeps: [\"host\"],\n });\n}\n\nexport async function writeInitSnapshot(\n destination: string,\n extendsAccount: string,\n extendsGateway: string,\n sourceDir: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<void> {\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n const fileHashes: Record<string, string> = {};\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n const content = readFileSync(src);\n const destPath = sourcePathToDestinationPath(filePath);\n fileHashes[destPath] = computeHash(content);\n }\n\n await writeSnapshot(destination, {\n parentRef: `bos://${extendsAccount}/${extendsGateway}`,\n files: fileHashes,\n });\n}\n\nfunction computeHash(data: Uint8Array): string {\n return createHash(\"sha256\").update(data).digest(\"hex\").substring(0, 16);\n}\n\nfunction mkTmpDir(prefix: string): string {\n return mkdtempSync(join(tmpdir(), `${prefix}-`));\n}\n\nexport async function generateDatabaseMigrations(destination: string): Promise<void> {\n const drizzleConfigs = await glob(\"**/drizzle.config.ts\", {\n cwd: destination,\n nodir: true,\n dot: false,\n absolute: false,\n ignore: [\"**/node_modules/**\"],\n });\n\n for (const configPath of drizzleConfigs) {\n const workspaceDir = dirname(configPath);\n const pkgPath = join(destination, workspaceDir, \"package.json\");\n if (!existsSync(pkgPath)) continue;\n\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const scripts = pkg.scripts as Record<string, string> | undefined;\n if (!scripts?.[\"db:generate\"]) continue;\n\n const cwd = join(destination, workspaceDir);\n await execCommand(\"bun\", [\"run\", \"db:generate\"], cwd);\n }\n}\n\nconst COMMAND_TIMEOUTS: Record<string, number> = {\n bun: 5 * 60_000,\n docker: 5 * 60_000,\n node_modules: 2 * 60_000,\n tar: 60_000,\n};\n\nexport async function execCommand(\n command: string,\n args: string[],\n cwd?: string,\n options?: { stdio?: \"pipe\" | \"inherit\" },\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n await execa(command, args, { cwd, stdio: options?.stdio ?? \"pipe\", timeout });\n}\n\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C,OAAO,cAAc,sBAD9B,aAAa,aACsB,CAAC;;;AAIzD,MAAM,mBAA2C;CAC/C,KAAK,IAAI;CACT,QAAQ,IAAI;CACZ,cAAc,IAAI;CAClB,KAAK;CACN;AAED,eAAsB,YACpB,SACA,MACA,KACA,SACe;CACf,MAAM,UAAU,iBAAiB,YAAY,IAAI;AACjD,wBAAY,SAAS,MAAM;EAAE;EAAK,OAAO,SAAS,SAAS;EAAQ;EAAS,CAAC;;AAG/E,SAAS,oBAA4B;AACnC,QAAO"}
package/dist/cli/init.mjs CHANGED
@@ -320,7 +320,7 @@ function buildRootTypecheckScript(sections) {
320
320
  }
321
321
  function buildChildRootScripts(sections) {
322
322
  const scripts = {
323
- dev: "node_modules/.bin/bos dev --host remote",
323
+ dev: "node_modules/.bin/bos dev",
324
324
  "dev:proxy": "node_modules/.bin/bos dev --proxy",
325
325
  build: "node_modules/.bin/bos build",
326
326
  deploy: "node_modules/.bin/bos build --deploy",
@@ -862,6 +862,7 @@ function generateGitignore() {
862
862
  dist/
863
863
  .env
864
864
  .bos/
865
+ docker-compose.yml
865
866
  *.gen.ts
866
867
  *.gen.tsx
867
868
  `;
@@ -1 +1 @@
1
- {"version":3,"file":"init.mjs","names":[],"sources":["../../src/cli/init.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { execa } from \"execa\";\nimport { glob } from \"glob\";\nimport type { OverrideSection } from \"../contract\";\nimport { fetchBosConfigFromFastKv } from \"../fastkv\";\nimport {\n loadManifestNormalizationSpec,\n normalizePackageManifestsInTree,\n} from \"../internal/manifest-normalizer\";\nimport { resolveExtendsRef } from \"../merge\";\nimport type { BosConfig, BosConfigInput } from \"../types\";\nimport { saveBosConfig } from \"../utils/save-config\";\nimport { writeSnapshot } from \"./snapshot\";\n\nconst require = createRequire(import.meta.url);\n\nexport const INIT_ROOT_PATTERNS = [\n \"bos.config.json\",\n \"package.json\",\n \".env.example\",\n \".gitignore\",\n \"biome.json\",\n \"bunfig.toml\",\n \"Dockerfile\",\n \"railway.json\",\n \"railway.toml\",\n \"AGENTS.md\",\n \".changeset/config.json\",\n \".changeset/README.md\",\n \"README.md\",\n \"CONTRIBUTING.md\",\n \".github/templates/**\",\n] as const;\n\nconst OVERRIDE_WORKSPACE_MAP: Record<OverrideSection, string[]> = {\n ui: [\"ui\"],\n api: [\"api\"],\n host: [\"host\"],\n plugins: [],\n};\n\ninterface SourceResult {\n sourceDir: string;\n parentConfig: BosConfig;\n cleanup: () => Promise<void>;\n}\n\nexport interface CatalogChainSource {\n catalog: Record<string, string>;\n repository?: string;\n extendsChain: string[];\n}\n\nfunction getExtendsRef(config: Record<string, unknown>): string | undefined {\n if (typeof config.extends === \"string\") {\n return config.extends;\n }\n\n if (config.extends && typeof config.extends === \"object\") {\n return resolveExtendsRef(config.extends as Record<string, string>, \"production\");\n }\n\n return undefined;\n}\n\nfunction parseBosRef(ref: string): { account: string; gateway: string } | null {\n const match = ref.match(/^bos:\\/\\/([^/]+)\\/(.+)$/);\n if (!match?.[1] || !match[2]) return null;\n return { account: match[1], gateway: match[2] };\n}\n\nfunction readWorkspaceCatalog(sourceDir: string): Record<string, string> {\n const pkgPath = join(sourceDir, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n\n const pkg = readJsonFile<{ workspaces?: { catalog?: Record<string, string> } }>(pkgPath);\n return { ...(pkg.workspaces?.catalog ?? {}) };\n}\n\nexport async function resolveCatalogChainSource(opts: {\n extendsAccount: string;\n extendsGateway: string;\n sourceDir?: string;\n}): Promise<CatalogChainSource> {\n const catalogs: Record<string, string>[] = [];\n const cleanups: Array<() => Promise<void>> = [];\n const extendsChain: string[] = [];\n const visited = new Set<string>();\n let repository: string | undefined;\n let currentRef = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n let sourceDir = opts.sourceDir ? resolve(opts.sourceDir) : undefined;\n let configPath = sourceDir ? join(sourceDir, \"bos.config.json\") : undefined;\n\n try {\n while (true) {\n if (visited.has(currentRef)) {\n throw new Error(`Circular extends detected while resolving catalog source: ${currentRef}`);\n }\n\n visited.add(currentRef);\n extendsChain.push(currentRef);\n\n let config: Record<string, unknown>;\n let currentSourceDir = sourceDir;\n let cleanup: () => Promise<void> = async () => {};\n\n if (configPath) {\n config = readJsonFile<Record<string, unknown>>(configPath);\n currentSourceDir = dirname(configPath);\n } else {\n const parsed = parseBosRef(currentRef);\n if (!parsed) {\n break;\n }\n const sourceResult = await resolveSourceDir({\n extendsAccount: parsed.account,\n extendsGateway: parsed.gateway,\n });\n config = sourceResult.parentConfig as Record<string, unknown>;\n currentSourceDir = sourceResult.sourceDir || undefined;\n cleanup = sourceResult.cleanup;\n }\n\n cleanups.push(cleanup);\n catalogs.push(currentSourceDir ? readWorkspaceCatalog(currentSourceDir) : {});\n\n if (typeof config.repository === \"string\") {\n repository = config.repository;\n }\n\n const nextExtendsRef = getExtendsRef(config);\n if (!nextExtendsRef) {\n break;\n }\n\n if (nextExtendsRef.startsWith(\"bos://\")) {\n currentRef = nextExtendsRef;\n sourceDir = undefined;\n configPath = undefined;\n continue;\n }\n\n if (!currentSourceDir) {\n break;\n }\n\n const nextConfigPath = resolve(currentSourceDir, nextExtendsRef);\n if (!existsSync(nextConfigPath)) {\n break;\n }\n\n currentRef = nextConfigPath;\n sourceDir = dirname(nextConfigPath);\n configPath = nextConfigPath;\n }\n } finally {\n for (const cleanup of cleanups.reverse()) {\n await cleanup();\n }\n }\n\n return {\n catalog: Object.assign({}, ...catalogs.reverse()),\n repository,\n extendsChain,\n };\n}\n\nexport async function resolveSourceDir(opts: {\n extendsAccount: string;\n extendsGateway: string;\n source?: string;\n}): Promise<SourceResult> {\n if (opts.source) {\n const sourceDir = resolve(opts.source);\n if (!existsSync(join(sourceDir, \"bos.config.json\"))) {\n throw new Error(`No bos.config.json found in source directory: ${sourceDir}`);\n }\n const parentConfig = JSON.parse(\n readFileSync(join(sourceDir, \"bos.config.json\"), \"utf-8\"),\n ) as BosConfig;\n return { sourceDir, parentConfig, cleanup: async () => {} };\n }\n\n const parentConfig = await fetchParentConfig(opts.extendsAccount, opts.extendsGateway);\n\n if (parentConfig.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(parentConfig.repository);\n return { sourceDir, parentConfig, cleanup };\n }\n\n const chainResult = await resolveRepositoryViaExtendsChain(\n opts.extendsAccount,\n opts.extendsGateway,\n );\n if (chainResult?.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(chainResult.repository);\n return { sourceDir, parentConfig: chainResult.config, cleanup };\n }\n\n return {\n sourceDir: \"\",\n parentConfig,\n cleanup: async () => {},\n };\n}\n\nexport function buildInitPatterns(overrides: OverrideSection[], plugins?: string[]): string[] {\n const has = (section: OverrideSection) => overrides.includes(section);\n const patterns: string[] = [...INIT_ROOT_PATTERNS];\n\n if (has(\"ui\")) patterns.push(\"ui/**\");\n if (has(\"api\")) patterns.push(\"api/**\");\n if (has(\"host\")) patterns.push(\"host/**\");\n if (has(\"plugins\")) {\n for (const plugin of plugins ?? []) {\n patterns.push(`plugins/${plugin}/**`);\n }\n }\n\n return patterns;\n}\n\nexport function sourcePathToDestinationPath(filePath: string): string {\n return filePath.startsWith(\".github/templates/\")\n ? filePath.replace(/^\\.github\\/templates\\//, \".github/\")\n : filePath;\n}\n\nexport async function fetchParentConfig(\n extendsAccount: string,\n extendsGateway: string,\n): Promise<BosConfig> {\n const bosUrl = `bos://${extendsAccount}/${extendsGateway}`;\n return fetchBosConfigFromFastKv<BosConfig>(bosUrl);\n}\n\nexport async function resolveRepositoryViaExtendsChain(\n extendsAccount: string,\n extendsGateway: string,\n visited = new Set<string>(),\n): Promise<{ repository: string; config: BosConfig } | null> {\n const key = `bos://${extendsAccount}/${extendsGateway}`;\n if (visited.has(key)) return null;\n visited.add(key);\n\n try {\n const config = await fetchParentConfig(extendsAccount, extendsGateway);\n if (config.repository) {\n return { repository: config.repository, config };\n }\n\n const extendsRef = getExtendsRef(config as Record<string, unknown>);\n if (extendsRef) {\n const normalized = extendsRef.startsWith(\"bos://\") ? extendsRef : `bos://${extendsRef}`;\n const parsed = parseBosRef(normalized);\n if (parsed) {\n const result = await resolveRepositoryViaExtendsChain(\n parsed.account,\n parsed.gateway,\n visited,\n );\n if (result) return result;\n }\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function detectGitRemoteUrl(directory: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd: directory,\n stdio: \"pipe\",\n });\n const url = stdout.trim();\n if (!url) return undefined;\n return normalizeGitUrl(url);\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeGitUrl(url: string): string | undefined {\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;\n }\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;\n }\n return url.endsWith(\".git\") ? url.slice(0, -4) : url;\n}\n\nexport async function downloadTarball(\n repoUrl: string,\n): Promise<{ dir: string; cleanup: () => Promise<void> }> {\n const parsed = parseGitHubUrl(repoUrl);\n if (!parsed) {\n throw new Error(`Cannot parse repository URL: ${repoUrl}`);\n }\n\n const { owner, repo } = parsed;\n let response: Response | null = null;\n\n for (const branch of [\"main\", \"master\"]) {\n const candidate = await fetch(\n `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`,\n {\n headers: { \"User-Agent\": \"everything-dev\" },\n redirect: \"follow\",\n },\n );\n if (candidate.ok) {\n response = candidate;\n break;\n }\n if (candidate.status !== 404) {\n throw new Error(\n `GitHub tarball download failed: ${candidate.status} ${candidate.statusText}`,\n );\n }\n }\n\n if (!response) {\n throw new Error(`GitHub tarball download failed for ${repoUrl}: tried main and master`);\n }\n\n if (!response.body) {\n throw new Error(\"GitHub tarball download returned empty body\");\n }\n\n const tmpDir = mkTmpDir(\"bos-init-tarball-\");\n const tarballPath = join(tmpDir, \"source.tar.gz\");\n\n const fileStream = createWriteStream(tarballPath);\n const reader = response.body as unknown as NodeJS.ReadableStream;\n await pipeline(reader, fileStream);\n\n const extractDir = mkTmpDir(\"bos-init-extract-\");\n try {\n const tar = require(\"tar\") as {\n extract: (opts: { cwd: string; file: string; strip: number }) => Promise<void>;\n };\n await tar.extract({ cwd: extractDir, file: tarballPath, strip: 1 });\n } catch {\n await execCommand(\"tar\", [\"-xzf\", tarballPath, \"--strip-components=1\", \"-C\", extractDir]);\n }\n\n rmSync(tmpDir, { recursive: true, force: true });\n\n return {\n dir: extractDir,\n cleanup: async () => {\n rmSync(extractDir, { recursive: true, force: true });\n },\n };\n}\n\nfunction parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return { owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return { owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n return null;\n}\n\nexport async function copyFilteredFiles(\n sourceDir: string,\n destination: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<number> {\n if (patterns.length === 0) {\n return 0;\n }\n\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n mkdirSync(destination, { recursive: true });\n\n let count = 0;\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n\n const destPath = sourcePathToDestinationPath(filePath);\n const dest = join(destination, destPath);\n mkdirSync(dirname(dest), { recursive: true });\n const content = readFileSync(src);\n writeFileSync(dest, content);\n count++;\n }\n\n return count;\n}\n\nfunction stripProductionFields(entry: Record<string, unknown>): void {\n delete entry.production;\n delete entry.integrity;\n delete entry.ssr;\n delete entry.ssrIntegrity;\n}\n\nfunction buildRootTypecheckScript(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): string {\n const commands = [\"bun run types:gen\"];\n\n if (sections.ui) {\n commands.push(\"if [ -d ui ]; then bun run --cwd ui typecheck; fi\");\n }\n if (sections.api) {\n commands.push(\"if [ -d api ]; then bun run --cwd api typecheck; fi\");\n }\n if (sections.host) {\n commands.push(\"if [ -d host ]; then bun run --cwd host typecheck; fi\");\n }\n if (sections.plugins) {\n commands.push(\n 'if [ -d plugins ]; then for dir in plugins/*; do if [ -f \"$dir/package.json\" ]; then bun run --cwd \"$dir\" typecheck; fi; done; fi',\n );\n }\n\n return commands.join(\" && \");\n}\n\nexport function buildChildRootScripts(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): Record<string, string> {\n const scripts: Record<string, string> = {\n dev: \"node_modules/.bin/bos dev --host remote\",\n \"dev:proxy\": \"node_modules/.bin/bos dev --proxy\",\n build: \"node_modules/.bin/bos build\",\n deploy: \"node_modules/.bin/bos build --deploy\",\n publish: \"node_modules/.bin/bos publish\",\n start: \"node_modules/.bin/bos start\",\n typecheck: buildRootTypecheckScript(sections),\n lint: \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n format: \"biome format --write .\",\n \"format:check\": \"biome format .\",\n changeset: \"changeset\",\n version: \"changeset version\",\n release: \"echo 'Packages versioned - app release handled by workflow'\",\n postinstall: \"node_modules/.bin/bos types gen || true\",\n \"types:gen\": \"node_modules/.bin/bos types gen\",\n bos: \"node_modules/.bin/bos\",\n };\n\n if (sections.api) {\n scripts[\"db:push\"] = \"bun run --cwd api drizzle-kit push\";\n scripts[\"db:studio\"] = \"bun run --cwd api drizzle-kit studio\";\n scripts[\"db:generate\"] = \"bun run --cwd api drizzle-kit generate\";\n scripts[\"db:migrate\"] = \"bun run --cwd api drizzle-kit migrate\";\n scripts[\"test:api\"] = \"cd api && bun run test tests/integration/ tests/unit/\";\n scripts[\"test:integration\"] = \"cd api && bun run test tests/integration/\";\n }\n\n if (sections.host) {\n scripts[\"test:e2e\"] = \"bun run --cwd host test:e2e\";\n }\n\n if (sections.api && sections.host) {\n scripts.test = \"bun run test:api && bun run test:e2e\";\n } else if (sections.api) {\n scripts.test = \"bun run test:api\";\n } else if (sections.host) {\n scripts.test = \"bun run test:e2e\";\n }\n\n if (sections.api || sections.host) {\n scripts[\"dev:postgres\"] = \"docker compose up -d --wait && bun run dev\";\n scripts[\"dev:postgres:down\"] = \"docker compose down\";\n scripts[\"dev:postgres:reset\"] = \"docker compose down -v && docker compose up -d --wait\";\n }\n\n if (sections.ui) {\n scripts[\"dev:ui\"] = \"node_modules/.bin/bos dev --ui local --api remote\";\n }\n if (sections.api) {\n scripts[\"dev:api\"] = \"node_modules/.bin/bos dev --ui remote --api local\";\n }\n\n return scripts;\n}\n\nexport async function personalizeConfig(\n destination: string,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n pluginRoutes?: Record<string, string[]>;\n workspaceOpts?: { localOverrides?: boolean; sourceDir?: string };\n mode?: \"init\" | \"sync\";\n existingConfig?: Record<string, unknown>;\n repository?: string;\n title?: string;\n description?: string;\n testnet?: string;\n staging?: unknown;\n },\n): Promise<void> {\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n const existingApp =\n opts.mode === \"sync\" && opts.existingConfig?.app && typeof opts.existingConfig.app === \"object\"\n ? (opts.existingConfig.app as Record<string, unknown>)\n : undefined;\n const preservedAuth = existingApp?.auth;\n\n const explicitRootKeys = new Set(\n Object.entries(opts)\n .filter(\n ([key, value]) =>\n value !== undefined &&\n ![\n \"extendsAccount\",\n \"extendsGateway\",\n \"plugins\",\n \"overrides\",\n \"pluginRoutes\",\n \"workspaceOpts\",\n \"mode\",\n \"existingConfig\",\n ].includes(key),\n )\n .map(([key]) => key),\n );\n\n const configPath = join(destination, \"bos.config.json\");\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>;\n\n config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n if (opts.account) {\n config.account = opts.account;\n }\n if (opts.domain) {\n config.domain = opts.domain;\n }\n if (opts.repository) {\n config.repository = opts.repository;\n } else {\n delete config.repository;\n }\n\n const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n for (const field of inheritableFields) {\n if (!(field in opts)) {\n delete config[field];\n }\n }\n\n if (config.app && typeof config.app === \"object\") {\n const app = config.app as Record<string, unknown>;\n\n for (const entryKey of Object.keys(app)) {\n if (\n !has(entryKey as OverrideSection) &&\n (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n ) {\n delete app[entryKey];\n continue;\n }\n if (entryKey === \"auth\") {\n delete app[entryKey];\n continue;\n }\n const entry = app[entryKey];\n if (entry && typeof entry === \"object\") {\n stripProductionFields(entry as Record<string, unknown>);\n }\n }\n\n if (preservedAuth !== undefined) {\n app.auth = preservedAuth;\n }\n\n if (Object.keys(app).length === 0) {\n delete config.app;\n }\n }\n\n if (has(\"plugins\")) {\n if (config.plugins && typeof config.plugins === \"object\") {\n const plugins = config.plugins as Record<string, unknown>;\n\n if (opts.plugins !== undefined) {\n for (const pluginKey of Object.keys(plugins)) {\n if (!opts.plugins.includes(pluginKey)) {\n delete plugins[pluginKey];\n }\n }\n }\n\n for (const pluginKey of Object.keys(plugins)) {\n const plugin = plugins[pluginKey];\n let pluginObj: Record<string, unknown>;\n\n if (typeof plugin === \"string\") {\n pluginObj = { extends: plugin };\n plugins[pluginKey] = pluginObj;\n } else if (plugin && typeof plugin === \"object\") {\n pluginObj = { ...(plugin as Record<string, unknown>) };\n plugins[pluginKey] = pluginObj;\n } else {\n continue;\n }\n\n stripProductionFields(pluginObj);\n }\n\n if (Object.keys(plugins).length === 0) {\n config.plugins = {};\n }\n }\n } else {\n config.plugins = {};\n }\n\n if (opts.mode === \"sync\" && opts.existingConfig) {\n const managedRootKeys = new Set([\"extends\", \"account\", \"domain\", \"app\", \"plugins\"]);\n const preservedRootKeys = new Set([\n ...managedRootKeys,\n ...Object.keys(opts.existingConfig),\n ...explicitRootKeys,\n ]);\n\n for (const key of Object.keys(config)) {\n if (!preservedRootKeys.has(key)) {\n delete config[key];\n }\n }\n\n for (const [key, value] of Object.entries(opts.existingConfig)) {\n if (!(key in config) && !managedRootKeys.has(key) && !explicitRootKeys.has(key)) {\n config[key] = value;\n }\n }\n }\n\n await saveBosConfig(destination, config);\n }\n\n const pkgPath = join(destination, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const childScripts = buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n });\n\n if (typeof pkg.name !== \"string\" || pkg.name.length === 0) {\n pkg.name = \"monorepo\";\n }\n pkg.private = true;\n pkg.type = \"module\";\n delete pkg.module;\n delete pkg.peerDependencies;\n\n if (pkg.workspaces && typeof pkg.workspaces === \"object\") {\n const ws = pkg.workspaces as { packages?: string[] };\n if (Array.isArray(ws.packages)) {\n ws.packages = ws.packages.filter((p: string) => {\n if (p.startsWith(\"packages/\")) return false;\n if (p === \"ui\") return has(\"ui\");\n if (p === \"api\") return has(\"api\");\n if (p === \"host\") return has(\"host\");\n if (p.startsWith(\"plugins/\")) return false;\n return true;\n });\n\n if (has(\"plugins\")) {\n if (!ws.packages.includes(\"plugins/*\")) {\n ws.packages.push(\"plugins/*\");\n }\n }\n }\n }\n\n if (!pkg.scripts || typeof pkg.scripts !== \"object\") {\n pkg.scripts = {};\n }\n const scripts = pkg.scripts as Record<string, string>;\n for (const [key, value] of Object.entries(childScripts)) {\n scripts[key] = value;\n }\n for (const obsoleteScript of [\n \"init\",\n \"sync-catalog\",\n \"db:push\",\n \"db:studio\",\n \"db:generate\",\n \"db:migrate\",\n \"test\",\n \"test:api\",\n \"test:integration\",\n \"test:e2e\",\n \"dev:postgres\",\n \"dev:postgres:down\",\n \"dev:postgres:reset\",\n \"dev:ui\",\n \"dev:api\",\n ]) {\n if (!(obsoleteScript in childScripts)) {\n delete scripts[obsoleteScript];\n }\n }\n\n if (pkg.devDependencies && typeof pkg.devDependencies === \"object\") {\n const deps = pkg.devDependencies as Record<string, string>;\n delete deps[\"every-plugin\"];\n delete deps[\"everything-dev\"];\n }\n\n if (!pkg.workspaces || typeof pkg.workspaces !== \"object\") {\n pkg.workspaces = { packages: [], catalog: {} };\n }\n const workspaces = pkg.workspaces as { packages?: string[]; catalog?: Record<string, string> };\n if (!workspaces.catalog || typeof workspaces.catalog !== \"object\") {\n workspaces.catalog = {};\n }\n\n if (!pkg.dependencies) pkg.dependencies = {};\n const deps = pkg.dependencies as Record<string, string>;\n const spec = opts.workspaceOpts?.sourceDir\n ? loadManifestNormalizationSpec(opts.workspaceOpts.sourceDir)\n : null;\n if (spec) {\n workspaces.catalog[\"everything-dev\"] = spec.rootCatalog[\"everything-dev\"];\n workspaces.catalog[\"every-plugin\"] = spec.rootCatalog[\"every-plugin\"];\n }\n const frameworkCatalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n sourceDir: opts.workspaceOpts?.sourceDir,\n })\n ).catalog;\n for (const [name, version] of Object.entries(frameworkCatalog)) {\n workspaces.catalog[name] = version;\n }\n if (!deps[\"everything-dev\"]) deps[\"everything-dev\"] = \"catalog:\";\n if (!deps[\"every-plugin\"]) deps[\"every-plugin\"] = \"catalog:\";\n\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n }\n\n const apiTsConfigPath = join(destination, \"api\", \"tsconfig.json\");\n if (existsSync(apiTsConfigPath)) {\n const apiTsConfig = JSON.parse(readFileSync(apiTsConfigPath, \"utf-8\")) as {\n files?: string[];\n [key: string]: unknown;\n };\n if (apiTsConfig.files) {\n const validFiles = apiTsConfig.files.filter((f) => existsSync(join(destination, \"api\", f)));\n if (validFiles.length !== apiTsConfig.files.length) {\n if (validFiles.length === 0) {\n delete apiTsConfig.files;\n } else {\n apiTsConfig.files = validFiles;\n }\n writeFileSync(apiTsConfigPath, `${JSON.stringify(apiTsConfig, null, 2)}\\n`);\n }\n }\n }\n\n await resolveWorkspaceRefs(destination, opts.workspaceOpts);\n\n if (has(\"ui\")) {\n const genContractPath = join(destination, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n if (!existsSync(genContractPath)) {\n mkdirSync(dirname(genContractPath), { recursive: true });\n writeFileSync(genContractPath, `export type ApiContract = Record<string, never>;\\n`);\n }\n }\n\n if (has(\"api\")) {\n const pluginsClientGenPath = join(destination, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n if (!existsSync(pluginsClientGenPath)) {\n mkdirSync(dirname(pluginsClientGenPath), { recursive: true });\n writeFileSync(\n pluginsClientGenPath,\n `import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";\\ntype ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\\nexport type PluginsClient = Record<string, never>;\\n`,\n );\n }\n }\n\n const authTypesPaths: string[] = [];\n if (has(\"ui\")) {\n authTypesPaths.push(join(destination, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"api\")) {\n authTypesPaths.push(join(destination, \"api\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"host\") && existsSync(join(destination, \"host\", \"src\"))) {\n authTypesPaths.push(join(destination, \"host\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n for (const authTypesGenPath of authTypesPaths) {\n if (!existsSync(authTypesGenPath)) {\n mkdirSync(dirname(authTypesGenPath), { recursive: true });\n writeFileSync(authTypesGenPath, generateAuthTypesContent(authTypesGenPath, destination));\n }\n }\n\n if (authTypesPaths.length > 0) {\n const authDir = join(destination, \".bos\", \"generated\", \"auth\");\n if (!existsSync(authDir)) {\n mkdirSync(authDir, { recursive: true });\n }\n const authExportStubPath = join(authDir, \"auth-export.d.ts\");\n if (!existsSync(authExportStubPath)) {\n writeFileSync(\n authExportStubPath,\n `export type Auth = any;\nexport type AuthOrganizationContext = any;\nexport type AuthOrganization = any;\nexport type AuthOrganizationSummary = any;\nexport type AuthOrganizationMember = any;\nexport type AuthApiKey = any;\nexport type AuthInvitation = any;\nexport type GetActiveMemberInput = any;\nexport type GetOrganizationInput = any;\nexport type ListMembersInput = any;\nexport type ListInvitationsInput = any;\nexport type ListApiKeysInput = any;\nexport type AuthServices = any;\nexport type createAuthInstance = any;\n`,\n );\n }\n const contractStubPath = join(authDir, \"contract.d.ts\");\n if (!existsSync(contractStubPath)) {\n writeFileSync(\n contractStubPath,\n `export type ContractType = any;\nexport type InferOutput<_TRoute extends string> = any;\n`,\n );\n }\n }\n\n if (has(\"plugins\")) {\n for (const plugin of opts.plugins ?? []) {\n const pluginSrcDir = join(destination, \"plugins\", plugin, \"src\");\n const pluginIndexPath = join(pluginSrcDir, \"index.ts\");\n const pluginClientGenPath = join(pluginSrcDir, \"plugins-client.gen.ts\");\n if (!existsSync(pluginIndexPath) || existsSync(pluginClientGenPath)) {\n continue;\n }\n const pluginIndex = readFileSync(pluginIndexPath, \"utf-8\");\n if (!pluginIndex.includes(\"./plugins-client.gen\")) {\n continue;\n }\n writeFileSync(pluginClientGenPath, \"export type PluginsClient = Record<string, never>;\\n\");\n }\n }\n}\n\nfunction generateAuthTypesContent(targetPath: string, configDir: string): string {\n const authExportRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"auth-export.d.ts\"),\n targetPath,\n );\n const contractRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"contract.d.ts\"),\n targetPath,\n );\n\n return `export type {\n Auth,\n AuthOrganizationContext,\n AuthOrganization,\n AuthOrganizationSummary,\n AuthOrganizationMember,\n AuthApiKey,\n AuthInvitation,\n GetActiveMemberInput,\n GetOrganizationInput,\n ListMembersInput,\n ListInvitationsInput,\n ListApiKeysInput,\n AuthServices,\n createAuthInstance,\n} from \"${authExportRel}\";\nimport type { InferOutput, ContractType as AuthContract } from \"${contractRel}\";\nimport type { Auth as BaseAuth } from \"${authExportRel}\";\n\ntype RawAuthSession = InferOutput<\"getSession\">;\ntype RawAuthRequestContext = InferOutput<\"getContext\">;\ntype RawAuthActiveMember = InferOutput<\"getActiveMember\">;\n\nexport type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {\n role?: string | null;\n isAnonymous?: boolean | null;\n walletAddress?: string | null;\n banned?: boolean | null;\n};\nexport type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {\n activeOrganizationId?: string | null;\n};\nexport type AuthSession = {\n user: AuthSessionUser | null;\n session: AuthSessionData | null;\n};\nexport type AuthRequestContext = RawAuthRequestContext & {\n organization?: { activeOrganizationId?: string | null } | null;\n apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;\n};\nexport type AuthActiveMember = RawAuthActiveMember;\nexport type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];\nexport type AuthContractType = AuthContract;\n`;\n}\n\nfunction toRelativeImportPath(fromPath: string, toPath: string): string {\n const rel = relative(dirname(toPath), fromPath);\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport async function runBunInstall(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--ignore-scripts\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runBunInstallForUpgrade(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--force\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runTypesGen(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n const localBosBin = join(destination, \"node_modules\", \".bin\", \"bos\");\n if (existsSync(localBosBin)) {\n await runWithProgress(\n \"node_modules/.bin/bos\",\n [\"types\", \"gen\"],\n destination,\n spinner,\n \"Generating types\",\n );\n return;\n }\n\n throw new Error(\"Unable to locate bos CLI for types generation\");\n}\n\nexport async function runDockerComposeUp(destination: string): Promise<void> {\n await execCommand(\"docker\", [\"compose\", \"up\", \"-d\", \"--wait\"], destination, { stdio: \"inherit\" });\n}\n\nasync function runWithProgress(\n command: string,\n args: string[],\n cwd: string,\n spinner: { message: (msg: string) => void } | undefined,\n label: string,\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n const child = execa(command, args, { cwd, stdio: \"inherit\", timeout });\n\n if (spinner) {\n const start = Date.now();\n const interval = setInterval(() => {\n const elapsed = Math.round((Date.now() - start) / 1000);\n spinner.message(`${label}... (${elapsed}s)`);\n }, 2000);\n try {\n await child;\n } finally {\n clearInterval(interval);\n }\n } else {\n await child;\n }\n}\n\nexport function stripOrphanedWorkspacesFromLockfile(\n lockfilePath: string,\n allowedWorkspaces: string[],\n): void {\n if (!existsSync(lockfilePath)) return;\n\n const content = readFileSync(lockfilePath, \"utf-8\");\n let lockfile: Record<string, unknown>;\n try {\n lockfile = JSON.parse(content) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const workspaces = lockfile.workspaces;\n if (!workspaces || typeof workspaces !== \"object\") return;\n\n const workspaceMap = workspaces as Record<string, unknown>;\n const allowed = new Set([\"\", ...allowedWorkspaces]);\n\n const keys = Object.keys(workspaceMap);\n let changed = false;\n for (const key of keys) {\n if (allowed.has(key)) continue;\n if (\n allowedWorkspaces.some(\n (pattern) => pattern.endsWith(\"/*\") && key.startsWith(pattern.slice(0, -1)),\n )\n )\n continue;\n delete workspaceMap[key];\n changed = true;\n }\n\n if (changed) {\n writeFileSync(lockfilePath, `${JSON.stringify(lockfile, null, 2)}\\n`);\n }\n}\n\nexport function removeInitLockfile(lockfilePath: string): void {\n if (!existsSync(lockfilePath)) return;\n rmSync(lockfilePath, { force: true });\n}\n\nfunction readJsonFile<T>(filePath: string): T {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n}\n\nexport async function scaffoldMinimalProject(\n destination: string,\n parentConfig: BosConfigInput,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n repository?: string;\n title?: string;\n description?: string;\n },\n): Promise<number> {\n mkdirSync(destination, { recursive: true });\n\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n\n const config: Record<string, unknown> = {\n extends: `bos://${opts.extendsAccount}/${opts.extendsGateway}`,\n account: opts.account || opts.extendsAccount,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.repository ? { repository: opts.repository } : {}),\n ...(opts.title ? { title: opts.title } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n };\n\n if (parentConfig.app && typeof parentConfig.app === \"object\") {\n const app: Record<string, unknown> = {};\n const parentApp = parentConfig.app as Record<string, Record<string, unknown>>;\n\n if (has(\"host\") && parentApp.host) {\n app.host = { ...parentApp.host };\n stripProductionFields(app.host as Record<string, unknown>);\n }\n\n if (has(\"ui\") && parentApp.ui) {\n app.ui = { ...parentApp.ui };\n stripProductionFields(app.ui as Record<string, unknown>);\n }\n\n if (has(\"api\") && parentApp.api) {\n app.api = { ...parentApp.api };\n stripProductionFields(app.api as Record<string, unknown>);\n }\n\n if (Object.keys(app).length > 0) {\n config.app = app;\n }\n }\n\n if (has(\"plugins\") && opts.plugins && opts.plugins.length > 0 && parentConfig.plugins) {\n const plugins: Record<string, unknown> = {};\n for (const key of opts.plugins) {\n const parentPlugin = (parentConfig.plugins as Record<string, unknown>)?.[key];\n if (parentPlugin) {\n if (typeof parentPlugin === \"string\") {\n plugins[key] = { extends: parentPlugin };\n } else {\n const pluginCopy = { ...(parentPlugin as Record<string, unknown>) };\n stripProductionFields(pluginCopy);\n plugins[key] = pluginCopy;\n }\n }\n }\n config.plugins = plugins;\n } else if (has(\"plugins\")) {\n config.plugins = {};\n }\n\n await saveBosConfig(destination, config);\n\n const workspacePackages: string[] = [];\n for (const section of opts.overrides) {\n workspacePackages.push(...OVERRIDE_WORKSPACE_MAP[section]);\n }\n if (has(\"plugins\")) {\n workspacePackages.push(\"plugins/*\");\n }\n\n const catalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n })\n ).catalog;\n\n const pkg: Record<string, unknown> = {\n name: \"monorepo\",\n private: true,\n type: \"module\",\n scripts: buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n }),\n dependencies: {\n \"everything-dev\": \"catalog:\",\n \"every-plugin\": \"catalog:\",\n },\n devDependencies: {},\n workspaces: {\n packages: workspacePackages,\n catalog,\n },\n };\n writeFileSync(join(destination, \"package.json\"), `${JSON.stringify(pkg, null, 2)}\\n`);\n\n writeFileSync(join(destination, \".gitignore\"), generateGitignore());\n\n return 4;\n}\n\nasync function resolveWorkspaceRefs(\n destination: string,\n options?: { localOverrides?: boolean; sourceDir?: string },\n): Promise<void> {\n await normalizePackageManifestsInTree({\n sourceRootDir: options?.sourceDir ?? destination,\n targetDir: destination,\n resolveCatalogRefs: false,\n preserveCatalogRefs: true,\n removeWorkspaceDeps: [\"host\"],\n });\n}\n\nexport async function writeInitSnapshot(\n destination: string,\n extendsAccount: string,\n extendsGateway: string,\n sourceDir: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<void> {\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n const fileHashes: Record<string, string> = {};\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n const content = readFileSync(src);\n const destPath = sourcePathToDestinationPath(filePath);\n fileHashes[destPath] = computeHash(content);\n }\n\n await writeSnapshot(destination, {\n parentRef: `bos://${extendsAccount}/${extendsGateway}`,\n files: fileHashes,\n });\n}\n\nfunction computeHash(data: Uint8Array): string {\n return createHash(\"sha256\").update(data).digest(\"hex\").substring(0, 16);\n}\n\nfunction mkTmpDir(prefix: string): string {\n return mkdtempSync(join(tmpdir(), `${prefix}-`));\n}\n\nexport async function generateDatabaseMigrations(destination: string): Promise<void> {\n const drizzleConfigs = await glob(\"**/drizzle.config.ts\", {\n cwd: destination,\n nodir: true,\n dot: false,\n absolute: false,\n ignore: [\"**/node_modules/**\"],\n });\n\n for (const configPath of drizzleConfigs) {\n const workspaceDir = dirname(configPath);\n const pkgPath = join(destination, workspaceDir, \"package.json\");\n if (!existsSync(pkgPath)) continue;\n\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const scripts = pkg.scripts as Record<string, string> | undefined;\n if (!scripts?.[\"db:generate\"]) continue;\n\n const cwd = join(destination, workspaceDir);\n await execCommand(\"bun\", [\"run\", \"db:generate\"], cwd);\n }\n}\n\nconst COMMAND_TIMEOUTS: Record<string, number> = {\n bun: 5 * 60_000,\n docker: 5 * 60_000,\n node_modules: 2 * 60_000,\n tar: 60_000,\n};\n\nexport async function execCommand(\n command: string,\n args: string[],\n cwd?: string,\n options?: { stdio?: \"pipe\" | \"inherit\" },\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n await execa(command, args, { cwd, stdio: options?.stdio ?? \"pipe\", timeout });\n}\n\nfunction generateGitignore(): string {\n return `node_modules/\ndist/\n.env\n.bos/\n*.gen.ts\n*.gen.tsx\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAE9C,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,yBAA4D;CAChE,IAAI,CAAC,KAAK;CACV,KAAK,CAAC,MAAM;CACZ,MAAM,CAAC,OAAO;CACd,SAAS,EAAE;CACZ;AAcD,SAAS,cAAc,QAAqD;AAC1E,KAAI,OAAO,OAAO,YAAY,SAC5B,QAAO,OAAO;AAGhB,KAAI,OAAO,WAAW,OAAO,OAAO,YAAY,SAC9C,QAAO,kBAAkB,OAAO,SAAmC,aAAa;;AAMpF,SAAS,YAAY,KAA0D;CAC7E,MAAM,QAAQ,IAAI,MAAM,0BAA0B;AAClD,KAAI,CAAC,QAAQ,MAAM,CAAC,MAAM,GAAI,QAAO;AACrC,QAAO;EAAE,SAAS,MAAM;EAAI,SAAS,MAAM;EAAI;;AAGjD,SAAS,qBAAqB,WAA2C;CACvE,MAAM,UAAU,KAAK,WAAW,eAAe;AAC/C,KAAI,CAAC,WAAW,QAAQ,CACtB,QAAO,EAAE;AAIX,QAAO,EAAE,GADG,aAAoE,QAChE,CAAC,YAAY,WAAW,EAAE,EAAG;;AAG/C,eAAsB,0BAA0B,MAIhB;CAC9B,MAAM,WAAqC,EAAE;CAC7C,MAAM,WAAuC,EAAE;CAC/C,MAAM,eAAyB,EAAE;CACjC,MAAM,0BAAU,IAAI,KAAa;CACjC,IAAI;CACJ,IAAI,aAAa,SAAS,KAAK,eAA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AAS,CAAC,OAAO,KAAK,CAAC,OAAO,MAAM,CAAC,UAAU,GAAG,GAAG;;AAGzE,SAAS,SAAS,QAAwB;AACxC,QAAO,YAAY,KAAK,QAAQ,EAAE,GAAG,OAAO,GAAG,CAAC;;AAGlD,eAAsB,2BAA2B,aAAoC;CACnF,MAAM,iBAAiB,MAAM,KAAK,wBAAwB;EACxD,KAAK;EACL,OAAO;EACP,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,qBAAqB;EAC/B,CAAC;AAEF,MAAK,MAAM,cAAc,gBAAgB;EACvC,MAAM,eAAe,QAAQ,WAAW;EACxC,MAAM,UAAU,KAAK,aAAa,cAAc,eAAe;AAC/D,MAAI,CAAC,WAAW,QAAQ,CAAE;AAI1B,MAAI,CAFQ,KAAK,MAAM,aAAa,SAAS,QAAQ,CAClC,CAAC,UACL,eAAgB;AAG/B,QAAM,YAAY,OAAO,CAAC,OAAO,cAAc,EADnC,KAAK,aAAa,aACsB,CAAC;;;AAIzD,MAAM,mBAA2C;CAC/C,KAAK,IAAI;CACT,QAAQ,IAAI;CACZ,cAAc,IAAI;CAClB,KAAK;CACN;AAED,eAAsB,YACpB,SACA,MACA,KACA,SACe;CACf,MAAM,UAAU,iBAAiB,YAAY,IAAI;AACjD,OAAM,MAAM,SAAS,MAAM;EAAE;EAAK,OAAO,SAAS,SAAS;EAAQ;EAAS,CAAC;;AAG/E,SAAS,oBAA4B;AACnC,QAAO"}
1
+ {"version":3,"file":"init.mjs","names":[],"sources":["../../src/cli/init.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { execa } from \"execa\";\nimport { glob } from \"glob\";\nimport type { OverrideSection } from \"../contract\";\nimport { fetchBosConfigFromFastKv } from \"../fastkv\";\nimport {\n loadManifestNormalizationSpec,\n normalizePackageManifestsInTree,\n} from \"../internal/manifest-normalizer\";\nimport { resolveExtendsRef } from \"../merge\";\nimport type { BosConfig, BosConfigInput } from \"../types\";\nimport { saveBosConfig } from \"../utils/save-config\";\nimport { writeSnapshot } from \"./snapshot\";\n\nconst require = createRequire(import.meta.url);\n\nexport const INIT_ROOT_PATTERNS = [\n \"bos.config.json\",\n \"package.json\",\n \".env.example\",\n \".gitignore\",\n \"biome.json\",\n \"bunfig.toml\",\n \"Dockerfile\",\n \"railway.json\",\n \"railway.toml\",\n \"AGENTS.md\",\n \".changeset/config.json\",\n \".changeset/README.md\",\n \"README.md\",\n \"CONTRIBUTING.md\",\n \".github/templates/**\",\n] as const;\n\nconst OVERRIDE_WORKSPACE_MAP: Record<OverrideSection, string[]> = {\n ui: [\"ui\"],\n api: [\"api\"],\n host: [\"host\"],\n plugins: [],\n};\n\ninterface SourceResult {\n sourceDir: string;\n parentConfig: BosConfig;\n cleanup: () => Promise<void>;\n}\n\nexport interface CatalogChainSource {\n catalog: Record<string, string>;\n repository?: string;\n extendsChain: string[];\n}\n\nfunction getExtendsRef(config: Record<string, unknown>): string | undefined {\n if (typeof config.extends === \"string\") {\n return config.extends;\n }\n\n if (config.extends && typeof config.extends === \"object\") {\n return resolveExtendsRef(config.extends as Record<string, string>, \"production\");\n }\n\n return undefined;\n}\n\nfunction parseBosRef(ref: string): { account: string; gateway: string } | null {\n const match = ref.match(/^bos:\\/\\/([^/]+)\\/(.+)$/);\n if (!match?.[1] || !match[2]) return null;\n return { account: match[1], gateway: match[2] };\n}\n\nfunction readWorkspaceCatalog(sourceDir: string): Record<string, string> {\n const pkgPath = join(sourceDir, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n\n const pkg = readJsonFile<{ workspaces?: { catalog?: Record<string, string> } }>(pkgPath);\n return { ...(pkg.workspaces?.catalog ?? {}) };\n}\n\nexport async function resolveCatalogChainSource(opts: {\n extendsAccount: string;\n extendsGateway: string;\n sourceDir?: string;\n}): Promise<CatalogChainSource> {\n const catalogs: Record<string, string>[] = [];\n const cleanups: Array<() => Promise<void>> = [];\n const extendsChain: string[] = [];\n const visited = new Set<string>();\n let repository: string | undefined;\n let currentRef = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n let sourceDir = opts.sourceDir ? resolve(opts.sourceDir) : undefined;\n let configPath = sourceDir ? join(sourceDir, \"bos.config.json\") : undefined;\n\n try {\n while (true) {\n if (visited.has(currentRef)) {\n throw new Error(`Circular extends detected while resolving catalog source: ${currentRef}`);\n }\n\n visited.add(currentRef);\n extendsChain.push(currentRef);\n\n let config: Record<string, unknown>;\n let currentSourceDir = sourceDir;\n let cleanup: () => Promise<void> = async () => {};\n\n if (configPath) {\n config = readJsonFile<Record<string, unknown>>(configPath);\n currentSourceDir = dirname(configPath);\n } else {\n const parsed = parseBosRef(currentRef);\n if (!parsed) {\n break;\n }\n const sourceResult = await resolveSourceDir({\n extendsAccount: parsed.account,\n extendsGateway: parsed.gateway,\n });\n config = sourceResult.parentConfig as Record<string, unknown>;\n currentSourceDir = sourceResult.sourceDir || undefined;\n cleanup = sourceResult.cleanup;\n }\n\n cleanups.push(cleanup);\n catalogs.push(currentSourceDir ? readWorkspaceCatalog(currentSourceDir) : {});\n\n if (typeof config.repository === \"string\") {\n repository = config.repository;\n }\n\n const nextExtendsRef = getExtendsRef(config);\n if (!nextExtendsRef) {\n break;\n }\n\n if (nextExtendsRef.startsWith(\"bos://\")) {\n currentRef = nextExtendsRef;\n sourceDir = undefined;\n configPath = undefined;\n continue;\n }\n\n if (!currentSourceDir) {\n break;\n }\n\n const nextConfigPath = resolve(currentSourceDir, nextExtendsRef);\n if (!existsSync(nextConfigPath)) {\n break;\n }\n\n currentRef = nextConfigPath;\n sourceDir = dirname(nextConfigPath);\n configPath = nextConfigPath;\n }\n } finally {\n for (const cleanup of cleanups.reverse()) {\n await cleanup();\n }\n }\n\n return {\n catalog: Object.assign({}, ...catalogs.reverse()),\n repository,\n extendsChain,\n };\n}\n\nexport async function resolveSourceDir(opts: {\n extendsAccount: string;\n extendsGateway: string;\n source?: string;\n}): Promise<SourceResult> {\n if (opts.source) {\n const sourceDir = resolve(opts.source);\n if (!existsSync(join(sourceDir, \"bos.config.json\"))) {\n throw new Error(`No bos.config.json found in source directory: ${sourceDir}`);\n }\n const parentConfig = JSON.parse(\n readFileSync(join(sourceDir, \"bos.config.json\"), \"utf-8\"),\n ) as BosConfig;\n return { sourceDir, parentConfig, cleanup: async () => {} };\n }\n\n const parentConfig = await fetchParentConfig(opts.extendsAccount, opts.extendsGateway);\n\n if (parentConfig.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(parentConfig.repository);\n return { sourceDir, parentConfig, cleanup };\n }\n\n const chainResult = await resolveRepositoryViaExtendsChain(\n opts.extendsAccount,\n opts.extendsGateway,\n );\n if (chainResult?.repository) {\n const { dir: sourceDir, cleanup } = await downloadTarball(chainResult.repository);\n return { sourceDir, parentConfig: chainResult.config, cleanup };\n }\n\n return {\n sourceDir: \"\",\n parentConfig,\n cleanup: async () => {},\n };\n}\n\nexport function buildInitPatterns(overrides: OverrideSection[], plugins?: string[]): string[] {\n const has = (section: OverrideSection) => overrides.includes(section);\n const patterns: string[] = [...INIT_ROOT_PATTERNS];\n\n if (has(\"ui\")) patterns.push(\"ui/**\");\n if (has(\"api\")) patterns.push(\"api/**\");\n if (has(\"host\")) patterns.push(\"host/**\");\n if (has(\"plugins\")) {\n for (const plugin of plugins ?? []) {\n patterns.push(`plugins/${plugin}/**`);\n }\n }\n\n return patterns;\n}\n\nexport function sourcePathToDestinationPath(filePath: string): string {\n return filePath.startsWith(\".github/templates/\")\n ? filePath.replace(/^\\.github\\/templates\\//, \".github/\")\n : filePath;\n}\n\nexport async function fetchParentConfig(\n extendsAccount: string,\n extendsGateway: string,\n): Promise<BosConfig> {\n const bosUrl = `bos://${extendsAccount}/${extendsGateway}`;\n return fetchBosConfigFromFastKv<BosConfig>(bosUrl);\n}\n\nexport async function resolveRepositoryViaExtendsChain(\n extendsAccount: string,\n extendsGateway: string,\n visited = new Set<string>(),\n): Promise<{ repository: string; config: BosConfig } | null> {\n const key = `bos://${extendsAccount}/${extendsGateway}`;\n if (visited.has(key)) return null;\n visited.add(key);\n\n try {\n const config = await fetchParentConfig(extendsAccount, extendsGateway);\n if (config.repository) {\n return { repository: config.repository, config };\n }\n\n const extendsRef = getExtendsRef(config as Record<string, unknown>);\n if (extendsRef) {\n const normalized = extendsRef.startsWith(\"bos://\") ? extendsRef : `bos://${extendsRef}`;\n const parsed = parseBosRef(normalized);\n if (parsed) {\n const result = await resolveRepositoryViaExtendsChain(\n parsed.account,\n parsed.gateway,\n visited,\n );\n if (result) return result;\n }\n }\n\n return null;\n } catch {\n return null;\n }\n}\n\nexport async function detectGitRemoteUrl(directory: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd: directory,\n stdio: \"pipe\",\n });\n const url = stdout.trim();\n if (!url) return undefined;\n return normalizeGitUrl(url);\n } catch {\n return undefined;\n }\n}\n\nfunction normalizeGitUrl(url: string): string | undefined {\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;\n }\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;\n }\n return url.endsWith(\".git\") ? url.slice(0, -4) : url;\n}\n\nexport async function downloadTarball(\n repoUrl: string,\n): Promise<{ dir: string; cleanup: () => Promise<void> }> {\n const parsed = parseGitHubUrl(repoUrl);\n if (!parsed) {\n throw new Error(`Cannot parse repository URL: ${repoUrl}`);\n }\n\n const { owner, repo } = parsed;\n let response: Response | null = null;\n\n for (const branch of [\"main\", \"master\"]) {\n const candidate = await fetch(\n `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`,\n {\n headers: { \"User-Agent\": \"everything-dev\" },\n redirect: \"follow\",\n },\n );\n if (candidate.ok) {\n response = candidate;\n break;\n }\n if (candidate.status !== 404) {\n throw new Error(\n `GitHub tarball download failed: ${candidate.status} ${candidate.statusText}`,\n );\n }\n }\n\n if (!response) {\n throw new Error(`GitHub tarball download failed for ${repoUrl}: tried main and master`);\n }\n\n if (!response.body) {\n throw new Error(\"GitHub tarball download returned empty body\");\n }\n\n const tmpDir = mkTmpDir(\"bos-init-tarball-\");\n const tarballPath = join(tmpDir, \"source.tar.gz\");\n\n const fileStream = createWriteStream(tarballPath);\n const reader = response.body as unknown as NodeJS.ReadableStream;\n await pipeline(reader, fileStream);\n\n const extractDir = mkTmpDir(\"bos-init-extract-\");\n try {\n const tar = require(\"tar\") as {\n extract: (opts: { cwd: string; file: string; strip: number }) => Promise<void>;\n };\n await tar.extract({ cwd: extractDir, file: tarballPath, strip: 1 });\n } catch {\n await execCommand(\"tar\", [\"-xzf\", tarballPath, \"--strip-components=1\", \"-C\", extractDir]);\n }\n\n rmSync(tmpDir, { recursive: true, force: true });\n\n return {\n dir: extractDir,\n cleanup: async () => {\n rmSync(extractDir, { recursive: true, force: true });\n },\n };\n}\n\nfunction parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n if (httpsMatch) {\n return { owner: httpsMatch[1], repo: httpsMatch[2] };\n }\n\n const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n if (sshMatch) {\n return { owner: sshMatch[1], repo: sshMatch[2] };\n }\n\n return null;\n}\n\nexport async function copyFilteredFiles(\n sourceDir: string,\n destination: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<number> {\n if (patterns.length === 0) {\n return 0;\n }\n\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n mkdirSync(destination, { recursive: true });\n\n let count = 0;\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n\n const destPath = sourcePathToDestinationPath(filePath);\n const dest = join(destination, destPath);\n mkdirSync(dirname(dest), { recursive: true });\n const content = readFileSync(src);\n writeFileSync(dest, content);\n count++;\n }\n\n return count;\n}\n\nfunction stripProductionFields(entry: Record<string, unknown>): void {\n delete entry.production;\n delete entry.integrity;\n delete entry.ssr;\n delete entry.ssrIntegrity;\n}\n\nfunction buildRootTypecheckScript(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): string {\n const commands = [\"bun run types:gen\"];\n\n if (sections.ui) {\n commands.push(\"if [ -d ui ]; then bun run --cwd ui typecheck; fi\");\n }\n if (sections.api) {\n commands.push(\"if [ -d api ]; then bun run --cwd api typecheck; fi\");\n }\n if (sections.host) {\n commands.push(\"if [ -d host ]; then bun run --cwd host typecheck; fi\");\n }\n if (sections.plugins) {\n commands.push(\n 'if [ -d plugins ]; then for dir in plugins/*; do if [ -f \"$dir/package.json\" ]; then bun run --cwd \"$dir\" typecheck; fi; done; fi',\n );\n }\n\n return commands.join(\" && \");\n}\n\nexport function buildChildRootScripts(sections: {\n ui: boolean;\n api: boolean;\n host: boolean;\n plugins: boolean;\n}): Record<string, string> {\n const scripts: Record<string, string> = {\n dev: \"node_modules/.bin/bos dev\",\n \"dev:proxy\": \"node_modules/.bin/bos dev --proxy\",\n build: \"node_modules/.bin/bos build\",\n deploy: \"node_modules/.bin/bos build --deploy\",\n publish: \"node_modules/.bin/bos publish\",\n start: \"node_modules/.bin/bos start\",\n typecheck: buildRootTypecheckScript(sections),\n lint: \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n format: \"biome format --write .\",\n \"format:check\": \"biome format .\",\n changeset: \"changeset\",\n version: \"changeset version\",\n release: \"echo 'Packages versioned - app release handled by workflow'\",\n postinstall: \"node_modules/.bin/bos types gen || true\",\n \"types:gen\": \"node_modules/.bin/bos types gen\",\n bos: \"node_modules/.bin/bos\",\n };\n\n if (sections.api) {\n scripts[\"db:push\"] = \"bun run --cwd api drizzle-kit push\";\n scripts[\"db:studio\"] = \"bun run --cwd api drizzle-kit studio\";\n scripts[\"db:generate\"] = \"bun run --cwd api drizzle-kit generate\";\n scripts[\"db:migrate\"] = \"bun run --cwd api drizzle-kit migrate\";\n scripts[\"test:api\"] = \"cd api && bun run test tests/integration/ tests/unit/\";\n scripts[\"test:integration\"] = \"cd api && bun run test tests/integration/\";\n }\n\n if (sections.host) {\n scripts[\"test:e2e\"] = \"bun run --cwd host test:e2e\";\n }\n\n if (sections.api && sections.host) {\n scripts.test = \"bun run test:api && bun run test:e2e\";\n } else if (sections.api) {\n scripts.test = \"bun run test:api\";\n } else if (sections.host) {\n scripts.test = \"bun run test:e2e\";\n }\n\n if (sections.api || sections.host) {\n scripts[\"dev:postgres\"] = \"docker compose up -d --wait && bun run dev\";\n scripts[\"dev:postgres:down\"] = \"docker compose down\";\n scripts[\"dev:postgres:reset\"] = \"docker compose down -v && docker compose up -d --wait\";\n }\n\n if (sections.ui) {\n scripts[\"dev:ui\"] = \"node_modules/.bin/bos dev --ui local --api remote\";\n }\n if (sections.api) {\n scripts[\"dev:api\"] = \"node_modules/.bin/bos dev --ui remote --api local\";\n }\n\n return scripts;\n}\n\nexport async function personalizeConfig(\n destination: string,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n pluginRoutes?: Record<string, string[]>;\n workspaceOpts?: { localOverrides?: boolean; sourceDir?: string };\n mode?: \"init\" | \"sync\";\n existingConfig?: Record<string, unknown>;\n repository?: string;\n title?: string;\n description?: string;\n testnet?: string;\n staging?: unknown;\n },\n): Promise<void> {\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n const existingApp =\n opts.mode === \"sync\" && opts.existingConfig?.app && typeof opts.existingConfig.app === \"object\"\n ? (opts.existingConfig.app as Record<string, unknown>)\n : undefined;\n const preservedAuth = existingApp?.auth;\n\n const explicitRootKeys = new Set(\n Object.entries(opts)\n .filter(\n ([key, value]) =>\n value !== undefined &&\n ![\n \"extendsAccount\",\n \"extendsGateway\",\n \"plugins\",\n \"overrides\",\n \"pluginRoutes\",\n \"workspaceOpts\",\n \"mode\",\n \"existingConfig\",\n ].includes(key),\n )\n .map(([key]) => key),\n );\n\n const configPath = join(destination, \"bos.config.json\");\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>;\n\n config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n if (opts.account) {\n config.account = opts.account;\n }\n if (opts.domain) {\n config.domain = opts.domain;\n }\n if (opts.repository) {\n config.repository = opts.repository;\n } else {\n delete config.repository;\n }\n\n const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n for (const field of inheritableFields) {\n if (!(field in opts)) {\n delete config[field];\n }\n }\n\n if (config.app && typeof config.app === \"object\") {\n const app = config.app as Record<string, unknown>;\n\n for (const entryKey of Object.keys(app)) {\n if (\n !has(entryKey as OverrideSection) &&\n (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n ) {\n delete app[entryKey];\n continue;\n }\n if (entryKey === \"auth\") {\n delete app[entryKey];\n continue;\n }\n const entry = app[entryKey];\n if (entry && typeof entry === \"object\") {\n stripProductionFields(entry as Record<string, unknown>);\n }\n }\n\n if (preservedAuth !== undefined) {\n app.auth = preservedAuth;\n }\n\n if (Object.keys(app).length === 0) {\n delete config.app;\n }\n }\n\n if (has(\"plugins\")) {\n if (config.plugins && typeof config.plugins === \"object\") {\n const plugins = config.plugins as Record<string, unknown>;\n\n if (opts.plugins !== undefined) {\n for (const pluginKey of Object.keys(plugins)) {\n if (!opts.plugins.includes(pluginKey)) {\n delete plugins[pluginKey];\n }\n }\n }\n\n for (const pluginKey of Object.keys(plugins)) {\n const plugin = plugins[pluginKey];\n let pluginObj: Record<string, unknown>;\n\n if (typeof plugin === \"string\") {\n pluginObj = { extends: plugin };\n plugins[pluginKey] = pluginObj;\n } else if (plugin && typeof plugin === \"object\") {\n pluginObj = { ...(plugin as Record<string, unknown>) };\n plugins[pluginKey] = pluginObj;\n } else {\n continue;\n }\n\n stripProductionFields(pluginObj);\n }\n\n if (Object.keys(plugins).length === 0) {\n config.plugins = {};\n }\n }\n } else {\n config.plugins = {};\n }\n\n if (opts.mode === \"sync\" && opts.existingConfig) {\n const managedRootKeys = new Set([\"extends\", \"account\", \"domain\", \"app\", \"plugins\"]);\n const preservedRootKeys = new Set([\n ...managedRootKeys,\n ...Object.keys(opts.existingConfig),\n ...explicitRootKeys,\n ]);\n\n for (const key of Object.keys(config)) {\n if (!preservedRootKeys.has(key)) {\n delete config[key];\n }\n }\n\n for (const [key, value] of Object.entries(opts.existingConfig)) {\n if (!(key in config) && !managedRootKeys.has(key) && !explicitRootKeys.has(key)) {\n config[key] = value;\n }\n }\n }\n\n await saveBosConfig(destination, config);\n }\n\n const pkgPath = join(destination, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const childScripts = buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n });\n\n if (typeof pkg.name !== \"string\" || pkg.name.length === 0) {\n pkg.name = \"monorepo\";\n }\n pkg.private = true;\n pkg.type = \"module\";\n delete pkg.module;\n delete pkg.peerDependencies;\n\n if (pkg.workspaces && typeof pkg.workspaces === \"object\") {\n const ws = pkg.workspaces as { packages?: string[] };\n if (Array.isArray(ws.packages)) {\n ws.packages = ws.packages.filter((p: string) => {\n if (p.startsWith(\"packages/\")) return false;\n if (p === \"ui\") return has(\"ui\");\n if (p === \"api\") return has(\"api\");\n if (p === \"host\") return has(\"host\");\n if (p.startsWith(\"plugins/\")) return false;\n return true;\n });\n\n if (has(\"plugins\")) {\n if (!ws.packages.includes(\"plugins/*\")) {\n ws.packages.push(\"plugins/*\");\n }\n }\n }\n }\n\n if (!pkg.scripts || typeof pkg.scripts !== \"object\") {\n pkg.scripts = {};\n }\n const scripts = pkg.scripts as Record<string, string>;\n for (const [key, value] of Object.entries(childScripts)) {\n scripts[key] = value;\n }\n for (const obsoleteScript of [\n \"init\",\n \"sync-catalog\",\n \"db:push\",\n \"db:studio\",\n \"db:generate\",\n \"db:migrate\",\n \"test\",\n \"test:api\",\n \"test:integration\",\n \"test:e2e\",\n \"dev:postgres\",\n \"dev:postgres:down\",\n \"dev:postgres:reset\",\n \"dev:ui\",\n \"dev:api\",\n ]) {\n if (!(obsoleteScript in childScripts)) {\n delete scripts[obsoleteScript];\n }\n }\n\n if (pkg.devDependencies && typeof pkg.devDependencies === \"object\") {\n const deps = pkg.devDependencies as Record<string, string>;\n delete deps[\"every-plugin\"];\n delete deps[\"everything-dev\"];\n }\n\n if (!pkg.workspaces || typeof pkg.workspaces !== \"object\") {\n pkg.workspaces = { packages: [], catalog: {} };\n }\n const workspaces = pkg.workspaces as { packages?: string[]; catalog?: Record<string, string> };\n if (!workspaces.catalog || typeof workspaces.catalog !== \"object\") {\n workspaces.catalog = {};\n }\n\n if (!pkg.dependencies) pkg.dependencies = {};\n const deps = pkg.dependencies as Record<string, string>;\n const spec = opts.workspaceOpts?.sourceDir\n ? loadManifestNormalizationSpec(opts.workspaceOpts.sourceDir)\n : null;\n if (spec) {\n workspaces.catalog[\"everything-dev\"] = spec.rootCatalog[\"everything-dev\"];\n workspaces.catalog[\"every-plugin\"] = spec.rootCatalog[\"every-plugin\"];\n }\n const frameworkCatalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n sourceDir: opts.workspaceOpts?.sourceDir,\n })\n ).catalog;\n for (const [name, version] of Object.entries(frameworkCatalog)) {\n workspaces.catalog[name] = version;\n }\n if (!deps[\"everything-dev\"]) deps[\"everything-dev\"] = \"catalog:\";\n if (!deps[\"every-plugin\"]) deps[\"every-plugin\"] = \"catalog:\";\n\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n }\n\n const apiTsConfigPath = join(destination, \"api\", \"tsconfig.json\");\n if (existsSync(apiTsConfigPath)) {\n const apiTsConfig = JSON.parse(readFileSync(apiTsConfigPath, \"utf-8\")) as {\n files?: string[];\n [key: string]: unknown;\n };\n if (apiTsConfig.files) {\n const validFiles = apiTsConfig.files.filter((f) => existsSync(join(destination, \"api\", f)));\n if (validFiles.length !== apiTsConfig.files.length) {\n if (validFiles.length === 0) {\n delete apiTsConfig.files;\n } else {\n apiTsConfig.files = validFiles;\n }\n writeFileSync(apiTsConfigPath, `${JSON.stringify(apiTsConfig, null, 2)}\\n`);\n }\n }\n }\n\n await resolveWorkspaceRefs(destination, opts.workspaceOpts);\n\n if (has(\"ui\")) {\n const genContractPath = join(destination, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n if (!existsSync(genContractPath)) {\n mkdirSync(dirname(genContractPath), { recursive: true });\n writeFileSync(genContractPath, `export type ApiContract = Record<string, never>;\\n`);\n }\n }\n\n if (has(\"api\")) {\n const pluginsClientGenPath = join(destination, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n if (!existsSync(pluginsClientGenPath)) {\n mkdirSync(dirname(pluginsClientGenPath), { recursive: true });\n writeFileSync(\n pluginsClientGenPath,\n `import type { ContractRouterClient, AnyContractRouter } from \"@orpc/contract\";\\ntype ClientFactory<C extends AnyContractRouter> = (context?: Record<string, unknown>) => ContractRouterClient<C>;\\nexport type PluginsClient = Record<string, never>;\\n`,\n );\n }\n }\n\n const authTypesPaths: string[] = [];\n if (has(\"ui\")) {\n authTypesPaths.push(join(destination, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"api\")) {\n authTypesPaths.push(join(destination, \"api\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n if (has(\"host\") && existsSync(join(destination, \"host\", \"src\"))) {\n authTypesPaths.push(join(destination, \"host\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n }\n for (const authTypesGenPath of authTypesPaths) {\n if (!existsSync(authTypesGenPath)) {\n mkdirSync(dirname(authTypesGenPath), { recursive: true });\n writeFileSync(authTypesGenPath, generateAuthTypesContent(authTypesGenPath, destination));\n }\n }\n\n if (authTypesPaths.length > 0) {\n const authDir = join(destination, \".bos\", \"generated\", \"auth\");\n if (!existsSync(authDir)) {\n mkdirSync(authDir, { recursive: true });\n }\n const authExportStubPath = join(authDir, \"auth-export.d.ts\");\n if (!existsSync(authExportStubPath)) {\n writeFileSync(\n authExportStubPath,\n `export type Auth = any;\nexport type AuthOrganizationContext = any;\nexport type AuthOrganization = any;\nexport type AuthOrganizationSummary = any;\nexport type AuthOrganizationMember = any;\nexport type AuthApiKey = any;\nexport type AuthInvitation = any;\nexport type GetActiveMemberInput = any;\nexport type GetOrganizationInput = any;\nexport type ListMembersInput = any;\nexport type ListInvitationsInput = any;\nexport type ListApiKeysInput = any;\nexport type AuthServices = any;\nexport type createAuthInstance = any;\n`,\n );\n }\n const contractStubPath = join(authDir, \"contract.d.ts\");\n if (!existsSync(contractStubPath)) {\n writeFileSync(\n contractStubPath,\n `export type ContractType = any;\nexport type InferOutput<_TRoute extends string> = any;\n`,\n );\n }\n }\n\n if (has(\"plugins\")) {\n for (const plugin of opts.plugins ?? []) {\n const pluginSrcDir = join(destination, \"plugins\", plugin, \"src\");\n const pluginIndexPath = join(pluginSrcDir, \"index.ts\");\n const pluginClientGenPath = join(pluginSrcDir, \"plugins-client.gen.ts\");\n if (!existsSync(pluginIndexPath) || existsSync(pluginClientGenPath)) {\n continue;\n }\n const pluginIndex = readFileSync(pluginIndexPath, \"utf-8\");\n if (!pluginIndex.includes(\"./plugins-client.gen\")) {\n continue;\n }\n writeFileSync(pluginClientGenPath, \"export type PluginsClient = Record<string, never>;\\n\");\n }\n }\n}\n\nfunction generateAuthTypesContent(targetPath: string, configDir: string): string {\n const authExportRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"auth-export.d.ts\"),\n targetPath,\n );\n const contractRel = toRelativeImportPath(\n join(configDir, \".bos\", \"generated\", \"auth\", \"contract.d.ts\"),\n targetPath,\n );\n\n return `export type {\n Auth,\n AuthOrganizationContext,\n AuthOrganization,\n AuthOrganizationSummary,\n AuthOrganizationMember,\n AuthApiKey,\n AuthInvitation,\n GetActiveMemberInput,\n GetOrganizationInput,\n ListMembersInput,\n ListInvitationsInput,\n ListApiKeysInput,\n AuthServices,\n createAuthInstance,\n} from \"${authExportRel}\";\nimport type { InferOutput, ContractType as AuthContract } from \"${contractRel}\";\nimport type { Auth as BaseAuth } from \"${authExportRel}\";\n\ntype RawAuthSession = InferOutput<\"getSession\">;\ntype RawAuthRequestContext = InferOutput<\"getContext\">;\ntype RawAuthActiveMember = InferOutput<\"getActiveMember\">;\n\nexport type AuthSessionUser = NonNullable<RawAuthSession[\"user\"]> & {\n role?: string | null;\n isAnonymous?: boolean | null;\n walletAddress?: string | null;\n banned?: boolean | null;\n};\nexport type AuthSessionData = NonNullable<RawAuthSession[\"session\"]> & {\n activeOrganizationId?: string | null;\n};\nexport type AuthSession = {\n user: AuthSessionUser | null;\n session: AuthSessionData | null;\n};\nexport type AuthRequestContext = RawAuthRequestContext & {\n organization?: { activeOrganizationId?: string | null } | null;\n apiKey?: { id: string; permissions?: Record<string, string[]> | null } | null;\n};\nexport type AuthActiveMember = RawAuthActiveMember;\nexport type AuthBaseSession = BaseAuth[\"$Infer\"][\"Session\"];\nexport type AuthContractType = AuthContract;\n`;\n}\n\nfunction toRelativeImportPath(fromPath: string, toPath: string): string {\n const rel = relative(dirname(toPath), fromPath);\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport async function runBunInstall(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--ignore-scripts\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runBunInstallForUpgrade(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n await runWithProgress(\n \"bun\",\n [\"install\", \"--force\"],\n destination,\n spinner,\n \"Installing dependencies\",\n );\n}\n\nexport async function runTypesGen(\n destination: string,\n spinner?: { message: (msg: string) => void },\n): Promise<void> {\n const localBosBin = join(destination, \"node_modules\", \".bin\", \"bos\");\n if (existsSync(localBosBin)) {\n await runWithProgress(\n \"node_modules/.bin/bos\",\n [\"types\", \"gen\"],\n destination,\n spinner,\n \"Generating types\",\n );\n return;\n }\n\n throw new Error(\"Unable to locate bos CLI for types generation\");\n}\n\nexport async function runDockerComposeUp(destination: string): Promise<void> {\n await execCommand(\"docker\", [\"compose\", \"up\", \"-d\", \"--wait\"], destination, { stdio: \"inherit\" });\n}\n\nasync function runWithProgress(\n command: string,\n args: string[],\n cwd: string,\n spinner: { message: (msg: string) => void } | undefined,\n label: string,\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n const child = execa(command, args, { cwd, stdio: \"inherit\", timeout });\n\n if (spinner) {\n const start = Date.now();\n const interval = setInterval(() => {\n const elapsed = Math.round((Date.now() - start) / 1000);\n spinner.message(`${label}... (${elapsed}s)`);\n }, 2000);\n try {\n await child;\n } finally {\n clearInterval(interval);\n }\n } else {\n await child;\n }\n}\n\nexport function stripOrphanedWorkspacesFromLockfile(\n lockfilePath: string,\n allowedWorkspaces: string[],\n): void {\n if (!existsSync(lockfilePath)) return;\n\n const content = readFileSync(lockfilePath, \"utf-8\");\n let lockfile: Record<string, unknown>;\n try {\n lockfile = JSON.parse(content) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const workspaces = lockfile.workspaces;\n if (!workspaces || typeof workspaces !== \"object\") return;\n\n const workspaceMap = workspaces as Record<string, unknown>;\n const allowed = new Set([\"\", ...allowedWorkspaces]);\n\n const keys = Object.keys(workspaceMap);\n let changed = false;\n for (const key of keys) {\n if (allowed.has(key)) continue;\n if (\n allowedWorkspaces.some(\n (pattern) => pattern.endsWith(\"/*\") && key.startsWith(pattern.slice(0, -1)),\n )\n )\n continue;\n delete workspaceMap[key];\n changed = true;\n }\n\n if (changed) {\n writeFileSync(lockfilePath, `${JSON.stringify(lockfile, null, 2)}\\n`);\n }\n}\n\nexport function removeInitLockfile(lockfilePath: string): void {\n if (!existsSync(lockfilePath)) return;\n rmSync(lockfilePath, { force: true });\n}\n\nfunction readJsonFile<T>(filePath: string): T {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n}\n\nexport async function scaffoldMinimalProject(\n destination: string,\n parentConfig: BosConfigInput,\n opts: {\n extendsAccount: string;\n extendsGateway: string;\n account?: string;\n domain?: string;\n plugins?: string[];\n overrides: OverrideSection[];\n repository?: string;\n title?: string;\n description?: string;\n },\n): Promise<number> {\n mkdirSync(destination, { recursive: true });\n\n const has = (section: OverrideSection) => opts.overrides.includes(section);\n\n const config: Record<string, unknown> = {\n extends: `bos://${opts.extendsAccount}/${opts.extendsGateway}`,\n account: opts.account || opts.extendsAccount,\n ...(opts.domain ? { domain: opts.domain } : {}),\n ...(opts.repository ? { repository: opts.repository } : {}),\n ...(opts.title ? { title: opts.title } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n };\n\n if (parentConfig.app && typeof parentConfig.app === \"object\") {\n const app: Record<string, unknown> = {};\n const parentApp = parentConfig.app as Record<string, Record<string, unknown>>;\n\n if (has(\"host\") && parentApp.host) {\n app.host = { ...parentApp.host };\n stripProductionFields(app.host as Record<string, unknown>);\n }\n\n if (has(\"ui\") && parentApp.ui) {\n app.ui = { ...parentApp.ui };\n stripProductionFields(app.ui as Record<string, unknown>);\n }\n\n if (has(\"api\") && parentApp.api) {\n app.api = { ...parentApp.api };\n stripProductionFields(app.api as Record<string, unknown>);\n }\n\n if (Object.keys(app).length > 0) {\n config.app = app;\n }\n }\n\n if (has(\"plugins\") && opts.plugins && opts.plugins.length > 0 && parentConfig.plugins) {\n const plugins: Record<string, unknown> = {};\n for (const key of opts.plugins) {\n const parentPlugin = (parentConfig.plugins as Record<string, unknown>)?.[key];\n if (parentPlugin) {\n if (typeof parentPlugin === \"string\") {\n plugins[key] = { extends: parentPlugin };\n } else {\n const pluginCopy = { ...(parentPlugin as Record<string, unknown>) };\n stripProductionFields(pluginCopy);\n plugins[key] = pluginCopy;\n }\n }\n }\n config.plugins = plugins;\n } else if (has(\"plugins\")) {\n config.plugins = {};\n }\n\n await saveBosConfig(destination, config);\n\n const workspacePackages: string[] = [];\n for (const section of opts.overrides) {\n workspacePackages.push(...OVERRIDE_WORKSPACE_MAP[section]);\n }\n if (has(\"plugins\")) {\n workspacePackages.push(\"plugins/*\");\n }\n\n const catalog = (\n await resolveCatalogChainSource({\n extendsAccount: opts.extendsAccount,\n extendsGateway: opts.extendsGateway,\n })\n ).catalog;\n\n const pkg: Record<string, unknown> = {\n name: \"monorepo\",\n private: true,\n type: \"module\",\n scripts: buildChildRootScripts({\n ui: has(\"ui\"),\n api: has(\"api\"),\n host: has(\"host\"),\n plugins: has(\"plugins\"),\n }),\n dependencies: {\n \"everything-dev\": \"catalog:\",\n \"every-plugin\": \"catalog:\",\n },\n devDependencies: {},\n workspaces: {\n packages: workspacePackages,\n catalog,\n },\n };\n writeFileSync(join(destination, \"package.json\"), `${JSON.stringify(pkg, null, 2)}\\n`);\n\n writeFileSync(join(destination, \".gitignore\"), generateGitignore());\n\n return 4;\n}\n\nasync function resolveWorkspaceRefs(\n destination: string,\n options?: { localOverrides?: boolean; sourceDir?: string },\n): Promise<void> {\n await normalizePackageManifestsInTree({\n sourceRootDir: options?.sourceDir ?? destination,\n targetDir: destination,\n resolveCatalogRefs: false,\n preserveCatalogRefs: true,\n removeWorkspaceDeps: [\"host\"],\n });\n}\n\nexport async function writeInitSnapshot(\n destination: string,\n extendsAccount: string,\n extendsGateway: string,\n sourceDir: string,\n patterns: string[],\n _options: {\n overrides: OverrideSection[];\n plugins?: string[];\n },\n): Promise<void> {\n const allFiles = new Set<string>();\n for (const pattern of patterns) {\n const matches = await glob(pattern, {\n cwd: sourceDir,\n nodir: true,\n dot: true,\n absolute: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"],\n });\n for (const match of matches) {\n allFiles.add(match);\n }\n }\n\n const fileHashes: Record<string, string> = {};\n for (const filePath of allFiles) {\n const src = join(sourceDir, filePath);\n const stat = lstatSync(src);\n if (!stat.isFile()) continue;\n const content = readFileSync(src);\n const destPath = sourcePathToDestinationPath(filePath);\n fileHashes[destPath] = computeHash(content);\n }\n\n await writeSnapshot(destination, {\n parentRef: `bos://${extendsAccount}/${extendsGateway}`,\n files: fileHashes,\n });\n}\n\nfunction computeHash(data: Uint8Array): string {\n return createHash(\"sha256\").update(data).digest(\"hex\").substring(0, 16);\n}\n\nfunction mkTmpDir(prefix: string): string {\n return mkdtempSync(join(tmpdir(), `${prefix}-`));\n}\n\nexport async function generateDatabaseMigrations(destination: string): Promise<void> {\n const drizzleConfigs = await glob(\"**/drizzle.config.ts\", {\n cwd: destination,\n nodir: true,\n dot: false,\n absolute: false,\n ignore: [\"**/node_modules/**\"],\n });\n\n for (const configPath of drizzleConfigs) {\n const workspaceDir = dirname(configPath);\n const pkgPath = join(destination, workspaceDir, \"package.json\");\n if (!existsSync(pkgPath)) continue;\n\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n const scripts = pkg.scripts as Record<string, string> | undefined;\n if (!scripts?.[\"db:generate\"]) continue;\n\n const cwd = join(destination, workspaceDir);\n await execCommand(\"bun\", [\"run\", \"db:generate\"], cwd);\n }\n}\n\nconst COMMAND_TIMEOUTS: Record<string, number> = {\n bun: 5 * 60_000,\n docker: 5 * 60_000,\n node_modules: 2 * 60_000,\n tar: 60_000,\n};\n\nexport async function execCommand(\n command: string,\n args: string[],\n cwd?: string,\n options?: { stdio?: \"pipe\" | \"inherit\" },\n): Promise<void> {\n const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n await execa(command, args, { cwd, stdio: options?.stdio ?? \"pipe\", timeout });\n}\n\nfunction generateGitignore(): string {\n return `node_modules/\ndist/\n.env\n.bos/\ndocker-compose.yml\n*.gen.ts\n*.gen.tsx\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAE9C,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,yBAA4D;CAChE,IAAI,CAAC,KAAK;CACV,KAAK,CAAC,MAAM;CACZ,MAAM,CAAC,OAAO;CACd,SAAS,EAAE;CACZ;AAcD,SAAS,cAAc,QAAqD;AAC1E,KAAI,OAAO,OAAO,YAAY,SAC5B,QAAO,OAAO;AAGhB,KAAI,OAAO,WAAW,OAAO,OAAO,YAAY,SAC9C,QAAO,kBAAkB,OAAO,SAAmC,aAAa;;AAMpF,SAAS,YAAY,KAA0D;CAC7E,MAAM,QAAQ,IAAI,MAAM,0BAA0B;AAClD,KAAI,CAAC,QAAQ,MAAM,CAAC,MAAM,GAAI,QAAO;AACrC,QAAO;EAAE,SAAS,MAAM;EAAI,SAAS,MAAM;EAAI;;AAGjD,SAAS,qBAAqB,WAA2C;CACvE,MAAM,UAAU,KAAK,WAAW,eAAe;AAC/C,KAAI,CAAC,WAAW,QAAQ,CACtB,QAAO,EAAE;AAIX,QAAO,EAAE,GADG,aAAoE,QAChE,CAAC,YAAY,WAAW,EAAE,EAAG;;AAG/C,eAAsB,0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A4B,SAAS;AACtD,aAAW,YAAY,YAAY,QAAQ;;AAG7C,OAAM,cAAc,aAAa;EAC/B,WAAW,SAAS,eAAe,GAAG;EACtC,OAAO;EACR,CAAC;;AAGJ,SAAS,YAAY,MAA0B;AAC7C,QAAO,WAAW,SAAS,CAAC,OAAO,KAAK,CAAC,OAAO,MAAM,CAAC,UAAU,GAAG,GAAG;;AAGzE,SAAS,SAAS,QAAwB;AACxC,QAAO,YAAY,KAAK,QAAQ,EAAE,GAAG,OAAO,GAAG,CAAC;;AAGlD,eAAsB,2BAA2B,aAAoC;CACnF,MAAM,iBAAiB,MAAM,KAAK,wBAAwB;EACxD,KAAK;EACL,OAAO;EACP,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,qBAAqB;EAC/B,CAAC;AAEF,MAAK,MAAM,cAAc,gBAAgB;EACvC,MAAM,eAAe,QAAQ,WAAW;EACxC,MAAM,UAAU,KAAK,aAAa,cAAc,eAAe;AAC/D,MAAI,CAAC,WAAW,QAAQ,CAAE;AAI1B,MAAI,CAFQ,KAAK,MAAM,aAAa,SAAS,QAAQ,CAClC,CAAC,UACL,eAAgB;AAG/B,QAAM,YAAY,OAAO,CAAC,OAAO,cAAc,EADnC,KAAK,aAAa,aACsB,CAAC;;;AAIzD,MAAM,mBAA2C;CAC/C,KAAK,IAAI;CACT,QAAQ,IAAI;CACZ,cAAc,IAAI;CAClB,KAAK;CACN;AAED,eAAsB,YACpB,SACA,MACA,KACA,SACe;CACf,MAAM,UAAU,iBAAiB,YAAY,IAAI;AACjD,OAAM,MAAM,SAAS,MAAM;EAAE;EAAK,OAAO,SAAS,SAAS;EAAQ;EAAS,CAAC;;AAG/E,SAAS,oBAA4B;AACnC,QAAO"}
@@ -489,8 +489,8 @@ declare const StatusResultSchema: z.ZodObject<{
489
489
  }, z.core.$strip>;
490
490
  declare const TypesGenOptionsSchema: z.ZodObject<{
491
491
  env: z.ZodOptional<z.ZodEnum<{
492
- development: "development";
493
492
  production: "production";
493
+ development: "development";
494
494
  }>>;
495
495
  dryRun: z.ZodDefault<z.ZodBoolean>;
496
496
  }, z.core.$strip>;
@@ -963,8 +963,8 @@ declare const bosContract: {
963
963
  }, z.core.$strip>, _$_orpc_contract0.MergedErrorMap<Record<never, never>, Record<never, never>>, Record<never, never>>;
964
964
  typesGen: _$_orpc_contract0.ContractProcedure<z.ZodObject<{
965
965
  env: z.ZodOptional<z.ZodEnum<{
966
- development: "development";
967
966
  production: "production";
967
+ development: "development";
968
968
  }>>;
969
969
  dryRun: z.ZodDefault<z.ZodBoolean>;
970
970
  }, z.core.$strip>, z.ZodObject<{
@@ -489,8 +489,8 @@ declare const StatusResultSchema: z.ZodObject<{
489
489
  }, z.core.$strip>;
490
490
  declare const TypesGenOptionsSchema: z.ZodObject<{
491
491
  env: z.ZodOptional<z.ZodEnum<{
492
- development: "development";
493
492
  production: "production";
493
+ development: "development";
494
494
  }>>;
495
495
  dryRun: z.ZodDefault<z.ZodBoolean>;
496
496
  }, z.core.$strip>;
@@ -963,8 +963,8 @@ declare const bosContract: {
963
963
  }, z.core.$strip>, _$_orpc_contract0.MergedErrorMap<Record<never, never>, Record<never, never>>, Record<never, never>>;
964
964
  typesGen: _$_orpc_contract0.ContractProcedure<z.ZodObject<{
965
965
  env: z.ZodOptional<z.ZodEnum<{
966
- development: "development";
967
966
  production: "production";
967
+ development: "development";
968
968
  }>>;
969
969
  dryRun: z.ZodDefault<z.ZodBoolean>;
970
970
  }, z.core.$strip>, z.ZodObject<{
package/dist/plugin.d.cts CHANGED
@@ -495,8 +495,8 @@ declare const _default: _$every_plugin0.LoadedPluginWithBinding<{
495
495
  }, z.core.$strip>, _$_orpc_contract0.MergedErrorMap<Record<never, never>, Record<never, never>>, Record<never, never>>;
496
496
  typesGen: _$_orpc_contract0.ContractProcedure<z.ZodObject<{
497
497
  env: z.ZodOptional<z.ZodEnum<{
498
- development: "development";
499
498
  production: "production";
499
+ development: "development";
500
500
  }>>;
501
501
  dryRun: z.ZodDefault<z.ZodBoolean>;
502
502
  }, z.core.$strip>, z.ZodObject<{
@@ -645,7 +645,7 @@ declare const _default: _$every_plugin0.LoadedPluginWithBinding<{
645
645
  }> | undefined;
646
646
  } | null;
647
647
  runtimeConfig: {
648
- env: "development" | "production" | "staging";
648
+ env: "production" | "development" | "staging";
649
649
  account: string;
650
650
  networkId: "testnet" | "mainnet";
651
651
  host: {
package/dist/plugin.d.mts CHANGED
@@ -495,8 +495,8 @@ declare const _default: _$every_plugin0.LoadedPluginWithBinding<{
495
495
  }, z.core.$strip>, _$_orpc_contract0.MergedErrorMap<Record<never, never>, Record<never, never>>, Record<never, never>>;
496
496
  typesGen: _$_orpc_contract0.ContractProcedure<z.ZodObject<{
497
497
  env: z.ZodOptional<z.ZodEnum<{
498
- development: "development";
499
498
  production: "production";
499
+ development: "development";
500
500
  }>>;
501
501
  dryRun: z.ZodDefault<z.ZodBoolean>;
502
502
  }, z.core.$strip>, z.ZodObject<{
@@ -645,7 +645,7 @@ declare const _default: _$every_plugin0.LoadedPluginWithBinding<{
645
645
  }> | undefined;
646
646
  } | null;
647
647
  runtimeConfig: {
648
- env: "development" | "production" | "staging";
648
+ env: "production" | "development" | "staging";
649
649
  account: string;
650
650
  networkId: "testnet" | "mainnet";
651
651
  host: {
package/dist/types.d.cts CHANGED
@@ -466,8 +466,8 @@ declare const BosConfigSchema: z.ZodObject<{
466
466
  type BosConfig = z.infer<typeof BosConfigSchema>;
467
467
  declare const RuntimeConfigSchema: z.ZodObject<{
468
468
  env: z.ZodEnum<{
469
- development: "development";
470
469
  production: "production";
470
+ development: "development";
471
471
  staging: "staging";
472
472
  }>;
473
473
  account: z.ZodString;
@@ -613,8 +613,8 @@ declare const RuntimeConfigSchema: z.ZodObject<{
613
613
  type RuntimeConfig = z.infer<typeof RuntimeConfigSchema>;
614
614
  declare const ClientRuntimeConfigSchema: z.ZodObject<{
615
615
  env: z.ZodEnum<{
616
- development: "development";
617
616
  production: "production";
617
+ development: "development";
618
618
  staging: "staging";
619
619
  }>;
620
620
  account: z.ZodString;
package/dist/types.d.mts CHANGED
@@ -466,8 +466,8 @@ declare const BosConfigSchema: z.ZodObject<{
466
466
  type BosConfig = z.infer<typeof BosConfigSchema>;
467
467
  declare const RuntimeConfigSchema: z.ZodObject<{
468
468
  env: z.ZodEnum<{
469
- development: "development";
470
469
  production: "production";
470
+ development: "development";
471
471
  staging: "staging";
472
472
  }>;
473
473
  account: z.ZodString;
@@ -613,8 +613,8 @@ declare const RuntimeConfigSchema: z.ZodObject<{
613
613
  type RuntimeConfig = z.infer<typeof RuntimeConfigSchema>;
614
614
  declare const ClientRuntimeConfigSchema: z.ZodObject<{
615
615
  env: z.ZodEnum<{
616
- development: "development";
617
616
  production: "production";
617
+ development: "development";
618
618
  staging: "staging";
619
619
  }>;
620
620
  account: z.ZodString;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "everything-dev",
3
- "version": "1.35.2",
3
+ "version": "1.35.3",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -10,8 +10,8 @@ metadata:
10
10
  ## Starting Development
11
11
 
12
12
  ```bash
13
- # Typical: remote host, local UI + API
14
- bos dev --host remote
13
+ # Typical: start development (host mode auto-detected)
14
+ bos dev
15
15
 
16
16
  # Isolate work
17
17
  bos dev --api remote # UI only
@@ -49,7 +49,7 @@ The orchestrator:
49
49
 
50
50
  - **UI changes**: Rsbuild HMR — instant at :3003, no rebuild
51
51
  - **API changes**: Rspack HMR — instant at :3001, no rebuild
52
- - **Config changes**: Require host restart (`bos kill && bos dev --host remote`)
52
+ - **Config changes**: Require host restart (`bos kill && bos dev`)
53
53
 
54
54
  ## Contract Sync & Type Generation
55
55
 
@@ -159,5 +159,5 @@ Process issues:
159
159
  ```bash
160
160
  bos kill # Kill all tracked processes
161
161
  bun install # Reinstall deps
162
- bos dev --host remote # Restart
162
+ bos dev # Restart
163
163
  ```
@@ -134,14 +134,14 @@ The tenant config must:
134
134
  For the base runtime:
135
135
 
136
136
  ```bash
137
- bos dev --host remote
137
+ bos dev
138
138
  bos publish --deploy
139
139
  ```
140
140
 
141
141
  For a shared-host child UI app:
142
142
 
143
143
  ```bash
144
- bos dev --host remote --api remote
144
+ bos dev --api remote
145
145
  bos publish --deploy
146
146
  ```
147
147