@vercel/python 6.54.1 → 6.55.1

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/index.js CHANGED
@@ -137,12 +137,12 @@ var require_isexe = __commonJS({
137
137
  if (typeof Promise !== "function") {
138
138
  throw new TypeError("callback not provided");
139
139
  }
140
- return new Promise(function(resolve3, reject) {
140
+ return new Promise(function(resolve4, reject) {
141
141
  isexe(path, options || {}, function(er, is) {
142
142
  if (er) {
143
143
  reject(er);
144
144
  } else {
145
- resolve3(is);
145
+ resolve4(is);
146
146
  }
147
147
  });
148
148
  });
@@ -423,15 +423,15 @@ var require_readShebang = __commonJS({
423
423
  var require_semver = __commonJS({
424
424
  "../../node_modules/.pnpm/semver@5.7.2/node_modules/semver/semver.js"(exports, module2) {
425
425
  exports = module2.exports = SemVer;
426
- var debug17;
426
+ var debug18;
427
427
  if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
428
- debug17 = function() {
428
+ debug18 = function() {
429
429
  var args = Array.prototype.slice.call(arguments, 0);
430
430
  args.unshift("SEMVER");
431
431
  console.log.apply(console, args);
432
432
  };
433
433
  } else {
434
- debug17 = function() {
434
+ debug18 = function() {
435
435
  };
436
436
  }
437
437
  exports.SEMVER_SPEC_VERSION = "2.0.0";
@@ -540,7 +540,7 @@ var require_semver = __commonJS({
540
540
  var STAR = R++;
541
541
  src[STAR] = "(<|>)?=?\\s*\\*";
542
542
  for (i = 0; i < R; i++) {
543
- debug17(i, src[i]);
543
+ debug18(i, src[i]);
544
544
  if (!re[i]) {
545
545
  re[i] = new RegExp(src[i]);
546
546
  safeRe[i] = new RegExp(makeSafeRe(src[i]));
@@ -607,7 +607,7 @@ var require_semver = __commonJS({
607
607
  if (!(this instanceof SemVer)) {
608
608
  return new SemVer(version2, options);
609
609
  }
610
- debug17("SemVer", version2, options);
610
+ debug18("SemVer", version2, options);
611
611
  this.options = options;
612
612
  this.loose = !!options.loose;
613
613
  var m = version2.trim().match(options.loose ? safeRe[LOOSE] : safeRe[FULL]);
@@ -654,7 +654,7 @@ var require_semver = __commonJS({
654
654
  return this.version;
655
655
  };
656
656
  SemVer.prototype.compare = function(other) {
657
- debug17("SemVer.compare", this.version, this.options, other);
657
+ debug18("SemVer.compare", this.version, this.options, other);
658
658
  if (!(other instanceof SemVer)) {
659
659
  other = new SemVer(other, this.options);
660
660
  }
@@ -681,7 +681,7 @@ var require_semver = __commonJS({
681
681
  do {
682
682
  var a = this.prerelease[i2];
683
683
  var b = other.prerelease[i2];
684
- debug17("prerelease compare", i2, a, b);
684
+ debug18("prerelease compare", i2, a, b);
685
685
  if (a === void 0 && b === void 0) {
686
686
  return 0;
687
687
  } else if (b === void 0) {
@@ -935,7 +935,7 @@ var require_semver = __commonJS({
935
935
  return new Comparator(comp, options);
936
936
  }
937
937
  comp = comp.trim().split(/\s+/).join(" ");
938
- debug17("comparator", comp, options);
938
+ debug18("comparator", comp, options);
939
939
  this.options = options;
940
940
  this.loose = !!options.loose;
941
941
  this.parse(comp);
@@ -944,7 +944,7 @@ var require_semver = __commonJS({
944
944
  } else {
945
945
  this.value = this.operator + this.semver.version;
946
946
  }
947
- debug17("comp", this);
947
+ debug18("comp", this);
948
948
  }
949
949
  var ANY = {};
950
950
  Comparator.prototype.parse = function(comp) {
@@ -967,7 +967,7 @@ var require_semver = __commonJS({
967
967
  return this.value;
968
968
  };
969
969
  Comparator.prototype.test = function(version2) {
970
- debug17("Comparator.test", version2, this.options.loose);
970
+ debug18("Comparator.test", version2, this.options.loose);
971
971
  if (this.semver === ANY) {
972
972
  return true;
973
973
  }
@@ -1050,9 +1050,9 @@ var require_semver = __commonJS({
1050
1050
  var loose = this.options.loose;
1051
1051
  var hr = loose ? safeRe[HYPHENRANGELOOSE] : safeRe[HYPHENRANGE];
1052
1052
  range = range.replace(hr, hyphenReplace);
1053
- debug17("hyphen replace", range);
1053
+ debug18("hyphen replace", range);
1054
1054
  range = range.replace(safeRe[COMPARATORTRIM], comparatorTrimReplace);
1055
- debug17("comparator trim", range, safeRe[COMPARATORTRIM]);
1055
+ debug18("comparator trim", range, safeRe[COMPARATORTRIM]);
1056
1056
  range = range.replace(safeRe[TILDETRIM], tildeTrimReplace);
1057
1057
  range = range.replace(safeRe[CARETTRIM], caretTrimReplace);
1058
1058
  var compRe = loose ? safeRe[COMPARATORLOOSE] : safeRe[COMPARATOR];
@@ -1092,15 +1092,15 @@ var require_semver = __commonJS({
1092
1092
  });
1093
1093
  }
1094
1094
  function parseComparator(comp, options) {
1095
- debug17("comp", comp, options);
1095
+ debug18("comp", comp, options);
1096
1096
  comp = replaceCarets(comp, options);
1097
- debug17("caret", comp);
1097
+ debug18("caret", comp);
1098
1098
  comp = replaceTildes(comp, options);
1099
- debug17("tildes", comp);
1099
+ debug18("tildes", comp);
1100
1100
  comp = replaceXRanges(comp, options);
1101
- debug17("xrange", comp);
1101
+ debug18("xrange", comp);
1102
1102
  comp = replaceStars(comp, options);
1103
- debug17("stars", comp);
1103
+ debug18("stars", comp);
1104
1104
  return comp;
1105
1105
  }
1106
1106
  function isX(id) {
@@ -1114,7 +1114,7 @@ var require_semver = __commonJS({
1114
1114
  function replaceTilde(comp, options) {
1115
1115
  var r = options.loose ? safeRe[TILDELOOSE] : safeRe[TILDE];
1116
1116
  return comp.replace(r, function(_, M, m, p, pr) {
1117
- debug17("tilde", comp, _, M, m, p, pr);
1117
+ debug18("tilde", comp, _, M, m, p, pr);
1118
1118
  var ret;
1119
1119
  if (isX(M)) {
1120
1120
  ret = "";
@@ -1123,12 +1123,12 @@ var require_semver = __commonJS({
1123
1123
  } else if (isX(p)) {
1124
1124
  ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
1125
1125
  } else if (pr) {
1126
- debug17("replaceTilde pr", pr);
1126
+ debug18("replaceTilde pr", pr);
1127
1127
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
1128
1128
  } else {
1129
1129
  ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
1130
1130
  }
1131
- debug17("tilde return", ret);
1131
+ debug18("tilde return", ret);
1132
1132
  return ret;
1133
1133
  });
1134
1134
  }
@@ -1138,10 +1138,10 @@ var require_semver = __commonJS({
1138
1138
  }).join(" ");
1139
1139
  }
1140
1140
  function replaceCaret(comp, options) {
1141
- debug17("caret", comp, options);
1141
+ debug18("caret", comp, options);
1142
1142
  var r = options.loose ? safeRe[CARETLOOSE] : safeRe[CARET];
1143
1143
  return comp.replace(r, function(_, M, m, p, pr) {
1144
- debug17("caret", comp, _, M, m, p, pr);
1144
+ debug18("caret", comp, _, M, m, p, pr);
1145
1145
  var ret;
1146
1146
  if (isX(M)) {
1147
1147
  ret = "";
@@ -1154,7 +1154,7 @@ var require_semver = __commonJS({
1154
1154
  ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0";
1155
1155
  }
1156
1156
  } else if (pr) {
1157
- debug17("replaceCaret pr", pr);
1157
+ debug18("replaceCaret pr", pr);
1158
1158
  if (M === "0") {
1159
1159
  if (m === "0") {
1160
1160
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1);
@@ -1165,7 +1165,7 @@ var require_semver = __commonJS({
1165
1165
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0";
1166
1166
  }
1167
1167
  } else {
1168
- debug17("no pr");
1168
+ debug18("no pr");
1169
1169
  if (M === "0") {
1170
1170
  if (m === "0") {
1171
1171
  ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1);
@@ -1176,12 +1176,12 @@ var require_semver = __commonJS({
1176
1176
  ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0";
1177
1177
  }
1178
1178
  }
1179
- debug17("caret return", ret);
1179
+ debug18("caret return", ret);
1180
1180
  return ret;
1181
1181
  });
1182
1182
  }
1183
1183
  function replaceXRanges(comp, options) {
1184
- debug17("replaceXRanges", comp, options);
1184
+ debug18("replaceXRanges", comp, options);
1185
1185
  return comp.split(/\s+/).map(function(comp2) {
1186
1186
  return replaceXRange(comp2, options);
1187
1187
  }).join(" ");
@@ -1190,7 +1190,7 @@ var require_semver = __commonJS({
1190
1190
  comp = comp.trim();
1191
1191
  var r = options.loose ? safeRe[XRANGELOOSE] : safeRe[XRANGE];
1192
1192
  return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
1193
- debug17("xRange", comp, ret, gtlt, M, m, p, pr);
1193
+ debug18("xRange", comp, ret, gtlt, M, m, p, pr);
1194
1194
  var xM = isX(M);
1195
1195
  var xm = xM || isX(m);
1196
1196
  var xp = xm || isX(p);
@@ -1233,12 +1233,12 @@ var require_semver = __commonJS({
1233
1233
  } else if (xp) {
1234
1234
  ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
1235
1235
  }
1236
- debug17("xRange return", ret);
1236
+ debug18("xRange return", ret);
1237
1237
  return ret;
1238
1238
  });
1239
1239
  }
1240
1240
  function replaceStars(comp, options) {
1241
- debug17("replaceStars", comp, options);
1241
+ debug18("replaceStars", comp, options);
1242
1242
  return comp.trim().replace(safeRe[STAR], "");
1243
1243
  }
1244
1244
  function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
@@ -1286,7 +1286,7 @@ var require_semver = __commonJS({
1286
1286
  }
1287
1287
  if (version2.prerelease.length && !options.includePrerelease) {
1288
1288
  for (i2 = 0; i2 < set.length; i2++) {
1289
- debug17(set[i2].semver);
1289
+ debug18(set[i2].semver);
1290
1290
  if (set[i2].semver === ANY) {
1291
1291
  continue;
1292
1292
  }
@@ -2042,7 +2042,7 @@ var require_get_stream = __commonJS({
2042
2042
  options = Object.assign({ maxBuffer: Infinity }, options);
2043
2043
  const { maxBuffer } = options;
2044
2044
  let stream;
2045
- return new Promise((resolve3, reject) => {
2045
+ return new Promise((resolve4, reject) => {
2046
2046
  const rejectPromise = (error) => {
2047
2047
  if (error) {
2048
2048
  error.bufferedData = stream.getBufferedValue();
@@ -2054,7 +2054,7 @@ var require_get_stream = __commonJS({
2054
2054
  rejectPromise(error);
2055
2055
  return;
2056
2056
  }
2057
- resolve3();
2057
+ resolve4();
2058
2058
  });
2059
2059
  stream.on("data", () => {
2060
2060
  if (stream.getBufferedLength() > maxBuffer) {
@@ -2078,11 +2078,11 @@ var require_p_finally = __commonJS({
2078
2078
  onFinally = onFinally || (() => {
2079
2079
  });
2080
2080
  return promise.then(
2081
- (val) => new Promise((resolve3) => {
2082
- resolve3(onFinally());
2081
+ (val) => new Promise((resolve4) => {
2082
+ resolve4(onFinally());
2083
2083
  }).then(() => val),
2084
- (err) => new Promise((resolve3) => {
2085
- resolve3(onFinally());
2084
+ (err) => new Promise((resolve4) => {
2085
+ resolve4(onFinally());
2086
2086
  }).then(() => {
2087
2087
  throw err;
2088
2088
  })
@@ -2461,8 +2461,8 @@ var require_execa = __commonJS({
2461
2461
  }
2462
2462
  let ret;
2463
2463
  if (!buffer) {
2464
- ret = new Promise((resolve3, reject) => {
2465
- process2[stream].once("end", resolve3).once("error", reject);
2464
+ ret = new Promise((resolve4, reject) => {
2465
+ process2[stream].once("end", resolve4).once("error", reject);
2466
2466
  });
2467
2467
  } else if (encoding) {
2468
2468
  ret = _getStream(process2[stream], {
@@ -2551,19 +2551,19 @@ ${stderr}${stdout}`;
2551
2551
  spawned.kill(parsed.opts.killSignal);
2552
2552
  }, parsed.opts.timeout);
2553
2553
  }
2554
- const processDone = new Promise((resolve3) => {
2554
+ const processDone = new Promise((resolve4) => {
2555
2555
  spawned.on("exit", (code, signal) => {
2556
2556
  cleanup();
2557
- resolve3({ code, signal });
2557
+ resolve4({ code, signal });
2558
2558
  });
2559
2559
  spawned.on("error", (err) => {
2560
2560
  cleanup();
2561
- resolve3({ error: err });
2561
+ resolve4({ error: err });
2562
2562
  });
2563
2563
  if (spawned.stdin) {
2564
2564
  spawned.stdin.on("error", (err) => {
2565
2565
  cleanup();
2566
- resolve3({ error: err });
2566
+ resolve4({ error: err });
2567
2567
  });
2568
2568
  }
2569
2569
  });
@@ -3301,9 +3301,9 @@ var require_pep440 = __commonJS({
3301
3301
  var require_lib = __commonJS({
3302
3302
  "../../node_modules/.pnpm/which@3.0.0/node_modules/which/lib/index.js"(exports, module2) {
3303
3303
  var isexe = require_isexe();
3304
- var { join: join20, delimiter: delimiter2, sep: sep3, posix } = require("path");
3304
+ var { join: join21, delimiter: delimiter2, sep: sep4, posix } = require("path");
3305
3305
  var isWindows = process.platform === "win32";
3306
- var rSlash = new RegExp(`[${posix.sep}${sep3 === posix.sep ? "" : sep3}]`.replace(/(\\)/g, "\\$1"));
3306
+ var rSlash = new RegExp(`[${posix.sep}${sep4 === posix.sep ? "" : sep4}]`.replace(/(\\)/g, "\\$1"));
3307
3307
  var rRel = new RegExp(`^\\.${rSlash.source}`);
3308
3308
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
3309
3309
  var getPathInfo = (cmd, {
@@ -3330,7 +3330,7 @@ var require_lib = __commonJS({
3330
3330
  var getPathPart = (raw, cmd) => {
3331
3331
  const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
3332
3332
  const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
3333
- return prefix + join20(pathPart, cmd);
3333
+ return prefix + join21(pathPart, cmd);
3334
3334
  };
3335
3335
  var which2 = async (cmd, opt = {}) => {
3336
3336
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
@@ -3389,15 +3389,15 @@ var require_lib = __commonJS({
3389
3389
  var require_semver2 = __commonJS({
3390
3390
  "../../node_modules/.pnpm/semver@6.3.1/node_modules/semver/semver.js"(exports, module2) {
3391
3391
  exports = module2.exports = SemVer;
3392
- var debug17;
3392
+ var debug18;
3393
3393
  if (typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
3394
- debug17 = function() {
3394
+ debug18 = function() {
3395
3395
  var args = Array.prototype.slice.call(arguments, 0);
3396
3396
  args.unshift("SEMVER");
3397
3397
  console.log.apply(console, args);
3398
3398
  };
3399
3399
  } else {
3400
- debug17 = function() {
3400
+ debug18 = function() {
3401
3401
  };
3402
3402
  }
3403
3403
  exports.SEMVER_SPEC_VERSION = "2.0.0";
@@ -3515,7 +3515,7 @@ var require_semver2 = __commonJS({
3515
3515
  tok("STAR");
3516
3516
  src[t.STAR] = "(<|>)?=?\\s*\\*";
3517
3517
  for (i = 0; i < R; i++) {
3518
- debug17(i, src[i]);
3518
+ debug18(i, src[i]);
3519
3519
  if (!re[i]) {
3520
3520
  re[i] = new RegExp(src[i]);
3521
3521
  safeRe[i] = new RegExp(makeSafeRe(src[i]));
@@ -3582,7 +3582,7 @@ var require_semver2 = __commonJS({
3582
3582
  if (!(this instanceof SemVer)) {
3583
3583
  return new SemVer(version2, options);
3584
3584
  }
3585
- debug17("SemVer", version2, options);
3585
+ debug18("SemVer", version2, options);
3586
3586
  this.options = options;
3587
3587
  this.loose = !!options.loose;
3588
3588
  var m = version2.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]);
@@ -3629,7 +3629,7 @@ var require_semver2 = __commonJS({
3629
3629
  return this.version;
3630
3630
  };
3631
3631
  SemVer.prototype.compare = function(other) {
3632
- debug17("SemVer.compare", this.version, this.options, other);
3632
+ debug18("SemVer.compare", this.version, this.options, other);
3633
3633
  if (!(other instanceof SemVer)) {
3634
3634
  other = new SemVer(other, this.options);
3635
3635
  }
@@ -3656,7 +3656,7 @@ var require_semver2 = __commonJS({
3656
3656
  do {
3657
3657
  var a = this.prerelease[i2];
3658
3658
  var b = other.prerelease[i2];
3659
- debug17("prerelease compare", i2, a, b);
3659
+ debug18("prerelease compare", i2, a, b);
3660
3660
  if (a === void 0 && b === void 0) {
3661
3661
  return 0;
3662
3662
  } else if (b === void 0) {
@@ -3678,7 +3678,7 @@ var require_semver2 = __commonJS({
3678
3678
  do {
3679
3679
  var a = this.build[i2];
3680
3680
  var b = other.build[i2];
3681
- debug17("prerelease compare", i2, a, b);
3681
+ debug18("prerelease compare", i2, a, b);
3682
3682
  if (a === void 0 && b === void 0) {
3683
3683
  return 0;
3684
3684
  } else if (b === void 0) {
@@ -3938,7 +3938,7 @@ var require_semver2 = __commonJS({
3938
3938
  return new Comparator(comp, options);
3939
3939
  }
3940
3940
  comp = comp.trim().split(/\s+/).join(" ");
3941
- debug17("comparator", comp, options);
3941
+ debug18("comparator", comp, options);
3942
3942
  this.options = options;
3943
3943
  this.loose = !!options.loose;
3944
3944
  this.parse(comp);
@@ -3947,7 +3947,7 @@ var require_semver2 = __commonJS({
3947
3947
  } else {
3948
3948
  this.value = this.operator + this.semver.version;
3949
3949
  }
3950
- debug17("comp", this);
3950
+ debug18("comp", this);
3951
3951
  }
3952
3952
  var ANY = {};
3953
3953
  Comparator.prototype.parse = function(comp) {
@@ -3970,7 +3970,7 @@ var require_semver2 = __commonJS({
3970
3970
  return this.value;
3971
3971
  };
3972
3972
  Comparator.prototype.test = function(version2) {
3973
- debug17("Comparator.test", version2, this.options.loose);
3973
+ debug18("Comparator.test", version2, this.options.loose);
3974
3974
  if (this.semver === ANY || version2 === ANY) {
3975
3975
  return true;
3976
3976
  }
@@ -4063,9 +4063,9 @@ var require_semver2 = __commonJS({
4063
4063
  var loose = this.options.loose;
4064
4064
  var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE];
4065
4065
  range = range.replace(hr, hyphenReplace);
4066
- debug17("hyphen replace", range);
4066
+ debug18("hyphen replace", range);
4067
4067
  range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace);
4068
- debug17("comparator trim", range, safeRe[t.COMPARATORTRIM]);
4068
+ debug18("comparator trim", range, safeRe[t.COMPARATORTRIM]);
4069
4069
  range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace);
4070
4070
  range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace);
4071
4071
  range = range.split(/\s+/).join(" ");
@@ -4118,15 +4118,15 @@ var require_semver2 = __commonJS({
4118
4118
  });
4119
4119
  }
4120
4120
  function parseComparator(comp, options) {
4121
- debug17("comp", comp, options);
4121
+ debug18("comp", comp, options);
4122
4122
  comp = replaceCarets(comp, options);
4123
- debug17("caret", comp);
4123
+ debug18("caret", comp);
4124
4124
  comp = replaceTildes(comp, options);
4125
- debug17("tildes", comp);
4125
+ debug18("tildes", comp);
4126
4126
  comp = replaceXRanges(comp, options);
4127
- debug17("xrange", comp);
4127
+ debug18("xrange", comp);
4128
4128
  comp = replaceStars(comp, options);
4129
- debug17("stars", comp);
4129
+ debug18("stars", comp);
4130
4130
  return comp;
4131
4131
  }
4132
4132
  function isX(id) {
@@ -4140,7 +4140,7 @@ var require_semver2 = __commonJS({
4140
4140
  function replaceTilde(comp, options) {
4141
4141
  var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE];
4142
4142
  return comp.replace(r, function(_, M, m, p, pr) {
4143
- debug17("tilde", comp, _, M, m, p, pr);
4143
+ debug18("tilde", comp, _, M, m, p, pr);
4144
4144
  var ret;
4145
4145
  if (isX(M)) {
4146
4146
  ret = "";
@@ -4149,12 +4149,12 @@ var require_semver2 = __commonJS({
4149
4149
  } else if (isX(p)) {
4150
4150
  ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
4151
4151
  } else if (pr) {
4152
- debug17("replaceTilde pr", pr);
4152
+ debug18("replaceTilde pr", pr);
4153
4153
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
4154
4154
  } else {
4155
4155
  ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
4156
4156
  }
4157
- debug17("tilde return", ret);
4157
+ debug18("tilde return", ret);
4158
4158
  return ret;
4159
4159
  });
4160
4160
  }
@@ -4164,10 +4164,10 @@ var require_semver2 = __commonJS({
4164
4164
  }).join(" ");
4165
4165
  }
4166
4166
  function replaceCaret(comp, options) {
4167
- debug17("caret", comp, options);
4167
+ debug18("caret", comp, options);
4168
4168
  var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET];
4169
4169
  return comp.replace(r, function(_, M, m, p, pr) {
4170
- debug17("caret", comp, _, M, m, p, pr);
4170
+ debug18("caret", comp, _, M, m, p, pr);
4171
4171
  var ret;
4172
4172
  if (isX(M)) {
4173
4173
  ret = "";
@@ -4180,7 +4180,7 @@ var require_semver2 = __commonJS({
4180
4180
  ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0";
4181
4181
  }
4182
4182
  } else if (pr) {
4183
- debug17("replaceCaret pr", pr);
4183
+ debug18("replaceCaret pr", pr);
4184
4184
  if (M === "0") {
4185
4185
  if (m === "0") {
4186
4186
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1);
@@ -4191,7 +4191,7 @@ var require_semver2 = __commonJS({
4191
4191
  ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0";
4192
4192
  }
4193
4193
  } else {
4194
- debug17("no pr");
4194
+ debug18("no pr");
4195
4195
  if (M === "0") {
4196
4196
  if (m === "0") {
4197
4197
  ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1);
@@ -4202,12 +4202,12 @@ var require_semver2 = __commonJS({
4202
4202
  ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0";
4203
4203
  }
4204
4204
  }
4205
- debug17("caret return", ret);
4205
+ debug18("caret return", ret);
4206
4206
  return ret;
4207
4207
  });
4208
4208
  }
4209
4209
  function replaceXRanges(comp, options) {
4210
- debug17("replaceXRanges", comp, options);
4210
+ debug18("replaceXRanges", comp, options);
4211
4211
  return comp.split(/\s+/).map(function(comp2) {
4212
4212
  return replaceXRange(comp2, options);
4213
4213
  }).join(" ");
@@ -4216,7 +4216,7 @@ var require_semver2 = __commonJS({
4216
4216
  comp = comp.trim();
4217
4217
  var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE];
4218
4218
  return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
4219
- debug17("xRange", comp, ret, gtlt, M, m, p, pr);
4219
+ debug18("xRange", comp, ret, gtlt, M, m, p, pr);
4220
4220
  var xM = isX(M);
4221
4221
  var xm = xM || isX(m);
4222
4222
  var xp = xm || isX(p);
@@ -4260,12 +4260,12 @@ var require_semver2 = __commonJS({
4260
4260
  } else if (xp) {
4261
4261
  ret = ">=" + M + "." + m + ".0" + pr + " <" + M + "." + (+m + 1) + ".0" + pr;
4262
4262
  }
4263
- debug17("xRange return", ret);
4263
+ debug18("xRange return", ret);
4264
4264
  return ret;
4265
4265
  });
4266
4266
  }
4267
4267
  function replaceStars(comp, options) {
4268
- debug17("replaceStars", comp, options);
4268
+ debug18("replaceStars", comp, options);
4269
4269
  return comp.trim().replace(safeRe[t.STAR], "");
4270
4270
  }
4271
4271
  function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
@@ -4317,7 +4317,7 @@ var require_semver2 = __commonJS({
4317
4317
  }
4318
4318
  if (version2.prerelease.length && !options.includePrerelease) {
4319
4319
  for (i2 = 0; i2 < set.length; i2++) {
4320
- debug17(set[i2].semver);
4320
+ debug18(set[i2].semver);
4321
4321
  if (set[i2].semver === ANY) {
4322
4322
  continue;
4323
4323
  }
@@ -4574,14 +4574,14 @@ var require_filesystem = __commonJS({
4574
4574
  });
4575
4575
  return buffer.subarray(0, bytesRead);
4576
4576
  };
4577
- var readFile2 = (path) => new Promise((resolve3, reject) => {
4577
+ var readFile2 = (path) => new Promise((resolve4, reject) => {
4578
4578
  fs19.open(path, "r", (err, fd) => {
4579
4579
  if (err) {
4580
4580
  reject(err);
4581
4581
  } else {
4582
4582
  const buffer = Buffer.alloc(MAX_LENGTH);
4583
4583
  fs19.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
4584
- resolve3(buffer.subarray(0, bytesRead));
4584
+ resolve4(buffer.subarray(0, bytesRead));
4585
4585
  fs19.close(fd, () => {
4586
4586
  });
4587
4587
  });
@@ -4649,10 +4649,10 @@ var require_detect_libc = __commonJS({
4649
4649
  var commandOut = "";
4650
4650
  var safeCommand = () => {
4651
4651
  if (!commandOut) {
4652
- return new Promise((resolve3) => {
4652
+ return new Promise((resolve4) => {
4653
4653
  childProcess.exec(command, (err, out) => {
4654
4654
  commandOut = err ? " " : out;
4655
- resolve3(commandOut);
4655
+ resolve4(commandOut);
4656
4656
  });
4657
4657
  });
4658
4658
  }
@@ -4905,14 +4905,14 @@ var require_get_port = __commonJS({
4905
4905
  };
4906
4906
  var releaseOldLockedPortsIntervalMs = 1e3 * 15;
4907
4907
  var interval;
4908
- var getAvailablePort = (options) => new Promise((resolve3, reject) => {
4908
+ var getAvailablePort = (options) => new Promise((resolve4, reject) => {
4909
4909
  const server = net.createServer();
4910
4910
  server.unref();
4911
4911
  server.on("error", reject);
4912
4912
  server.listen(options, () => {
4913
4913
  const { port } = server.address();
4914
4914
  server.close(() => {
4915
- resolve3(port);
4915
+ resolve4(port);
4916
4916
  });
4917
4917
  });
4918
4918
  });
@@ -4984,7 +4984,7 @@ var require_is_port_reachable = __commonJS({
4984
4984
  "use strict";
4985
4985
  var net = require("net");
4986
4986
  module2.exports = async (port, { timeout = 1e3, host } = {}) => {
4987
- const promise = new Promise((resolve3, reject) => {
4987
+ const promise = new Promise((resolve4, reject) => {
4988
4988
  const socket = new net.Socket();
4989
4989
  const onError = () => {
4990
4990
  socket.destroy();
@@ -4995,7 +4995,7 @@ var require_is_port_reachable = __commonJS({
4995
4995
  socket.once("timeout", onError);
4996
4996
  socket.connect(port, host, () => {
4997
4997
  socket.end();
4998
- resolve3();
4998
+ resolve4();
4999
4999
  });
5000
5000
  });
5001
5001
  try {
@@ -5011,8 +5011,6 @@ var require_is_port_reachable = __commonJS({
5011
5011
  // src/index.ts
5012
5012
  var src_exports = {};
5013
5013
  __export(src_exports, {
5014
- addCollectedVendorBytecode: () => addCollectedVendorBytecode,
5015
- addVendorBytecodeInTiers: () => addVendorBytecodeInTiers,
5016
5014
  build: () => build,
5017
5015
  defaultShouldServe: () => defaultShouldServe,
5018
5016
  detectEntrypoint: () => detectEntrypoint,
@@ -5021,6 +5019,7 @@ __export(src_exports, {
5021
5019
  getDevSidecars: () => getDevSidecars,
5022
5020
  installRequirement: () => installRequirement,
5023
5021
  installRequirementsFile: () => installRequirementsFile,
5022
+ moduleKeysForClosurePaths: () => moduleKeysForClosurePaths,
5024
5023
  prepareCache: () => prepareCache,
5025
5024
  runFrameworkHook: () => runFrameworkHook,
5026
5025
  shouldServe: () => shouldServe,
@@ -5030,7 +5029,7 @@ __export(src_exports, {
5030
5029
  module.exports = __toCommonJS(src_exports);
5031
5030
  var import_assert = __toESM(require("assert"));
5032
5031
  var import_fs20 = __toESM(require("fs"));
5033
- var import_path20 = require("path");
5032
+ var import_path21 = require("path");
5034
5033
 
5035
5034
  // src/package-versions.ts
5036
5035
  var VERCEL_RUNTIME_VERSION = "0.17.0";
@@ -5266,7 +5265,7 @@ async function queryPythonVercelSdkVersion({
5266
5265
  }
5267
5266
 
5268
5267
  // src/index.ts
5269
- var import_build_utils23 = require("@vercel/build-utils");
5268
+ var import_build_utils24 = require("@vercel/build-utils");
5270
5269
 
5271
5270
  // src/install.ts
5272
5271
  var import_execa4 = __toESM(require_execa());
@@ -8572,7 +8571,7 @@ function createLogListener(callback, stream) {
8572
8571
  };
8573
8572
  }
8574
8573
  function sleep(ms) {
8575
- return new Promise((resolve3) => setTimeout(resolve3, ms));
8574
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
8576
8575
  }
8577
8576
  async function checkForPort(port, timeout) {
8578
8577
  const start = Date.now();
@@ -8719,7 +8718,7 @@ async function runSync({
8719
8718
  (0, import_build_utils14.debug)(`Unknown manifest type: ${manifestType}`);
8720
8719
  return;
8721
8720
  }
8722
- await new Promise((resolve3, reject) => {
8721
+ await new Promise((resolve4, reject) => {
8723
8722
  (0, import_build_utils14.debug)(`Running "${spawnCmd} ${spawnArgs.join(" ")}" in ${projectDir}...`);
8724
8723
  const child = (0, import_child_process2.spawn)(spawnCmd, spawnArgs, {
8725
8724
  cwd: projectDir,
@@ -8743,7 +8742,7 @@ async function runSync({
8743
8742
  child.on("error", reject);
8744
8743
  child.on("exit", (code, signal) => {
8745
8744
  if (code === 0) {
8746
- resolve3();
8745
+ resolve4();
8747
8746
  } else {
8748
8747
  reject(
8749
8748
  new Error(
@@ -8809,7 +8808,7 @@ async function doInstallInjectedDevPackage(pkg, opts) {
8809
8808
  ...excludeOverride,
8810
8809
  dep
8811
8810
  ];
8812
- await new Promise((resolve3, reject) => {
8811
+ await new Promise((resolve4, reject) => {
8813
8812
  const child = (0, import_child_process2.spawn)(pip.cmd, spawnArgs, {
8814
8813
  cwd: workPath,
8815
8814
  env: getProtectedUvEnv(env),
@@ -8832,7 +8831,7 @@ async function doInstallInjectedDevPackage(pkg, opts) {
8832
8831
  child.on("error", reject);
8833
8832
  child.on("exit", (code, signal) => {
8834
8833
  if (code === 0) {
8835
- resolve3();
8834
+ resolve4();
8836
8835
  } else {
8837
8836
  reject(
8838
8837
  new Error(
@@ -9040,8 +9039,8 @@ var startDevServer = async (opts) => {
9040
9039
  let resolveChildReady;
9041
9040
  let rejectChildReady;
9042
9041
  const childReady = new Promise(
9043
- (resolve3, reject) => {
9044
- resolveChildReady = resolve3;
9042
+ (resolve4, reject) => {
9043
+ resolveChildReady = resolve4;
9045
9044
  rejectChildReady = reject;
9046
9045
  }
9047
9046
  );
@@ -9964,6 +9963,49 @@ async function runFastAPICollectStatic(venvPath, workPath, env, outputStaticDir,
9964
9963
  // src/index.ts
9965
9964
  var import_python_analysis12 = require("@vercel/python-analysis");
9966
9965
 
9966
+ // src/bytecode-packing.ts
9967
+ function isBytecodeAnalysisDisabled() {
9968
+ const val = process.env.VERCEL_PYTHON_DISABLE_BYTECODE_ANALYSIS;
9969
+ if (val === void 0 || val === "")
9970
+ return false;
9971
+ const lower = val.toLowerCase();
9972
+ return lower === "1" || lower === "true";
9973
+ }
9974
+ function annotateBytecodeItems(items, importedModules, timings) {
9975
+ return items.map((item) => ({
9976
+ ...item,
9977
+ imported: importedModules?.has(item.moduleKey) ?? false,
9978
+ compileSeconds: timings?.get(item.sourceAbsPath)
9979
+ }));
9980
+ }
9981
+ function rankBytecodeItems(items) {
9982
+ const densities = items.filter((i) => i.compileSeconds != null && i.size > 0).map((i) => i.compileSeconds / i.size).sort((a, b) => a - b);
9983
+ const medianDensity = densities.length > 0 ? densities[Math.floor(densities.length / 2)] : null;
9984
+ return [...items].sort((a, b) => {
9985
+ if (a.imported !== b.imported)
9986
+ return a.imported ? -1 : 1;
9987
+ if (medianDensity !== null) {
9988
+ const da = a.compileSeconds != null && a.size > 0 ? a.compileSeconds / a.size : medianDensity;
9989
+ const db = b.compileSeconds != null && b.size > 0 ? b.compileSeconds / b.size : medianDensity;
9990
+ if (da !== db)
9991
+ return db - da;
9992
+ }
9993
+ return b.size - a.size;
9994
+ });
9995
+ }
9996
+ function fillBytecodeWithinCapacity(files, rankedItems, capacity) {
9997
+ let remaining = capacity;
9998
+ for (const item of rankedItems) {
9999
+ if (remaining <= 0)
10000
+ break;
10001
+ if (item.size <= remaining) {
10002
+ files[item.bundlePath] = item.file;
10003
+ remaining -= item.size;
10004
+ }
10005
+ }
10006
+ return remaining;
10007
+ }
10008
+
9967
10009
  // src/compileall.ts
9968
10010
  var import_execa10 = __toESM(require_execa());
9969
10011
  var import_build_utils20 = require("@vercel/build-utils");
@@ -10001,7 +10043,7 @@ async function runCompileAll({
10001
10043
  }) {
10002
10044
  const uniqueSourceFiles = [...new Set(sourceFiles)];
10003
10045
  if (uniqueSourceFiles.length === 0) {
10004
- return false;
10046
+ return { success: false };
10005
10047
  }
10006
10048
  let tempDir;
10007
10049
  try {
@@ -10010,17 +10052,25 @@ async function runCompileAll({
10010
10052
  );
10011
10053
  const listPath = (0, import_path17.join)(tempDir, "pysources.json");
10012
10054
  await import_fs17.default.promises.writeFile(listPath, JSON.stringify(uniqueSourceFiles));
10055
+ const timingsPath = (0, import_path17.join)(tempDir, "timings.json");
10013
10056
  const scriptPath4 = (0, import_path17.join)(__dirname, "..", "templates", "vc_compileall.py");
10014
10057
  const baseEnv = env || process.env;
10015
10058
  const subprocessEnv = pycachePrefix ? { ...baseEnv, PYTHONPYCACHEPREFIX: pycachePrefix } : baseEnv;
10016
- await (0, import_execa10.default)(pythonBin, [scriptPath4, listPath], {
10059
+ await (0, import_execa10.default)(pythonBin, [scriptPath4, listPath, timingsPath], {
10017
10060
  env: subprocessEnv,
10018
10061
  timeout: COMPILEALL_TIMEOUT_MS
10019
10062
  });
10020
- return true;
10063
+ let timings;
10064
+ try {
10065
+ const raw = await import_fs17.default.promises.readFile(timingsPath, "utf8");
10066
+ timings = new Map(Object.entries(JSON.parse(raw)));
10067
+ } catch (err) {
10068
+ (0, import_build_utils20.debug)(`compileall timings unavailable: ${String(err)}`);
10069
+ }
10070
+ return { success: true, timings };
10021
10071
  } catch (err) {
10022
10072
  (0, import_build_utils20.debug)(`compileall error details: ${JSON.stringify(err)}`);
10023
- return false;
10073
+ return { success: false };
10024
10074
  } finally {
10025
10075
  if (tempDir) {
10026
10076
  try {
@@ -10087,9 +10137,10 @@ async function collectAppPrefixBytecodeFiles({
10087
10137
  for (const bundlePath of Object.keys(appFiles)) {
10088
10138
  if (!bundlePath.endsWith(".py"))
10089
10139
  continue;
10140
+ const sourceAbsPath = (0, import_path17.join)(workPath, bundlePath.replaceAll("/", import_path17.sep));
10090
10141
  const stagedFsPath = deriveStagedPycFsPath(
10091
10142
  stagingDir,
10092
- (0, import_path17.join)(workPath, bundlePath.replaceAll("/", import_path17.sep)),
10143
+ sourceAbsPath,
10093
10144
  pythonMajor,
10094
10145
  pythonMinor
10095
10146
  );
@@ -10100,13 +10151,24 @@ async function collectAppPrefixBytecodeFiles({
10100
10151
  );
10101
10152
  if (!stagedFsPath || !pycBundlePath)
10102
10153
  continue;
10103
- pending.push({ bundlePath: pycBundlePath, srcFsPath: stagedFsPath });
10154
+ pending.push({
10155
+ bundlePath: pycBundlePath,
10156
+ srcFsPath: stagedFsPath,
10157
+ moduleKey: bundlePath,
10158
+ sourceAbsPath
10159
+ });
10104
10160
  }
10105
10161
  const results = await Promise.all(
10106
- pending.map(async ({ bundlePath, srcFsPath }) => {
10162
+ pending.map(async ({ bundlePath, srcFsPath, moduleKey, sourceAbsPath }) => {
10107
10163
  try {
10108
10164
  const stats = await import_fs17.default.promises.stat(srcFsPath);
10109
- return { bundlePath, srcFsPath, size: stats.size };
10165
+ return {
10166
+ bundlePath,
10167
+ srcFsPath,
10168
+ moduleKey,
10169
+ sourceAbsPath,
10170
+ size: stats.size
10171
+ };
10110
10172
  } catch {
10111
10173
  return null;
10112
10174
  }
@@ -10114,18 +10176,27 @@ async function collectAppPrefixBytecodeFiles({
10114
10176
  );
10115
10177
  const files = {};
10116
10178
  const perItemSizes = /* @__PURE__ */ new Map();
10179
+ const items = [];
10117
10180
  let totalSize = 0;
10118
10181
  for (const result of results) {
10119
10182
  if (!result)
10120
10183
  continue;
10121
- files[result.bundlePath] = new import_build_utils20.FileFsRef({
10184
+ const file = new import_build_utils20.FileFsRef({
10122
10185
  fsPath: result.srcFsPath,
10123
10186
  size: result.size
10124
10187
  });
10188
+ files[result.bundlePath] = file;
10125
10189
  perItemSizes.set(result.bundlePath, result.size);
10190
+ items.push({
10191
+ bundlePath: result.bundlePath,
10192
+ file,
10193
+ size: result.size,
10194
+ moduleKey: result.moduleKey,
10195
+ sourceAbsPath: result.sourceAbsPath
10196
+ });
10126
10197
  totalSize += result.size;
10127
10198
  }
10128
- return { files, totalSize, perItemSizes };
10199
+ return { files, totalSize, perItemSizes, items };
10129
10200
  }
10130
10201
  async function collectAppBytecodeFiles({
10131
10202
  workPath,
@@ -10140,14 +10211,22 @@ async function collectAppBytecodeFiles({
10140
10211
  continue;
10141
10212
  pending.push({
10142
10213
  bundlePath: pycRel,
10143
- srcFsPath: (0, import_path17.join)(workPath, pycRel.replaceAll("/", import_path17.sep))
10214
+ srcFsPath: (0, import_path17.join)(workPath, pycRel.replaceAll("/", import_path17.sep)),
10215
+ moduleKey: bundlePath,
10216
+ sourceAbsPath: (0, import_path17.join)(workPath, bundlePath.replaceAll("/", import_path17.sep))
10144
10217
  });
10145
10218
  }
10146
10219
  const results = await Promise.all(
10147
- pending.map(async ({ bundlePath, srcFsPath }) => {
10220
+ pending.map(async ({ bundlePath, srcFsPath, moduleKey, sourceAbsPath }) => {
10148
10221
  try {
10149
10222
  const stats = await import_fs17.default.promises.stat(srcFsPath);
10150
- return { bundlePath, srcFsPath, size: stats.size };
10223
+ return {
10224
+ bundlePath,
10225
+ srcFsPath,
10226
+ moduleKey,
10227
+ sourceAbsPath,
10228
+ size: stats.size
10229
+ };
10151
10230
  } catch {
10152
10231
  return null;
10153
10232
  }
@@ -10155,18 +10234,27 @@ async function collectAppBytecodeFiles({
10155
10234
  );
10156
10235
  const files = {};
10157
10236
  const perItemSizes = /* @__PURE__ */ new Map();
10237
+ const items = [];
10158
10238
  let totalSize = 0;
10159
10239
  for (const result of results) {
10160
10240
  if (!result)
10161
10241
  continue;
10162
- files[result.bundlePath] = new import_build_utils20.FileFsRef({
10242
+ const file = new import_build_utils20.FileFsRef({
10163
10243
  fsPath: result.srcFsPath,
10164
10244
  size: result.size
10165
10245
  });
10246
+ files[result.bundlePath] = file;
10166
10247
  perItemSizes.set(result.bundlePath, result.size);
10248
+ items.push({
10249
+ bundlePath: result.bundlePath,
10250
+ file,
10251
+ size: result.size,
10252
+ moduleKey: result.moduleKey,
10253
+ sourceAbsPath: result.sourceAbsPath
10254
+ });
10167
10255
  totalSize += result.size;
10168
10256
  }
10169
- return { files, totalSize, perItemSizes };
10257
+ return { files, totalSize, perItemSizes, items };
10170
10258
  }
10171
10259
 
10172
10260
  // src/installed-distributions.ts
@@ -10256,6 +10344,13 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10256
10344
  this.pythonMajor = options.pythonMajor;
10257
10345
  this.pythonMinor = options.pythonMinor;
10258
10346
  }
10347
+ /**
10348
+ * Site-packages roots of the build venv (resolved). Used as import-closure
10349
+ * search roots and to map traced module files to vendor module keys.
10350
+ */
10351
+ getSitePackageDirs() {
10352
+ return this.sitePackageDirs;
10353
+ }
10259
10354
  async mirrorPackagesIntoVendor({
10260
10355
  vendorDirName,
10261
10356
  includePackages
@@ -10354,7 +10449,7 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10354
10449
  includePackages
10355
10450
  }) {
10356
10451
  if (this.pythonMajor == null || this.pythonMinor == null) {
10357
- return { files: {}, totalSize: 0, perItemSizes: /* @__PURE__ */ new Map() };
10452
+ return { files: {}, totalSize: 0, perItemSizes: /* @__PURE__ */ new Map(), items: [] };
10358
10453
  }
10359
10454
  const pending = [];
10360
10455
  const distributionGroups = getDistributionFileGroups({
@@ -10364,8 +10459,9 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10364
10459
  });
10365
10460
  for (const { packageName, sitePackagesDir, files } of distributionGroups) {
10366
10461
  for (const { relativePath } of files) {
10462
+ const moduleKey = relativePath.replaceAll(import_path18.sep, "/");
10367
10463
  const pycRelativePath = derivePycPath(
10368
- relativePath.replaceAll(import_path18.sep, "/"),
10464
+ moduleKey,
10369
10465
  this.pythonMajor,
10370
10466
  this.pythonMinor
10371
10467
  );
@@ -10375,7 +10471,9 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10375
10471
  pending.push({
10376
10472
  bundlePath: (0, import_path18.join)(vendorDirName, pycFilePath).replace(/\\/g, "/"),
10377
10473
  srcFsPath: (0, import_path18.join)(sitePackagesDir, pycFilePath),
10378
- packageName
10474
+ packageName,
10475
+ moduleKey,
10476
+ sourceAbsPath: (0, import_path18.join)(sitePackagesDir, relativePath)
10379
10477
  });
10380
10478
  }
10381
10479
  }
@@ -10391,7 +10489,7 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10391
10489
  includePackages
10392
10490
  }) {
10393
10491
  if (this.pythonMajor == null || this.pythonMinor == null) {
10394
- return { files: {}, totalSize: 0, perItemSizes: /* @__PURE__ */ new Map() };
10492
+ return { files: {}, totalSize: 0, perItemSizes: /* @__PURE__ */ new Map(), items: [] };
10395
10493
  }
10396
10494
  const pending = [];
10397
10495
  const distributionGroups = getDistributionFileGroups({
@@ -10417,7 +10515,13 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10417
10515
  );
10418
10516
  if (!srcFsPath || !bundlePath)
10419
10517
  continue;
10420
- pending.push({ bundlePath, srcFsPath, packageName });
10518
+ pending.push({
10519
+ bundlePath,
10520
+ srcFsPath,
10521
+ packageName,
10522
+ moduleKey: recordPath,
10523
+ sourceAbsPath: absolutePath
10524
+ });
10421
10525
  }
10422
10526
  }
10423
10527
  const result = await this.collectExistingBytecode(pending);
@@ -10428,32 +10532,56 @@ var InstalledPythonDistributions = class _InstalledPythonDistributions {
10428
10532
  }
10429
10533
  async collectExistingBytecode(pending) {
10430
10534
  const results = await Promise.all(
10431
- pending.map(async ({ bundlePath, srcFsPath, packageName }) => {
10432
- try {
10433
- const stats = await import_fs18.default.promises.stat(srcFsPath);
10434
- return { bundlePath, srcFsPath, size: stats.size, packageName };
10435
- } catch {
10436
- return null;
10535
+ pending.map(
10536
+ async ({
10537
+ bundlePath,
10538
+ srcFsPath,
10539
+ packageName,
10540
+ moduleKey,
10541
+ sourceAbsPath
10542
+ }) => {
10543
+ try {
10544
+ const stats = await import_fs18.default.promises.stat(srcFsPath);
10545
+ return {
10546
+ bundlePath,
10547
+ srcFsPath,
10548
+ size: stats.size,
10549
+ packageName,
10550
+ moduleKey,
10551
+ sourceAbsPath
10552
+ };
10553
+ } catch {
10554
+ return null;
10555
+ }
10437
10556
  }
10438
- })
10557
+ )
10439
10558
  );
10440
10559
  const files = {};
10441
10560
  let totalSize = 0;
10442
10561
  const perItemSizes = /* @__PURE__ */ new Map();
10562
+ const items = [];
10443
10563
  for (const result of results) {
10444
10564
  if (!result)
10445
10565
  continue;
10446
- files[result.bundlePath] = new import_build_utils21.FileFsRef({
10566
+ const file = new import_build_utils21.FileFsRef({
10447
10567
  fsPath: result.srcFsPath,
10448
10568
  size: result.size
10449
10569
  });
10570
+ files[result.bundlePath] = file;
10450
10571
  totalSize += result.size;
10451
10572
  perItemSizes.set(
10452
10573
  result.packageName,
10453
10574
  (perItemSizes.get(result.packageName) ?? 0) + result.size
10454
10575
  );
10576
+ items.push({
10577
+ bundlePath: result.bundlePath,
10578
+ file,
10579
+ size: result.size,
10580
+ moduleKey: result.moduleKey,
10581
+ sourceAbsPath: result.sourceAbsPath
10582
+ });
10455
10583
  }
10456
- return { files, totalSize, perItemSizes };
10584
+ return { files, totalSize, perItemSizes, items };
10457
10585
  }
10458
10586
  };
10459
10587
 
@@ -10535,6 +10663,72 @@ function workflowError(message) {
10535
10663
  });
10536
10664
  }
10537
10665
 
10666
+ // src/import-closure.ts
10667
+ var import_path20 = require("path");
10668
+ var import_build_utils23 = require("@vercel/build-utils");
10669
+ var RUNTIME_BOOTSTRAP_MODULE = "vercel_runtime.vc_init";
10670
+ var IMPORT_CLOSURE_TIMEOUT_MS = 3e4;
10671
+ async function withTimeout(promise, ms, label) {
10672
+ let timer;
10673
+ const timeout = new Promise((resolvePromise) => {
10674
+ timer = setTimeout(() => {
10675
+ (0, import_build_utils23.debug)(`${label} timed out after ${ms}ms`);
10676
+ resolvePromise(void 0);
10677
+ }, ms);
10678
+ });
10679
+ try {
10680
+ return await Promise.race([promise, timeout]);
10681
+ } finally {
10682
+ clearTimeout(timer);
10683
+ }
10684
+ }
10685
+ function getImportClosureOptions({
10686
+ workPath,
10687
+ entrypoint,
10688
+ frameworkSeeds,
10689
+ extraPythonPath,
10690
+ subscriberDeclarations,
10691
+ subscribers,
10692
+ workflows,
10693
+ workflowMode,
10694
+ sitePackageDirs
10695
+ }) {
10696
+ const workerModules = [
10697
+ ...subscriberDeclarations.map((declaration) => declaration.moduleName),
10698
+ ...workflows.map((workflow) => workflow.moduleName)
10699
+ ];
10700
+ const generatedWorkerModules = [
10701
+ ...subscribers.map(
10702
+ (subscriber) => generatedPythonPathToModule(
10703
+ getGeneratedQueueHandlerPath(getSubscriberOutputPath(subscriber.name))
10704
+ )
10705
+ ),
10706
+ ...workflowMode === "queue" ? workflows.map(
10707
+ (workflow) => generatedPythonPathToModule(
10708
+ getGeneratedQueueHandlerPath(getWorkflowOutputPath(workflow.name))
10709
+ )
10710
+ ) : []
10711
+ ];
10712
+ return {
10713
+ seeds: [
10714
+ .../* @__PURE__ */ new Set([
10715
+ RUNTIME_BOOTSTRAP_MODULE,
10716
+ ...entrypoint ? [(0, import_path20.join)(workPath, entrypoint)] : [],
10717
+ ...frameworkSeeds,
10718
+ ...workerModules,
10719
+ ...generatedWorkerModules
10720
+ ])
10721
+ ],
10722
+ searchRoots: [
10723
+ .../* @__PURE__ */ new Set([
10724
+ ...extraPythonPath ? [extraPythonPath] : [],
10725
+ workPath,
10726
+ ...sitePackageDirs
10727
+ ])
10728
+ ]
10729
+ };
10730
+ }
10731
+
10538
10732
  // src/index.ts
10539
10733
  var writeFile = import_fs20.default.promises.writeFile;
10540
10734
  var PYTHON_ENTRYPOINT_DOCS_URL2 = "https://vercel.com/docs/functions/runtimes/python#python-entrypoints";
@@ -10556,9 +10750,9 @@ async function getDevSidecars({
10556
10750
  service
10557
10751
  }) {
10558
10752
  const framework = build2.config?.framework;
10559
- const isPyprojectEntrypoint = (0, import_path20.basename)(build2.src ?? "") === "pyproject.toml";
10560
- const isPyprojectService = service !== void 0 && (0, import_path20.basename)(service.entrypoint ?? "") === "pyproject.toml";
10561
- if (build2.config?.middleware === true || service !== void 0 && !isPyprojectService || service === void 0 && !isPyprojectEntrypoint && (typeof framework !== "string" || !(0, import_build_utils23.isPythonFramework)(framework))) {
10753
+ const isPyprojectEntrypoint = (0, import_path21.basename)(build2.src ?? "") === "pyproject.toml";
10754
+ const isPyprojectService = service !== void 0 && (0, import_path21.basename)(service.entrypoint ?? "") === "pyproject.toml";
10755
+ if (build2.config?.middleware === true || service !== void 0 && !isPyprojectService || service === void 0 && !isPyprojectEntrypoint && (typeof framework !== "string" || !(0, import_build_utils24.isPythonFramework)(framework))) {
10562
10756
  return [];
10563
10757
  }
10564
10758
  const legacyWorkers = await isLegacyWorkersProject(workPath);
@@ -10612,96 +10806,19 @@ function addFiles(target, source) {
10612
10806
  target[p] = f;
10613
10807
  }
10614
10808
  }
10615
- function addBytecodeWithinCapacity(files, bytecodeInfo, capacity) {
10616
- if (!bytecodeInfo || bytecodeInfo.totalSize <= 0 || capacity <= 0) {
10617
- return capacity;
10618
- }
10619
- if (bytecodeInfo.totalSize <= capacity) {
10620
- addFiles(files, bytecodeInfo.files);
10621
- return capacity - bytecodeInfo.totalSize;
10622
- }
10623
- const selected = lambdaKnapsack(bytecodeInfo.perItemSizes, capacity);
10624
- let remainingCapacity = capacity;
10625
- for (const p of selected) {
10626
- const file = bytecodeInfo.files[p];
10627
- if (!file)
10628
- continue;
10629
- files[p] = file;
10630
- remainingCapacity -= bytecodeInfo.perItemSizes.get(p) ?? 0;
10631
- }
10632
- return remainingCapacity;
10633
- }
10634
- async function addVendorBytecodeWithinCapacity({
10635
- files,
10636
- installedDistributions,
10637
- vendorDir,
10638
- bytecodeInfo,
10639
- capacity
10640
- }) {
10641
- if (!bytecodeInfo || bytecodeInfo.totalSize <= 0 || capacity <= 0) {
10642
- return capacity;
10643
- }
10644
- if (bytecodeInfo.totalSize <= capacity) {
10645
- addFiles(files, bytecodeInfo.files);
10646
- return capacity - bytecodeInfo.totalSize;
10647
- }
10648
- const selectedPkgs = lambdaKnapsack(bytecodeInfo.perItemSizes, capacity);
10649
- if (selectedPkgs.length === 0)
10650
- return capacity;
10651
- const selectedBytecode = await installedDistributions.collectBytecodeFiles({
10652
- vendorDirName: vendorDir,
10653
- includePackages: selectedPkgs
10654
- });
10655
- addFiles(files, selectedBytecode.files);
10656
- return capacity - selectedBytecode.totalSize;
10657
- }
10658
- async function addVendorBytecodeInTiers({
10659
- files,
10660
- installedDistributions,
10661
- vendorDir,
10662
- capacity,
10663
- vendorPackageTiers
10664
- }) {
10665
- let remainingCapacity = capacity;
10666
- for (const tier of vendorPackageTiers) {
10667
- if (remainingCapacity <= 0)
10668
- break;
10669
- if (tier && tier.length === 0)
10670
- continue;
10671
- const bytecodeInfo = await installedDistributions.collectBytecodeFiles({
10672
- vendorDirName: vendorDir,
10673
- includePackages: tier
10674
- });
10675
- remainingCapacity = await addVendorBytecodeWithinCapacity({
10676
- files,
10677
- installedDistributions,
10678
- vendorDir,
10679
- bytecodeInfo,
10680
- capacity: remainingCapacity
10681
- });
10809
+ function moduleKeysForClosurePaths(paths, workPath, sitePackageDirs) {
10810
+ const keys = /* @__PURE__ */ new Set();
10811
+ const roots = [...sitePackageDirs, workPath].map((r) => (0, import_path21.resolve)(r));
10812
+ for (const p of paths) {
10813
+ for (const root of roots) {
10814
+ const rel = (0, import_path21.relative)(root, p);
10815
+ if (rel && !rel.startsWith("..") && !(0, import_path21.isAbsolute)(rel)) {
10816
+ keys.add(rel.split(import_path21.sep).join("/"));
10817
+ break;
10818
+ }
10819
+ }
10682
10820
  }
10683
- return remainingCapacity;
10684
- }
10685
- async function addCollectedVendorBytecode({
10686
- files,
10687
- capacity,
10688
- collect
10689
- }) {
10690
- if (capacity <= 0)
10691
- return capacity;
10692
- const info = await collect(void 0);
10693
- if (!info || info.totalSize <= 0)
10694
- return capacity;
10695
- if (info.totalSize <= capacity) {
10696
- addFiles(files, info.files);
10697
- return capacity - info.totalSize;
10698
- }
10699
- const selected = lambdaKnapsack(info.perItemSizes, capacity);
10700
- if (selected.length === 0)
10701
- return capacity;
10702
- const selectedInfo = await collect(selected);
10703
- addFiles(files, selectedInfo.files);
10704
- return capacity - selectedInfo.totalSize;
10821
+ return keys;
10705
10822
  }
10706
10823
  async function runFrameworkHook(framework, ctx) {
10707
10824
  const hook = framework ? frameworkHooks[framework] : void 0;
@@ -10716,13 +10833,13 @@ var frameworkHooks = {
10716
10833
  }) => {
10717
10834
  let baseDir = detected?.baseDir;
10718
10835
  if (baseDir === void 0) {
10719
- if (!import_fs20.default.existsSync((0, import_path20.join)(workPath, "manage.py"))) {
10720
- (0, import_build_utils23.debug)("Django hook: no manage.py detected, skipping");
10836
+ if (!import_fs20.default.existsSync((0, import_path21.join)(workPath, "manage.py"))) {
10837
+ (0, import_build_utils24.debug)("Django hook: no manage.py detected, skipping");
10721
10838
  return;
10722
10839
  }
10723
10840
  baseDir = "";
10724
10841
  }
10725
- const djangoPath = (0, import_path20.join)(workPath, baseDir);
10842
+ const djangoPath = (0, import_path21.join)(workPath, baseDir);
10726
10843
  let settingsResult;
10727
10844
  try {
10728
10845
  settingsResult = await getDjangoSettings(djangoPath, pythonEnv);
@@ -10734,13 +10851,13 @@ Hint: activate a venv or run with \`uv run vercel dev\``;
10734
10851
  } else {
10735
10852
  detail = err?.stderr || err?.message || String(err);
10736
10853
  }
10737
- throw new import_build_utils23.NowBuildError({
10854
+ throw new import_build_utils24.NowBuildError({
10738
10855
  code: "DJANGO_SETTINGS_FAILED",
10739
10856
  message: `Failed to read Django application settings from ${djangoPath}/manage.py:
10740
10857
  ${detail}`
10741
10858
  });
10742
10859
  }
10743
- (0, import_build_utils23.debug)(`Django settings: ${JSON.stringify(settingsResult)}`);
10860
+ (0, import_build_utils24.debug)(`Django settings: ${JSON.stringify(settingsResult)}`);
10744
10861
  const { djangoSettings, settingsModule, djangoVersion } = settingsResult;
10745
10862
  if (djangoVersion) {
10746
10863
  console.log(`Django ${djangoVersion.join(".")} detected`);
@@ -10752,7 +10869,7 @@ ${detail}`
10752
10869
  const variableName = parts.at(-1);
10753
10870
  const rel = `${parts.slice(0, -1).join("/")}.py`;
10754
10871
  const ep = baseDir ? `${baseDir}/${rel}` : rel;
10755
- (0, import_build_utils23.debug)(`Django hook: ASGI entrypoint: ${ep} (variable: ${variableName})`);
10872
+ (0, import_build_utils24.debug)(`Django hook: ASGI entrypoint: ${ep} (variable: ${variableName})`);
10756
10873
  resolvedEntrypoint = { entrypoint: ep, variableName };
10757
10874
  } else {
10758
10875
  const wsgiApp = djangoSettings["WSGI_APPLICATION"];
@@ -10761,7 +10878,7 @@ ${detail}`
10761
10878
  const variableName = parts.at(-1);
10762
10879
  const rel = `${parts.slice(0, -1).join("/")}.py`;
10763
10880
  const ep = baseDir ? `${baseDir}/${rel}` : rel;
10764
- (0, import_build_utils23.debug)(
10881
+ (0, import_build_utils24.debug)(
10765
10882
  `Django hook: WSGI entrypoint: ${ep} (variable: ${variableName})`
10766
10883
  );
10767
10884
  resolvedEntrypoint = { entrypoint: ep, variableName };
@@ -10769,7 +10886,7 @@ ${detail}`
10769
10886
  }
10770
10887
  let djangoStatic = null;
10771
10888
  if (workPath && venvPath) {
10772
- const outputStaticDir = (0, import_path20.join)(workPath, ".vercel", "output", "static");
10889
+ const outputStaticDir = (0, import_path21.join)(workPath, ".vercel", "output", "static");
10773
10890
  djangoStatic = await runDjangoCollectStatic(
10774
10891
  venvPath,
10775
10892
  workPath,
@@ -10781,10 +10898,17 @@ ${detail}`
10781
10898
  djangoVersion
10782
10899
  );
10783
10900
  }
10901
+ const importSeeds = [
10902
+ settingsModule,
10903
+ djangoSettings["ROOT_URLCONF"],
10904
+ ...djangoSettings["INSTALLED_APPS"] ?? [],
10905
+ ...djangoSettings["MIDDLEWARE"] ?? []
10906
+ ].filter((s) => typeof s === "string");
10784
10907
  return {
10785
10908
  entrypoint: resolvedEntrypoint,
10786
10909
  djangoStatic,
10787
- extraPythonPath: baseDir ? (0, import_path20.join)(workPath, baseDir) : void 0
10910
+ importSeeds,
10911
+ extraPythonPath: baseDir ? (0, import_path21.join)(workPath, baseDir) : void 0
10788
10912
  };
10789
10913
  },
10790
10914
  fastapi: async ({
@@ -10795,27 +10919,27 @@ ${detail}`
10795
10919
  pyprojectData
10796
10920
  }) => {
10797
10921
  if (!detected?.entrypoint || !workPath || !venvPath) {
10798
- (0, import_build_utils23.debug)(
10922
+ (0, import_build_utils24.debug)(
10799
10923
  `FastAPI hook: skipping \u2014 detected.entrypoint=${JSON.stringify(detected?.entrypoint)}, workPath=${workPath}, venvPath=${venvPath}`
10800
10924
  );
10801
10925
  return;
10802
10926
  }
10803
10927
  const { entrypoint: entrypointRel, variableName } = detected.entrypoint;
10804
- (0, import_build_utils23.debug)(
10928
+ (0, import_build_utils24.debug)(
10805
10929
  `FastAPI hook: entrypoint=${entrypointRel}, variableName=${variableName}`
10806
10930
  );
10807
- const entrypointAbs = (0, import_path20.join)(workPath, entrypointRel);
10808
- const outputStaticDir = (0, import_path20.join)(workPath, ".vercel", "output", "static");
10931
+ const entrypointAbs = (0, import_path21.join)(workPath, entrypointRel);
10932
+ const outputStaticDir = (0, import_path21.join)(workPath, ".vercel", "output", "static");
10809
10933
  const cdnEnv = process.env.VERCEL_FASTAPI_STATIC_CDN?.toLowerCase();
10810
10934
  if (cdnEnv !== "1" && cdnEnv !== "true") {
10811
- (0, import_build_utils23.debug)(
10935
+ (0, import_build_utils24.debug)(
10812
10936
  "FastAPI: VERCEL_FASTAPI_STATIC_CDN not set, skipping static CDN collection"
10813
10937
  );
10814
10938
  return;
10815
10939
  }
10816
10940
  const staticCdn = pyprojectData?.tool?.vercel?.fastapi?.static?.cdn;
10817
10941
  if (staticCdn === false) {
10818
- (0, import_build_utils23.debug)(
10942
+ (0, import_build_utils24.debug)(
10819
10943
  "FastAPI: static.cdn = false in pyproject.toml, skipping CDN collection"
10820
10944
  );
10821
10945
  return;
@@ -10888,23 +11012,23 @@ async function downloadFilesInWorkPath({
10888
11012
  files,
10889
11013
  meta = {}
10890
11014
  }) {
10891
- (0, import_build_utils23.debug)("Downloading user files...");
10892
- let downloadedFiles = await (0, import_build_utils23.download)(files, workPath, meta);
11015
+ (0, import_build_utils24.debug)("Downloading user files...");
11016
+ let downloadedFiles = await (0, import_build_utils24.download)(files, workPath, meta);
10893
11017
  if (meta.isDev && entrypoint) {
10894
11018
  const normalizedEntrypoint = entrypoint.endsWith(".py") ? entrypoint : `${entrypoint}.py`;
10895
11019
  if (!hasProp(downloadedFiles, entrypoint) && !hasProp(downloadedFiles, normalizedEntrypoint)) {
10896
- throw new import_build_utils23.NowBuildError({
11020
+ throw new import_build_utils24.NowBuildError({
10897
11021
  code: "PYTHON_ENTRYPOINT_NOT_FOUND",
10898
11022
  message: `Configured Python entrypoint "${normalizedEntrypoint}" was not found.`,
10899
11023
  link: PYTHON_ENTRYPOINT_DOCS_URL2,
10900
11024
  action: "Learn More"
10901
11025
  });
10902
11026
  }
10903
- const { devCacheDir = (0, import_path20.join)(workPath, ".now", "cache") } = meta;
10904
- const cacheKey = (0, import_path20.basename)(entrypoint).replace(/\./g, "_");
10905
- const destCache = (0, import_path20.join)(devCacheDir, cacheKey);
10906
- await (0, import_build_utils23.download)(downloadedFiles, destCache);
10907
- downloadedFiles = await (0, import_build_utils23.glob)("**", destCache);
11027
+ const { devCacheDir = (0, import_path21.join)(workPath, ".now", "cache") } = meta;
11028
+ const cacheKey = (0, import_path21.basename)(entrypoint).replace(/\./g, "_");
11029
+ const destCache = (0, import_path21.join)(devCacheDir, cacheKey);
11030
+ await (0, import_build_utils24.download)(downloadedFiles, destCache);
11031
+ downloadedFiles = await (0, import_build_utils24.glob)("**", destCache);
10908
11032
  workPath = destCache;
10909
11033
  }
10910
11034
  return workPath;
@@ -10940,7 +11064,7 @@ async function getPythonLambdaOptions({
10940
11064
  sources.add(entrypoint.slice(0, -".py".length));
10941
11065
  }
10942
11066
  for (const sourceFile of sources) {
10943
- const lambdaOptions = await (0, import_build_utils23.getLambdaOptionsFromFunction)({
11067
+ const lambdaOptions = await (0, import_build_utils24.getLambdaOptionsFromFunction)({
10944
11068
  sourceFile,
10945
11069
  config
10946
11070
  });
@@ -10961,11 +11085,11 @@ async function installInjectedPackage({
10961
11085
  projectDir,
10962
11086
  pipPlatformArgs
10963
11087
  }) {
10964
- const localDir = (0, import_path20.join)(__dirname, "..", "..", "..", "python", name);
10965
- const isLocalDev = allowLocalSource && import_fs20.default.existsSync((0, import_path20.join)(localDir, "pyproject.toml"));
11088
+ const localDir = (0, import_path21.join)(__dirname, "..", "..", "..", "python", name);
11089
+ const isLocalDev = allowLocalSource && import_fs20.default.existsSync((0, import_path21.join)(localDir, "pyproject.toml"));
10966
11090
  const dep = envOverride || (isLocalDev ? localDir : requirement);
10967
11091
  const noExclude = ["--exclude-newer-package", `${name}=false`];
10968
- (0, import_build_utils23.debug)(`Installing ${dep}`);
11092
+ (0, import_build_utils24.debug)(`Installing ${dep}`);
10969
11093
  await uv.pip({
10970
11094
  venvPath,
10971
11095
  projectDir,
@@ -10991,14 +11115,14 @@ var build = async ({
10991
11115
  registerPreDeploy
10992
11116
  }) => {
10993
11117
  let entrypoint = rawEntrypoint === "<detect>" ? void 0 : rawEntrypoint;
10994
- const isPyprojectEntrypoint = entrypoint !== void 0 && (0, import_path20.basename)(entrypoint) === "pyproject.toml";
11118
+ const isPyprojectEntrypoint = entrypoint !== void 0 && (0, import_path21.basename)(entrypoint) === "pyproject.toml";
10995
11119
  if (isPyprojectEntrypoint && entrypoint !== "pyproject.toml") {
10996
- throw new import_build_utils23.NowBuildError({
11120
+ throw new import_build_utils24.NowBuildError({
10997
11121
  code: "PYTHON_INVALID_PYPROJECT_ENTRYPOINT",
10998
- message: `A "pyproject.toml" entrypoint must sit at the service root. Set the service "root" to "${(0, import_path20.dirname)(entrypoint)}" and use entrypoint "pyproject.toml".`
11122
+ message: `A "pyproject.toml" entrypoint must sit at the service root. Set the service "root" to "${(0, import_path21.dirname)(entrypoint)}" and use entrypoint "pyproject.toml".`
10999
11123
  });
11000
11124
  }
11001
- const builderSpan = parentSpan ?? new import_build_utils23.Span({ name: "vc.builder" });
11125
+ const builderSpan = parentSpan ?? new import_build_utils24.Span({ name: "vc.builder" });
11002
11126
  const framework = config?.framework;
11003
11127
  let subscriberDeclarations = [];
11004
11128
  let subscribers = [];
@@ -11009,7 +11133,7 @@ var build = async ({
11009
11133
  let projectInstallCommand;
11010
11134
  let hasCustomCommand = false;
11011
11135
  const target = getTargetPlatform(meta.isDev ?? false);
11012
- (0, import_build_utils23.debug)(`workPath: ${workPath}`);
11136
+ (0, import_build_utils24.debug)(`workPath: ${workPath}`);
11013
11137
  workPath = await downloadFilesInWorkPath({
11014
11138
  workPath,
11015
11139
  files: originalFiles,
@@ -11017,7 +11141,7 @@ var build = async ({
11017
11141
  meta
11018
11142
  });
11019
11143
  legacyWorkersProject = await isLegacyWorkersProject(workPath);
11020
- if (isPyprojectEntrypoint || !service && (0, import_build_utils23.isPythonFramework)(framework)) {
11144
+ if (isPyprojectEntrypoint || !service && (0, import_build_utils24.isPythonFramework)(framework)) {
11021
11145
  subscriberDeclarations = await getPyprojectSubscribers(workPath, {
11022
11146
  legacySchema: legacyWorkersProject
11023
11147
  });
@@ -11025,7 +11149,7 @@ var build = async ({
11025
11149
  }
11026
11150
  try {
11027
11151
  if (meta.isDev) {
11028
- const setupCfg = (0, import_path20.join)(workPath, "setup.cfg");
11152
+ const setupCfg = (0, import_path21.join)(workPath, "setup.cfg");
11029
11153
  await writeFile(setupCfg, "[install]\nprefix=\n");
11030
11154
  }
11031
11155
  } catch (err) {
@@ -11039,7 +11163,7 @@ var build = async ({
11039
11163
  if (declared) {
11040
11164
  detected = { entrypoint: declared };
11041
11165
  } else if (subscriberDeclarations.length === 0 && workflows.length === 0) {
11042
- throw new import_build_utils23.NowBuildError({
11166
+ throw new import_build_utils24.NowBuildError({
11043
11167
  code: "PYTHON_PYPROJECT_NOTHING_TO_BUILD",
11044
11168
  message: 'Entrypoint "pyproject.toml" declares nothing to build. Set "tool.vercel.entrypoint" for a web app and/or declare "[[tool.vercel.subscribers]]" or "[[tool.vercel.workflows]]" entries in pyproject.toml.'
11045
11169
  });
@@ -11053,7 +11177,7 @@ var build = async ({
11053
11177
  filePath: entrypoint,
11054
11178
  // For schedule-triggered jobs, the WSGI variable is always 'app' (created dynamically).
11055
11179
  // For other services, handlerFunction is used as the entrypoint variable name.
11056
- varName: service && (0, import_build_utils23.isScheduleTriggeredService)(service) ? void 0 : handlerFunction
11180
+ varName: service && (0, import_build_utils24.isScheduleTriggeredService)(service) ? void 0 : handlerFunction
11057
11181
  } : void 0,
11058
11182
  service,
11059
11183
  repoRootPath
@@ -11062,8 +11186,8 @@ var build = async ({
11062
11186
  if (detected?.error && detected?.baseDir === void 0) {
11063
11187
  throw detected?.error;
11064
11188
  }
11065
- const entryDirectory = detected?.baseDir ?? (entrypoint ? (0, import_path20.dirname)(entrypoint) : ".");
11066
- const entrypointAbsDir = (0, import_path20.join)(workPath, entryDirectory);
11189
+ const entryDirectory = detected?.baseDir ?? (entrypoint ? (0, import_path21.dirname)(entrypoint) : ".");
11190
+ const entrypointAbsDir = (0, import_path21.join)(workPath, entryDirectory);
11067
11191
  const rootDir = repoRootPath ?? workPath;
11068
11192
  const pythonPackage = await builderSpan.child("vc.builder.python.discover").trace(
11069
11193
  () => discoverPackage({
@@ -11104,12 +11228,12 @@ var build = async ({
11104
11228
  }
11105
11229
  const uvVersion = checkUvBinaryVersion(uv.getPath());
11106
11230
  console.log(`Using ${uvVersion}`);
11107
- const venvPath = service?.name ? (0, import_path20.join)(workPath, ".vercel", "python", "services", service.name, ".venv") : (0, import_path20.join)(workPath, ".vercel", "python", ".venv");
11108
- const hasCachedVenv = import_fs20.default.existsSync((0, import_path20.join)(venvPath, "pyvenv.cfg"));
11231
+ const venvPath = service?.name ? (0, import_path21.join)(workPath, ".vercel", "python", "services", service.name, ".venv") : (0, import_path21.join)(workPath, ".vercel", "python", ".venv");
11232
+ const hasCachedVenv = import_fs20.default.existsSync((0, import_path21.join)(venvPath, "pyvenv.cfg"));
11109
11233
  const hasCachedUv = import_fs20.default.existsSync(uvCacheDir);
11110
11234
  const restoredCache = hasCachedVenv && hasCachedUv ? "both" : hasCachedVenv ? "venv" : hasCachedUv ? "uv" : "none";
11111
11235
  if (hasCachedVenv || hasCachedUv) {
11112
- (0, import_build_utils23.debug)(
11236
+ (0, import_build_utils24.debug)(
11113
11237
  `Build cache detected: venv=${hasCachedVenv}, uv-cache=${hasCachedUv}`
11114
11238
  );
11115
11239
  }
@@ -11121,14 +11245,14 @@ var build = async ({
11121
11245
  uvCacheDir
11122
11246
  });
11123
11247
  });
11124
- if ((0, import_build_utils23.isPythonFramework)(framework)) {
11248
+ if ((0, import_build_utils24.isPythonFramework)(framework)) {
11125
11249
  const {
11126
11250
  cliType,
11127
11251
  lockfileVersion,
11128
11252
  packageJsonPackageManager,
11129
11253
  turboSupportsCorepackHome
11130
- } = await (0, import_build_utils23.scanParentDirs)(workPath, true);
11131
- spawnEnv = (0, import_build_utils23.getEnvForPackageManager)({
11254
+ } = await (0, import_build_utils24.scanParentDirs)(workPath, true);
11255
+ spawnEnv = (0, import_build_utils24.getEnvForPackageManager)({
11132
11256
  cliType,
11133
11257
  lockfileVersion,
11134
11258
  packageJsonPackageManager,
@@ -11154,7 +11278,7 @@ var build = async ({
11154
11278
  let uvProjectDir = null;
11155
11279
  let projectName;
11156
11280
  let usedUvManagedInstall = false;
11157
- await builderSpan.child(import_build_utils23.BUILDER_INSTALLER_STEP, {
11281
+ await builderSpan.child(import_build_utils24.BUILDER_INSTALLER_STEP, {
11158
11282
  installCommand: projectInstallCommand || void 0,
11159
11283
  runtime: "python",
11160
11284
  "python.cache.restored": restoredCache
@@ -11171,7 +11295,7 @@ var build = async ({
11171
11295
  console.log(
11172
11296
  `Running "install" command: \`${projectInstallCommand}\`...`
11173
11297
  );
11174
- await (0, import_build_utils23.execCommand)(projectInstallCommand, {
11298
+ await (0, import_build_utils24.execCommand)(projectInstallCommand, {
11175
11299
  env: pythonEnv,
11176
11300
  cwd: workPath
11177
11301
  });
@@ -11192,7 +11316,7 @@ var build = async ({
11192
11316
  }
11193
11317
  if (!assumeDepsInstalled) {
11194
11318
  const lockCacheKey = service?.name ? `uv.lock.${service.name}` : "uv.lock";
11195
- const cachedLockPath = (0, import_path20.join)(uvCacheDir, lockCacheKey);
11319
+ const cachedLockPath = (0, import_path21.join)(uvCacheDir, lockCacheKey);
11196
11320
  const { projectDir, lockPath, lockFileProvidedByUser } = await ensureUvProject({
11197
11321
  workPath,
11198
11322
  rootDir,
@@ -11220,15 +11344,15 @@ var build = async ({
11220
11344
  }
11221
11345
  }
11222
11346
  });
11223
- if ((0, import_build_utils23.isPythonFramework)(framework)) {
11347
+ if ((0, import_build_utils24.isPythonFramework)(framework)) {
11224
11348
  const projectBuildCommand = config?.projectSettings?.buildCommand ?? // fallback if provided directly on config (some callers set this)
11225
11349
  config?.buildCommand;
11226
- await builderSpan.child(import_build_utils23.BUILDER_COMPILE_STEP, {
11350
+ await builderSpan.child(import_build_utils24.BUILDER_COMPILE_STEP, {
11227
11351
  buildCommand: projectBuildCommand || void 0
11228
11352
  }).trace(async () => {
11229
11353
  if (projectBuildCommand) {
11230
11354
  console.log(`Running "${projectBuildCommand}"`);
11231
- await (0, import_build_utils23.execCommand)(projectBuildCommand, {
11355
+ await (0, import_build_utils24.execCommand)(projectBuildCommand, {
11232
11356
  env: pythonEnv,
11233
11357
  cwd: workPath
11234
11358
  });
@@ -11256,13 +11380,14 @@ var build = async ({
11256
11380
  entrypoint = resolved?.entrypoint;
11257
11381
  const isWorkersOnly = !entrypoint && isPyprojectEntrypoint && (subscriberDeclarations.length > 0 || workflows.length > 0);
11258
11382
  if (!entrypoint && !isWorkersOnly) {
11259
- throw new import_build_utils23.NowBuildError({
11383
+ throw new import_build_utils24.NowBuildError({
11260
11384
  code: "PYTHON_ENTRYPOINT_NOT_FOUND",
11261
11385
  message: "No Python entrypoint could be detected. Please specify an entrypoint file."
11262
11386
  });
11263
11387
  }
11264
11388
  const djangoStatic = hookResult?.djangoStatic ?? null;
11265
11389
  const fastapiStatic = hookResult?.fastapiStatic ?? null;
11390
+ const importSeeds = hookResult?.importSeeds ?? [];
11266
11391
  const cdnOutputDir = djangoStatic?.cdnOutputDir ?? fastapiStatic?.cdnOutputDir ?? null;
11267
11392
  const pipPlatformArgs = target.uvPlatform ? ["--python-platform", target.uvPlatform] : [];
11268
11393
  await installInjectedPackage({
@@ -11272,7 +11397,7 @@ var build = async ({
11272
11397
  allowLocalSource: true,
11273
11398
  uv,
11274
11399
  venvPath,
11275
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11400
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11276
11401
  pipPlatformArgs
11277
11402
  });
11278
11403
  const conditionalInjectedPackages = usedUvManagedInstall && !legacyWorkersProject ? await getConditionalInjectedPackages({
@@ -11284,7 +11409,7 @@ var build = async ({
11284
11409
  ...injectedPackage,
11285
11410
  uv,
11286
11411
  venvPath,
11287
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11412
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11288
11413
  pipPlatformArgs
11289
11414
  });
11290
11415
  }
@@ -11293,7 +11418,7 @@ var build = async ({
11293
11418
  pythonPackage,
11294
11419
  uv,
11295
11420
  venvPath,
11296
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11421
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11297
11422
  uvLockPath
11298
11423
  });
11299
11424
  }
@@ -11306,7 +11431,7 @@ var build = async ({
11306
11431
  allowLocalSource: true,
11307
11432
  uv,
11308
11433
  venvPath,
11309
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11434
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11310
11435
  pipPlatformArgs
11311
11436
  });
11312
11437
  }
@@ -11317,11 +11442,11 @@ var build = async ({
11317
11442
  const queueIntegrations = legacyWorkersProject ? [] : await getQueueIntegrations({ pythonPackage });
11318
11443
  const writeGeneratedQueueHandler = async (outputPath, declaration) => {
11319
11444
  const generatedPath = getGeneratedQueueHandlerPath(outputPath);
11320
- await import_fs20.default.promises.mkdir((0, import_path20.dirname)((0, import_path20.join)(workPath, generatedPath)), {
11445
+ await import_fs20.default.promises.mkdir((0, import_path21.dirname)((0, import_path21.join)(workPath, generatedPath)), {
11321
11446
  recursive: true
11322
11447
  });
11323
11448
  await import_fs20.default.promises.writeFile(
11324
- (0, import_path20.join)(workPath, generatedPath),
11449
+ (0, import_path21.join)(workPath, generatedPath),
11325
11450
  createQueueHandlerModule(declaration, queueIntegrations)
11326
11451
  );
11327
11452
  };
@@ -11330,7 +11455,7 @@ var build = async ({
11330
11455
  declarations: subscriberDeclarations,
11331
11456
  uv,
11332
11457
  venvPath,
11333
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11458
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11334
11459
  integrations: queueIntegrations
11335
11460
  });
11336
11461
  if (workflowMode === "queue") {
@@ -11361,7 +11486,7 @@ var build = async ({
11361
11486
  })),
11362
11487
  uv,
11363
11488
  venvPath,
11364
- projectDir: (0, import_path20.join)(workPath, entryDirectory),
11489
+ projectDir: (0, import_path21.join)(workPath, entryDirectory),
11365
11490
  kind: "workflow",
11366
11491
  integrations: queueIntegrations
11367
11492
  });
@@ -11378,11 +11503,11 @@ var build = async ({
11378
11503
  const capturedEnv = { ...pythonEnv };
11379
11504
  const capturedCwd = workPath;
11380
11505
  registerPreDeploy(async () => {
11381
- await builderSpan.child(import_build_utils23.BUILDER_PRE_DEPLOY_STEP, {
11506
+ await builderSpan.child(import_build_utils24.BUILDER_PRE_DEPLOY_STEP, {
11382
11507
  preDeployCommand
11383
11508
  }).trace(async () => {
11384
11509
  console.log(`Running pre-deploy command: \`${preDeployCommand}\``);
11385
- await (0, import_build_utils23.execCommand)(preDeployCommand, {
11510
+ await (0, import_build_utils24.execCommand)(preDeployCommand, {
11386
11511
  env: capturedEnv,
11387
11512
  cwd: capturedCwd
11388
11513
  });
@@ -11393,14 +11518,14 @@ var build = async ({
11393
11518
  let crons;
11394
11519
  let runtimeTrampoline;
11395
11520
  if (entrypoint) {
11396
- (0, import_build_utils23.debug)("Entrypoint is", entrypoint);
11521
+ (0, import_build_utils24.debug)("Entrypoint is", entrypoint);
11397
11522
  const moduleName = entrypointToModule(entrypoint);
11398
11523
  if (handlerFunction) {
11399
- const entrypointPath = (0, import_path20.join)(workPath, entrypoint);
11524
+ const entrypointPath = (0, import_path21.join)(workPath, entrypoint);
11400
11525
  const source = await import_fs20.default.promises.readFile(entrypointPath, "utf-8");
11401
11526
  const found = await (0, import_python_analysis12.containsTopLevelCallable)(source, handlerFunction);
11402
11527
  if (!found) {
11403
- throw new import_build_utils23.NowBuildError({
11528
+ throw new import_build_utils24.NowBuildError({
11404
11529
  code: "PYTHON_HANDLER_NOT_FOUND",
11405
11530
  message: `Handler function "${handlerFunction}" not found in ${entrypoint}. Ensure it is defined at the module's top level.`
11406
11531
  });
@@ -11408,7 +11533,7 @@ var build = async ({
11408
11533
  }
11409
11534
  const suffix = meta.isDev && !entrypoint.endsWith(".py") ? ".py" : "";
11410
11535
  const entrypointWithSuffix = `${entrypoint}${suffix}`;
11411
- (0, import_build_utils23.debug)("Entrypoint with suffix is", entrypointWithSuffix);
11536
+ (0, import_build_utils24.debug)("Entrypoint with suffix is", entrypointWithSuffix);
11412
11537
  crons = await getServiceCrons({
11413
11538
  service,
11414
11539
  entrypoint,
@@ -11474,17 +11599,17 @@ var build = async ({
11474
11599
  cwd: workPath,
11475
11600
  ignore: config && typeof config.excludeFiles === "string" ? [...predefinedExcludes, config.excludeFiles] : predefinedExcludes
11476
11601
  };
11477
- const files = await (0, import_build_utils23.glob)("**", globOptions);
11478
- const appPythonSourceFiles = Object.keys(files).filter((file) => file.endsWith(".py")).map((file) => (0, import_path20.join)(workPath, file)).sort();
11602
+ const files = await (0, import_build_utils24.glob)("**", globOptions);
11603
+ const appPythonSourceFiles = Object.keys(files).filter((file) => file.endsWith(".py")).map((file) => (0, import_path21.join)(workPath, file)).sort();
11479
11604
  if (djangoStatic?.manifestRelPath) {
11480
- files[djangoStatic.manifestRelPath] = new import_build_utils23.FileFsRef({
11481
- fsPath: (0, import_path20.join)(workPath, djangoStatic.manifestRelPath)
11605
+ files[djangoStatic.manifestRelPath] = new import_build_utils24.FileFsRef({
11606
+ fsPath: (0, import_path21.join)(workPath, djangoStatic.manifestRelPath)
11482
11607
  });
11483
11608
  }
11484
11609
  const handlerPyFilename = "vc__handler__python";
11485
11610
  if (config.framework === "fasthtml") {
11486
11611
  const { SESSKEY = "" } = process.env;
11487
- files[".sesskey"] = new import_build_utils23.FileBlob({ data: `"${SESSKEY}"` });
11612
+ files[".sesskey"] = new import_build_utils24.FileBlob({ data: `"${SESSKEY}"` });
11488
11613
  }
11489
11614
  await builderSpan.child("vc.builder.python.bundle").trace(async (bundleSpan) => {
11490
11615
  const installedDistributions = await InstalledPythonDistributions.load({
@@ -11525,15 +11650,17 @@ var build = async ({
11525
11650
  pycachePrefix
11526
11651
  }) => {
11527
11652
  if (!compileAllOptions)
11528
- return;
11653
+ return void 0;
11529
11654
  const vendorSourceFiles = installedDistributions.getPythonSourceFiles(includePackages);
11655
+ let timings;
11530
11656
  await builderSpan.child("vc.builder.python.compileall").trace(async (compileSpan) => {
11531
11657
  console.log("Compiling Python bytecode...");
11532
- await runCompileAll({
11658
+ const result = await runCompileAll({
11533
11659
  ...compileAllOptions,
11534
11660
  sourceFiles: [...appPythonSourceFiles, ...vendorSourceFiles],
11535
11661
  pycachePrefix
11536
11662
  });
11663
+ timings = result.timings;
11537
11664
  compileSpan.setAttributes({
11538
11665
  "python.compileall.enabled": "true",
11539
11666
  "python.compileall.appSourceFileCount": String(
@@ -11544,39 +11671,119 @@ var build = async ({
11544
11671
  )
11545
11672
  });
11546
11673
  });
11674
+ return timings;
11547
11675
  };
11548
- const runCompileAllAndFillBytecode = async (capacityBytes, vendorPackageTiers) => {
11549
- try {
11550
- await compileSources({
11551
- includePackages: vendorPackageTiers?.flat()
11552
- });
11553
- const currentSize = await calculateBundleSize(files);
11554
- let remainingCapacity = capacityBytes - currentSize;
11555
- if (pythonVersion.major != null && pythonVersion.minor != null) {
11556
- const appBytecodeInfo = await collectAppBytecodeFiles({
11676
+ let importClosurePromise;
11677
+ const getImportClosureKeys = () => {
11678
+ importClosurePromise ??= (async () => {
11679
+ try {
11680
+ const sitePackageDirs = installedDistributions.getSitePackageDirs();
11681
+ const closure = await withTimeout(
11682
+ (0, import_python_analysis12.collectImportClosure)(
11683
+ getImportClosureOptions({
11684
+ workPath,
11685
+ entrypoint,
11686
+ frameworkSeeds: importSeeds,
11687
+ extraPythonPath: hookResult?.extraPythonPath,
11688
+ subscriberDeclarations,
11689
+ subscribers,
11690
+ workflows,
11691
+ workflowMode,
11692
+ sitePackageDirs
11693
+ })
11694
+ ),
11695
+ IMPORT_CLOSURE_TIMEOUT_MS,
11696
+ "import closure"
11697
+ );
11698
+ if (!closure)
11699
+ return void 0;
11700
+ const keys = moduleKeysForClosurePaths(
11701
+ closure.files,
11557
11702
  workPath,
11558
- files,
11559
- pythonMajor: pythonVersion.major,
11560
- pythonMinor: pythonVersion.minor
11561
- });
11562
- remainingCapacity = addBytecodeWithinCapacity(
11563
- files,
11564
- appBytecodeInfo,
11565
- remainingCapacity
11703
+ sitePackageDirs
11704
+ );
11705
+ (0, import_build_utils24.debug)(
11706
+ `import closure: ${closure.files.size} files, ${keys.size} bundled modules` + (closure.truncated ? " (truncated)" : "")
11707
+ );
11708
+ return keys;
11709
+ } catch (err) {
11710
+ (0, import_build_utils24.debug)(
11711
+ `import closure unavailable, ranking by compile density only: ${err}`
11566
11712
  );
11713
+ return void 0;
11567
11714
  }
11568
- await addVendorBytecodeInTiers({
11715
+ })();
11716
+ return importClosurePromise;
11717
+ };
11718
+ const fillBytecodeWithValueRanking = async ({
11719
+ items,
11720
+ totalSize,
11721
+ capacity,
11722
+ timings
11723
+ }) => {
11724
+ if (totalSize <= 0 || capacity <= 0)
11725
+ return 0;
11726
+ if (totalSize <= capacity) {
11727
+ for (const item of items) {
11728
+ files[item.bundlePath] = item.file;
11729
+ }
11730
+ return totalSize;
11731
+ }
11732
+ return bundleSpan.child("vc.builder.python.bundle.optimize").trace(async (optimizeSpan) => {
11733
+ console.log("Optimizing Python bundle...");
11734
+ const analysisDisabled = isBytecodeAnalysisDisabled();
11735
+ if (analysisDisabled) {
11736
+ (0, import_build_utils24.debug)(
11737
+ "bytecode analysis disabled via VERCEL_PYTHON_DISABLE_BYTECODE_ANALYSIS; ranking by size"
11738
+ );
11739
+ }
11740
+ const importedModules = analysisDisabled ? void 0 : await getImportClosureKeys();
11741
+ const ranked = rankBytecodeItems(
11742
+ annotateBytecodeItems(
11743
+ items,
11744
+ importedModules,
11745
+ analysisDisabled ? void 0 : timings
11746
+ )
11747
+ );
11748
+ const selectedSize = capacity - fillBytecodeWithinCapacity(files, ranked, capacity);
11749
+ optimizeSpan.setAttributes({
11750
+ "python.bundle.optimize.bytecodeCoveragePercent": (selectedSize / totalSize * 100).toFixed(2)
11751
+ });
11752
+ return selectedSize;
11753
+ });
11754
+ };
11755
+ const runAdjacentCompileAndFill = async (capacityBytes, includePackages) => {
11756
+ try {
11757
+ const pyMajor = pythonVersion.major;
11758
+ const pyMinor = pythonVersion.minor;
11759
+ if (pyMajor == null || pyMinor == null)
11760
+ return;
11761
+ const timings = await compileSources({ includePackages });
11762
+ const currentSize = await calculateBundleSize(files);
11763
+ const remaining = capacityBytes - currentSize;
11764
+ if (remaining <= 0)
11765
+ return;
11766
+ const appInfo = await collectAppBytecodeFiles({
11767
+ workPath,
11569
11768
  files,
11570
- installedDistributions,
11571
- vendorDir,
11572
- capacity: remainingCapacity,
11573
- vendorPackageTiers: vendorPackageTiers ?? [void 0]
11769
+ pythonMajor: pyMajor,
11770
+ pythonMinor: pyMinor
11771
+ });
11772
+ const vendorInfo = await installedDistributions.collectBytecodeFiles({
11773
+ vendorDirName: vendorDir,
11774
+ includePackages
11775
+ });
11776
+ await fillBytecodeWithValueRanking({
11777
+ items: [...appInfo.items, ...vendorInfo.items],
11778
+ totalSize: appInfo.totalSize + vendorInfo.totalSize,
11779
+ capacity: remaining,
11780
+ timings
11574
11781
  });
11575
11782
  } catch (err) {
11576
11783
  console.log(
11577
11784
  "Bytecode precompilation failed; continuing without precompiled bytecode."
11578
11785
  );
11579
- (0, import_build_utils23.debug)(`bytecode precompilation error details: ${err}`);
11786
+ (0, import_build_utils24.debug)(`bytecode precompilation error details: ${err}`);
11580
11787
  }
11581
11788
  };
11582
11789
  const runPrefixCompileAndFill = async (bundleResult) => {
@@ -11586,25 +11793,27 @@ var build = async ({
11586
11793
  return;
11587
11794
  try {
11588
11795
  const currentSize = await calculateBundleSize(files);
11589
- let remainingCapacity = BYTECODE_FILL_CEILING_BYTES - currentSize;
11796
+ const remainingCapacity = BYTECODE_FILL_CEILING_BYTES - currentSize;
11590
11797
  if (remainingCapacity <= 0) {
11591
- (0, import_build_utils23.debug)(
11798
+ (0, import_build_utils24.debug)(
11592
11799
  `skipping bytecode precompilation: no zip capacity remaining (bundle is ${(currentSize / (1024 * 1024)).toFixed(2)} MB)`
11593
11800
  );
11594
11801
  return;
11595
11802
  }
11596
- const stagingDir = (0, import_path20.join)(workPath, ".vercel", "python", "pycache");
11803
+ const stagingDir = (0, import_path21.join)(workPath, ".vercel", "python", "pycache");
11597
11804
  await import_fs20.default.promises.rm(stagingDir, { recursive: true, force: true });
11598
11805
  await import_fs20.default.promises.mkdir(stagingDir, { recursive: true });
11599
- await compileSources({
11806
+ const alwaysBundled = bundleResult.alwaysBundledPackages ?? [];
11807
+ const bundledPublic = bundleResult.bundledPublicPackages ?? [];
11808
+ const externalized = bundleResult.externalizedPublicPackages ?? [];
11809
+ const timings = await compileSources({
11600
11810
  includePackages: [
11601
- ...bundleResult.alwaysBundledPackages ?? [],
11602
- ...bundleResult.bundledPublicPackages ?? [],
11603
- ...bundleResult.externalizedPublicPackages ?? []
11811
+ ...alwaysBundled,
11812
+ ...bundledPublic,
11813
+ ...externalized
11604
11814
  ],
11605
11815
  pycachePrefix: stagingDir
11606
11816
  });
11607
- const beforeCount = Object.keys(files).length;
11608
11817
  const appInfo = await collectAppPrefixBytecodeFiles({
11609
11818
  stagingDir,
11610
11819
  workPath,
@@ -11613,39 +11822,34 @@ var build = async ({
11613
11822
  pythonMajor: pyMajor,
11614
11823
  pythonMinor: pyMinor
11615
11824
  });
11616
- remainingCapacity = addBytecodeWithinCapacity(
11617
- files,
11618
- appInfo,
11619
- remainingCapacity
11620
- );
11621
- const alwaysBundled = bundleResult.alwaysBundledPackages ?? [];
11622
- remainingCapacity = await addCollectedVendorBytecode({
11623
- files,
11624
- capacity: remainingCapacity,
11625
- collect: (include) => installedDistributions.collectPrefixBytecodeFiles({
11626
- stagingDir,
11627
- runtimeRoot: `/var/task/${vendorDir}`,
11628
- includePackages: include ?? alwaysBundled
11629
- })
11825
+ const bundledVendorInfo = await installedDistributions.collectPrefixBytecodeFiles({
11826
+ stagingDir,
11827
+ runtimeRoot: `/var/task/${vendorDir}`,
11828
+ includePackages: [...alwaysBundled, ...bundledPublic]
11630
11829
  });
11631
- const externalized = bundleResult.externalizedPublicPackages ?? [];
11632
- await addCollectedVendorBytecode({
11633
- files,
11830
+ const externalizedInfo = await installedDistributions.collectPrefixBytecodeFiles({
11831
+ stagingDir,
11832
+ runtimeRoot: `${RUNTIME_DEPS_DIR}/lib/python${pyMajor}.${pyMinor}/site-packages`,
11833
+ includePackages: externalized
11834
+ });
11835
+ const bytesAdded = await fillBytecodeWithValueRanking({
11836
+ items: [
11837
+ ...appInfo.items,
11838
+ ...bundledVendorInfo.items,
11839
+ ...externalizedInfo.items
11840
+ ],
11841
+ totalSize: appInfo.totalSize + bundledVendorInfo.totalSize + externalizedInfo.totalSize,
11634
11842
  capacity: remainingCapacity,
11635
- collect: (include) => installedDistributions.collectPrefixBytecodeFiles({
11636
- stagingDir,
11637
- runtimeRoot: `${RUNTIME_DEPS_DIR}/lib/python${pyMajor}.${pyMinor}/site-packages`,
11638
- includePackages: include ?? externalized
11639
- })
11843
+ timings
11640
11844
  });
11641
- if (Object.keys(files).length > beforeCount) {
11845
+ if (bytesAdded > 0) {
11642
11846
  lambdaEnv.PYTHONPYCACHEPREFIX = RUNTIME_PYCACHE_PREFIX;
11643
11847
  }
11644
11848
  } catch (err) {
11645
11849
  console.log(
11646
11850
  "Bytecode precompilation failed; continuing without precompiled bytecode."
11647
11851
  );
11648
- (0, import_build_utils23.debug)(`bytecode precompilation error details: ${err}`);
11852
+ (0, import_build_utils24.debug)(`bytecode precompilation error details: ${err}`);
11649
11853
  }
11650
11854
  };
11651
11855
  const announceLargeFunction = () => console.log(
@@ -11662,9 +11866,7 @@ var build = async ({
11662
11866
  packingMode = "hive";
11663
11867
  announceLargeFunction();
11664
11868
  if (compileAllEnabled) {
11665
- await runCompileAllAndFillBytecode(
11666
- LARGE_FUNCTION_FILL_CEILING_BYTES
11667
- );
11869
+ await runAdjacentCompileAndFill(LARGE_FUNCTION_FILL_CEILING_BYTES);
11668
11870
  }
11669
11871
  } else if (bundleResult.packingMode === "bytecode-first") {
11670
11872
  await runPrefixCompileAndFill(bundleResult);
@@ -11672,12 +11874,12 @@ var build = async ({
11672
11874
  const currentSize = await calculateBundleSize(files);
11673
11875
  const capacity = BYTECODE_FILL_CEILING_BYTES - currentSize;
11674
11876
  if (capacity > 0) {
11675
- await runCompileAllAndFillBytecode(BYTECODE_FILL_CEILING_BYTES, [
11676
- bundleResult.alwaysBundledPackages ?? [],
11677
- bundleResult.bundledPublicPackages ?? []
11877
+ await runAdjacentCompileAndFill(BYTECODE_FILL_CEILING_BYTES, [
11878
+ ...bundleResult.alwaysBundledPackages ?? [],
11879
+ ...bundleResult.bundledPublicPackages ?? []
11678
11880
  ]);
11679
11881
  } else {
11680
- (0, import_build_utils23.debug)(
11882
+ (0, import_build_utils24.debug)(
11681
11883
  `skipping bytecode precompilation: no zip capacity remaining (bundle is ${(currentSize / (1024 * 1024)).toFixed(2)} MB)`
11682
11884
  );
11683
11885
  }
@@ -11690,18 +11892,16 @@ var build = async ({
11690
11892
  announceLargeFunction();
11691
11893
  }
11692
11894
  if (compileAllEnabled) {
11693
- await runCompileAllAndFillBytecode(
11694
- LARGE_FUNCTION_FILL_CEILING_BYTES
11695
- );
11895
+ await runAdjacentCompileAndFill(LARGE_FUNCTION_FILL_CEILING_BYTES);
11696
11896
  }
11697
11897
  } else {
11698
11898
  packingMode = "standard";
11699
11899
  if (compileAllEnabled) {
11700
11900
  const capacity = BYTECODE_FILL_CEILING_BYTES - depAnalysis.totalBundleSize;
11701
11901
  if (capacity > 0) {
11702
- await runCompileAllAndFillBytecode(BYTECODE_FILL_CEILING_BYTES);
11902
+ await runAdjacentCompileAndFill(BYTECODE_FILL_CEILING_BYTES);
11703
11903
  } else {
11704
- (0, import_build_utils23.debug)(
11904
+ (0, import_build_utils24.debug)(
11705
11905
  `skipping bytecode precompilation: no zip capacity remaining (bundle is ${(depAnalysis.totalBundleSize / (1024 * 1024)).toFixed(2)} MB)`
11706
11906
  );
11707
11907
  }
@@ -11719,13 +11919,13 @@ var build = async ({
11719
11919
  if (entrypoint && runtimeTrampoline) {
11720
11920
  const webFiles = {
11721
11921
  ...files,
11722
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({ data: runtimeTrampoline })
11922
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({ data: runtimeTrampoline })
11723
11923
  };
11724
11924
  const lambdaOptions = await getPythonLambdaOptions({
11725
11925
  config,
11726
11926
  entrypoint
11727
11927
  });
11728
- output = new import_build_utils23.Lambda({
11928
+ output = new import_build_utils24.Lambda({
11729
11929
  files: webFiles,
11730
11930
  handler: `${handlerPyFilename}.vc_handler`,
11731
11931
  runtime: pythonVersion.runtime,
@@ -11754,10 +11954,10 @@ var build = async ({
11754
11954
  ...subscription.triggerDefaults
11755
11955
  })
11756
11956
  );
11757
- subscriberLambdas[outputPath] = new import_build_utils23.Lambda({
11957
+ subscriberLambdas[outputPath] = new import_build_utils24.Lambda({
11758
11958
  files: {
11759
11959
  ...files,
11760
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({
11960
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({
11761
11961
  data: createRuntimeTrampoline({
11762
11962
  moduleName: generatedPythonPathToModule(generatedHandlerPath),
11763
11963
  entrypoint: generatedHandlerPath,
@@ -11787,10 +11987,10 @@ var build = async ({
11787
11987
  consumer,
11788
11988
  ...legacy.triggerDefaults
11789
11989
  }));
11790
- subscriberLambdas[outputPath] = new import_build_utils23.Lambda({
11990
+ subscriberLambdas[outputPath] = new import_build_utils24.Lambda({
11791
11991
  files: {
11792
11992
  ...files,
11793
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({
11993
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({
11794
11994
  data: createRuntimeTrampoline({
11795
11995
  moduleName: declaration.moduleName,
11796
11996
  entrypoint: declaration.entrypoint,
@@ -11823,10 +12023,10 @@ var build = async ({
11823
12023
  ...subscription.triggerDefaults
11824
12024
  })
11825
12025
  );
11826
- workflowLambdas[outputPath] = new import_build_utils23.Lambda({
12026
+ workflowLambdas[outputPath] = new import_build_utils24.Lambda({
11827
12027
  files: {
11828
12028
  ...files,
11829
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({
12029
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({
11830
12030
  data: createRuntimeTrampoline({
11831
12031
  moduleName: generatedPythonPathToModule(generatedHandlerPath),
11832
12032
  entrypoint: generatedHandlerPath,
@@ -11852,10 +12052,10 @@ var build = async ({
11852
12052
  consumer: getWorkflowConsumerName(workflow.name)
11853
12053
  }
11854
12054
  ];
11855
- workflowLambdas[outputPath] = new import_build_utils23.Lambda({
12055
+ workflowLambdas[outputPath] = new import_build_utils24.Lambda({
11856
12056
  files: {
11857
12057
  ...files,
11858
- [`${handlerPyFilename}.py`]: new import_build_utils23.FileBlob({
12058
+ [`${handlerPyFilename}.py`]: new import_build_utils24.FileBlob({
11859
12059
  data: createRuntimeTrampoline({
11860
12060
  moduleName: workflow.moduleName,
11861
12061
  entrypoint: workflow.entrypoint,
@@ -11880,21 +12080,21 @@ var build = async ({
11880
12080
  pythonVersion,
11881
12081
  uvLockPath,
11882
12082
  framework,
11883
- serviceType: service ? (0, import_build_utils23.getReportedServiceType)(service) : void 0
12083
+ serviceType: service ? (0, import_build_utils24.getReportedServiceType)(service) : void 0
11884
12084
  });
11885
12085
  } catch (err) {
11886
- (0, import_build_utils23.debug)(
12086
+ (0, import_build_utils24.debug)(
11887
12087
  `Failed to write project manifest: ${err instanceof Error ? err.message : String(err)}`
11888
12088
  );
11889
12089
  }
11890
12090
  }
11891
- if (!(0, import_build_utils23.isPythonFramework)(framework) && !service?.name && !isPyprojectEntrypoint) {
12091
+ if (!(0, import_build_utils24.isPythonFramework)(framework) && !service?.name && !isPyprojectEntrypoint) {
11892
12092
  (0, import_assert.default)(output, "web Lambda must exist for non-service builds");
11893
12093
  return { resultVersion: 3, result: { output } };
11894
12094
  }
11895
12095
  const frameworkLambdaName = framework ?? "python";
11896
12096
  const lambdaPath = service?.name && service.type ? `_svc/${service.name}/index` : frameworkLambdaName;
11897
- const staticFiles = cdnOutputDir ? await (0, import_build_utils23.glob)("**", { cwd: cdnOutputDir }) : {};
12097
+ const staticFiles = cdnOutputDir ? await (0, import_build_utils24.glob)("**", { cwd: cdnOutputDir }) : {};
11898
12098
  const isNonWebService = service?.name && service.type && service.type !== "web";
11899
12099
  const queueRoutes = queueRoutePaths.map((outputPath) => ({
11900
12100
  src: `/${outputPath}`,
@@ -11947,14 +12147,14 @@ var prepareCache = async ({
11947
12147
  }
11948
12148
  } catch {
11949
12149
  }
11950
- return (0, import_build_utils23.glob)("**/.vercel/python/{.venv,services/*/.venv,cache/uv}/**", {
12150
+ return (0, import_build_utils24.glob)("**/.vercel/python/{.venv,services/*/.venv,cache/uv}/**", {
11951
12151
  cwd: root,
11952
12152
  ignore
11953
12153
  });
11954
12154
  };
11955
12155
  var shouldServe = (opts) => {
11956
12156
  const framework = opts.config.framework;
11957
- if ((0, import_build_utils23.isPythonFramework)(framework)) {
12157
+ if ((0, import_build_utils24.isPythonFramework)(framework)) {
11958
12158
  const requestPath = opts.requestPath.replace(/\/$/, "");
11959
12159
  if (requestPath.startsWith("api") && opts.hasMatched) {
11960
12160
  return false;
@@ -11973,7 +12173,7 @@ var defaultShouldServe = ({
11973
12173
  if (entrypoint === requestPath && hasProp(files, entrypoint)) {
11974
12174
  return true;
11975
12175
  }
11976
- const { dir, name } = (0, import_path20.parse)(entrypoint);
12176
+ const { dir, name } = (0, import_path21.parse)(entrypoint);
11977
12177
  if (name === "index" && dir === requestPath && hasProp(files, entrypoint)) {
11978
12178
  return true;
11979
12179
  }
@@ -11984,8 +12184,6 @@ function hasProp(obj, key) {
11984
12184
  }
11985
12185
  // Annotate the CommonJS export names for ESM import in node:
11986
12186
  0 && (module.exports = {
11987
- addCollectedVendorBytecode,
11988
- addVendorBytecodeInTiers,
11989
12187
  build,
11990
12188
  defaultShouldServe,
11991
12189
  detectEntrypoint,
@@ -11994,6 +12192,7 @@ function hasProp(obj, key) {
11994
12192
  getDevSidecars,
11995
12193
  installRequirement,
11996
12194
  installRequirementsFile,
12195
+ moduleKeysForClosurePaths,
11997
12196
  prepareCache,
11998
12197
  runFrameworkHook,
11999
12198
  shouldServe,