@adep/cli 0.5.0 → 0.5.2

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
@@ -256,6 +256,42 @@ function resolveExecutionDeps(config, projectId, manifestContent) {
256
256
  };
257
257
  }
258
258
 
259
+ // packages/runtime/src/shared/function-timeout.ts
260
+ var TIMEOUT_DECL_RE = /^export const timeoutMs = (\d+)$/;
261
+ function parseDeclaredTimeoutMs(entrySource) {
262
+ for (const rawLine of entrySource.split(/\r?\n/)) {
263
+ const line = rawLine.trim();
264
+ if (line.length === 0 || line.startsWith("//") || line.startsWith("*")) continue;
265
+ if (!line.startsWith("export const timeoutMs")) continue;
266
+ const match = TIMEOUT_DECL_RE.exec(line);
267
+ if (match === null) {
268
+ return {
269
+ value: void 0,
270
+ error: `timeoutMs \u58F0\u660E\u975E\u6CD5\uFF1A"${line}"\u3002\u552F\u4E00\u5408\u6CD5\u5F62\u6001\u662F\u5355\u884C "export const timeoutMs = <\u6B63\u6574\u6570\u6BEB\u79D2>"\uFF08\u65E0\u5F15\u53F7 / \u65E0\u4E0B\u5212\u7EBF\u5206\u9694 / \u65E0\u5355\u4F4D / \u65E0\u5C3E\u968F\u6CE8\u91CA\uFF09\uFF0C\u4F8B\u5982 "export const timeoutMs = 30000"`
271
+ };
272
+ }
273
+ const value = Number(match[1]);
274
+ if (!Number.isInteger(value) || value <= 0) {
275
+ return {
276
+ value: void 0,
277
+ error: `timeoutMs \u58F0\u660E\u975E\u6CD5\uFF1A"${line}"\uFF08\u987B\u4E3A\u6B63\u6574\u6570\u6BEB\u79D2\uFF09`
278
+ };
279
+ }
280
+ return { value, error: null };
281
+ }
282
+ return { value: void 0, error: null };
283
+ }
284
+ function resolveExecutionBudget(params) {
285
+ const declared = params.declaredMs;
286
+ const declaredField = declared === void 0 ? {} : { declaredMs: declared };
287
+ const base = params.inputTimeoutMs ?? declared ?? DEFAULT_TIMEOUT_MS;
288
+ const ceiling = params.ceilingMs;
289
+ if (ceiling === void 0 || base <= ceiling) {
290
+ return { timeoutMs: base, clamped: false, ...declaredField };
291
+ }
292
+ return { timeoutMs: ceiling, clamped: true, ...declaredField };
293
+ }
294
+
259
295
  // packages/runtime/src/functions/runtime/worker-executor.ts
260
296
  function resolveWorkerEntry(baseDir = fileURLToPath(new URL(".", import.meta.url))) {
261
297
  const candidates = [
@@ -296,16 +332,35 @@ function rpcReply(worker, id, ok, payload) {
296
332
  var WorkerFunctionExecutor = class {
297
333
  depsConfig;
298
334
  fetchConfig;
335
+ parity;
336
+ timeoutMaxMs;
299
337
  constructor(options = {}) {
300
338
  this.depsConfig = options.deps;
301
339
  this.fetchConfig = options.fetch;
340
+ this.parity = options.parity === true;
341
+ this.timeoutMaxMs = options.timeoutMaxMs;
302
342
  }
303
343
  async execute(input) {
304
- const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
305
- const memoryLimitMb = input.memoryLimitMb ?? DEFAULT_MEMORY_LIMIT_MB;
306
344
  const entry = input.entry ?? resolveDraftEntry(input.fn.name, input.files) ?? "index.ts";
345
+ const declared = parseDeclaredTimeoutMs(input.files[entry] ?? "");
346
+ if (declared.error !== null) {
347
+ throw new ExecutorError(400, "FN_EXEC_TIMEOUT_DECL_INVALID", declared.error);
348
+ }
349
+ const budget = resolveExecutionBudget({
350
+ inputTimeoutMs: input.timeoutMs,
351
+ declaredMs: declared.value,
352
+ ceilingMs: this.timeoutMaxMs
353
+ });
354
+ const timeoutMs = budget.timeoutMs;
355
+ const memoryLimitMb = input.memoryLimitMb ?? DEFAULT_MEMORY_LIMIT_MB;
307
356
  const deps = this.depsConfig === void 0 ? void 0 : resolveExecutionDeps(this.depsConfig, input.project.id, input.files["package.json"]);
357
+ const effectiveFetchConfig = this.fetchConfig === void 0 ? void 0 : input.fetchAllowlist === void 0 ? this.fetchConfig : { ...this.fetchConfig, allowlist: input.fetchAllowlist };
308
358
  const logs = [];
359
+ if (budget.clamped) {
360
+ logs.push(
361
+ `[adep] timeoutMs \u58F0\u660E ${budget.declaredMs}ms \u8D85\u8FC7\u6267\u884C\u9884\u7B97\u4E0A\u9650 ${this.timeoutMaxMs}ms\uFF0C\u5DF2\u6309\u4E0A\u9650\u94B3\u5236\uFF08FN_EXEC_TIMEOUT_CLAMPED\uFF09`
362
+ );
363
+ }
309
364
  return new Promise((resolve5, reject) => {
310
365
  let worker;
311
366
  try {
@@ -317,7 +372,8 @@ var WorkerFunctionExecutor = class {
317
372
  capabilities: input.capabilities ?? [],
318
373
  ...input.env === void 0 ? {} : { env: input.env },
319
374
  ...deps === void 0 ? {} : { deps },
320
- ...this.fetchConfig === void 0 ? {} : { fetch: this.fetchConfig }
375
+ ...this.parity ? { parity: true } : {},
376
+ ...effectiveFetchConfig === void 0 ? {} : { fetch: effectiveFetchConfig }
321
377
  },
322
378
  resourceLimits: { maxOldGenerationSizeMb: memoryLimitMb }
323
379
  });
@@ -465,10 +521,10 @@ function assertSafeStatement(sql) {
465
521
  if (stripped.includes(";")) {
466
522
  throw unsafeOperation("\u4EC5\u5141\u8BB8\u5355\u6761\u8BED\u53E5\uFF0C\u7981\u6B62\u591A\u8BED\u53E5\u5806\u53E0");
467
523
  }
468
- if (/ATTACH|DETACH/.test(stripped.toUpperCase())) {
524
+ if (/\b(ATTACH|DETACH)\b/.test(stripped.toUpperCase())) {
469
525
  throw unsafeOperation("\u7981\u6B62\u8DE8\u5E93\u64CD\u4F5C\uFF08ATTACH / DETACH\uFF09");
470
526
  }
471
- if (/SQLITE_\w+/i.test(stripped)) {
527
+ if (/\bSQLITE_\w+/i.test(stripped)) {
472
528
  throw unsafeOperation("\u7981\u6B62\u8BBF\u95EE\u7CFB\u7EDF\u8868\uFF08sqlite_*\uFF09");
473
529
  }
474
530
  return sqlHead(stripped);
@@ -1601,10 +1657,10 @@ function assertReadOnly(sql) {
1601
1657
  if (!head.startsWith("SELECT") && !head.startsWith("WITH")) {
1602
1658
  throw new SimDbError("DB_UNSAFE_OP", "cloud.db.query \u4EC5\u5141\u8BB8\u53EA\u8BFB\u67E5\u8BE2\uFF08SELECT / WITH\uFF09");
1603
1659
  }
1604
- if (/ATTACH|DETACH/.test(stripped.toUpperCase())) {
1660
+ if (/\b(ATTACH|DETACH)\b/.test(stripped.toUpperCase())) {
1605
1661
  throw new SimDbError("DB_UNSAFE_OP", "\u7981\u6B62\u8DE8\u5E93\u64CD\u4F5C\uFF08ATTACH / DETACH\uFF09");
1606
1662
  }
1607
- if (/SQLITE_\w+/i.test(stripped) && !/SQLITE_MASTER\b/i.test(stripped)) {
1663
+ if (/\bSQLITE_\w+/i.test(stripped) && !/SQLITE_MASTER\b/i.test(stripped)) {
1608
1664
  throw new SimDbError("DB_UNSAFE_OP", "\u7981\u6B62\u8BBF\u95EE\u7CFB\u7EDF\u8868\uFF08sqlite_*\uFF09");
1609
1665
  }
1610
1666
  }
@@ -2593,7 +2649,7 @@ function createSimStorageCapability(options) {
2593
2649
  baseUrl: options.baseUrl ?? "http://127.0.0.1:8787"
2594
2650
  };
2595
2651
  const bundle = createStorageCapability(driver, signer, options.projectId ?? "sim-project");
2596
- return { bundle, driver };
2652
+ return { bundle, driver, signer };
2597
2653
  }
2598
2654
 
2599
2655
  // packages/runtime/src/sim/realtime.ts
@@ -2842,6 +2898,169 @@ function splitSqlStatements(source) {
2842
2898
  return statements;
2843
2899
  }
2844
2900
 
2901
+ // packages/runtime/src/shared/schema-diff.ts
2902
+ function quoteIdent(name) {
2903
+ return `"${name.replaceAll('"', '""')}"`;
2904
+ }
2905
+ function unquoteIdent(raw) {
2906
+ const text = raw.trim();
2907
+ if (text.length >= 2) {
2908
+ const first = text[0];
2909
+ const last = text[text.length - 1];
2910
+ if (first === '"' && last === '"' || first === "`" && last === "`") {
2911
+ return text.slice(1, -1).replaceAll(first + first, first);
2912
+ }
2913
+ if (first === "[" && last === "]") return text.slice(1, -1);
2914
+ if (first === "'" && last === "'") return text.slice(1, -1).replaceAll("''", "'");
2915
+ }
2916
+ return text;
2917
+ }
2918
+ function splitTopLevel2(body) {
2919
+ const parts = [];
2920
+ let depth = 0;
2921
+ let quote = null;
2922
+ let start = 0;
2923
+ for (let index = 0; index < body.length; index += 1) {
2924
+ const char = body[index];
2925
+ if (quote !== null) {
2926
+ if (char === quote) {
2927
+ if (body[index + 1] === quote) index += 1;
2928
+ else quote = null;
2929
+ }
2930
+ continue;
2931
+ }
2932
+ if (char === '"' || char === "`" || char === "'") {
2933
+ quote = char;
2934
+ continue;
2935
+ }
2936
+ if (char === "[") {
2937
+ quote = "]";
2938
+ continue;
2939
+ }
2940
+ if (char === "(") depth += 1;
2941
+ else if (char === ")") depth -= 1;
2942
+ else if (char === "," && depth === 0) {
2943
+ parts.push(body.slice(start, index));
2944
+ start = index + 1;
2945
+ }
2946
+ }
2947
+ parts.push(body.slice(start));
2948
+ return parts.map((part) => part.trim()).filter((part) => part.length > 0);
2949
+ }
2950
+ function findTableBody(statement, openIndex) {
2951
+ let depth = 0;
2952
+ let quote = null;
2953
+ for (let index = openIndex; index < statement.length; index += 1) {
2954
+ const char = statement[index];
2955
+ if (quote !== null) {
2956
+ if (char === quote) {
2957
+ if (statement[index + 1] === quote) index += 1;
2958
+ else quote = null;
2959
+ }
2960
+ continue;
2961
+ }
2962
+ if (char === '"' || char === "`" || char === "'") {
2963
+ quote = char;
2964
+ continue;
2965
+ }
2966
+ if (char === "[") {
2967
+ quote = "]";
2968
+ continue;
2969
+ }
2970
+ if (char === "(") depth += 1;
2971
+ else if (char === ")") {
2972
+ depth -= 1;
2973
+ if (depth === 0) return statement.slice(openIndex + 1, index);
2974
+ }
2975
+ }
2976
+ return null;
2977
+ }
2978
+ var TABLE_CONSTRAINTS = /* @__PURE__ */ new Set(["CONSTRAINT", "PRIMARY", "UNIQUE", "FOREIGN", "CHECK", "KEY", "EXCLUDE"]);
2979
+ var COLUMN_CONSTRAINTS = [
2980
+ "NOT",
2981
+ "NULL",
2982
+ "DEFAULT",
2983
+ "PRIMARY",
2984
+ "UNIQUE",
2985
+ "CHECK",
2986
+ "REFERENCES",
2987
+ "COLLATE",
2988
+ "GENERATED",
2989
+ "AS",
2990
+ "AUTOINCREMENT",
2991
+ "CONSTRAINT"
2992
+ ];
2993
+ function parseColumn(part) {
2994
+ const nameMatch = /^("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|'[^']*'|[A-Za-z_][A-Za-z0-9_$]*)/.exec(
2995
+ part.trim()
2996
+ );
2997
+ if (nameMatch === null) return null;
2998
+ const name = unquoteIdent(nameMatch[1]);
2999
+ const head = nameMatch[1].toUpperCase();
3000
+ if (TABLE_CONSTRAINTS.has(head)) return null;
3001
+ let rest = part.trim().slice(nameMatch[1].length).trim();
3002
+ if (TABLE_CONSTRAINTS.has(name.toUpperCase()) && rest.startsWith("(")) return null;
3003
+ const upperRest = rest.toUpperCase();
3004
+ let typeEnd = rest.length;
3005
+ for (const keyword of COLUMN_CONSTRAINTS) {
3006
+ const match = new RegExp(`\\b${keyword}\\b`).exec(upperRest);
3007
+ if (match !== null && match.index < typeEnd) typeEnd = match.index;
3008
+ }
3009
+ const type = rest.slice(0, typeEnd).trim();
3010
+ rest = rest.slice(typeEnd).trim();
3011
+ const notNull = /\bNOT\s+NULL\b/i.test(rest);
3012
+ const primaryKey = /\bPRIMARY\s+KEY\b/i.test(rest);
3013
+ const defaultMatch = /\bDEFAULT\s+(.+?)(?=\s+(?:NOT|PRIMARY|UNIQUE|CHECK|REFERENCES|COLLATE|GENERATED|AS|AUTOINCREMENT|CONSTRAINT)\b|$)/i.exec(
3014
+ rest
3015
+ );
3016
+ return {
3017
+ name,
3018
+ type,
3019
+ notNull,
3020
+ primaryKey,
3021
+ defaultValue: defaultMatch === null ? null : defaultMatch[1].trim()
3022
+ };
3023
+ }
3024
+ function parseSchemaTables(sql) {
3025
+ const tables = [];
3026
+ const pattern = /CREATE\s+(?:TEMP|TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|'[^']*'|[A-Za-z_][A-Za-z0-9_$.]*)\s*\(/gi;
3027
+ for (const statement of splitSqlStatements(sql)) {
3028
+ const match = pattern.exec(statement);
3029
+ pattern.lastIndex = 0;
3030
+ if (match === null) continue;
3031
+ const openIndex = match.index + match[0].length - 1;
3032
+ const body = findTableBody(statement, openIndex);
3033
+ if (body === null) continue;
3034
+ const rawName = match[1];
3035
+ const name = unquoteIdent(rawName.split(".").pop() ?? rawName);
3036
+ const columns = [];
3037
+ for (const part of splitTopLevel2(body)) {
3038
+ const column = parseColumn(part);
3039
+ if (column !== null) columns.push(column);
3040
+ }
3041
+ tables.push({ name, columns, statement: statement.trim() });
3042
+ }
3043
+ return tables;
3044
+ }
3045
+ function planMissingColumn(table, column) {
3046
+ const base = `ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${quoteIdent(column.name)}`;
3047
+ let blocked = null;
3048
+ if (column.primaryKey) {
3049
+ blocked = `\u5217 ${table}.${column.name} \u662F PRIMARY KEY\uFF1ASQLite / PG \u7684 ADD COLUMN \u4E0D\u80FD\u65B0\u589E\u4E3B\u952E\u5217\uFF0C\u9700\u8981\u91CD\u5EFA\u8868\uFF08\u5BFC\u51FA \u2192 \u5EFA\u65B0\u8868 \u2192 \u8FC1\u6570\u636E\uFF09\u3002`;
3050
+ } else if (column.notNull && column.defaultValue === null) {
3051
+ blocked = `\u5217 ${table}.${column.name} \u4E3A NOT NULL \u4E14\u65E0 DEFAULT\uFF1A\u65E2\u6709\u884C\u65E0\u6CD5\u81EA\u52A8\u586B\u5145\uFF0C\u8BF7\u5148 \`adep db exec --sql "ALTER TABLE ${table} ADD COLUMN ${column.name} <type> DEFAULT <value>"\` \u56DE\u586B\u540E\u518D\u52A0\u7EA6\u675F\u3002`;
3052
+ }
3053
+ const type = column.type.length === 0 ? "" : ` ${column.type}`;
3054
+ const notNull = column.notNull && column.defaultValue !== null ? " NOT NULL" : "";
3055
+ const fallback = column.defaultValue === null ? "" : ` DEFAULT ${column.defaultValue}`;
3056
+ return {
3057
+ table,
3058
+ column,
3059
+ sql: `${base}${type}${notNull}${fallback}`,
3060
+ blocked
3061
+ };
3062
+ }
3063
+
2845
3064
  // packages/cli/src/serve/sqlite-driver.ts
2846
3065
  import { mkdir as mkdir3 } from "node:fs/promises";
2847
3066
  import { dirname as dirname4, resolve as resolve2 } from "node:path";
@@ -3000,6 +3219,51 @@ async function openLocalDbDriver(target, options) {
3000
3219
  return { mode: "sim", file: null, module: null, driver: null };
3001
3220
  }
3002
3221
  }
3222
+ async function detectMissingColumns(driver, schemaSource, options) {
3223
+ const { mode, tag, log } = options;
3224
+ if (mode !== "sqlite") {
3225
+ log(
3226
+ `[${tag}] sim \u6A21\u5F0F\u4E0D\u505A\u7F3A\u5217\u68C0\u6D4B\uFF08\u5F15\u64CE\u65E0\u5217\u76EE\u5F55\u67E5\u8BE2\uFF09\uFF1B\u7F3A\u5217\u5B88\u536B\u53EA\u5728 sqlite \u6A21\u5F0F\u751F\u6548\u3002`
3227
+ );
3228
+ return null;
3229
+ }
3230
+ const declared = parseSchemaTables(schemaSource);
3231
+ const missing = [];
3232
+ for (const table of declared) {
3233
+ const rows = await driver.all(`SELECT name FROM pragma_table_info(?)`, [table.name]);
3234
+ if (rows.length === 0) continue;
3235
+ const liveNames = new Set(rows.map((row) => String(row["name"] ?? "")));
3236
+ for (const column of table.columns) {
3237
+ if (!liveNames.has(column.name)) missing.push(planMissingColumn(table.name, column));
3238
+ }
3239
+ }
3240
+ if (missing.length === 0) return { missing: [], fixed: [] };
3241
+ const fixable = missing.filter((plan) => plan.blocked === null);
3242
+ const blocked = missing.filter((plan) => plan.blocked !== null);
3243
+ for (const plan of fixable) {
3244
+ log(
3245
+ `[${tag}] \u8B66\u544A\uFF1A\u5B58\u91CF\u8868 "${plan.table}" \u7F3A\u5C11 schema.sql \u58F0\u660E\u7684\u5217 "${plan.column.name}"\uFF08--schema-fix \u53EF\u81EA\u52A8\u8865\u5217\uFF09`
3246
+ );
3247
+ }
3248
+ for (const plan of blocked) {
3249
+ log(`[${tag}] \u8B66\u544A\uFF1A\u5B58\u91CF\u8868 "${plan.table}" \u7F3A\u5C11\u5217 "${plan.column.name}"\u2014\u2014${plan.blocked}`);
3250
+ }
3251
+ const fixed = [];
3252
+ if (options.fix) {
3253
+ for (const plan of fixable) {
3254
+ await driver.run(plan.sql);
3255
+ fixed.push(`${plan.table}.${plan.column.name}`);
3256
+ log(`[${tag}] \u5DF2\u81EA\u52A8\u8865\u5217\uFF1A${plan.table}.${plan.column.name}\uFF08--schema-fix\uFF09`);
3257
+ }
3258
+ }
3259
+ const unresolved = options.fix ? blocked.length : missing.length;
3260
+ if (unresolved > 0) {
3261
+ log(
3262
+ `[${tag}] \u8B66\u544A\uFF1Aschema \u7F3A\u5217\u672A\u89E3\u51B3 ${unresolved} \u5904\u3002RENAME / \u5220\u5217 / \u6539\u7C7B\u578B\u7EF4\u6301\u624B\u5DE5\u8FC1\u79FB\u53E3\u5F84\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u81EA\u52A8\u6267\u884C\u3002`
3263
+ );
3264
+ }
3265
+ return { missing, fixed };
3266
+ }
3003
3267
  async function applyLocalSchema(driver, options) {
3004
3268
  const { schemaFile, mode, tag, cwd, log } = options;
3005
3269
  const schemaPath = resolve3(cwd, schemaFile);
@@ -3033,6 +3297,14 @@ async function applyLocalSchema(driver, options) {
3033
3297
  }
3034
3298
  const skipNote = skipped > 0 ? `\uFF0C\u8DF3\u8FC7 ${skipped} \u6761` : "";
3035
3299
  log(`[${tag}] \u5DF2\u5E94\u7528\u6570\u636E\u5E93\u7ED3\u6784\uFF08--schema ${schemaFile}\uFF09\uFF1A${applied} \u6761\u8BED\u53E5${skipNote}`);
3300
+ const drift = await detectMissingColumns(driver, schemaSource, {
3301
+ cwd,
3302
+ tag,
3303
+ log,
3304
+ mode,
3305
+ fix: options.schemaFix === true
3306
+ });
3307
+ return { applied, skipped, drift };
3036
3308
  }
3037
3309
 
3038
3310
  // packages/runtime/src/shared/fetch-blocked-ports.ts
@@ -4269,6 +4541,14 @@ function resolveModulePath(fromDir, request, files) {
4269
4541
  }
4270
4542
  return null;
4271
4543
  }
4544
+ function escapesFunctionRoot(fromDir, request) {
4545
+ const depth = fromDir.split("/").filter((part) => part.length > 0).length;
4546
+ let ups = 0;
4547
+ for (const part of request.split("/")) {
4548
+ if (part === "..") ups += 1;
4549
+ }
4550
+ return ups > depth;
4551
+ }
4272
4552
  function joinPosix(dir, request) {
4273
4553
  const parts = [...dir.split("/"), ...request.split("/")];
4274
4554
  const stack = [];
@@ -4297,7 +4577,7 @@ function syntaxErrorWithLocation(error, path) {
4297
4577
  if (typeof code === "string") wrapped.code = code;
4298
4578
  return wrapped;
4299
4579
  }
4300
- function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache) {
4580
+ function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache, strictPaths = false) {
4301
4581
  const cached = cache.get(path);
4302
4582
  if (cached !== void 0) return cached;
4303
4583
  const source = files[path];
@@ -4309,9 +4589,16 @@ function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache)
4309
4589
  const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
4310
4590
  const module = { exports, default: void 0 };
4311
4591
  const require2 = (request) => {
4592
+ if (strictPaths && request.startsWith("../") && escapesFunctionRoot(dir, request)) {
4593
+ const error2 = new Error(
4594
+ `\u6C99\u7BB1\u62D2\u7EDD\u8D8A\u6839\u5F15\u7528\uFF1A"${request}"\uFF08\u51FD\u6570\u76EE\u5F55\u4E4B\u5916\u4E0D\u53EF\u5F15\u7528\uFF1B\u5E73\u53F0\u6C99\u7BB1\u540C\u6B64\u7EA6\u675F\uFF0CFN_SANDBOX_ESCAPE_BLOCKED\uFF09`
4595
+ );
4596
+ error2.code = "FN_SANDBOX_ESCAPE_BLOCKED";
4597
+ throw error2;
4598
+ }
4312
4599
  const resolved = resolveModulePath(dir, request, files);
4313
4600
  if (resolved !== null) {
4314
- return loadModule(resolved, files, sandboxGlobals, cache, resolveBare, bareCache);
4601
+ return loadModule(resolved, files, sandboxGlobals, cache, resolveBare, bareCache, strictPaths);
4315
4602
  }
4316
4603
  if (resolveBare !== void 0 && !request.startsWith("./") && !request.startsWith("../")) {
4317
4604
  const cachedModule = bareCache?.get(request);
@@ -4350,10 +4637,18 @@ function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache)
4350
4637
  }
4351
4638
  return exports;
4352
4639
  }
4353
- function loadFunctionModule(files, entry, sandboxGlobals, resolveBare) {
4640
+ function loadFunctionModule(files, entry, sandboxGlobals, resolveBare, strictPaths = false) {
4354
4641
  const cache = /* @__PURE__ */ new Map();
4355
4642
  const bareCache = /* @__PURE__ */ new Map();
4356
- const entryExports = loadModule(entry, files, sandboxGlobals, cache, resolveBare, bareCache);
4643
+ const entryExports = loadModule(
4644
+ entry,
4645
+ files,
4646
+ sandboxGlobals,
4647
+ cache,
4648
+ resolveBare,
4649
+ bareCache,
4650
+ strictPaths
4651
+ );
4357
4652
  const handler = entryExports["default"];
4358
4653
  if (typeof handler !== "function") {
4359
4654
  throw new Error(`\u5165\u53E3\u6587\u4EF6 ${entry} \u7F3A\u5C11 default \u5BFC\u51FA\u7684\u51FD\u6570`);
@@ -5062,9 +5357,14 @@ function runWorker(input, port) {
5062
5357
  performance,
5063
5358
  atob,
5064
5359
  btoa,
5065
- structuredClone
5360
+ structuredClone,
5361
+ // CORE-154:定时器家族(纯本地定时,无出网/句柄面;清单见 SANDBOX_GLOBAL_KEYS 钉测面)。
5362
+ setTimeout,
5363
+ clearTimeout,
5364
+ setInterval,
5365
+ clearInterval
5066
5366
  };
5067
- if (input.env !== void 0) {
5367
+ if (input.env !== void 0 && input.parity !== true) {
5068
5368
  sandboxGlobals["process"] = realmValue({ env: input.env });
5069
5369
  }
5070
5370
  if (input.fetch !== void 0) {
@@ -5092,7 +5392,9 @@ function runWorker(input, port) {
5092
5392
  input.files,
5093
5393
  input.entry,
5094
5394
  sandboxGlobals,
5095
- input.deps === void 0 ? void 0 : createBareResolver(input.deps)
5395
+ input.deps === void 0 ? void 0 : createBareResolver(input.deps),
5396
+ // CORE-154:--parity 严格模式连带 `../` 越根引用报错(与容器形态真实 fs 同形)。
5397
+ input.parity === true
5096
5398
  );
5097
5399
  const result = Promise.resolve(handler(ctx));
5098
5400
  void result.then(
@@ -5267,9 +5569,12 @@ function parseMultipart(contentType, raw) {
5267
5569
  // packages/cli/src/dev-shared.ts
5268
5570
  var BEARER_TOKEN_RE = /^Bearer\s+(.+)$/i;
5269
5571
  function bearerUserResolverFromEnv(fileEnv = {}) {
5270
- const raw = firstNonEmpty(process.env.ADEP_AUTH_ISSUER, fileEnv.ADEP_AUTH_ISSUER);
5572
+ const raw = resolveEffectiveIssuer(fileEnv);
5271
5573
  return raw === void 0 ? void 0 : createBearerUserResolver(raw);
5272
5574
  }
5575
+ function resolveEffectiveIssuer(fileEnv = {}) {
5576
+ return firstNonEmpty(process.env.ADEP_AUTH_ISSUER, fileEnv.ADEP_AUTH_ISSUER);
5577
+ }
5273
5578
  function firstNonEmpty(...values) {
5274
5579
  for (const value of values) {
5275
5580
  const trimmed = value?.trim();
@@ -441,6 +441,14 @@ function resolveModulePath(fromDir, request, files) {
441
441
  }
442
442
  return null;
443
443
  }
444
+ function escapesFunctionRoot(fromDir, request) {
445
+ const depth = fromDir.split("/").filter((part) => part.length > 0).length;
446
+ let ups = 0;
447
+ for (const part of request.split("/")) {
448
+ if (part === "..") ups += 1;
449
+ }
450
+ return ups > depth;
451
+ }
444
452
  function joinPosix(dir, request) {
445
453
  const parts = [...dir.split("/"), ...request.split("/")];
446
454
  const stack = [];
@@ -469,7 +477,7 @@ function syntaxErrorWithLocation(error, path) {
469
477
  if (typeof code === "string") wrapped.code = code;
470
478
  return wrapped;
471
479
  }
472
- function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache) {
480
+ function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache, strictPaths = false) {
473
481
  const cached = cache.get(path);
474
482
  if (cached !== void 0) return cached;
475
483
  const source = files[path];
@@ -481,9 +489,16 @@ function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache)
481
489
  const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
482
490
  const module = { exports, default: void 0 };
483
491
  const require2 = (request) => {
492
+ if (strictPaths && request.startsWith("../") && escapesFunctionRoot(dir, request)) {
493
+ const error2 = new Error(
494
+ `\u6C99\u7BB1\u62D2\u7EDD\u8D8A\u6839\u5F15\u7528\uFF1A"${request}"\uFF08\u51FD\u6570\u76EE\u5F55\u4E4B\u5916\u4E0D\u53EF\u5F15\u7528\uFF1B\u5E73\u53F0\u6C99\u7BB1\u540C\u6B64\u7EA6\u675F\uFF0CFN_SANDBOX_ESCAPE_BLOCKED\uFF09`
495
+ );
496
+ error2.code = "FN_SANDBOX_ESCAPE_BLOCKED";
497
+ throw error2;
498
+ }
484
499
  const resolved = resolveModulePath(dir, request, files);
485
500
  if (resolved !== null) {
486
- return loadModule(resolved, files, sandboxGlobals, cache, resolveBare, bareCache);
501
+ return loadModule(resolved, files, sandboxGlobals, cache, resolveBare, bareCache, strictPaths);
487
502
  }
488
503
  if (resolveBare !== void 0 && !request.startsWith("./") && !request.startsWith("../")) {
489
504
  const cachedModule = bareCache?.get(request);
@@ -522,10 +537,18 @@ function loadModule(path, files, sandboxGlobals, cache, resolveBare, bareCache)
522
537
  }
523
538
  return exports;
524
539
  }
525
- function loadFunctionModule(files, entry, sandboxGlobals, resolveBare) {
540
+ function loadFunctionModule(files, entry, sandboxGlobals, resolveBare, strictPaths = false) {
526
541
  const cache = /* @__PURE__ */ new Map();
527
542
  const bareCache = /* @__PURE__ */ new Map();
528
- const entryExports = loadModule(entry, files, sandboxGlobals, cache, resolveBare, bareCache);
543
+ const entryExports = loadModule(
544
+ entry,
545
+ files,
546
+ sandboxGlobals,
547
+ cache,
548
+ resolveBare,
549
+ bareCache,
550
+ strictPaths
551
+ );
529
552
  const handler = entryExports["default"];
530
553
  if (typeof handler !== "function") {
531
554
  throw new Error(`\u5165\u53E3\u6587\u4EF6 ${entry} \u7F3A\u5C11 default \u5BFC\u51FA\u7684\u51FD\u6570`);
@@ -1023,6 +1046,37 @@ function splitBareSpecifier(request) {
1023
1046
  }
1024
1047
 
1025
1048
  // packages/runtime/src/functions/runtime/worker-entry.ts
1049
+ var SANDBOX_GLOBAL_KEYS = [
1050
+ "console",
1051
+ // CF-015:Cloudflare Workers 代码重度依赖 Web 标准 API(URL / Request / Response /
1052
+ // Headers / 流 / 编码 / crypto 等)。Node 18+ 全局内置,直接注入 vm 上下文;
1053
+ // 与 @adep/cf-compat 的 Workers 适配(ctxToRequest / responseToEnvelopeBody)配套。
1054
+ "URL",
1055
+ "URLSearchParams",
1056
+ "Request",
1057
+ "Response",
1058
+ "Headers",
1059
+ "TextEncoder",
1060
+ "TextDecoder",
1061
+ "AbortController",
1062
+ "AbortSignal",
1063
+ "ReadableStream",
1064
+ "WritableStream",
1065
+ "TransformStream",
1066
+ "Blob",
1067
+ "FormData",
1068
+ "crypto",
1069
+ "performance",
1070
+ "atob",
1071
+ "btoa",
1072
+ "structuredClone",
1073
+ // CORE-154:定时器家族——esign 重试退避用 setTimeout 直接 ReferenceError(比原错误更难排查),
1074
+ // 被迫借 AbortSignal.timeout 的 abort 事件定时。本地定时无出网面,注入后与容器形态同形。
1075
+ "setTimeout",
1076
+ "clearTimeout",
1077
+ "setInterval",
1078
+ "clearInterval"
1079
+ ];
1026
1080
  function errorMessageOf2(error) {
1027
1081
  if (error instanceof Error) return error.message;
1028
1082
  if (typeof error === "object" && error !== null && "message" in error) {
@@ -1151,9 +1205,14 @@ function runWorker(input, port) {
1151
1205
  performance,
1152
1206
  atob,
1153
1207
  btoa,
1154
- structuredClone
1208
+ structuredClone,
1209
+ // CORE-154:定时器家族(纯本地定时,无出网/句柄面;清单见 SANDBOX_GLOBAL_KEYS 钉测面)。
1210
+ setTimeout,
1211
+ clearTimeout,
1212
+ setInterval,
1213
+ clearInterval
1155
1214
  };
1156
- if (input.env !== void 0) {
1215
+ if (input.env !== void 0 && input.parity !== true) {
1157
1216
  sandboxGlobals["process"] = realmValue({ env: input.env });
1158
1217
  }
1159
1218
  if (input.fetch !== void 0) {
@@ -1181,7 +1240,9 @@ function runWorker(input, port) {
1181
1240
  input.files,
1182
1241
  input.entry,
1183
1242
  sandboxGlobals,
1184
- input.deps === void 0 ? void 0 : createBareResolver(input.deps)
1243
+ input.deps === void 0 ? void 0 : createBareResolver(input.deps),
1244
+ // CORE-154:--parity 严格模式连带 `../` 越根引用报错(与容器形态真实 fs 同形)。
1245
+ input.parity === true
1185
1246
  );
1186
1247
  const result = Promise.resolve(handler(ctx));
1187
1248
  void result.then(
@@ -1233,6 +1294,7 @@ if (workerPort !== null && workerData !== void 0) {
1233
1294
  runWorker(workerData, port);
1234
1295
  }
1235
1296
  export {
1297
+ SANDBOX_GLOBAL_KEYS,
1236
1298
  createBareResolver,
1237
1299
  runWorker
1238
1300
  };
package/package.json CHANGED
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://adep.top",
9
9
  "bugs": "https://gitcode.com/yunqiang_wu/ai-yunke/issues",
10
- "version": "0.5.0",
10
+ "version": "0.5.2",
11
11
  "type": "module",
12
12
  "description": "`adep` 命令行工具包位:登录 / 初始化 / 本地调试 / 部署 / 数据库维护 / 云存储 / 静态托管 / 微前端组件(widget),实现见任务单 CLI-001 ~ CLI-003 与 FE-002;子路径 `@adep/cli/vite` 提供云函数 vite 插件(CLI-014)",
13
13
  "bin": {
@@ -30,14 +30,14 @@
30
30
  "esbuild": "0.25.12",
31
31
  "yaml": "2.9.1",
32
32
  "zod": "^4.6.6",
33
- "@adep/app-runtime": "0.1.1",
34
33
  "@adep/cf-compat": "0.1.4",
35
- "@adep/crypto": "0.1.1",
34
+ "@adep/app-runtime": "0.1.1",
36
35
  "@adep/vite-plugin": "0.1.11",
37
- "@adep/runtime": "0.3.8"
36
+ "@adep/crypto": "0.1.1",
37
+ "@adep/runtime": "0.3.9"
38
38
  },
39
39
  "devDependencies": {
40
- "@adep/types": "0.4.0"
40
+ "@adep/types": "0.4.2"
41
41
  },
42
42
  "scripts": {
43
43
  "test": "vitest run",