@gadicc/loom 1.33.0 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,7 @@ import { filesR2PolicyIssues, parseWranglerR2Cors, r2CorsMatchesPolicy, } from "
12
12
  import { resolveProductionBranch, } from "./releaseConfig.js";
13
13
  import { configureGithubVercelReleaseCredential, } from "./releaseCredentials.js";
14
14
  import { runGithubReleaseTrustCommand } from "./releaseTrustCommand.js";
15
+ import { checkLocalDatabase, setupLocalDatabase } from "./localDb.js";
15
16
  import { DEFAULT_API_KEY_AUDIT_RETENTION } from "../apiKeys/retention.js";
16
17
  import { checkProjectSkills, getProjectSkillStatus, LOOM_EXTERNAL_SKILLS_GITIGNORE_LINE, removeLegacyNextSkillLink, setProjectSkillDisabled, syncExternalProjectSkills, syncInstalledPackageSkills, } from "./projectSkills.js";
17
18
  import { resolveMigrationEnvironment, resolveMigrationEnvironmentFromEnvFile, verifyMigrationConnection, verifyMigrationConnectionFromEnvFile, } from "./migrationEnv.js";
@@ -5986,32 +5987,66 @@ async function promptForVercelSecret(cwd, commandRunner, env, vercelCommand, nam
5986
5987
  }
5987
5988
  const VERCEL_FILES_ENV_PROBE_SCRIPT = "process.stdout.write(JSON.stringify({FILES_S3_BUCKET:process.env.FILES_S3_BUCKET,FILES_S3_ENDPOINT:process.env.FILES_S3_ENDPOINT,FILES_S3_FORCE_PATH_STYLE:process.env.FILES_S3_FORCE_PATH_STYLE,FILES_S3_REGION:process.env.FILES_S3_REGION,FILES_STORAGE_PROVIDER:process.env.FILES_STORAGE_PROVIDER}))";
5988
5989
  /** Builds the Vercel env-run probe that prints only non-secret Files values. */
5989
- export function buildVercelFilesEnvProbeArgs(environment) {
5990
+ export function buildVercelFilesEnvProbeArgs(environment, project) {
5990
5991
  return [
5992
+ ...(project ? ["--scope", project.orgId] : []),
5991
5993
  "env",
5992
5994
  "run",
5993
5995
  "-e",
5994
5996
  environment,
5997
+ ...(project ? ["--project", project.projectId] : []),
5995
5998
  "--",
5996
5999
  "node",
5997
6000
  "-e",
5998
6001
  VERCEL_FILES_ENV_PROBE_SCRIPT,
5999
6002
  ];
6000
6003
  }
6004
+ function buildVercelFilesEnvListArgs(environment, project) {
6005
+ return [
6006
+ "--scope",
6007
+ project.orgId,
6008
+ "env",
6009
+ "ls",
6010
+ environment,
6011
+ "--project",
6012
+ project.projectId,
6013
+ ];
6014
+ }
6015
+ function withoutInheritedVercelProject(env) {
6016
+ const result = { ...env };
6017
+ delete result.VERCEL_ORG_ID;
6018
+ delete result.VERCEL_PROJECT_ID;
6019
+ return result;
6020
+ }
6001
6021
  async function readVercelFilesNonSecretValues(cwd, commandRunner, env, vercelCommand, environment) {
6002
- const result = await commandRunner(vercelCommand, buildVercelFilesEnvProbeArgs(environment), { cwd, env, stdio: "pipe" });
6003
- if (result.code !== 0)
6004
- return null;
6005
- const jsonLine = normalizeText(result.stdout).split("\n").findLast((line) => line.trim().startsWith("{"));
6006
- if (!jsonLine)
6022
+ const link = await readVercelProjectLink(cwd);
6023
+ if (!link.linked || !link.orgId || !link.projectId)
6007
6024
  return null;
6025
+ const probeEnv = withoutInheritedVercelProject(env);
6026
+ for (const name of Object.keys(probeEnv)) {
6027
+ if (name.startsWith("FILES_"))
6028
+ delete probeEnv[name];
6029
+ }
6030
+ const probeCwd = await mkdtemp(join(tmpdir(), "loom-vercel-files-probe-"));
6008
6031
  try {
6032
+ // Vercel env run loads .env.local from cwd and preserves inherited values.
6033
+ // Probe the linked project from an empty directory so local MinIO cannot
6034
+ // masquerade as remote R2 drift.
6035
+ const result = await commandRunner(vercelCommand, buildVercelFilesEnvProbeArgs(environment, link), { cwd: probeCwd, env: probeEnv, stdio: "pipe" });
6036
+ if (result.code !== 0)
6037
+ return null;
6038
+ const jsonLine = normalizeText(result.stdout).split("\n").findLast((line) => line.trim().startsWith("{"));
6039
+ if (!jsonLine)
6040
+ return null;
6009
6041
  const parsed = JSON.parse(jsonLine);
6010
6042
  return isJsonObject(parsed) ? parsed : null;
6011
6043
  }
6012
6044
  catch {
6013
6045
  return null;
6014
6046
  }
6047
+ finally {
6048
+ await rm(probeCwd, { recursive: true, force: true });
6049
+ }
6015
6050
  }
6016
6051
  async function detectMinioClient(cwd, commandRunner, env) {
6017
6052
  for (const command of ["mcli", "mc"]) {
@@ -6060,9 +6095,11 @@ async function ensureMinioBucket(cwd, commandRunner, env, endpoint, bucket, acce
6060
6095
  ok: false,
6061
6096
  };
6062
6097
  }
6063
- async function promptForLocalFilesValue(question, secret = false) {
6098
+ async function promptForLocalFilesValue(question, secret = false, context = "MinIO") {
6064
6099
  if (!process.stdin.isTTY) {
6065
- throw new Error("MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment.");
6100
+ throw new Error(context === "MinIO"
6101
+ ? "MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment."
6102
+ : "PostgreSQL admin credentials are required. Run interactively or set LOOM_DB_LOCAL_ADMIN_PASSWORD in the command environment.");
6066
6103
  }
6067
6104
  if (!secret) {
6068
6105
  const input = createInterface({
@@ -6094,7 +6131,7 @@ async function promptForLocalFilesValue(question, secret = false) {
6094
6131
  }
6095
6132
  if (character === "\u0003") {
6096
6133
  stdin.off("data", onData);
6097
- rejectPromise(new Error("MinIO setup was cancelled."));
6134
+ rejectPromise(new Error(`${context} setup was cancelled.`));
6098
6135
  return;
6099
6136
  }
6100
6137
  if (character === "\u007f" || character === "\b") {
@@ -7575,6 +7612,7 @@ function checkFilesNetworkFeature(context) {
7575
7612
  accountAvailable: false,
7576
7613
  vercelCommand: null,
7577
7614
  vercelLinked: false,
7615
+ vercelProject: null,
7578
7616
  wranglerCommand: null,
7579
7617
  };
7580
7618
  const providerEnv = {
@@ -7724,6 +7762,9 @@ function checkFilesNetworkFeature(context) {
7724
7762
  state.vercelCommand = detected.command;
7725
7763
  const link = await readVercelProjectLink(context.cwd);
7726
7764
  state.vercelLinked = link.linked;
7765
+ state.vercelProject = link.linked && link.orgId && link.projectId
7766
+ ? { orgId: link.orgId, projectId: link.projectId }
7767
+ : null;
7727
7768
  if (!state.vercelCommand || !state.vercelLinked) {
7728
7769
  return networkCheckResult("issue", !state.vercelCommand ? "Vercel CLI is unavailable." : link.detail, {
7729
7770
  issues: [
@@ -7753,10 +7794,14 @@ function checkFilesNetworkFeature(context) {
7753
7794
  steps.push({
7754
7795
  label: `Vercel ${environment} has all Files R2 variables`,
7755
7796
  run: async () => {
7756
- if (!state.vercelCommand || !state.vercelLinked) {
7797
+ if (!state.vercelCommand || !state.vercelLinked || !state.vercelProject) {
7757
7798
  return networkCheckResult("skipped", "Skipped until Vercel CLI/link checks pass.");
7758
7799
  }
7759
- const result = await context.commandRunner(state.vercelCommand, ["env", "ls", environment], { cwd: context.cwd, env: context.env, stdio: "pipe" });
7800
+ const result = await context.commandRunner(state.vercelCommand, buildVercelFilesEnvListArgs(environment, state.vercelProject), {
7801
+ cwd: context.cwd,
7802
+ env: withoutInheritedVercelProject(context.env),
7803
+ stdio: "pipe",
7804
+ });
7760
7805
  if (result.code !== 0) {
7761
7806
  return networkCheckResult("warning", `Could not list Vercel ${environment} env vars.`, {
7762
7807
  warnings: [
@@ -7784,7 +7829,7 @@ function checkFilesNetworkFeature(context) {
7784
7829
  `Could not inspect non-secret Files values in Vercel ${environment}.`,
7785
7830
  ],
7786
7831
  suggestions: [
7787
- `Run \`vercel env run -e ${environment} -- node -e '<inspect only FILES_S3_BUCKET/ENDPOINT/provider settings>'\` manually without printing credentials.`,
7832
+ `Run a non-secret Files probe from a temporary directory with \`vercel env run -e ${environment} --project <linked-project> --scope <linked-scope> -- node -e '<inspect only FILES_S3_BUCKET/ENDPOINT/provider settings>'\`.`,
7788
7833
  ],
7789
7834
  });
7790
7835
  }
@@ -7811,10 +7856,14 @@ function checkFilesNetworkFeature(context) {
7811
7856
  steps.push({
7812
7857
  label: "Vercel Development has no R2 Files credentials",
7813
7858
  run: async () => {
7814
- if (!state.vercelCommand || !state.vercelLinked) {
7859
+ if (!state.vercelCommand || !state.vercelLinked || !state.vercelProject) {
7815
7860
  return networkCheckResult("skipped", "Skipped until Vercel CLI/link checks pass.");
7816
7861
  }
7817
- const result = await context.commandRunner(state.vercelCommand, ["env", "ls", "development"], { cwd: context.cwd, env: context.env, stdio: "pipe" });
7862
+ const result = await context.commandRunner(state.vercelCommand, buildVercelFilesEnvListArgs("development", state.vercelProject), {
7863
+ cwd: context.cwd,
7864
+ env: withoutInheritedVercelProject(context.env),
7865
+ stdio: "pipe",
7866
+ });
7818
7867
  if (result.code !== 0) {
7819
7868
  return networkCheckResult("warning", "Could not list Vercel Development env vars.");
7820
7869
  }
@@ -11222,6 +11271,7 @@ function printHelp({ out }) {
11222
11271
  out(" db fixtures Run the Loom-managed DB fixture dump script for the active DB feature.");
11223
11272
  out(" db schema-gen Run the Loom-managed Valibot generator workflow for the active DB feature. Pass extra generator args after `--`.");
11224
11273
  out(" db schemas sync Materialize active Loom-managed DB schema blueprints into app-local schema files.");
11274
+ out(" db local setup|check Provision or verify a restricted project database on existing local PostgreSQL.");
11225
11275
  out(" db neon setup Provision and connect a Vercel-managed Neon database for Production and Preview.");
11226
11276
  out(" db neon check Run the DB/Neon network checks registered for the active DB feature.");
11227
11277
  out(" db migrations verify-env Validate migration URL precedence and role metadata without printing credentials. Add --connect for a live access preflight.");
@@ -11244,6 +11294,9 @@ function printHelp({ out }) {
11244
11294
  out(" --network Run registered network checks after the local project checks.");
11245
11295
  out(" --production Treat local Loom dev overrides and local lockfile resolutions as release-blocking check failures.");
11246
11296
  out(" --no-progress Disable the interactive network progress renderer.");
11297
+ out(" --local-db-host <host> Local PostgreSQL host (default: db.localtest.me).");
11298
+ out(" --local-db-port <port> Local PostgreSQL port (default: 5432).");
11299
+ out(" --replace-local-target Replace an existing development URL during local DB setup.");
11247
11300
  out(" --no-color Disable colored CLI output.");
11248
11301
  out(" --no-sync Skip automatic local-dev package sync.");
11249
11302
  out(" --force Force `loom dev sync` to rebuild and reinstall.");
@@ -12011,6 +12064,27 @@ async function runDb(cwd, command, args, io, options = {}) {
12011
12064
  return 1;
12012
12065
  }
12013
12066
  switch (command) {
12067
+ case "local": {
12068
+ const localOptions = {
12069
+ commandRunner: defaultCommandRunner,
12070
+ host: options.localDbHost,
12071
+ port: options.localDbPort,
12072
+ replaceLocalTarget: options.replaceLocalTarget,
12073
+ promptSecret: async (question) => await promptForLocalFilesValue(question, true, "PostgreSQL"),
12074
+ };
12075
+ if (args[0] === "setup") {
12076
+ const result = await setupLocalDatabase(cwd, localOptions);
12077
+ io.out(`Local PostgreSQL is ready: ${result.database} at ${result.host}:${result.port}.`);
12078
+ return 0;
12079
+ }
12080
+ if (args[0] === "check") {
12081
+ const result = await checkLocalDatabase(cwd, localOptions);
12082
+ io.out(`Local PostgreSQL check passed: ${result.database} as ${result.role}.`);
12083
+ return 0;
12084
+ }
12085
+ io.err("Usage: loom db local setup|check");
12086
+ return 1;
12087
+ }
12014
12088
  case "fixtures":
12015
12089
  return await runDbFixtures(cwd, args);
12016
12090
  case "schema-gen":
@@ -12175,6 +12249,8 @@ export async function runCli(args = process.argv.slice(2), io = {
12175
12249
  help: { short: "h", type: "boolean" },
12176
12250
  jurisdiction: { type: "string" },
12177
12251
  "local-bucket": { type: "string" },
12252
+ "local-db-host": { type: "string" },
12253
+ "local-db-port": { type: "string" },
12178
12254
  "local-endpoint": { type: "string" },
12179
12255
  "local-provider": { type: "string" },
12180
12256
  "location-hint": { type: "string" },
@@ -12191,6 +12267,7 @@ export async function runCli(args = process.argv.slice(2), io = {
12191
12267
  "production-bucket": { type: "string" },
12192
12268
  "preview-bucket": { type: "string" },
12193
12269
  repair: { type: "boolean" },
12270
+ "replace-local-target": { type: "boolean" },
12194
12271
  region: { type: "string" },
12195
12272
  resource: { type: "string" },
12196
12273
  "strict-skills": { type: "boolean" },
@@ -12277,6 +12354,9 @@ export async function runCli(args = process.argv.slice(2), io = {
12277
12354
  case "db":
12278
12355
  return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
12279
12356
  connect: parsed.values.connect,
12357
+ localDbHost: parsed.values["local-db-host"],
12358
+ localDbPort: parsed.values["local-db-port"],
12359
+ replaceLocalTarget: parsed.values["replace-local-target"],
12280
12360
  name: parsed.values.name,
12281
12361
  environment: parsed.values.environment,
12282
12362
  envFile: parsed.values["env-file"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gadicc/loom",
3
- "version": "1.33.0",
3
+ "version": "1.34.0",
4
4
  "description": "Deno-first shared helpers for extracting common Next.js app code.",
5
5
  "homepage": "https://github.com/gadicc/loom#readme",
6
6
  "repository": {
@@ -244,7 +244,7 @@
244
244
  },
245
245
  "scripts": {},
246
246
  "loom": {
247
- "gitCommit": "842f835dc4fb04467f435a509e5723b6c4a0ccab"
247
+ "gitCommit": "693de7acf98e6502a9986742695a3996b49d4d9a"
248
248
  },
249
249
  "bin": {
250
250
  "loom": "script/bin/loom.js"
@@ -0,0 +1,28 @@
1
+ import type { CommandRunner } from "./mod.js";
2
+ type LocalDbOptions = {
3
+ commandRunner: CommandRunner;
4
+ env?: Record<string, string | undefined>;
5
+ host?: string;
6
+ port?: string;
7
+ replaceLocalTarget?: boolean;
8
+ promptSecret?: (question: string) => Promise<string>;
9
+ resolveHost?: (host: string) => Promise<Array<{
10
+ address: string;
11
+ }>>;
12
+ };
13
+ /** Check all configured URL candidates and authenticate as the restricted project role. */
14
+ export declare function checkLocalDatabase(cwd: string, options: LocalDbOptions): Promise<{
15
+ database: string;
16
+ role: string;
17
+ host: string;
18
+ port: string;
19
+ }>;
20
+ /** Provision one project database and role on an existing local PostgreSQL server. */
21
+ export declare function setupLocalDatabase(cwd: string, options: LocalDbOptions): Promise<{
22
+ database: string;
23
+ role: string;
24
+ host: string;
25
+ port: string;
26
+ }>;
27
+ export {};
28
+ //# sourceMappingURL=localDb.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localDb.d.ts","sourceRoot":"","sources":["../../../src/src/cli/localDb.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAqB9C,KAAK,cAAc,GAAG;IACpB,aAAa,EAAE,aAAa,CAAC;IAC7B,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IACzC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,YAAY,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACrD,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC,CAAC;CACrE,CAAC;AAmPF,2FAA2F;AAC3F,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc;;;;;GA4C5E;AAED,sFAAsF;AACtF,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc;;;;;GA0L5E"}
@@ -0,0 +1,370 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkLocalDatabase = checkLocalDatabase;
4
+ exports.setupLocalDatabase = setupLocalDatabase;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const promises_1 = require("node:dns/promises");
7
+ const promises_2 = require("node:fs/promises");
8
+ const node_path_1 = require("node:path");
9
+ const node_util_1 = require("node:util");
10
+ const URL_NAMES = [
11
+ "DATABASE_URL",
12
+ "DATABASE_URL_UNPOOLED",
13
+ "DATABASE_URL_DIRECT",
14
+ "POSTGRES_URL",
15
+ "POSTGRES_URL_NON_POOLING",
16
+ "MIGRATION_DATABASE_URL",
17
+ "MIGRATION_DATABASE_URL_UNPOOLED",
18
+ ];
19
+ const ROLE_FLAGS = "t|f|f|f|f|f|f";
20
+ const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "db.localtest.me"]);
21
+ function failure(message) {
22
+ throw new Error(`Local PostgreSQL: ${message}`);
23
+ }
24
+ function quote(value) {
25
+ return `'${value.replaceAll("'", "''")}'`;
26
+ }
27
+ function databaseName(project) {
28
+ const name = `${project.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "")}_dev`;
29
+ if (!/^[a-z][a-z0-9_]{2,59}$/.test(name)) {
30
+ failure("project name cannot form a safe local database name.");
31
+ }
32
+ return name;
33
+ }
34
+ function endpoint(host, port) {
35
+ if (!LOCAL_HOSTS.has(host) || !/^[0-9]{1,5}$/.test(port) || Number(port) < 1 ||
36
+ Number(port) > 65535) {
37
+ failure("the PostgreSQL endpoint must be a supported loopback host and valid port.");
38
+ }
39
+ return { host, port };
40
+ }
41
+ async function verifyLoopbackResolution(host, options) {
42
+ let addresses;
43
+ try {
44
+ addresses = await (options.resolveHost ?? ((name) => (0, promises_1.lookup)(name, { all: true })))(host);
45
+ }
46
+ catch {
47
+ failure("could not resolve the local PostgreSQL host.");
48
+ }
49
+ if (!addresses.length ||
50
+ addresses.some(({ address }) => address !== "127.0.0.1" && address !== "::1")) {
51
+ failure("local PostgreSQL host does not resolve exclusively to loopback.");
52
+ }
53
+ }
54
+ function parseDatabaseUrl(value) {
55
+ let url;
56
+ try {
57
+ url = new URL(value);
58
+ }
59
+ catch {
60
+ return failure("invalid local database URL.");
61
+ }
62
+ if (!["postgres:", "postgresql:"].includes(url.protocol) || !url.username ||
63
+ !url.password ||
64
+ !url.pathname.slice(1) || url.hash ||
65
+ (url.search && url.search !== "?sslmode=disable"))
66
+ failure("invalid local database URL.");
67
+ endpoint(url.hostname, url.port || "5432");
68
+ return {
69
+ host: url.hostname,
70
+ port: url.port || "5432",
71
+ database: decodeURIComponent(url.pathname.slice(1)),
72
+ user: decodeURIComponent(url.username),
73
+ password: decodeURIComponent(url.password),
74
+ };
75
+ }
76
+ function assignmentLines(text) {
77
+ const lines = text.split(/\r?\n/);
78
+ const positions = new Map();
79
+ for (const [index, line] of lines.entries()) {
80
+ const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);
81
+ if (!match)
82
+ continue;
83
+ if (positions.has(match[1])) {
84
+ failure(`duplicate ${match[1]} in .env.local.`);
85
+ }
86
+ positions.set(match[1], index);
87
+ }
88
+ return { lines, positions };
89
+ }
90
+ async function localFiles(cwd, runner, env) {
91
+ const manifest = JSON.parse(await (0, promises_2.readFile)((0, node_path_1.join)(cwd, "loom.json"), "utf8"));
92
+ if (manifest.features?.db?.status !== "active") {
93
+ failure("activate the DB feature first.");
94
+ }
95
+ const name = databaseName(manifest.project?.name ?? "");
96
+ const path = (0, node_path_1.join)(cwd, ".env.local");
97
+ const tracked = await runner("git", [
98
+ "ls-files",
99
+ "--error-unmatch",
100
+ "--",
101
+ ".env.local",
102
+ ], { cwd, env, stdio: "pipe" });
103
+ if (tracked.code === 0) {
104
+ failure(".env.local is tracked by Git; refusing to write credentials.");
105
+ }
106
+ if (tracked.code !== 1) {
107
+ failure("could not verify that .env.local is untracked.");
108
+ }
109
+ const ignored = await runner("git", [
110
+ "check-ignore",
111
+ "-q",
112
+ "--",
113
+ ".env.local",
114
+ ], {
115
+ cwd,
116
+ env,
117
+ stdio: "pipe",
118
+ });
119
+ if (ignored.code !== 0) {
120
+ failure(".env.local must be Git ignored before writing credentials.");
121
+ }
122
+ let text = "";
123
+ try {
124
+ const file = await (0, promises_2.lstat)(path);
125
+ if (!file.isFile() || file.isSymbolicLink() || (file.mode & 0o077) !== 0) {
126
+ failure(".env.local must be an owner-only regular file.");
127
+ }
128
+ text = await (0, promises_2.readFile)(path, "utf8");
129
+ }
130
+ catch (error) {
131
+ if (!(error && typeof error === "object" && "code" in error &&
132
+ error.code === "ENOENT"))
133
+ throw error;
134
+ }
135
+ const { lines, positions } = assignmentLines(text);
136
+ const values = (0, node_util_1.parseEnv)(text);
137
+ const migrationDir = manifest.features.db.config?.dirs?.drizzleOutDir ??
138
+ "drizzle";
139
+ if (typeof migrationDir !== "string" || migrationDir.startsWith("/") ||
140
+ migrationDir.split("/").includes("..")) {
141
+ failure("invalid configured Drizzle migration directory.");
142
+ }
143
+ return { name, path, text, lines, positions, values, migrationDir };
144
+ }
145
+ async function requiresUuidV7(cwd, migrationDir) {
146
+ try {
147
+ for (const file of await (0, promises_2.readdir)((0, node_path_1.join)(cwd, migrationDir))) {
148
+ if (file.endsWith(".sql") &&
149
+ (await (0, promises_2.readFile)((0, node_path_1.join)(cwd, migrationDir, file), "utf8")).includes("uuid_generate_v7("))
150
+ return true;
151
+ }
152
+ }
153
+ catch (error) {
154
+ if (!(error && typeof error === "object" && "code" in error &&
155
+ error.code === "ENOENT"))
156
+ throw error;
157
+ }
158
+ return false;
159
+ }
160
+ async function psql(runner, cwd, connection, sql) {
161
+ const result = await runner("psql", [
162
+ "-X",
163
+ "-A",
164
+ "-t",
165
+ "-q",
166
+ "-w",
167
+ "-v",
168
+ "ON_ERROR_STOP=1",
169
+ "-d",
170
+ connection.database,
171
+ ], {
172
+ cwd,
173
+ env: {
174
+ ...process.env,
175
+ LOOM_DB_LOCAL_ADMIN_PASSWORD: undefined,
176
+ PGHOST: connection.host,
177
+ PGPORT: connection.port,
178
+ PGUSER: connection.user,
179
+ PGPASSWORD: connection.password,
180
+ PGSSLMODE: "disable",
181
+ },
182
+ input: sql,
183
+ stdio: "pipe",
184
+ });
185
+ if (result.code !== 0) {
186
+ const errorKind = result.stderr.match(/ERROR:\s*([A-Za-z0-9 .,:_()-]+)/)?.[1]?.trim();
187
+ failure(`connection or SQL check failed${errorKind ? ` (${errorKind})` : ""}; inspect the server without logging credentials.`);
188
+ }
189
+ return result.stdout.trim();
190
+ }
191
+ function appConnection(values, expected, host, port) {
192
+ const configured = URL_NAMES.filter((name) => values[name]);
193
+ if (!values.DATABASE_URL || !values.DATABASE_URL_UNPOOLED) {
194
+ failure("DATABASE_URL and DATABASE_URL_UNPOOLED are required in .env.local.");
195
+ }
196
+ if (configured.some((name) => values[name] !== values.DATABASE_URL)) {
197
+ failure("configured local database URL candidates disagree.");
198
+ }
199
+ const parsed = parseDatabaseUrl(values.DATABASE_URL);
200
+ if (parsed.database !== expected || parsed.user !== expected ||
201
+ parsed.host !== host || parsed.port !== port) {
202
+ failure("local database URL does not select the project database, role, and endpoint.");
203
+ }
204
+ return parsed;
205
+ }
206
+ function targetUrl(connection) {
207
+ return `postgresql://${encodeURIComponent(connection.user)}:${encodeURIComponent(connection.password)}@${connection.host}:${connection.port}/${connection.database}?sslmode=disable`;
208
+ }
209
+ /** Check all configured URL candidates and authenticate as the restricted project role. */
210
+ async function checkLocalDatabase(cwd, options) {
211
+ const env = options.env ?? process.env;
212
+ const { host, port } = endpoint(options.host ?? "db.localtest.me", options.port ?? "5432");
213
+ await verifyLoopbackResolution(host, options);
214
+ const files = await localFiles(cwd, options.commandRunner, env);
215
+ const connection = appConnection(files.values, files.name, host, port);
216
+ const marker = `Loom local development database for ${files.name}`;
217
+ const result = await psql(options.commandRunner, cwd, connection, `
218
+ select concat_ws('|', current_database(), current_user,
219
+ (select pg_get_userbyid(datdba) from pg_database where datname = current_database()),
220
+ (select shobj_description(oid, 'pg_database') from pg_database where datname = current_database()),
221
+ (select concat_ws('|', rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, rolreplication, rolbypassrls)
222
+ from pg_roles where rolname = current_user),
223
+ has_schema_privilege(current_user, 'public', 'USAGE'),
224
+ has_schema_privilege(current_user, 'public', 'CREATE'));
225
+ `);
226
+ if (result !==
227
+ `${files.name}|${files.name}|${files.name}|${marker}|${ROLE_FLAGS}|t|t`) {
228
+ failure("authenticated database identity, owner, marker, or role privileges are unexpected.");
229
+ }
230
+ if (await requiresUuidV7(cwd, files.migrationDir)) {
231
+ const extension = await psql(options.commandRunner, cwd, connection, "select to_regprocedure('uuid_generate_v7()') is not null;");
232
+ if (extension !== "t") {
233
+ failure("pg_uuidv7 is missing from the local project database.");
234
+ }
235
+ }
236
+ return { database: files.name, role: files.name, host, port };
237
+ }
238
+ /** Provision one project database and role on an existing local PostgreSQL server. */
239
+ async function setupLocalDatabase(cwd, options) {
240
+ const env = options.env ?? process.env;
241
+ const { host, port } = endpoint(options.host ?? "db.localtest.me", options.port ?? "5432");
242
+ await verifyLoopbackResolution(host, options);
243
+ const files = await localFiles(cwd, options.commandRunner, env);
244
+ const current = files.values.DATABASE_URL;
245
+ if (!current && URL_NAMES.some((name) => files.values[name])) {
246
+ failure("configured database URL candidates require DATABASE_URL.");
247
+ }
248
+ const existing = current ? parseDatabaseUrl(current) : null;
249
+ if (existing && !options.replaceLocalTarget) {
250
+ appConnection(files.values, files.name, host, port);
251
+ try {
252
+ return await checkLocalDatabase(cwd, options);
253
+ }
254
+ catch {
255
+ // Repair the marked project database below when the check fails.
256
+ }
257
+ }
258
+ if (existing &&
259
+ (existing.database.includes("acceptance") ||
260
+ (existing.database !== files.name &&
261
+ !existing.database.startsWith(`${files.name}_`)))) {
262
+ failure("refusing to replace an acceptance or non-development database URL.");
263
+ }
264
+ if (existing) {
265
+ for (const name of URL_NAMES) {
266
+ if (files.values[name] && files.values[name] !== current) {
267
+ failure("configured database URL candidates disagree.");
268
+ }
269
+ }
270
+ }
271
+ const adminPassword = env.LOOM_DB_LOCAL_ADMIN_PASSWORD ??
272
+ (options.promptSecret
273
+ ? await options.promptSecret("Local PostgreSQL admin password: ")
274
+ : "");
275
+ if (!adminPassword) {
276
+ failure("set LOOM_DB_LOCAL_ADMIN_PASSWORD or run interactively.");
277
+ }
278
+ const admin = {
279
+ host,
280
+ port,
281
+ database: env.LOOM_DB_LOCAL_ADMIN_DATABASE ?? "postgres",
282
+ user: env.LOOM_DB_LOCAL_ADMIN_USER ?? "postgres",
283
+ password: adminPassword,
284
+ };
285
+ const marker = `Loom local development database for ${files.name}`;
286
+ const state = await psql(options.commandRunner, cwd, admin, `
287
+ select concat_ws('|',
288
+ exists(select 1 from pg_roles where rolname = ${quote(files.name)}),
289
+ coalesce((select shobj_description(oid, 'pg_authid') = ${quote(marker)} from pg_roles where rolname = ${quote(files.name)}), false),
290
+ exists(select 1 from pg_database where datname = ${quote(files.name)}),
291
+ coalesce((select pg_get_userbyid(datdba) = ${quote(files.name)} from pg_database where datname = ${quote(files.name)}), false),
292
+ coalesce((select shobj_description(oid, 'pg_database') = ${quote(marker)} from pg_database where datname = ${quote(files.name)}), false));
293
+ `);
294
+ if (!["f|f|f|f|f", "t|t|f|f|f", "t|t|t|t|t"].includes(state)) {
295
+ failure("existing database or role is not owned by this local setup.");
296
+ }
297
+ if (state === "t|t|t|t|t" && !existing && !options.replaceLocalTarget) {
298
+ failure("existing project database has no local credential; restore it rather than rotate implicitly.");
299
+ }
300
+ const existingIsTarget = existing?.database === files.name &&
301
+ existing.user === files.name && existing.host === host &&
302
+ existing.port === port;
303
+ const password = state === "t|t|t|t|t" && existingIsTarget
304
+ ? existing.password
305
+ : (0, node_crypto_1.randomBytes)(32).toString("base64url");
306
+ if (state !== "t|t|t|t|t") {
307
+ if (state === "f|f|f|f|f") {
308
+ await psql(options.commandRunner, cwd, admin, `
309
+ begin;
310
+ create role ${files.name} login nosuperuser nocreatedb nocreaterole noinherit noreplication nobypassrls password ${quote(password)};
311
+ comment on role ${files.name} is ${quote(marker)};
312
+ commit;
313
+ `);
314
+ }
315
+ else {
316
+ await psql(options.commandRunner, cwd, admin, `alter role ${files.name} password ${quote(password)};`);
317
+ }
318
+ await psql(options.commandRunner, cwd, admin, `create database ${files.name} owner ${files.name};`);
319
+ await psql(options.commandRunner, cwd, admin, `comment on database ${files.name} is ${quote(marker)};`);
320
+ }
321
+ if (state === "t|t|t|t|t" && !existingIsTarget) {
322
+ await psql(options.commandRunner, cwd, admin, `alter role ${files.name} password ${quote(password)};`);
323
+ }
324
+ await psql(options.commandRunner, cwd, admin, `alter role ${files.name} login nosuperuser nocreatedb nocreaterole noinherit noreplication nobypassrls;`);
325
+ const projectDb = { ...admin, database: files.name };
326
+ await psql(options.commandRunner, cwd, projectDb, `
327
+ revoke all on database ${files.name} from public;
328
+ grant connect, temporary on database ${files.name} to ${files.name};
329
+ grant usage, create on schema public to ${files.name};
330
+ `);
331
+ if (await requiresUuidV7(cwd, files.migrationDir)) {
332
+ await psql(options.commandRunner, cwd, projectDb, "create extension if not exists pg_uuidv7;");
333
+ }
334
+ const connection = {
335
+ host,
336
+ port,
337
+ database: files.name,
338
+ user: files.name,
339
+ password,
340
+ };
341
+ const url = targetUrl(connection);
342
+ const names = new Set(["DATABASE_URL", "DATABASE_URL_UNPOOLED"]);
343
+ for (const name of URL_NAMES)
344
+ if (files.positions.has(name))
345
+ names.add(name);
346
+ const lines = files.lines.at(-1) === ""
347
+ ? files.lines.slice(0, -1)
348
+ : [...files.lines];
349
+ for (const name of names) {
350
+ const assignment = `${name}=${JSON.stringify(url)}`;
351
+ const index = files.positions.get(name);
352
+ if (index === undefined)
353
+ lines.push(assignment);
354
+ else
355
+ lines[index] = assignment;
356
+ }
357
+ const temporaryPath = `${files.path}.tmp-${(0, node_crypto_1.randomBytes)(8).toString("hex")}`;
358
+ try {
359
+ await (0, promises_2.writeFile)(temporaryPath, `${lines.join("\n")}\n`, {
360
+ flag: "wx",
361
+ mode: 0o600,
362
+ });
363
+ await (0, promises_2.chmod)(temporaryPath, 0o600);
364
+ await (0, promises_2.rename)(temporaryPath, files.path);
365
+ }
366
+ finally {
367
+ await (0, promises_2.rm)(temporaryPath, { force: true });
368
+ }
369
+ return await checkLocalDatabase(cwd, options);
370
+ }
@@ -273,7 +273,10 @@ export declare function configureFilesIdGeneration(cwd: string, idGeneration: Fi
273
273
  notes: string[];
274
274
  }>;
275
275
  /** Builds the Vercel env-run probe that prints only non-secret Files values. */
276
- export declare function buildVercelFilesEnvProbeArgs(environment: FilesR2Environment): string[];
276
+ export declare function buildVercelFilesEnvProbeArgs(environment: FilesR2Environment, project?: {
277
+ orgId: string;
278
+ projectId: string;
279
+ }): string[];
277
280
  /**
278
281
  * Configures Files against local MinIO, preserving any existing app key and
279
282
  * verifying a newly created bucket-scoped key before writing it to .env.local.