wrangler 2.0.3 → 2.0.7

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/src/pages.tsx CHANGED
@@ -4,7 +4,7 @@ import { execSync, spawn } from "node:child_process";
4
4
  import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { readdir, readFile, stat } from "node:fs/promises";
6
6
  import { tmpdir } from "node:os";
7
- import { dirname, join, sep } from "node:path";
7
+ import { dirname, join, sep, extname, basename } from "node:path";
8
8
  import { cwd } from "node:process";
9
9
  import { URL } from "node:url";
10
10
  import { hash } from "blake3-wasm";
@@ -14,6 +14,7 @@ import SelectInput from "ink-select-input";
14
14
  import Spinner from "ink-spinner";
15
15
  import Table from "ink-table";
16
16
  import { getType } from "mime";
17
+ import PQueue from "p-queue";
17
18
  import prettyBytes from "pretty-bytes";
18
19
  import React from "react";
19
20
  import { format as timeagoFormat } from "timeago.js";
@@ -32,7 +33,11 @@ import openInBrowser from "./open-in-browser";
32
33
  import { toUrlPath } from "./paths";
33
34
  import { requireAuth } from "./user";
34
35
  import type { Config } from "../pages/functions/routes";
35
- import type { Headers, Request, fetch } from "@miniflare/core";
36
+ import type {
37
+ Headers as MiniflareHeaders,
38
+ Request as MiniflareRequest,
39
+ fetch as miniflareFetch,
40
+ } from "@miniflare/core";
36
41
  import type { BuildResult } from "esbuild";
37
42
  import type { MiniflareOptions } from "miniflare";
38
43
  import type { BuilderCallback, CommandModule } from "yargs";
@@ -68,12 +73,23 @@ export type Deployment = {
68
73
  project_name: string;
69
74
  };
70
75
 
76
+ export type UploadPayloadFile = {
77
+ key: string;
78
+ value: string;
79
+ metadata: { contentType: string };
80
+ base64: boolean;
81
+ };
82
+
71
83
  interface PagesConfigCache {
72
84
  account_id?: string;
73
85
  project_name?: string;
74
86
  }
75
87
 
76
88
  const PAGES_CONFIG_CACHE_FILENAME = "pages.json";
89
+ const MAX_BUCKET_SIZE = 50 * 1024 * 1024;
90
+ const MAX_BUCKET_FILE_COUNT = 5000;
91
+ const BULK_UPLOAD_CONCURRENCY = 3;
92
+ const MAX_UPLOAD_ATTEMPTS = 5;
77
93
 
78
94
  // Defer importing miniflare until we really need it. This takes ~0.5s
79
95
  // and also modifies some `stream/web` and `undici` prototypes, so we
@@ -284,7 +300,7 @@ function generateRulesMatcher<T>(
284
300
  T
285
301
  ][];
286
302
 
287
- return ({ request }: { request: Request }) => {
303
+ return ({ request }: { request: MiniflareRequest }) => {
288
304
  const { pathname, host } = new URL(request.url);
289
305
 
290
306
  return compiledRules
@@ -357,7 +373,7 @@ function generateHeadersMatcher(headersFile: string) {
357
373
  )
358
374
  );
359
375
 
360
- return (request: Request) => {
376
+ return (request: MiniflareRequest) => {
361
377
  const matches = rulesMatcher({
362
378
  request,
363
379
  });
@@ -406,7 +422,7 @@ function generateRedirectsMatcher(redirectsFile: string) {
406
422
  })
407
423
  );
408
424
 
409
- return (request: Request) => {
425
+ return (request: MiniflareRequest) => {
410
426
  const match = rulesMatcher({
411
427
  request,
412
428
  })[0];
@@ -461,7 +477,9 @@ function hasFileExtension(pathname: string) {
461
477
  return /\/.+\.[a-z0-9]+$/i.test(pathname);
462
478
  }
463
479
 
464
- async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
480
+ async function generateAssetsFetch(
481
+ directory: string
482
+ ): Promise<typeof miniflareFetch> {
465
483
  // Defer importing miniflare until we really need it
466
484
  const { Headers, Request, Response } = await import("@miniflare/core");
467
485
 
@@ -510,12 +528,12 @@ async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
510
528
  return readFileSync(file);
511
529
  };
512
530
 
513
- const generateResponse = (request: Request) => {
531
+ const generateResponse = (request: MiniflareRequest) => {
514
532
  const url = new URL(request.url);
515
533
 
516
534
  const deconstructedResponse: {
517
535
  status: number;
518
- headers: Headers;
536
+ headers: MiniflareHeaders;
519
537
  body?: Buffer;
520
538
  } = {
521
539
  status: 200,
@@ -667,8 +685,12 @@ async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
667
685
  };
668
686
 
669
687
  const attachHeaders = (
670
- request: Request,
671
- deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
688
+ request: MiniflareRequest,
689
+ deconstructedResponse: {
690
+ status: number;
691
+ headers: MiniflareHeaders;
692
+ body?: Buffer;
693
+ }
672
694
  ) => {
673
695
  const headers = deconstructedResponse.headers;
674
696
  const newHeaders = new Headers({});
@@ -722,6 +744,7 @@ async function buildFunctions({
722
744
  onEnd,
723
745
  plugin = false,
724
746
  buildOutputDirectory,
747
+ nodeCompat,
725
748
  }: {
726
749
  outfile: string;
727
750
  outputConfigPath?: string;
@@ -733,12 +756,13 @@ async function buildFunctions({
733
756
  onEnd?: () => void;
734
757
  plugin?: boolean;
735
758
  buildOutputDirectory?: string;
759
+ nodeCompat?: boolean;
736
760
  }) {
737
761
  RUNNING_BUILDERS.forEach(
738
762
  (runningBuilder) => runningBuilder.stop && runningBuilder.stop()
739
763
  );
740
764
 
741
- const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
765
+ const routesModule = join(tmpdir(), `./functionsRoutes-${Math.random()}.mjs`);
742
766
  const baseURL = toUrlPath("/");
743
767
 
744
768
  const config: Config = await generateConfigFromFileTree({
@@ -767,6 +791,7 @@ async function buildFunctions({
767
791
  minify,
768
792
  sourcemap,
769
793
  watch,
794
+ nodeCompat,
770
795
  onEnd,
771
796
  })
772
797
  );
@@ -781,6 +806,7 @@ async function buildFunctions({
781
806
  watch,
782
807
  onEnd,
783
808
  buildOutputDirectory,
809
+ nodeCompat,
784
810
  })
785
811
  );
786
812
  }
@@ -1001,7 +1027,7 @@ const createDeployment: CommandModule<
1001
1027
 
1002
1028
  if (isGitDirty && !commitDirty) {
1003
1029
  logger.warn(
1004
- `Warning: Your working directory is a git repo and has uncommitted changes\nTo silense this warning, pass in --commit-dirty=true`
1030
+ `Warning: Your working directory is a git repo and has uncommitted changes\nTo silence this warning, pass in --commit-dirty=true`
1005
1031
  );
1006
1032
  }
1007
1033
 
@@ -1013,7 +1039,7 @@ const createDeployment: CommandModule<
1013
1039
  let builtFunctions: string | undefined = undefined;
1014
1040
  const functionsDirectory = join(cwd(), "functions");
1015
1041
  if (existsSync(functionsDirectory)) {
1016
- const outfile = join(tmpdir(), "./functionsWorker.js");
1042
+ const outfile = join(tmpdir(), `./functionsWorker-${Math.random()}.js`);
1017
1043
 
1018
1044
  await new Promise((resolve) =>
1019
1045
  buildFunctions({
@@ -1027,12 +1053,9 @@ const createDeployment: CommandModule<
1027
1053
  builtFunctions = readFileSync(outfile, "utf-8");
1028
1054
  }
1029
1055
 
1030
- type File = {
1031
- content: Buffer;
1032
- metadata: Metadata;
1033
- };
1034
-
1035
- type Metadata = {
1056
+ type FileContainer = {
1057
+ content: string;
1058
+ contentType: string;
1036
1059
  sizeInBytes: number;
1037
1060
  hash: string;
1038
1061
  };
@@ -1047,7 +1070,7 @@ const createDeployment: CommandModule<
1047
1070
 
1048
1071
  const walk = async (
1049
1072
  dir: string,
1050
- fileMap: Map<string, File> = new Map(),
1073
+ fileMap: Map<string, FileContainer> = new Map(),
1051
1074
  depth = 0
1052
1075
  ) => {
1053
1076
  const files = await readdir(dir);
@@ -1079,10 +1102,7 @@ const createDeployment: CommandModule<
1079
1102
  const fileContent = await readFile(filepath);
1080
1103
 
1081
1104
  const base64Content = fileContent.toString("base64");
1082
- const extension =
1083
- name.split(".").length > 1 ? name.split(".").at(-1) || "" : "";
1084
-
1085
- const content = base64Content + extension;
1105
+ const extension = extname(basename(name)).substring(1);
1086
1106
 
1087
1107
  if (filestat.size > 25 * 1024 * 1024) {
1088
1108
  throw new Error(
@@ -1093,11 +1113,12 @@ const createDeployment: CommandModule<
1093
1113
  }
1094
1114
 
1095
1115
  fileMap.set(name, {
1096
- content: fileContent,
1097
- metadata: {
1098
- sizeInBytes: filestat.size,
1099
- hash: hash(content).toString("hex").slice(0, 32),
1100
- },
1116
+ content: base64Content,
1117
+ contentType: getType(name) || "application/octet-stream",
1118
+ sizeInBytes: filestat.size,
1119
+ hash: hash(base64Content + extension)
1120
+ .toString("hex")
1121
+ .slice(0, 32),
1101
1122
  });
1102
1123
  }
1103
1124
  })
@@ -1108,51 +1129,139 @@ const createDeployment: CommandModule<
1108
1129
 
1109
1130
  const fileMap = await walk(directory);
1110
1131
 
1132
+ if (fileMap.size > 20000) {
1133
+ throw new FatalError(
1134
+ `Error: Pages only supports up to 20,000 files in a deployment. Ensure you have specified your build output directory correctly.`,
1135
+ 1
1136
+ );
1137
+ }
1138
+
1139
+ const files = [...fileMap.values()];
1140
+
1141
+ const { jwt } = await fetchResult<{ jwt: string }>(
1142
+ `/accounts/${accountId}/pages/projects/${projectName}/upload-token`
1143
+ );
1144
+
1111
1145
  const start = Date.now();
1112
1146
 
1113
- const files: Array<Promise<void>> = [];
1147
+ const missingHashes = await fetchResult<string[]>(
1148
+ `/pages/assets/check-missing`,
1149
+ {
1150
+ method: "POST",
1151
+ headers: {
1152
+ "Content-Type": "application/json",
1153
+ Authorization: `Bearer ${jwt}`,
1154
+ },
1155
+ body: JSON.stringify({
1156
+ hashes: files.map(({ hash }) => hash),
1157
+ }),
1158
+ }
1159
+ );
1114
1160
 
1115
- if (fileMap.size > 1000) {
1116
- throw new Error(
1117
- `Error: Pages only supports up to 1,000 files in a deployment at the moment.\nTry a smaller project perhaps?`
1118
- );
1119
- }
1161
+ const sortedFiles = files
1162
+ .filter((file) => missingHashes.includes(file.hash))
1163
+ .sort((a, b) => b.sizeInBytes - a.sizeInBytes);
1164
+
1165
+ // Start with a few buckets so small projects still get
1166
+ // the benefit of multiple upload streams
1167
+ const buckets: {
1168
+ files: FileContainer[];
1169
+ remainingSize: number;
1170
+ }[] = new Array(BULK_UPLOAD_CONCURRENCY).fill(null).map(() => ({
1171
+ files: [],
1172
+ remainingSize: MAX_BUCKET_SIZE,
1173
+ }));
1174
+
1175
+ let bucketOffset = 0;
1176
+ for (const file of sortedFiles) {
1177
+ let inserted = false;
1178
+
1179
+ for (let i = 0; i < buckets.length; i++) {
1180
+ // Start at a different bucket for each new file
1181
+ const bucket = buckets[(i + bucketOffset) % buckets.length];
1182
+ if (
1183
+ bucket.remainingSize >= file.sizeInBytes &&
1184
+ bucket.files.length < MAX_BUCKET_FILE_COUNT
1185
+ ) {
1186
+ bucket.files.push(file);
1187
+ bucket.remainingSize -= file.sizeInBytes;
1188
+ inserted = true;
1189
+ break;
1190
+ }
1191
+ }
1120
1192
 
1121
- let counter = 0;
1193
+ if (!inserted) {
1194
+ buckets.push({
1195
+ files: [file],
1196
+ remainingSize: MAX_BUCKET_SIZE - file.sizeInBytes,
1197
+ });
1198
+ }
1199
+ bucketOffset++;
1200
+ }
1122
1201
 
1202
+ let counter = fileMap.size - sortedFiles.length;
1123
1203
  const { rerender, unmount } = render(
1124
1204
  <Progress done={counter} total={fileMap.size} />
1125
1205
  );
1126
1206
 
1127
- fileMap.forEach((file: File, name: string) => {
1128
- const form = new FormData();
1129
- form.append(
1130
- "file",
1131
- new File([new Uint8Array(file.content.buffer)], name)
1132
- );
1207
+ const queue = new PQueue({ concurrency: BULK_UPLOAD_CONCURRENCY });
1133
1208
 
1134
- // TODO: Consider a retry
1209
+ for (const bucket of buckets) {
1210
+ // Don't upload empty buckets (can happen for tiny projects)
1211
+ if (bucket.files.length === 0) continue;
1135
1212
 
1136
- const promise = fetchResult<{ id: string }>(
1137
- `/accounts/${accountId}/pages/projects/${projectName}/file`,
1138
- {
1139
- method: "POST",
1140
- body: form,
1141
- }
1142
- ).then((response) => {
1143
- counter++;
1144
- rerender(<Progress done={counter} total={fileMap.size} />);
1145
- if (response.id != file.metadata.hash) {
1146
- throw new Error(
1147
- `Looks like there was an issue uploading '${name}'. Try again perhaps?`
1148
- );
1213
+ const payload: UploadPayloadFile[] = bucket.files.map((file) => ({
1214
+ key: file.hash,
1215
+ value: file.content,
1216
+ metadata: {
1217
+ contentType: file.contentType,
1218
+ },
1219
+ base64: true,
1220
+ }));
1221
+
1222
+ let attempts = 0;
1223
+ const doUpload = async (): Promise<void> => {
1224
+ try {
1225
+ return await fetchResult(`/pages/assets/upload`, {
1226
+ method: "POST",
1227
+ headers: {
1228
+ "Content-Type": "application/json",
1229
+ Authorization: `Bearer ${jwt}`,
1230
+ },
1231
+ body: JSON.stringify(payload),
1232
+ });
1233
+ } catch (e) {
1234
+ if (attempts < MAX_UPLOAD_ATTEMPTS) {
1235
+ // Linear backoff, 0 second first time, then 1 second etc.
1236
+ await new Promise((resolve) =>
1237
+ setTimeout(resolve, attempts++ * 1000)
1238
+ );
1239
+ return doUpload();
1240
+ } else {
1241
+ throw e;
1242
+ }
1149
1243
  }
1150
- });
1244
+ };
1151
1245
 
1152
- files.push(promise);
1153
- });
1246
+ queue.add(() =>
1247
+ doUpload().then(
1248
+ () => {
1249
+ counter += bucket.files.length;
1250
+ rerender(<Progress done={counter} total={fileMap.size} />);
1251
+ },
1252
+ (error) => {
1253
+ return Promise.reject(
1254
+ new FatalError(
1255
+ "Failed to upload files. Please try again.",
1256
+ error.code || 1
1257
+ )
1258
+ );
1259
+ }
1260
+ )
1261
+ );
1262
+ }
1154
1263
 
1155
- await Promise.all(files);
1264
+ await queue.onIdle();
1156
1265
 
1157
1266
  unmount();
1158
1267
 
@@ -1170,7 +1279,7 @@ const createDeployment: CommandModule<
1170
1279
  Object.fromEntries(
1171
1280
  [...fileMap.entries()].map(([fileName, file]) => [
1172
1281
  `/${fileName}`,
1173
- file.metadata.hash,
1282
+ file.hash,
1174
1283
  ])
1175
1284
  )
1176
1285
  )
@@ -1244,7 +1353,7 @@ const createDeployment: CommandModule<
1244
1353
  export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1245
1354
  return yargs
1246
1355
  .command(
1247
- "dev [directory] [-- command]",
1356
+ "dev [directory] [-- command..]",
1248
1357
  "🧑‍💻 Develop your full-stack Pages application locally",
1249
1358
  (yargs) => {
1250
1359
  return yargs
@@ -1300,6 +1409,12 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1300
1409
  default: false,
1301
1410
  description: "Auto reload HTML pages when change is detected",
1302
1411
  },
1412
+ "node-compat": {
1413
+ describe: "Enable node.js compatibility",
1414
+ default: false,
1415
+ type: "boolean",
1416
+ hidden: true,
1417
+ },
1303
1418
  // TODO: Miniflare user options
1304
1419
  })
1305
1420
  .epilogue(pagesBetaWarning);
@@ -1314,6 +1429,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1314
1429
  kv: kvs = [],
1315
1430
  do: durableObjects = [],
1316
1431
  "live-reload": liveReload,
1432
+ "node-compat": nodeCompat,
1317
1433
  _: [_pages, _dev, ...remaining],
1318
1434
  }) => {
1319
1435
  // Beta message for `wrangler pages <commands>` usage
@@ -1347,7 +1463,16 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1347
1463
  );
1348
1464
 
1349
1465
  if (usingFunctions) {
1350
- const outfile = join(tmpdir(), "./functionsWorker.js");
1466
+ const outfile = join(
1467
+ tmpdir(),
1468
+ `./functionsWorker-${Math.random()}.js`
1469
+ );
1470
+
1471
+ if (nodeCompat) {
1472
+ console.warn(
1473
+ "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
1474
+ );
1475
+ }
1351
1476
 
1352
1477
  logger.log(`Compiling worker to "${outfile}"...`);
1353
1478
 
@@ -1359,6 +1484,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1359
1484
  watch: true,
1360
1485
  onEnd: () => scriptReadyResolve(),
1361
1486
  buildOutputDirectory: directory,
1487
+ nodeCompat,
1362
1488
  });
1363
1489
  } catch {}
1364
1490
 
@@ -1373,6 +1499,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1373
1499
  watch: true,
1374
1500
  onEnd: () => scriptReadyResolve(),
1375
1501
  buildOutputDirectory: directory,
1502
+ nodeCompat,
1376
1503
  });
1377
1504
  });
1378
1505
 
@@ -1456,7 +1583,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1456
1583
 
1457
1584
  // env.ASSETS.fetch
1458
1585
  serviceBindings: {
1459
- async ASSETS(request: Request) {
1586
+ async ASSETS(request: MiniflareRequest) {
1460
1587
  if (proxyPort) {
1461
1588
  try {
1462
1589
  const url = new URL(request.url);
@@ -1580,6 +1707,12 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1580
1707
  type: "string",
1581
1708
  description: "The directory to output static assets to",
1582
1709
  },
1710
+ "node-compat": {
1711
+ describe: "Enable node.js compatibility",
1712
+ default: false,
1713
+ type: "boolean",
1714
+ hidden: true,
1715
+ },
1583
1716
  })
1584
1717
  .epilogue(pagesBetaWarning),
1585
1718
  async ({
@@ -1592,12 +1725,19 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1592
1725
  watch,
1593
1726
  plugin,
1594
1727
  "build-output-directory": buildOutputDirectory,
1728
+ "node-compat": nodeCompat,
1595
1729
  }) => {
1596
1730
  if (!isInPagesCI) {
1597
1731
  // Beta message for `wrangler pages <commands>` usage
1598
1732
  logger.log(pagesBetaWarning);
1599
1733
  }
1600
1734
 
1735
+ if (nodeCompat) {
1736
+ console.warn(
1737
+ "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
1738
+ );
1739
+ }
1740
+
1601
1741
  buildOutputDirectory ??= dirname(outfile);
1602
1742
 
1603
1743
  await buildFunctions({
@@ -1610,6 +1750,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1610
1750
  watch,
1611
1751
  plugin,
1612
1752
  buildOutputDirectory,
1753
+ nodeCompat,
1613
1754
  });
1614
1755
  }
1615
1756
  )
@@ -1834,7 +1975,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1834
1975
  } as CommandModule);
1835
1976
  };
1836
1977
 
1837
- const invalidAssetsFetch: typeof fetch = () => {
1978
+ const invalidAssetsFetch: typeof miniflareFetch = () => {
1838
1979
  throw new Error(
1839
1980
  "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
1840
1981
  );
package/src/parse.ts CHANGED
@@ -62,8 +62,6 @@ export class ParseError extends Error implements Message {
62
62
  }
63
63
  }
64
64
 
65
- /* eslint-disable @typescript-eslint/no-explicit-any */
66
-
67
65
  const TOML_ERROR_NAME = "TomlError";
68
66
  const TOML_ERROR_SUFFIX = " at row ";
69
67
 
@@ -78,7 +76,7 @@ type TomlError = Error & {
78
76
  export function parseTOML(input: string, file?: string): TOML.JsonMap | never {
79
77
  try {
80
78
  // Normalize CRLF to LF to avoid hitting https://github.com/iarna/iarna-toml/issues/33.
81
- const normalizedInput = input.replace(/\r\n$/g, "\n");
79
+ const normalizedInput = input.replace(/\r\n/g, "\n");
82
80
  return TOML.parse(normalizedInput);
83
81
  } catch (err) {
84
82
  const { name, message, line, col } = err as TomlError;
@@ -100,10 +98,29 @@ export function parseTOML(input: string, file?: string): TOML.JsonMap | never {
100
98
 
101
99
  const JSON_ERROR_SUFFIX = " in JSON at position ";
102
100
 
101
+ /**
102
+ * A minimal type describing a package.json file.
103
+ */
104
+ export type PackageJSON = {
105
+ devDependencies?: Record<string, unknown>;
106
+ dependencies?: Record<string, unknown>;
107
+ scripts?: Record<string, unknown>;
108
+ };
109
+
110
+ /**
111
+ * A typed version of `parseJSON()`.
112
+ */
113
+ export function parsePackageJSON<T extends PackageJSON = PackageJSON>(
114
+ input: string,
115
+ file?: string
116
+ ): T {
117
+ return parseJSON<T>(input, file);
118
+ }
119
+
103
120
  /**
104
121
  * A wrapper around `JSON.parse` that throws a `ParseError`.
105
122
  */
106
- export function parseJSON(input: string, file?: string): any {
123
+ export function parseJSON<T>(input: string, file?: string): T {
107
124
  try {
108
125
  return JSON.parse(input);
109
126
  } catch (err) {