@adep/cli 0.5.3 → 0.5.5

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.
package/dist/vite.js CHANGED
@@ -2137,9 +2137,20 @@ var StorageError = class extends Error {
2137
2137
  var STORAGE_CODES = {
2138
2138
  invalidPath: "STORAGE_INVALID_PATH",
2139
2139
  invalidData: "STORAGE_INVALID_DATA",
2140
+ invalidVisibility: "STORAGE_INVALID_VISIBILITY",
2141
+ invalidSignedUrlTtl: "STORAGE_SIGNED_URL_TTL_INVALID",
2142
+ signedUrlTtlExceeded: "STORAGE_SIGNED_URL_TTL_EXCEEDED",
2140
2143
  notFound: "STORAGE_NOT_FOUND",
2141
2144
  quotaExceeded: "STORAGE_QUOTA_EXCEEDED"
2142
2145
  };
2146
+ function assertFileVisibility(value) {
2147
+ if (value === "public" || value === "private") return value;
2148
+ throw new StorageError(
2149
+ 400,
2150
+ STORAGE_CODES.invalidVisibility,
2151
+ `\u975E\u6CD5\u7684\u6587\u4EF6\u53EF\u89C1\u6027 ${JSON.stringify(value)}\uFF08\u53EA\u652F\u6301 'public' / 'private'\uFF09`
2152
+ );
2153
+ }
2143
2154
  function assertSafeStoragePath(path) {
2144
2155
  if (typeof path !== "string" || path.length === 0) {
2145
2156
  throw new StorageError(400, STORAGE_CODES.invalidPath, "\u5B58\u50A8\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A");
@@ -2347,17 +2358,51 @@ function hmacSha256Hex(key, message) {
2347
2358
 
2348
2359
  // packages/runtime/src/storage/signature.ts
2349
2360
  var DEFAULT_SIGN_TTL_SECONDS = 15 * 60;
2361
+ var MAX_SIGNED_URL_TTL_SECONDS = 7 * 24 * 60 * 60;
2350
2362
  var SIGN_EXPIRES_KEY = "x-expires";
2351
2363
  var SIGN_SIGNATURE_KEY = "x-signature";
2364
+ function resolveSignedUrlTtl(ttlSeconds, options) {
2365
+ if (ttlSeconds === void 0) return DEFAULT_SIGN_TTL_SECONDS;
2366
+ if (!Number.isInteger(ttlSeconds) || ttlSeconds <= 0) {
2367
+ throw new StorageError(
2368
+ 400,
2369
+ STORAGE_CODES.invalidSignedUrlTtl,
2370
+ `\u7B7E\u540D\u6709\u6548\u671F\u5FC5\u987B\u662F\u6B63\u6574\u6570\u79D2\uFF08\u6536\u5230 ${ttlSeconds}\uFF09`
2371
+ );
2372
+ }
2373
+ if (ttlSeconds > MAX_SIGNED_URL_TTL_SECONDS && options?.force !== true) {
2374
+ throw new StorageError(
2375
+ 400,
2376
+ STORAGE_CODES.signedUrlTtlExceeded,
2377
+ `\u7B7E\u540D URL \u6709\u6548\u671F\u6700\u957F ${MAX_SIGNED_URL_TTL_SECONDS / 86400} \u5929\uFF08\u6536\u5230 ${ttlSeconds} \u79D2\uFF09\u3002\u9700\u8981\u957F\u671F\u7A33\u5B9A\u7684\u94FE\u63A5\u8BF7\u628A\u6587\u4EF6\u4E0A\u4F20\u4E3A visibility: 'public' \u5E76\u7528 getUrl() \u53D6\u76F4\u94FE\uFF1B\u786E\u9700\u8D85\u957F\u79C1\u6709\u94FE\u63A5\u8BF7\u663E\u5F0F\u4F20 { force: true }\uFF08\u8FC7\u671F\u524D\u94FE\u63A5\u6CC4\u6F0F\u5373\u957F\u671F\u53EF\u8BFB\uFF09\u3002`
2378
+ );
2379
+ }
2380
+ if (ttlSeconds > DEFAULT_SIGN_TTL_SECONDS && options?.force !== true) {
2381
+ console.warn(
2382
+ `[deprecation] \u79C1\u6709\u7B7E\u540D URL \u4F7F\u7528\u4E86\u8D85\u8FC7\u7F3A\u7701 15 \u5206\u949F\u7684\u957F TTL\uFF08${String(ttlSeconds)}s\uFF09\uFF1A\u957F TTL \u79C1\u6709\u94FE\u63A5\u5C06\u5728\u4E0A\u9650\u6536\u7A84\u65F6\u5931\u6548\uFF0C\u957F\u671F\u5C55\u793A\u8BF7\u8FC1\u79FB visibility: 'public' + getUrl() \u53D6\u76F4\u94FE\u3002`
2383
+ );
2384
+ }
2385
+ return ttlSeconds;
2386
+ }
2352
2387
  function sign(secret, projectId, path, expires) {
2353
2388
  const payload = `${projectId}|${path}|${expires}`;
2354
2389
  return hmacSha256Hex(secret, payload);
2355
2390
  }
2356
- function signDownloadUrl(config, projectId, path, ttlSeconds = DEFAULT_SIGN_TTL_SECONDS) {
2357
- const expires = Math.floor(Date.now() / 1e3) + ttlSeconds;
2358
- const base = `${config.baseUrl}/api/v1/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}`;
2391
+ function publicDownloadUrl(config, projectId, path) {
2392
+ return `${config.baseUrl}/api/v1/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}`;
2393
+ }
2394
+ function signDownloadUrlWithExpiry(config, projectId, path, ttlSeconds = DEFAULT_SIGN_TTL_SECONDS, options) {
2395
+ const ttl = resolveSignedUrlTtl(ttlSeconds, options);
2396
+ const expires = Math.floor(Date.now() / 1e3) + ttl;
2397
+ const base = publicDownloadUrl(config, projectId, path);
2359
2398
  const signature = sign(config.secret, projectId, path, expires);
2360
- return `${base}?${SIGN_EXPIRES_KEY}=${expires}&${SIGN_SIGNATURE_KEY}=${signature}`;
2399
+ return {
2400
+ url: `${base}?${SIGN_EXPIRES_KEY}=${expires}&${SIGN_SIGNATURE_KEY}=${signature}`,
2401
+ expires
2402
+ };
2403
+ }
2404
+ function signDownloadUrl(config, projectId, path, ttlSeconds = DEFAULT_SIGN_TTL_SECONDS, options) {
2405
+ return signDownloadUrlWithExpiry(config, projectId, path, ttlSeconds, options).url;
2361
2406
  }
2362
2407
 
2363
2408
  // packages/runtime/src/storage/cloud.ts
@@ -2406,9 +2451,10 @@ function createStorageCapability(driver, signer, projectId) {
2406
2451
  switch (method) {
2407
2452
  case "upload": {
2408
2453
  const [path, data, options] = args;
2454
+ const visibility = assertFileVisibility(options?.visibility ?? DEFAULT_VISIBILITY);
2409
2455
  return toStoredFile(
2410
2456
  await driver.put(projectId, path, asBytes(data), {
2411
- visibility: DEFAULT_VISIBILITY,
2457
+ visibility,
2412
2458
  ...options?.contentType === void 0 ? {} : { contentType: options.contentType }
2413
2459
  })
2414
2460
  );
@@ -2426,9 +2472,26 @@ function createStorageCapability(driver, signer, projectId) {
2426
2472
  const [prefix] = args;
2427
2473
  return (await driver.list(projectId, prefix)).map(toStoredFile);
2428
2474
  }
2475
+ case "getUrl": {
2476
+ const [path] = args;
2477
+ const meta = await driver.getMeta(projectId, path);
2478
+ if (meta.visibility === "public") {
2479
+ const result2 = {
2480
+ url: publicDownloadUrl(signer, projectId, path),
2481
+ expiresAt: null
2482
+ };
2483
+ return result2;
2484
+ }
2485
+ const signed = signDownloadUrlWithExpiry(signer, projectId, path);
2486
+ const result = {
2487
+ url: signed.url,
2488
+ expiresAt: new Date(signed.expires * 1e3).toISOString()
2489
+ };
2490
+ return result;
2491
+ }
2429
2492
  case "getSignedUrl": {
2430
- const [path, ttlSeconds] = args;
2431
- return signDownloadUrl(signer, projectId, path, ttlSeconds);
2493
+ const [path, ttlSeconds, options] = args;
2494
+ return signDownloadUrl(signer, projectId, path, ttlSeconds, options);
2432
2495
  }
2433
2496
  default:
2434
2497
  throw new StorageError(
@@ -2917,6 +2980,53 @@ function unquoteIdent(raw) {
2917
2980
  }
2918
2981
  return text;
2919
2982
  }
2983
+ function parsePlainIdent(raw) {
2984
+ const text = raw.trim();
2985
+ if (text.length === 0) return null;
2986
+ const first = text[0];
2987
+ if (first === '"' || first === "`" || first === "[" || first === "'") {
2988
+ const unquoted = unquoteIdent(text);
2989
+ return unquoted === text.trim() ? null : unquoted;
2990
+ }
2991
+ return /^[A-Za-z_][A-Za-z0-9_$]*$/.test(text) ? text : null;
2992
+ }
2993
+ function takeIdent(text) {
2994
+ const trimmed = text.trimStart();
2995
+ const first = trimmed[0];
2996
+ if (first === '"' || first === "`" || first === "'") {
2997
+ let i = 1;
2998
+ while (i < trimmed.length) {
2999
+ if (trimmed[i] === first) {
3000
+ if (trimmed[i + 1] === first) {
3001
+ i += 2;
3002
+ continue;
3003
+ }
3004
+ return { name: unquoteIdent(trimmed.slice(0, i + 1)), rest: trimmed.slice(i + 1) };
3005
+ }
3006
+ i += 1;
3007
+ }
3008
+ return null;
3009
+ }
3010
+ if (first === "[") {
3011
+ const close = trimmed.indexOf("]");
3012
+ if (close === -1) return null;
3013
+ return { name: unquoteIdent(trimmed.slice(0, close + 1)), rest: trimmed.slice(close + 1) };
3014
+ }
3015
+ const bare = /^[A-Za-z_][A-Za-z0-9_$]*/.exec(trimmed);
3016
+ if (bare === null) return null;
3017
+ return { name: bare[0], rest: trimmed.slice(bare[0].length) };
3018
+ }
3019
+ function parseAlterAddColumn(sql) {
3020
+ const head = /^ALTER\s+TABLE\s+/i.exec(sql.trim());
3021
+ if (head === null) return null;
3022
+ const table = takeIdent(sql.trim().slice(head[0].length));
3023
+ if (table === null) return null;
3024
+ const add = /^\s+ADD\s+(?:COLUMN\s+)?/i.exec(table.rest);
3025
+ if (add === null) return null;
3026
+ const column = takeIdent(table.rest.slice(add[0].length));
3027
+ if (column === null) return null;
3028
+ return { table: table.name, column: column.name };
3029
+ }
2920
3030
  function splitTopLevel2(body) {
2921
3031
  const parts = [];
2922
3032
  let depth = 0;
@@ -3010,19 +3120,47 @@ function parseColumn(part) {
3010
3120
  }
3011
3121
  const type = rest.slice(0, typeEnd).trim();
3012
3122
  rest = rest.slice(typeEnd).trim();
3013
- const notNull = /\bNOT\s+NULL\b/i.test(rest);
3014
- const primaryKey = /\bPRIMARY\s+KEY\b/i.test(rest);
3015
3123
  const defaultMatch = /\bDEFAULT\s+(.+?)(?=\s+(?:NOT|PRIMARY|UNIQUE|CHECK|REFERENCES|COLLATE|GENERATED|AS|AUTOINCREMENT|CONSTRAINT)\b|$)/i.exec(
3016
3124
  rest
3017
3125
  );
3126
+ const constraintText = defaultMatch === null ? rest : rest.replace(defaultMatch[0], " ");
3127
+ const declarationText = stripNonNullabilityClauses(constraintText);
3128
+ const notNull = /\bNOT\s+NULL\b/i.test(declarationText);
3129
+ const explicitNullable = !notNull && /\bNULL\b/i.test(declarationText);
3130
+ const primaryKey = /\bPRIMARY\s+KEY\b/i.test(declarationText);
3131
+ const unique = /\bUNIQUE\b/i.test(declarationText);
3018
3132
  return {
3019
3133
  name,
3020
3134
  type,
3021
3135
  notNull,
3136
+ explicitNullable,
3022
3137
  primaryKey,
3138
+ unique,
3023
3139
  defaultValue: defaultMatch === null ? null : defaultMatch[1].trim()
3024
3140
  };
3025
3141
  }
3142
+ function stripNonNullabilityClauses(text) {
3143
+ return text.replace(
3144
+ /\bREFERENCES\s+\S+(?:\s*\([^)]*\))?(?:\s+ON\s+(?:DELETE|UPDATE)\s+(?:CASCADE|RESTRICT|SET\s+NULL|SET\s+DEFAULT|NO\s+ACTION))*/gi,
3145
+ " "
3146
+ ).replace(/\bCHECK\s*\([^)]*\)/gi, " ").replace(/\bGENERATED\s+ALWAYS\s+AS\s*\([^)]*\)(?:\s+STORED|\s+VIRTUAL)?/gi, " ");
3147
+ }
3148
+ function parseTableUnique(part) {
3149
+ const trimmed = part.trim();
3150
+ const match = /^(?:CONSTRAINT\s+(?:"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)\s+)?UNIQUE\s*\(/i.exec(
3151
+ trimmed
3152
+ );
3153
+ if (match === null) return null;
3154
+ const body = findTableBody(trimmed, match[0].lastIndexOf("("));
3155
+ if (body === null) return null;
3156
+ const columns = [];
3157
+ for (const entry of splitTopLevel2(body)) {
3158
+ const column = parsePlainIdent(entry);
3159
+ if (column === null) return null;
3160
+ columns.push(column);
3161
+ }
3162
+ return columns.length === 0 ? null : columns;
3163
+ }
3026
3164
  function parseSchemaTables(sql) {
3027
3165
  const tables = [];
3028
3166
  const pattern = /CREATE\s+(?:TEMP|TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|'[^']*'|[A-Za-z_][A-Za-z0-9_$.]*)\s*\(/gi;
@@ -3036,11 +3174,14 @@ function parseSchemaTables(sql) {
3036
3174
  const rawName = match[1];
3037
3175
  const name = unquoteIdent(rawName.split(".").pop() ?? rawName);
3038
3176
  const columns = [];
3177
+ const uniqueConstraints = [];
3039
3178
  for (const part of splitTopLevel2(body)) {
3179
+ const unique = parseTableUnique(part);
3180
+ if (unique !== null) uniqueConstraints.push(unique);
3040
3181
  const column = parseColumn(part);
3041
3182
  if (column !== null) columns.push(column);
3042
3183
  }
3043
- tables.push({ name, columns, statement: statement.trim() });
3184
+ tables.push({ name, columns, uniqueConstraints, statement: statement.trim() });
3044
3185
  }
3045
3186
  return tables;
3046
3187
  }
@@ -3063,6 +3204,18 @@ function planMissingColumn(table, column) {
3063
3204
  };
3064
3205
  }
3065
3206
 
3207
+ // packages/cli/src/auth.ts
3208
+ var CliError = class extends Error {
3209
+ constructor(code, message, exitCode = 1) {
3210
+ super(message);
3211
+ this.code = code;
3212
+ this.exitCode = exitCode;
3213
+ this.name = "CliError";
3214
+ }
3215
+ code;
3216
+ exitCode;
3217
+ };
3218
+
3066
3219
  // packages/cli/src/serve/sqlite-driver.ts
3067
3220
  import { mkdir as mkdir3 } from "node:fs/promises";
3068
3221
  import { dirname as dirname4, resolve as resolve2 } from "node:path";
@@ -3279,6 +3432,22 @@ async function applyLocalSchema(driver, options) {
3279
3432
  let applied = 0;
3280
3433
  let skipped = 0;
3281
3434
  for (const [index, statement] of statements.entries()) {
3435
+ if (mode === "sqlite") {
3436
+ const addColumn = parseAlterAddColumn(statement);
3437
+ if (addColumn !== null) {
3438
+ const rows = await driver.all(`SELECT name FROM pragma_table_info(?)`, [addColumn.table]);
3439
+ const exists = rows.some(
3440
+ (row) => String(row["name"] ?? "").toLowerCase() === addColumn.column.toLowerCase()
3441
+ );
3442
+ if (exists) {
3443
+ skipped += 1;
3444
+ log(
3445
+ `[${tag}] \u8DF3\u8FC7\u5DF2\u5B58\u5728\u7684\u5217\uFF08--schema \u5E42\u7B49\u9884\u68C0\uFF09\uFF1A${addColumn.table}.${addColumn.column}`
3446
+ );
3447
+ continue;
3448
+ }
3449
+ }
3450
+ }
3282
3451
  try {
3283
3452
  await driver.run(statement);
3284
3453
  applied += 1;
@@ -3403,6 +3572,13 @@ function isFetchBlockedPort(port) {
3403
3572
 
3404
3573
  // packages/cli/src/serve/fetch-safe-port.ts
3405
3574
  var MAX_FETCH_SAFE_LISTEN_ATTEMPTS = 8;
3575
+ var DEFAULT_PORT_FALLBACK_SPAN = 12;
3576
+ var PortFallbackExhaustedError = class extends Error {
3577
+ constructor(message) {
3578
+ super(message);
3579
+ this.name = "PortFallbackExhaustedError";
3580
+ }
3581
+ };
3406
3582
  function listenOnce(server, port, host) {
3407
3583
  return new Promise((resolve6, reject) => {
3408
3584
  const onError = (error) => {
@@ -3444,6 +3620,21 @@ function buildExhaustedMessage(input) {
3444
3620
  "\u53EF\u80FD\u539F\u56E0\uFF1A\u7CFB\u7EDF\u4E34\u65F6\u7AEF\u53E3\u8D77\u59CB\u503C\u88AB\u8C03\u4F4E\uFF08Windows \u7528 netsh int ipv4 show dynamicport tcp \u6838\u5BF9\uFF0CHyper-V / \u5BB9\u5668\u7F51\u7EDC\u4F1A\u6539\u5B83\uFF09\u3002\u53EF\u7528 --port \u6307\u5B9A\u4E00\u4E2A\u672A\u5360\u7528\u7684\u7AEF\u53E3\u7ED5\u8FC7\u3002"
3445
3621
  ].join("\n");
3446
3622
  }
3623
+ function isAddrInUseCode(error) {
3624
+ return error?.code === "EADDRINUSE";
3625
+ }
3626
+ function formatFallbackNotice(info) {
3627
+ return `[adep] \u7AEF\u53E3 ${info.requested} \u5DF2\u88AB\u5360\u7528\uFF0C\u5DF2\u6539\u7528 ${info.actual}\uFF08\u7F3A\u7701\u7AEF\u53E3\u81EA\u52A8\u987A\u5EF6\uFF1B\u663E\u5F0F\u6307\u5B9A\u7684\u7AEF\u53E3\u4E0D\u6362\u53F7\uFF09`;
3628
+ }
3629
+ function buildFallbackExhaustedMessage(input) {
3630
+ const first = input.requested + 1;
3631
+ const last = input.requested + input.span;
3632
+ return [
3633
+ `[adep] \u7AEF\u53E3 ${input.requested} \u5DF2\u88AB\u5360\u7528\uFF0C\u5176\u540E ${input.span} \u4E2A\u5019\u9009\u7AEF\u53E3\uFF08${first}~${last}\uFF09\u4E5F\u4E0D\u53EF\u7528\uFF0C\u5DF2\u653E\u5F03\u542F\u52A8\u3002`,
3634
+ "\u7F3A\u7701\u7AEF\u53E3\u81EA\u52A8\u987A\u5EF6\u53EA\u8986\u76D6\u8FD9\u4E00\u5C0F\u6BB5\uFF1B\u8BF7\u7528 --port \u6307\u5B9A\u4E00\u4E2A\u7A7A\u95F2\u7AEF\u53E3\uFF08\u663E\u5F0F\u7AEF\u53E3\u4E0D\u4F1A\u81EA\u52A8\u6362\u53F7\uFF09\u3002",
3635
+ `\u5360\u7528\u8005\u6392\u67E5\uFF1Alsof -nP -iTCP:${input.requested} -sTCP:LISTEN\uFF08Windows\uFF1Anetstat -ano | findstr :${input.requested}\uFF09`
3636
+ ].join("\n");
3637
+ }
3447
3638
  async function listenOnFetchSafePort(server, options) {
3448
3639
  const isBlocked = options.isBlocked ?? isFetchBlockedPort;
3449
3640
  const warn = options.warn ?? (() => {
@@ -3454,12 +3645,46 @@ async function listenOnFetchSafePort(server, options) {
3454
3645
  } catch {
3455
3646
  }
3456
3647
  };
3457
- if (options.port !== 0) {
3648
+ const requestedPort = options.port;
3649
+ if (requestedPort !== 0) {
3458
3650
  try {
3459
- await listenOnce(server, options.port, options.host);
3651
+ await listenOnce(server, requestedPort, options.host);
3460
3652
  } catch (error) {
3461
- await notifyListenError(error);
3462
- throw error;
3653
+ const fallback = options.fallbackOnInUse;
3654
+ if (fallback === void 0 || !isAddrInUseCode(error)) {
3655
+ await notifyListenError(error);
3656
+ throw error;
3657
+ }
3658
+ const span = fallback.span ?? DEFAULT_PORT_FALLBACK_SPAN;
3659
+ if (!Number.isInteger(span) || span < 1) {
3660
+ await notifyListenError(error);
3661
+ throw new Error(`[adep] fallbackOnInUse.span \u5FC5\u987B\u662F\u6B63\u6574\u6570\uFF08\u6536\u5230 ${String(span)}\uFF09\u3002`, {
3662
+ cause: error
3663
+ });
3664
+ }
3665
+ let lastError = error;
3666
+ for (let offset = 1; offset <= span; offset += 1) {
3667
+ const candidate = requestedPort + offset;
3668
+ if (candidate > 65535) break;
3669
+ if (isBlocked(candidate)) continue;
3670
+ try {
3671
+ await listenOnce(server, candidate, options.host);
3672
+ } catch (candidateError) {
3673
+ if (isAddrInUseCode(candidateError)) {
3674
+ lastError = candidateError;
3675
+ continue;
3676
+ }
3677
+ await notifyListenError(candidateError);
3678
+ throw candidateError;
3679
+ }
3680
+ const report = options.onFallback ?? ((info) => warn(formatFallbackNotice(info)));
3681
+ report({ requested: requestedPort, actual: candidate });
3682
+ return candidate;
3683
+ }
3684
+ await notifyListenError(lastError);
3685
+ throw new PortFallbackExhaustedError(
3686
+ buildFallbackExhaustedMessage({ requested: requestedPort, span })
3687
+ );
3463
3688
  }
3464
3689
  const actual = readTcpPort(server, options.host);
3465
3690
  if (isBlocked(actual)) {
@@ -3492,6 +3717,79 @@ async function listenOnFetchSafePort(server, options) {
3492
3717
  throw new Error(buildExhaustedMessage({ host: options.host, hits, maxAttempts }));
3493
3718
  }
3494
3719
 
3720
+ // packages/cli/src/serve/port-in-use.ts
3721
+ import { execFile } from "node:child_process";
3722
+ function parsePortOccupier(stdout) {
3723
+ for (const line of stdout.split(/\r?\n/)) {
3724
+ const trimmed = line.trim();
3725
+ if (trimmed.length === 0 || trimmed.startsWith("COMMAND")) continue;
3726
+ const [command, pid] = trimmed.split(/\s+/);
3727
+ if (command === void 0 || pid === void 0 || !/^\d+$/u.test(pid)) return null;
3728
+ return `${command} ${pid}`;
3729
+ }
3730
+ return null;
3731
+ }
3732
+ function runLsof(port) {
3733
+ return new Promise((resolve6, reject) => {
3734
+ execFile(
3735
+ "lsof",
3736
+ ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"],
3737
+ { timeout: 2e3, windowsHide: true },
3738
+ (error, stdout) => {
3739
+ if (error !== null) {
3740
+ reject(error);
3741
+ return;
3742
+ }
3743
+ resolve6(stdout);
3744
+ }
3745
+ );
3746
+ });
3747
+ }
3748
+ async function lookupPortOccupier(port, options = {}) {
3749
+ if (process.platform === "win32") return null;
3750
+ const execute = options.execute ?? runLsof;
3751
+ try {
3752
+ return parsePortOccupier(await execute(port));
3753
+ } catch {
3754
+ return null;
3755
+ }
3756
+ }
3757
+ async function describePortInUse(options) {
3758
+ const occupier = await (options.lookup ?? lookupPortOccupier)(options.port);
3759
+ const nextPort = options.port < 65535 ? options.port + 1 : options.port - 1;
3760
+ const command = `adep ${options.scope}`;
3761
+ return [
3762
+ `[adep] \u7AEF\u53E3 ${options.port} \u5DF2\u88AB\u5360\u7528\uFF08EADDRINUSE\uFF09\uFF1B\u8BE5\u7AEF\u53E3\u662F\u663E\u5F0F\u6307\u5B9A\u7684\uFF08--port / PORT\uFF09\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u6539\u7528\u5176\u5B83\u7AEF\u53E3\u3002`,
3763
+ occupier === null ? `\u5360\u7528\u8005\uFF1A\u65E0\u6CD5\u5B9A\u4F4D\u3002\u624B\u52A8\u68C0\u67E5\uFF1Alsof -nP -iTCP:${options.port} -sTCP:LISTEN\uFF08Windows\uFF1Anetstat -ano | findstr :${options.port}\uFF09` : `\u5360\u7528\u8005\uFF1A${occupier}\uFF08\u590D\u6838\u547D\u4EE4\uFF1Alsof -nP -iTCP:${options.port} -sTCP:LISTEN\uFF09`,
3764
+ `\u5904\u7F6E\uFF1A\u6539\u7528\u5176\u5B83\u7AEF\u53E3\uFF08${command} --port ${nextPort}\uFF09\uFF0C\u6216\u5148\u505C\u6B62\u5360\u7528\u8BE5\u7AEF\u53E3\u7684\u8FDB\u7A0B\u3002`
3765
+ ].join("\n");
3766
+ }
3767
+ function isAddrInUse(error) {
3768
+ return error?.code === "EADDRINUSE";
3769
+ }
3770
+ async function toPortCliError(error, context) {
3771
+ if (isAddrInUse(error)) {
3772
+ return new CliError(
3773
+ "PORT_IN_USE",
3774
+ await describePortInUse({ port: context.port, scope: context.scope })
3775
+ );
3776
+ }
3777
+ if (error instanceof PortFallbackExhaustedError) {
3778
+ return new CliError("PORT_FALLBACK_EXHAUSTED", error.message);
3779
+ }
3780
+ return null;
3781
+ }
3782
+ function isPortConflictError(error) {
3783
+ if (isAddrInUse(error)) return true;
3784
+ return error instanceof CliError && error.code === "PORT_IN_USE";
3785
+ }
3786
+ function toAddrInUseError(error) {
3787
+ const message = error instanceof Error ? error.message : String(error);
3788
+ const wrapped = new Error(message, { cause: error });
3789
+ wrapped.code = "EADDRINUSE";
3790
+ return wrapped;
3791
+ }
3792
+
3495
3793
  // packages/cli/src/sim/env.ts
3496
3794
  import { readFile as readFile4 } from "node:fs/promises";
3497
3795
  import { join as join6 } from "node:path";
@@ -4569,12 +4867,24 @@ function errorLineIn(stack, path) {
4569
4867
  if (own !== null) return own[1];
4570
4868
  return /(?:^|\n):(\d+)(?:\n|$)/.exec(stack)?.[1];
4571
4869
  }
4572
- function syntaxErrorWithLocation(error, path) {
4870
+ var DYNAMIC_IMPORT_HINT = "\u63D0\u793A\uFF1AM1 \u6C99\u7BB1\u4E0D\u652F\u6301\u52A8\u6001 import\uFF0C\u6539\u9759\u6001 import";
4871
+ function isDynamicImportRejection(error) {
4872
+ const code = error.code;
4873
+ if (code === "ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING") return true;
4874
+ const message = error instanceof Error ? error.message : String(error);
4875
+ return /dynamic import callback/i.test(message);
4876
+ }
4877
+ function containsDynamicImport(source) {
4878
+ return /(^|[^\w$.])import\s*\(/.test(source);
4879
+ }
4880
+ function syntaxErrorWithLocation(error, path, source) {
4573
4881
  const rawMessage = error instanceof Error ? error.message : String(error);
4574
4882
  const stack = error.stack;
4575
4883
  const line = typeof stack === "string" ? errorLineIn(stack, path) : void 0;
4576
4884
  const location = line === void 0 ? path : `${path}:${line}`;
4577
- const wrapped = new Error(`\u6E90\u7801\u8BED\u6CD5\u9519\u8BEF\uFF08${location}\uFF09\uFF1A${rawMessage}`, { cause: error });
4885
+ const hint = containsDynamicImport(source) ? `
4886
+ ${DYNAMIC_IMPORT_HINT}` : "";
4887
+ const wrapped = new Error(`\u6E90\u7801\u8BED\u6CD5\u9519\u8BEF\uFF08${location}\uFF09\uFF1A${rawMessage}${hint}`, { cause: error });
4578
4888
  const code = error.code;
4579
4889
  if (typeof code === "string") wrapped.code = code;
4580
4890
  return wrapped;
@@ -4619,7 +4929,7 @@ function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache,
4619
4929
  try {
4620
4930
  transformed = transformExports(transpile(source));
4621
4931
  } catch (error) {
4622
- throw syntaxErrorWithLocation(error, path);
4932
+ throw syntaxErrorWithLocation(error, path, source);
4623
4933
  }
4624
4934
  const context = createSandboxContext(sandboxGlobals);
4625
4935
  let wrapper;
@@ -4631,7 +4941,7 @@ function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache,
4631
4941
  { filename: path }
4632
4942
  );
4633
4943
  } catch (error) {
4634
- throw syntaxErrorWithLocation(error, path);
4944
+ throw syntaxErrorWithLocation(error, path, source);
4635
4945
  }
4636
4946
  wrapper(module, exports, require2);
4637
4947
  if (module.default !== void 0 && exports["default"] === void 0) {
@@ -5278,10 +5588,10 @@ function firstUserFrame(stack, files) {
5278
5588
  function errorMessageWithLocation(error, files) {
5279
5589
  const message = errorMessageOf2(error);
5280
5590
  const stack = error.stack;
5281
- if (typeof stack !== "string") return message;
5282
- const frame = firstUserFrame(stack, files);
5283
- if (frame === void 0 || message.includes(`\uFF08${frame}\uFF09`)) return message;
5284
- return `${message}\uFF08${frame}\uFF09`;
5591
+ const frame = typeof stack === "string" ? firstUserFrame(stack, files) : void 0;
5592
+ const located = frame === void 0 || message.includes(`\uFF08${frame}\uFF09`) ? message : `${message}\uFF08${frame}\uFF09`;
5593
+ return isDynamicImportRejection(error) ? `${located}
5594
+ ${DYNAMIC_IMPORT_HINT}` : located;
5285
5595
  }
5286
5596
  function createBareResolver(deps) {
5287
5597
  const platformRequire = createRequire(import.meta.url);
@@ -5605,6 +5915,50 @@ function createBearerUserResolver(issuer) {
5605
5915
  }
5606
5916
  };
5607
5917
  }
5918
+ var SIM_USER_ENV_KEY = "ADEP_SIM_USER";
5919
+ function parseSimUserJson(raw) {
5920
+ let parsed;
5921
+ try {
5922
+ parsed = JSON.parse(raw);
5923
+ } catch {
5924
+ return { ok: false, reason: "\u4E0D\u662F\u5408\u6CD5 JSON" };
5925
+ }
5926
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
5927
+ return { ok: false, reason: `\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08{"id":"u1","name":"\u5192\u70DF"}\uFF09` };
5928
+ }
5929
+ const record = parsed;
5930
+ if (typeof record["id"] !== "string" || record["id"].length === 0) {
5931
+ return { ok: false, reason: `\u7F3A\u5C11\u975E\u7A7A\u5B57\u7B26\u4E32 id \u5B57\u6BB5\uFF08{"id":"u1","name":"\u5192\u70DF"}\uFF09` };
5932
+ }
5933
+ for (const key of ["name", "email"]) {
5934
+ const value = record[key];
5935
+ if (value !== void 0 && typeof value !== "string") {
5936
+ return { ok: false, reason: `${key} \u5B57\u6BB5\u5FC5\u987B\u662F\u5B57\u7B26\u4E32` };
5937
+ }
5938
+ }
5939
+ const name = record["name"];
5940
+ const email = record["email"];
5941
+ return {
5942
+ ok: true,
5943
+ user: {
5944
+ id: record["id"],
5945
+ ...typeof name === "string" && name !== "" ? { name } : {},
5946
+ ...typeof email === "string" && email !== "" ? { email } : {}
5947
+ }
5948
+ };
5949
+ }
5950
+ function simUserResolverFromEnv(fileEnv = {}) {
5951
+ const raw = firstNonEmpty(process.env[SIM_USER_ENV_KEY], fileEnv[SIM_USER_ENV_KEY]);
5952
+ if (raw === void 0) return { resolver: void 0, warning: void 0 };
5953
+ const parsed = parseSimUserJson(raw);
5954
+ if (!parsed.ok) {
5955
+ return {
5956
+ resolver: void 0,
5957
+ warning: `${SIM_USER_ENV_KEY}=${raw} \u89E3\u6790\u5931\u8D25\uFF08${parsed.reason}\uFF09\uFF1A\u5DF2\u8DF3\u8FC7\u6A21\u62DF\u767B\u5F55\u6001\u6CE8\u5165\uFF0C\u767B\u5F55\u6001\u94FE\u8DEF\u8D70\u539F\u8DEF\u5F84`
5958
+ };
5959
+ }
5960
+ return { resolver: async () => parsed.user, warning: void 0 };
5961
+ }
5608
5962
  function isRuntimeSource(name) {
5609
5963
  return (name.endsWith(".ts") || name.endsWith(".js")) && !name.endsWith(".d.ts") && !name.endsWith(".test.ts");
5610
5964
  }
@@ -5777,7 +6131,9 @@ async function startDevServer(options) {
5777
6131
  ...options.dbFile === void 0 ? {} : { dbFile: options.dbFile }
5778
6132
  });
5779
6133
  const simEnv = await loadSimEnv(cwd).catch(() => ({}));
5780
- let bearerUser = bearerUserResolverFromEnv(simEnv);
6134
+ let simUser = simUserResolverFromEnv(simEnv);
6135
+ if (simUser.warning !== void 0) log(`[adep] ${simUser.warning}`);
6136
+ let bearerUser = simUser.resolver ?? bearerUserResolverFromEnv(simEnv);
5781
6137
  const fetchConfig = resolveLocalFetchConfig(simEnv);
5782
6138
  const executor = new WorkerFunctionExecutor({
5783
6139
  deps: { rootDir: cwd, builtin: LOCAL_BUILTIN_DEPS },
@@ -5891,7 +6247,10 @@ async function startDevServer(options) {
5891
6247
  ]);
5892
6248
  files = nextFiles;
5893
6249
  env = { ...config.environment, ...parseEnvFile(envText2) };
5894
- bearerUser = bearerUserResolverFromEnv(await loadSimEnv(cwd).catch(() => ({})));
6250
+ const nextEnv = await loadSimEnv(cwd).catch(() => ({}));
6251
+ simUser = simUserResolverFromEnv(nextEnv);
6252
+ if (simUser.warning !== void 0) log(`[adep] ${simUser.warning}`);
6253
+ bearerUser = simUser.resolver ?? bearerUserResolverFromEnv(nextEnv);
5895
6254
  };
5896
6255
  const envText = await readFile7(join10(cwd, ".env.local"), "utf8").catch(() => "");
5897
6256
  env = { ...config.environment, ...parseEnvFile(envText) };
@@ -6035,13 +6394,22 @@ async function startDevServer(options) {
6035
6394
  } catch {
6036
6395
  }
6037
6396
  };
6038
- const actualPort = await listenOnFetchSafePort(server, {
6039
- port,
6040
- host: "127.0.0.1",
6041
- warn: log,
6042
- onListenError: disposeAfterListenError
6043
- });
6397
+ let actualPort;
6398
+ try {
6399
+ actualPort = await listenOnFetchSafePort(server, {
6400
+ port,
6401
+ host: "127.0.0.1",
6402
+ warn: log,
6403
+ ...options.port === void 0 ? { fallbackOnInUse: {} } : {},
6404
+ onListenError: disposeAfterListenError
6405
+ });
6406
+ } catch (error) {
6407
+ const portError = await toPortCliError(error, { port, scope: "dev" });
6408
+ if (portError !== null) throw portError;
6409
+ throw error;
6410
+ }
6044
6411
  const baseUrl = `http://127.0.0.1:${actualPort}`;
6412
+ runtime.storage.signer.baseUrl = baseUrl;
6045
6413
  const coldStartMs = Date.now() - coldStartAt;
6046
6414
  const curlPath = config.functionsPrefix.length === 0 ? "/hello" : `/${config.functionsPrefix}/hello`;
6047
6415
  const dbLabel = db.mode === "sqlite" ? `SQLite \u771F\u5B9E\u5E93${db.module === null ? "" : `\uFF08${db.module}\uFF09`}` : "sim \u5F15\u64CE\uFF08\u5185\u7F6E\u6A21\u62DF\uFF09";
@@ -6051,7 +6419,11 @@ async function startDevServer(options) {
6051
6419
  );
6052
6420
  log(`[adep] curl \u793A\u4F8B\uFF1Acurl ${baseUrl}${curlPath}`);
6053
6421
  printBoundaries(log);
6054
- if (bearerUser !== void 0) {
6422
+ if (simUser.resolver !== void 0) {
6423
+ log(
6424
+ `[adep] \u26A0\uFE0F \u6A21\u62DF\u767B\u5F55\u6001\uFF1AADEP_SIM_USER \u5DF2\u914D\u7F6E\uFF0C\u6240\u6709\u8BF7\u6C42\u7684 ctx.user \u5C06\u6CE8\u5165\u6A21\u62DF\u7528\u6237\uFF08\u4EC5\u672C\u5730 sim\uFF1B\u5E73\u53F0\u90E8\u7F72\u4E0D\u8BFB\u8BE5\u53D8\u91CF\uFF09`
6425
+ );
6426
+ } else if (bearerUser !== void 0) {
6055
6427
  log(
6056
6428
  `[adep] \u767B\u5F55\u5373\u670D\u52A1\uFF1AADEP_AUTH_ISSUER \u5DF2\u914D\u7F6E\uFF0CBearer token \u5C06\u89E3\u6790\u4E3A\u7528\u6237\u8EAB\u4EFD\uFF08userinfo \u7AEF\u70B9\uFF09`
6057
6429
  );
@@ -6080,17 +6452,24 @@ import {
6080
6452
  FN_FETCH_INTERCEPTOR_SCRIPT,
6081
6453
  injectAutomationScriptTag,
6082
6454
  injectFnProxyScriptTag,
6083
- isAddrInUse,
6455
+ isAddrInUse as isAddrInUse2,
6084
6456
  normalizeFunctionPrefix,
6085
6457
  PREVIEW_AUTOMATION_SCRIPT
6086
6458
  } from "@adep/vite-plugin";
6087
- var createDevServer = (opts) => startDevServer({
6088
- cwd: opts.cwd,
6089
- port: opts.port,
6090
- prefix: opts.prefix,
6091
- log: opts.log,
6092
- ...opts.schemaFile === void 0 ? {} : { schemaFile: opts.schemaFile }
6093
- });
6459
+ var createDevServer = async (opts) => {
6460
+ try {
6461
+ return await startDevServer({
6462
+ cwd: opts.cwd,
6463
+ port: opts.port,
6464
+ prefix: opts.prefix,
6465
+ log: opts.log,
6466
+ ...opts.schemaFile === void 0 ? {} : { schemaFile: opts.schemaFile }
6467
+ });
6468
+ } catch (error) {
6469
+ if (isPortConflictError(error)) throw toAddrInUseError(error);
6470
+ throw error;
6471
+ }
6472
+ };
6094
6473
  var loadConfig2 = (cwd) => loadAdepConfigModule(cwd);
6095
6474
  function resolveLocalSchemaFile(cwd, configured) {
6096
6475
  if (configured === false) return void 0;
@@ -6118,7 +6497,7 @@ export {
6118
6497
  vite_default as default,
6119
6498
  injectAutomationScriptTag,
6120
6499
  injectFnProxyScriptTag,
6121
- isAddrInUse,
6500
+ isAddrInUse2 as isAddrInUse,
6122
6501
  normalizeFunctionPrefix,
6123
6502
  resolveLocalSchemaFile
6124
6503
  };