@gadicc/loom 1.32.0 → 1.33.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.
@@ -1,10 +1,12 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { constants as fsConstants } from "node:fs";
4
- import { access, lstat, mkdir, readdir, readFile, readlink, rm, stat, symlink, unlink, writeFile, } from "node:fs/promises";
4
+ import { access, chmod, lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, symlink, unlink, writeFile, } from "node:fs/promises";
5
5
  import { createRequire } from "node:module";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
7
  import process from "node:process";
8
+ import { createInterface } from "node:readline/promises";
9
+ import { tmpdir } from "node:os";
8
10
  import { parseArgs } from "node:util";
9
11
  import { filesR2PolicyIssues, parseWranglerR2Cors, r2CorsMatchesPolicy, } from "./filesR2Policy.js";
10
12
  import { resolveProductionBranch, } from "./releaseConfig.js";
@@ -175,7 +177,7 @@ const DB_DEFAULT_DEPENDENCIES = {
175
177
  "valibot": "^1.4.2",
176
178
  };
177
179
  const DB_DEFAULT_DEV_DEPENDENCIES = {
178
- "@electric-sql/pglite": "^0.3.15",
180
+ "@electric-sql/pglite": "^0.5.8",
179
181
  "drizzle-kit": "^0.31.10",
180
182
  "drizzle-valibot": "^0.4.2",
181
183
  "tsx": "^4.23.1",
@@ -209,6 +211,7 @@ const FILES_S3_NON_SECRET_ENV_VALUES = {
209
211
  };
210
212
  const FILES_R2_ENVIRONMENTS = ["production", "preview"];
211
213
  const DEFAULT_MINIO_ENDPOINT = "http://127.0.0.1:9000";
214
+ const FILES_LOCAL_ENV_NAMES = FILES_S3_REQUIRED_ENV_NAMES;
212
215
  const API_KEY_AUDIT_SCHEMA_BLUEPRINT_VERSION = 3;
213
216
  const API_KEY_AUDIT_SCHEMA_DEFAULT_EXPORT = "loomApiKeyAuditEventsTable";
214
217
  const API_KEY_AUDIT_SCHEMA_DEFAULT_TABLE = "loom_api_key_audit_events";
@@ -5772,17 +5775,31 @@ export async function configureFilesIdGeneration(cwd, idGeneration) {
5772
5775
  }
5773
5776
  function parseEnvValue(rawValue) {
5774
5777
  const trimmed = rawValue.trim();
5775
- if (trimmed.length >= 2 &&
5776
- ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
5777
- (trimmed.startsWith("'") && trimmed.endsWith("'")))) {
5778
- return trimmed.slice(1, -1);
5778
+ const quote = trimmed[0];
5779
+ if (quote === '"' || quote === "'" || quote === "`") {
5780
+ for (let index = 1; index < trimmed.length; index++) {
5781
+ if (trimmed[index] === "\\") {
5782
+ index++;
5783
+ continue;
5784
+ }
5785
+ if (trimmed[index] !== quote)
5786
+ continue;
5787
+ const trailing = trimmed.slice(index + 1).trim();
5788
+ if (!trailing || trailing.startsWith("#")) {
5789
+ const value = trimmed.slice(1, index);
5790
+ return quote === '"'
5791
+ ? value.replaceAll("\\n", "\n").replaceAll("\\r", "\r")
5792
+ : value;
5793
+ }
5794
+ break;
5795
+ }
5779
5796
  }
5780
- return trimmed;
5797
+ return trimmed.split("#", 1)[0].trim();
5781
5798
  }
5782
5799
  function readEnvAssignments(text) {
5783
5800
  const assignments = new Map();
5784
5801
  for (const [lineIndex, line] of normalizeText(text).split("\n").entries()) {
5785
- const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
5802
+ const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
5786
5803
  if (!match)
5787
5804
  continue;
5788
5805
  assignments.set(match[1], {
@@ -6043,6 +6060,420 @@ async function ensureMinioBucket(cwd, commandRunner, env, endpoint, bucket, acce
6043
6060
  ok: false,
6044
6061
  };
6045
6062
  }
6063
+ async function promptForLocalFilesValue(question, secret = false) {
6064
+ 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.");
6066
+ }
6067
+ if (!secret) {
6068
+ const input = createInterface({
6069
+ input: process.stdin,
6070
+ output: process.stderr,
6071
+ });
6072
+ try {
6073
+ return (await input.question(question)).trim();
6074
+ }
6075
+ finally {
6076
+ input.close();
6077
+ }
6078
+ }
6079
+ process.stderr.write(question);
6080
+ const stdin = process.stdin;
6081
+ const wasRaw = stdin.isRaw;
6082
+ stdin.setRawMode(true);
6083
+ stdin.resume();
6084
+ try {
6085
+ return await new Promise((resolvePromise, rejectPromise) => {
6086
+ let value = "";
6087
+ const onData = (chunk) => {
6088
+ for (const character of new TextDecoder().decode(chunk)) {
6089
+ if (character === "\r" || character === "\n") {
6090
+ stdin.off("data", onData);
6091
+ process.stderr.write("\n");
6092
+ resolvePromise(value);
6093
+ return;
6094
+ }
6095
+ if (character === "\u0003") {
6096
+ stdin.off("data", onData);
6097
+ rejectPromise(new Error("MinIO setup was cancelled."));
6098
+ return;
6099
+ }
6100
+ if (character === "\u007f" || character === "\b") {
6101
+ value = value.slice(0, -1);
6102
+ }
6103
+ else {
6104
+ value += character;
6105
+ }
6106
+ }
6107
+ };
6108
+ stdin.on("data", onData);
6109
+ });
6110
+ }
6111
+ finally {
6112
+ stdin.setRawMode(wasRaw);
6113
+ stdin.pause();
6114
+ }
6115
+ }
6116
+ function minioHostEnv(env, endpoint, accessKey, secretKey) {
6117
+ const url = new URL(endpoint);
6118
+ url.username = accessKey;
6119
+ url.password = secretKey;
6120
+ return { ...env, MC_HOST_loomlocal: url.toString() };
6121
+ }
6122
+ async function checkMinioAdmin(cwd, runner, command, env, endpoint, user, password) {
6123
+ const result = await runner(command, ["admin", "info", "loomlocal"], {
6124
+ cwd,
6125
+ env: minioHostEnv(env, endpoint, user, password),
6126
+ stdio: "pipe",
6127
+ });
6128
+ return result.code === 0;
6129
+ }
6130
+ function filesBucketPolicy(bucket) {
6131
+ return {
6132
+ Version: "2012-10-17",
6133
+ Statement: [
6134
+ {
6135
+ Effect: "Allow",
6136
+ Action: ["s3:GetBucketLocation", "s3:ListBucket"],
6137
+ Resource: [`arn:aws:s3:::${bucket}`],
6138
+ },
6139
+ {
6140
+ Effect: "Allow",
6141
+ Action: ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
6142
+ Resource: [`arn:aws:s3:::${bucket}/*`],
6143
+ },
6144
+ ],
6145
+ };
6146
+ }
6147
+ async function verifyMinioReadWrite(cwd, runner, command, env, endpoint, bucket, accessKey, secretKey) {
6148
+ const target = `loomlocal/${bucket}/.loom-setup-${randomUUID()}`;
6149
+ const keyEnv = minioHostEnv(env, endpoint, accessKey, secretKey);
6150
+ const payload = "loom-files-local-check\n";
6151
+ const put = await runner(command, ["pipe", target], {
6152
+ cwd,
6153
+ env: keyEnv,
6154
+ input: payload,
6155
+ stdio: "pipe",
6156
+ });
6157
+ if (put.code !== 0) {
6158
+ throw new Error("The MinIO access key cannot write to its bucket.");
6159
+ }
6160
+ let readOk = false;
6161
+ let removeOk = false;
6162
+ try {
6163
+ const get = await runner(command, ["cat", target], {
6164
+ cwd,
6165
+ env: keyEnv,
6166
+ stdio: "pipe",
6167
+ });
6168
+ readOk = get.code === 0 && get.stdout === payload;
6169
+ }
6170
+ finally {
6171
+ const remove = await runner(command, ["rm", target], {
6172
+ cwd,
6173
+ env: keyEnv,
6174
+ stdio: "pipe",
6175
+ });
6176
+ removeOk = remove.code === 0;
6177
+ }
6178
+ if (!removeOk) {
6179
+ throw new Error("The MinIO access key could not remove its setup verification object.");
6180
+ }
6181
+ if (!readOk) {
6182
+ throw new Error("The MinIO access key cannot read from its bucket.");
6183
+ }
6184
+ }
6185
+ /**
6186
+ * Configures Files against local MinIO, preserving any existing app key and
6187
+ * verifying a newly created bucket-scoped key before writing it to .env.local.
6188
+ */
6189
+ export async function setupLocalFiles(cwd, options = {}) {
6190
+ const runner = options.commandRunner ?? defaultCommandRunner;
6191
+ const env = options.env ?? process.env;
6192
+ const prompt = options.prompt ?? promptForLocalFilesValue;
6193
+ const manifestPath = join(cwd, "loom.json");
6194
+ const manifestText = await readTextIfExists(manifestPath);
6195
+ if (!manifestText) {
6196
+ throw new Error("Missing loom.json. Run `loom add files` first.");
6197
+ }
6198
+ const manifest = parseJson(manifestText, "loom.json");
6199
+ const feature = manifest.features.files;
6200
+ if (feature?.status !== "active") {
6201
+ throw new Error("The files feature is not active. Run `loom add files` first.");
6202
+ }
6203
+ const { packageJson } = await readProjectPackageJson(cwd);
6204
+ const framework = await detectFramework(cwd, packageJson);
6205
+ const dbFeature = manifest.features.db;
6206
+ if (dbFeature?.status !== "active") {
6207
+ throw new Error("The files feature requires the active DB feature.");
6208
+ }
6209
+ const config = getFilesConfig(framework, mergeDbConfig(framework, dbFeature.config), feature.config);
6210
+ if (config.storage.provider?.localDevelopment.kind === "none") {
6211
+ throw new Error("Files local storage is disabled in loom.json. Change the provider policy before running local setup.");
6212
+ }
6213
+ if (config.storage.provider?.localDevelopment.kind === "r2") {
6214
+ throw new Error("Files local storage is set to R2. Change the local provider policy to MinIO before running local setup.");
6215
+ }
6216
+ const storagePath = join(cwd, config.modules.storageModule);
6217
+ const storageText = await readTextIfExists(storagePath);
6218
+ if (storageText && !isGeneratedFilesStorageStub(storageText) &&
6219
+ config.storage.adapter !== "s3") {
6220
+ throw new Error(`Files uses a custom storage adapter at ${config.modules.storageModule}; configure it locally without replacing it.`);
6221
+ }
6222
+ const envPath = join(cwd, ".env.local");
6223
+ const envText = await readTextIfExists(envPath);
6224
+ const tracked = await runner("git", [
6225
+ "ls-files",
6226
+ "--error-unmatch",
6227
+ "--",
6228
+ ".env.local",
6229
+ ], { cwd, env, stdio: "pipe" });
6230
+ if (tracked.code === 0) {
6231
+ throw new Error(".env.local is tracked by Git. Remove it from the index before Loom writes Files credentials.");
6232
+ }
6233
+ try {
6234
+ if ((await lstat(envPath)).isSymbolicLink()) {
6235
+ throw new Error(".env.local is a symlink; Loom will not write credentials through it.");
6236
+ }
6237
+ }
6238
+ catch (error) {
6239
+ if (!isNodeErrorCode(error, "ENOENT"))
6240
+ throw error;
6241
+ }
6242
+ const assignments = readEnvAssignments(envText ?? "");
6243
+ const bucket = normalizeBucketName(options.localBucket ??
6244
+ assignments.get("FILES_S3_BUCKET")?.value ??
6245
+ config.storage.provider?.localDevelopment.bucket ??
6246
+ `${getDefaultFilesBucketBase(cwd, packageJson, manifest)}-dev`, "--local-bucket");
6247
+ let endpoint = options.localEndpoint ??
6248
+ assignments.get("FILES_S3_ENDPOINT")?.value ??
6249
+ config.storage.provider?.localDevelopment.endpoint ??
6250
+ DEFAULT_MINIO_ENDPOINT;
6251
+ function validateEndpoint(value) {
6252
+ let url;
6253
+ try {
6254
+ url = new URL(value);
6255
+ }
6256
+ catch {
6257
+ throw new Error("--local-endpoint must be an HTTP(S) origin without credentials or a path.");
6258
+ }
6259
+ if (!["http:", "https:"].includes(url.protocol) || url.username ||
6260
+ url.password || url.pathname !== "/" || url.search || url.hash) {
6261
+ throw new Error("--local-endpoint must be an HTTP(S) origin without credentials or a path.");
6262
+ }
6263
+ return url.origin;
6264
+ }
6265
+ endpoint = validateEndpoint(endpoint);
6266
+ const client = await detectMinioClient(cwd, runner, env);
6267
+ if (!client) {
6268
+ throw new Error("MinIO Client is unavailable. Install `mcli` (Arch: `sudo pacman -S minio-client`) or `mc`, then rerun `loom files local setup`.");
6269
+ }
6270
+ const existingAccess = assignments.get("FILES_S3_ACCESS_KEY_ID")?.value;
6271
+ const existingSecret = assignments.get("FILES_S3_SECRET_ACCESS_KEY")?.value;
6272
+ if ((assignments.has("FILES_S3_ACCESS_KEY_ID") && !existingAccess) ||
6273
+ (assignments.has("FILES_S3_SECRET_ACCESS_KEY") && !existingSecret)) {
6274
+ throw new Error(".env.local contains an empty Files credential. Remove the empty assignment before local setup.");
6275
+ }
6276
+ if (Boolean(existingAccess) !== Boolean(existingSecret)) {
6277
+ throw new Error(".env.local has only one Files access credential. Restore the matching key and secret before local setup; Loom will not replace either one.");
6278
+ }
6279
+ let bucketStatus = existingAccess && existingSecret
6280
+ ? await ensureMinioBucket(cwd, runner, env, endpoint, bucket, existingAccess, existingSecret, { create: false })
6281
+ : null;
6282
+ if (bucketStatus?.ok && existingAccess && existingSecret) {
6283
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, existingAccess, existingSecret);
6284
+ }
6285
+ let createdKey = null;
6286
+ if (!bucketStatus?.ok) {
6287
+ if (Boolean(env.MINIO_ROOT_USER) !== Boolean(env.MINIO_ROOT_PASSWORD)) {
6288
+ throw new Error("Set both MINIO_ROOT_USER and MINIO_ROOT_PASSWORD, or leave both unset for interactive MinIO setup.");
6289
+ }
6290
+ let adminUser = env.MINIO_ROOT_USER || "minioadmin";
6291
+ let adminPassword = env.MINIO_ROOT_PASSWORD || "minioadmin";
6292
+ let authenticated = await checkMinioAdmin(cwd, runner, client, env, endpoint, adminUser, adminPassword);
6293
+ if (!authenticated) {
6294
+ const promptedEndpoint = (await prompt(`MinIO endpoint [${endpoint}]: `)).trim();
6295
+ if (promptedEndpoint)
6296
+ endpoint = validateEndpoint(promptedEndpoint);
6297
+ adminUser = (await prompt("MinIO admin user: ")).trim();
6298
+ adminPassword = await prompt("MinIO admin password: ", true);
6299
+ authenticated = await checkMinioAdmin(cwd, runner, client, env, endpoint, adminUser, adminPassword);
6300
+ }
6301
+ if (!authenticated) {
6302
+ throw new Error("Could not authenticate to MinIO. Check the server endpoint and admin credentials, then rerun local setup.");
6303
+ }
6304
+ const adminEnv = minioHostEnv(env, endpoint, adminUser, adminPassword);
6305
+ bucketStatus = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, adminUser, adminPassword);
6306
+ if (!bucketStatus.ok) {
6307
+ throw new Error(`Could not create or reuse MinIO bucket \`${bucket}\`. Check admin permissions and the endpoint.`);
6308
+ }
6309
+ if (existingAccess && existingSecret) {
6310
+ const existingCheck = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, existingAccess, existingSecret, { create: false });
6311
+ if (!existingCheck.ok) {
6312
+ throw new Error("Existing FILES_S3 credentials cannot access the bucket. Loom preserved them; repair or remove them manually before rerunning setup.");
6313
+ }
6314
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, existingAccess, existingSecret);
6315
+ }
6316
+ else {
6317
+ const policyDir = await mkdtemp(join(tmpdir(), "loom-files-policy-"));
6318
+ const policyPath = join(policyDir, "bucket.json");
6319
+ try {
6320
+ await writeFile(policyPath, `${JSON.stringify(filesBucketPolicy(bucket))}\n`, { mode: 0o600 });
6321
+ const result = await runner(client, [
6322
+ "--json",
6323
+ "admin",
6324
+ "accesskey",
6325
+ "create",
6326
+ "loomlocal/",
6327
+ "--policy",
6328
+ policyPath,
6329
+ ], { cwd, env: adminEnv, stdio: "pipe" });
6330
+ if (result.code !== 0) {
6331
+ throw new Error("MinIO could not create a bucket-scoped access key. Check that the client supports `admin accesskey create` and the admin account has permission.");
6332
+ }
6333
+ let parsed = {};
6334
+ try {
6335
+ parsed = JSON.parse(result.stdout.trim());
6336
+ }
6337
+ catch {
6338
+ throw new Error("MinIO returned malformed JSON while creating a local access key.");
6339
+ }
6340
+ if (typeof parsed.accessKey !== "string" ||
6341
+ typeof parsed.secretKey !== "string") {
6342
+ throw new Error("MinIO did not return an access key and secret key in JSON output.");
6343
+ }
6344
+ createdKey = {
6345
+ accessKey: parsed.accessKey,
6346
+ secretKey: parsed.secretKey,
6347
+ };
6348
+ }
6349
+ finally {
6350
+ await rm(policyDir, { recursive: true, force: true });
6351
+ }
6352
+ try {
6353
+ const keyCheck = await ensureMinioBucket(cwd, runner, env, endpoint, bucket, createdKey.accessKey, createdKey.secretKey, { create: false });
6354
+ if (!keyCheck.ok) {
6355
+ throw new Error("The new MinIO access key could not read its bucket. Check the MinIO policy before rerunning setup.");
6356
+ }
6357
+ await verifyMinioReadWrite(cwd, runner, client, env, endpoint, bucket, createdKey.accessKey, createdKey.secretKey);
6358
+ }
6359
+ catch (error) {
6360
+ const cleanup = await runner(client, ["admin", "accesskey", "remove", "loomlocal/", createdKey.accessKey], { cwd, env: adminEnv, stdio: "pipe" });
6361
+ if (cleanup.code !== 0) {
6362
+ throw new Error("The new MinIO key failed verification and could not be removed automatically. Remove the newly created key in MinIO before retrying.");
6363
+ }
6364
+ throw error;
6365
+ }
6366
+ }
6367
+ }
6368
+ const desired = {
6369
+ FILES_S3_BUCKET: bucket,
6370
+ FILES_S3_ENDPOINT: endpoint,
6371
+ FILES_S3_FORCE_PATH_STYLE: "true",
6372
+ FILES_S3_REGION: "auto",
6373
+ FILES_STORAGE_PROVIDER: "minio",
6374
+ FILES_S3_ACCESS_KEY_ID: existingAccess ?? createdKey?.accessKey ?? "",
6375
+ FILES_S3_SECRET_ACCESS_KEY: existingSecret ?? createdKey?.secretKey ?? "",
6376
+ };
6377
+ const merged = mergeEnvValues(envText, desired, {
6378
+ neverReplace: new Set([
6379
+ "FILES_S3_ACCESS_KEY_ID",
6380
+ "FILES_S3_SECRET_ACCESS_KEY",
6381
+ ]),
6382
+ repair: true,
6383
+ });
6384
+ if (merged.conflicts.length) {
6385
+ throw new Error(`Could not preserve existing Files credentials: ${merged.conflicts.join(", ")}.`);
6386
+ }
6387
+ const changedFiles = [];
6388
+ const notes = [];
6389
+ const gitignorePath = join(cwd, ".gitignore");
6390
+ const gitignore = await readTextIfExists(gitignorePath) ?? "";
6391
+ const lastIgnoreRule = normalizeText(gitignore).split("\n")
6392
+ .map((line) => line.trim()).filter(Boolean).at(-1);
6393
+ if (lastIgnoreRule !== ".env.local" && lastIgnoreRule !== "/.env.local") {
6394
+ if (await writeTextIfChanged(gitignorePath, `${gitignore && !gitignore.endsWith("\n") ? `${gitignore}\n` : gitignore}.env.local\n`))
6395
+ changedFiles.push(".gitignore");
6396
+ }
6397
+ if (envText !== merged.text) {
6398
+ await writeFile(envPath, merged.text, { mode: 0o600 });
6399
+ await chmod(envPath, 0o600);
6400
+ changedFiles.push(".env.local");
6401
+ }
6402
+ const tooling = await getProjectTooling(cwd, manifest);
6403
+ const dependencyUpdate = await mutateProjectDependencies(cwd, tooling.dependencies, { dependencies: FILES_S3_DEPENDENCIES });
6404
+ if (dependencyUpdate.changed) {
6405
+ changedFiles.push(dependencyUpdate.config);
6406
+ notes.push(`Run ${tooling.dependencies.manager} install to update the dependency lockfile.`);
6407
+ }
6408
+ if (!storageText || isGeneratedFilesStorageStub(storageText)) {
6409
+ if (await writeTextIfChanged(storagePath, filesS3StorageTemplate())) {
6410
+ changedFiles.push(config.modules.storageModule);
6411
+ }
6412
+ }
6413
+ config.storage.adapter = "s3";
6414
+ if (config.storage.provider) {
6415
+ config.storage.provider.localDevelopment = {
6416
+ kind: "minio",
6417
+ bucket,
6418
+ endpoint,
6419
+ };
6420
+ }
6421
+ feature.config = config;
6422
+ if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
6423
+ changedFiles.push("loom.json");
6424
+ }
6425
+ return {
6426
+ changedFiles,
6427
+ notes: [
6428
+ bucketStatus?.detail ?? `MinIO bucket \`${bucket}\` is ready.`,
6429
+ createdKey
6430
+ ? "Created a bucket-scoped MinIO access key and saved it to .env.local."
6431
+ : "Reused existing Files access credentials.",
6432
+ ...notes,
6433
+ ],
6434
+ };
6435
+ }
6436
+ async function checkLocalFilesEnvironment(cwd, options = {}) {
6437
+ const issues = [];
6438
+ const suggestions = [];
6439
+ const warnings = [];
6440
+ const text = await readTextIfExists(join(cwd, ".env.local"));
6441
+ const assignments = readEnvAssignments(text ?? "");
6442
+ const missing = FILES_LOCAL_ENV_NAMES.filter((name) => !assignments.get(name)?.value);
6443
+ if (!text || missing.length) {
6444
+ issues.push(!text
6445
+ ? "Files local storage is missing .env.local."
6446
+ : `Files .env.local is missing ${missing.join(", ")}.`);
6447
+ suggestions.push("Run `loom files local setup` to configure local MinIO.");
6448
+ suggestions.push("Install and start a MinIO server with `mcli` or `mc`, or configure another S3-compatible service with the canonical FILES_S3_* variables.");
6449
+ return { issues, suggestions, warnings };
6450
+ }
6451
+ const endpoint = assignments.get("FILES_S3_ENDPOINT")?.value ?? "";
6452
+ try {
6453
+ const url = new URL(endpoint);
6454
+ if (!["http:", "https:"].includes(url.protocol) || url.username ||
6455
+ url.password)
6456
+ throw new Error("invalid");
6457
+ }
6458
+ catch {
6459
+ issues.push("FILES_S3_ENDPOINT in .env.local must be an HTTP(S) URL without credentials.");
6460
+ }
6461
+ if (assignments.get("FILES_S3_FORCE_PATH_STYLE")?.value !== "true" &&
6462
+ assignments.get("FILES_STORAGE_PROVIDER")?.value === "minio") {
6463
+ issues.push("Local MinIO requires FILES_S3_FORCE_PATH_STYLE=true.");
6464
+ }
6465
+ if (options.verifyBucket && !issues.length) {
6466
+ const verified = await ensureMinioBucket(cwd, options.commandRunner ?? defaultCommandRunner, options.env ?? process.env, endpoint, assignments.get("FILES_S3_BUCKET")?.value ?? "", assignments.get("FILES_S3_ACCESS_KEY_ID")?.value ?? "", assignments.get("FILES_S3_SECRET_ACCESS_KEY")?.value ?? "", { create: false });
6467
+ if (!verified.ok) {
6468
+ issues.push("Files local bucket or credentials could not be verified.");
6469
+ suggestions.push("Start the configured storage server and check its endpoint, bucket, and credentials; use `loom files local setup` for MinIO.");
6470
+ if (verified.detail.includes("not available")) {
6471
+ suggestions.push("Install MinIO Client as `mcli` (Arch: `sudo pacman -S minio-client`) or `mc`.");
6472
+ }
6473
+ }
6474
+ }
6475
+ return { issues, suggestions, warnings };
6476
+ }
6046
6477
  function filesR2ProviderMatches(existing, desired) {
6047
6478
  if (!existing)
6048
6479
  return true;
@@ -6207,7 +6638,7 @@ export async function setupCloudflareR2(cwd, options = {}) {
6207
6638
  const envLocalText = await readTextIfExists(envLocalPath);
6208
6639
  const localAssignments = readEnvAssignments(envLocalText ?? "");
6209
6640
  const localBucket = normalizeBucketName(options.localBucket ?? existingProvider?.localDevelopment.bucket ??
6210
- localAssignments.get("FILES_S3_BUCKET")?.value ?? `${baseName}-files`, "--local-bucket");
6641
+ localAssignments.get("FILES_S3_BUCKET")?.value ?? `${baseName}-dev`, "--local-bucket");
6211
6642
  const localEndpoint = options.localEndpoint ??
6212
6643
  existingProvider?.localDevelopment.endpoint ??
6213
6644
  localAssignments.get("FILES_S3_ENDPOINT")?.value ??
@@ -6289,13 +6720,6 @@ export async function setupCloudflareR2(cwd, options = {}) {
6289
6720
  ? "minio"
6290
6721
  : "cloudflare-r2",
6291
6722
  };
6292
- if (!localAssignments.has("FILES_S3_ACCESS_KEY_ID") && env.MINIO_ROOT_USER) {
6293
- desiredLocalValues.FILES_S3_ACCESS_KEY_ID = env.MINIO_ROOT_USER;
6294
- }
6295
- if (!localAssignments.has("FILES_S3_SECRET_ACCESS_KEY") &&
6296
- env.MINIO_ROOT_PASSWORD) {
6297
- desiredLocalValues.FILES_S3_SECRET_ACCESS_KEY = env.MINIO_ROOT_PASSWORD;
6298
- }
6299
6723
  const localMerge = mergeEnvValues(envLocalText, desiredLocalValues, {
6300
6724
  neverReplace: new Set([
6301
6725
  "FILES_S3_ACCESS_KEY_ID",
@@ -6319,7 +6743,7 @@ export async function setupCloudflareR2(cwd, options = {}) {
6319
6743
  notes.push(minio.detail);
6320
6744
  }
6321
6745
  else if (!localAccessKey || !localSecretKey) {
6322
- notes.push("Local storage credentials were not found. Add FILES_S3_ACCESS_KEY_ID and FILES_S3_SECRET_ACCESS_KEY to gitignored .env.local; Loom did not synthesize credentials.");
6746
+ notes.push("Local storage credentials were not found. Run `loom files local setup` to create a bucket-scoped MinIO key, or add credentials for another S3-compatible provider to gitignored .env.local.");
6323
6747
  }
6324
6748
  }
6325
6749
  const envListings = new Map();
@@ -7415,7 +7839,7 @@ function checkFilesNetworkFeature(context) {
7415
7839
  if (!text) {
7416
7840
  return networkCheckResult("issue", "Gitignored .env.local is missing.", {
7417
7841
  issues: ["Local MinIO Files configuration is missing."],
7418
- suggestions: ["Run `loom files r2 setup`."],
7842
+ suggestions: ["Run `loom files local setup`."],
7419
7843
  });
7420
7844
  }
7421
7845
  const assignments = readEnvAssignments(text);
@@ -7426,7 +7850,7 @@ function checkFilesNetworkFeature(context) {
7426
7850
  `Local MinIO Files variables are incomplete: ${missing.join(", ")}.`,
7427
7851
  ],
7428
7852
  suggestions: [
7429
- "Add the existing MinIO credentials to .env.local; Loom never synthesizes or replaces them.",
7853
+ "Run `loom files local setup` to create a scoped MinIO key, or add an existing credential pair to .env.local.",
7430
7854
  ],
7431
7855
  });
7432
7856
  }
@@ -7440,7 +7864,7 @@ function checkFilesNetworkFeature(context) {
7440
7864
  "Local MinIO is configured but the bucket could not be verified.",
7441
7865
  ],
7442
7866
  suggestions: [
7443
- "Start MinIO or correct FILES_S3_ENDPOINT, then rerun `loom files r2 check`.",
7867
+ "Start MinIO or correct FILES_S3_ENDPOINT, then rerun `loom files local check`.",
7444
7868
  ],
7445
7869
  });
7446
7870
  },
@@ -9042,6 +9466,17 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
9042
9466
  : "Rerun `loom files r2 setup`; existing buckets and working credentials will be reused.");
9043
9467
  }
9044
9468
  }
9469
+ if (!options.production && provider?.localDevelopment.kind !== "none" &&
9470
+ (config.storage.adapter === "s3" ||
9471
+ (storageText !== null && isGeneratedFilesStorageStub(storageText)))) {
9472
+ const local = await checkLocalFilesEnvironment(cwd);
9473
+ if (config.storage.adapter === "s3")
9474
+ issues.push(...local.issues);
9475
+ else
9476
+ warnings.push(...local.issues);
9477
+ for (const suggestion of local.suggestions)
9478
+ suggestions.add(suggestion);
9479
+ }
9045
9480
  const routeText = await readTextIfExists(join(cwd, config.entrypoints.routeHandler));
9046
9481
  if (!routeText) {
9047
9482
  issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
@@ -10774,8 +11209,9 @@ function printHelp({ out }) {
10774
11209
  out(" init Set up package/Deno config, loom.json, managed AGENTS.md guidance, first-party links, and package skills.");
10775
11210
  out(" add <feature> Activate a shared feature. Run `loom add` to list available features.");
10776
11211
  out(" files id-generation uuid-v4|uuid-v7 Select the managed Files schema ID default.");
10777
- out(" files r2 setup Create/reuse private Cloudflare R2 buckets, configure Vercel Production/Preview, and configure local MinIO by default.");
10778
- out(" files r2 check Verify R2 buckets/account/privacy, Vercel env scoping, local MinIO, and Files adapter wiring.");
11212
+ out(" files local setup|check Provision or verify local MinIO and .env.local without R2/Vercel.");
11213
+ out(" files r2 setup Create/reuse private Cloudflare R2 buckets and configure Vercel Production/Preview.");
11214
+ out(" files r2 check Verify R2 buckets/account/privacy, Vercel env scoping, local storage, and Files adapter wiring.");
10779
11215
  out(" api-keys integrate jobs Record an explicit API-key jobs integration after the route has session/admin authorization.");
10780
11216
  out(" api-keys retention enable|disable Record API-key audit cleanup policy; scheduling remains app-owned.");
10781
11217
  out(" status Show the Loom package, manifest, active features, local-dev state, and project skill state.");
@@ -10889,8 +11325,53 @@ async function runFiles(cwd, command, target, options, io) {
10889
11325
  io.out(`Note: ${note}`);
10890
11326
  return 0;
10891
11327
  }
11328
+ if (command === "local") {
11329
+ if (target === "setup") {
11330
+ const result = await setupLocalFiles(cwd, {
11331
+ localBucket: options.localBucket,
11332
+ localEndpoint: options.localEndpoint,
11333
+ });
11334
+ io.out(result.changedFiles.length
11335
+ ? `Updated ${result.changedFiles.join(", ")}.`
11336
+ : "Files local storage already matches the configuration.");
11337
+ for (const note of result.notes)
11338
+ io.out(`Note: ${note}`);
11339
+ return 0;
11340
+ }
11341
+ if (target === "check") {
11342
+ const manifestText = await readTextIfExists(join(cwd, "loom.json"));
11343
+ const manifest = manifestText
11344
+ ? parseJson(manifestText, "loom.json")
11345
+ : null;
11346
+ if (manifest?.features.files?.status !== "active") {
11347
+ io.err("The files feature is not active. Run `loom add files` first.");
11348
+ return 1;
11349
+ }
11350
+ const filesConfig = manifest.features.files.config;
11351
+ if (filesConfig?.storage?.provider?.localDevelopment.kind === "none") {
11352
+ io.out("Files local storage is disabled in loom.json.");
11353
+ return 0;
11354
+ }
11355
+ const result = await checkLocalFilesEnvironment(cwd, {
11356
+ verifyBucket: true,
11357
+ });
11358
+ if (result.issues.length) {
11359
+ io.err("loom files local check found setup issues:");
11360
+ for (const issue of result.issues)
11361
+ io.err(`- ${issue}`);
11362
+ for (const suggestion of result.suggestions) {
11363
+ io.err(`Suggestion: ${suggestion}`);
11364
+ }
11365
+ return 1;
11366
+ }
11367
+ io.out("loom files local check: setup looks good.");
11368
+ return 0;
11369
+ }
11370
+ io.err("Usage: loom files local setup|check [--local-endpoint <url>] [--local-bucket <name>]");
11371
+ return 1;
11372
+ }
10892
11373
  if (command !== "r2" || !target) {
10893
- io.err("Usage: loom files id-generation uuid-v4|uuid-v7\n or: loom files r2 setup|check [R2 options]");
11374
+ io.err("Usage: loom files id-generation uuid-v4|uuid-v7\n or: loom files local setup|check\n or: loom files r2 setup|check [R2 options]");
10894
11375
  return 1;
10895
11376
  }
10896
11377
  const jurisdiction = options.jurisdiction;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gadicc/loom",
3
- "version": "1.32.0",
3
+ "version": "1.33.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": "305a8f35a662d0033fea1ef5d539a51c179ff598"
247
+ "gitCommit": "842f835dc4fb04467f435a509e5723b6c4a0ccab"
248
248
  },
249
249
  "bin": {
250
250
  "loom": "script/bin/loom.js"