-
Notifications
You must be signed in to change notification settings - Fork 770
/
Copy pathpages.tsx
1882 lines (1639 loc) · 52.9 KB
/
pages.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-shadow */
import { execSync, spawn } from "node:child_process";
import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
import { readdir, readFile, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, sep } from "node:path";
import { cwd } from "node:process";
import { URL } from "node:url";
import { hash } from "blake3-wasm";
import { watch } from "chokidar";
import { render, Text } from "ink";
import SelectInput from "ink-select-input";
import Spinner from "ink-spinner";
import Table from "ink-table";
import { getType } from "mime";
import prettyBytes from "pretty-bytes";
import React from "react";
import { format as timeagoFormat } from "timeago.js";
import { File, FormData } from "undici";
import { buildPlugin } from "../pages/functions/buildPlugin";
import { buildWorker } from "../pages/functions/buildWorker";
import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
import { writeRoutesModule } from "../pages/functions/routes";
import { fetchResult } from "./cfetch";
import { getConfigCache, saveToConfigCache } from "./config-cache";
import { prompt } from "./dialogs";
import { FatalError } from "./errors";
import { logger } from "./logger";
import { getRequestContextCheckOptions } from "./miniflare-cli/request-context";
import openInBrowser from "./open-in-browser";
import { toUrlPath } from "./paths";
import { requireAuth } from "./user";
import type { Config } from "../pages/functions/routes";
import type { Headers, Request, fetch } from "@miniflare/core";
import type { BuildResult } from "esbuild";
import type { MiniflareOptions } from "miniflare";
import type { BuilderCallback, CommandModule } from "yargs";
export type Project = {
name: string;
subdomain: string;
domains: Array<string>;
source?: {
type: string;
};
latest_deployment?: {
modified_on: string;
};
created_on: string;
production_branch: string;
};
export type Deployment = {
id: string;
environment: string;
deployment_trigger: {
metadata: {
commit_hash: string;
branch: string;
};
};
url: string;
latest_stage: {
status: string;
ended_on: string;
};
project_name: string;
};
interface PagesConfigCache {
account_id?: string;
project_name?: string;
}
const PAGES_CONFIG_CACHE_FILENAME = "pages.json";
// Defer importing miniflare until we really need it. This takes ~0.5s
// and also modifies some `stream/web` and `undici` prototypes, so we
// don't want to do this if pages commands aren't being called.
export const pagesBetaWarning =
"🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
const isInPagesCI = !!process.env.CF_PAGES;
const CLEANUP_CALLBACKS: (() => void)[] = [];
const CLEANUP = () => {
CLEANUP_CALLBACKS.forEach((callback) => callback());
RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
};
process.on("SIGINT", () => {
CLEANUP();
process.exit();
});
process.on("SIGTERM", () => {
CLEANUP();
process.exit();
});
function isWindows() {
return process.platform === "win32";
}
const SECONDS_TO_WAIT_FOR_PROXY = 5;
async function sleep(ms: number) {
await new Promise((resolve) => setTimeout(resolve, ms));
}
function getPids(pid: number) {
const pids: number[] = [pid];
let command: string, regExp: RegExp;
if (isWindows()) {
command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
regExp = new RegExp(/(\d+)/);
} else {
command = `pgrep -P ${pid}`;
regExp = new RegExp(/(\d+)/);
}
try {
const newPids = (
execSync(command)
.toString()
.split("\n")
.map((line) => line.match(regExp))
.filter((line) => line !== null) as RegExpExecArray[]
).map((match) => parseInt(match[1]));
pids.push(...newPids.map(getPids).flat());
} catch {}
return pids;
}
function getPort(pid: number) {
let command: string, regExp: RegExp;
if (isWindows()) {
command = "\\windows\\system32\\netstat.exe -nao";
regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
} else {
command = "lsof -nPi";
regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
}
try {
const matches = execSync(command)
.toString()
.split("\n")
.map((line) => line.match(regExp))
.filter((line) => line !== null) as RegExpExecArray[];
const match = matches[0];
if (match) return parseInt(match[1]);
} catch (thrown) {
logger.error(
`Error scanning for ports of process with PID ${pid}: ${thrown}`
);
}
}
async function spawnProxyProcess({
port,
command,
}: {
port?: number;
command: (string | number)[];
}): Promise<void | number> {
if (command.length === 0) {
CLEANUP();
throw new FatalError(
"Must specify a directory of static assets to serve or a command to run.",
1
);
}
logger.log(`Running ${command.join(" ")}...`);
const proxy = spawn(
command[0].toString(),
command.slice(1).map((value) => value.toString()),
{
shell: isWindows(),
env: {
BROWSER: "none",
...process.env,
},
}
);
CLEANUP_CALLBACKS.push(() => {
proxy.kill();
});
proxy.stdout.on("data", (data) => {
logger.log(`[proxy]: ${data}`);
});
proxy.stderr.on("data", (data) => {
logger.error(`[proxy]: ${data}`);
});
proxy.on("close", (code) => {
logger.error(`Proxy exited with status ${code}.`);
});
// Wait for proxy process to start...
while (!proxy.pid) {}
if (port === undefined) {
logger.log(
`Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
);
logger.log("To skip, specify the proxy port with --proxy.");
await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
port = getPids(proxy.pid)
.map(getPort)
.filter((port) => port !== undefined)[0];
if (port === undefined) {
CLEANUP();
throw new FatalError(
"Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
1
);
} else {
logger.log(`Automatically determined the proxy port to be ${port}.`);
}
}
return port;
}
function escapeRegex(str: string) {
return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
}
type Replacements = Record<string, string>;
function replacer(str: string, replacements: Replacements) {
for (const [replacement, value] of Object.entries(replacements)) {
str = str.replace(`:${replacement}`, value);
}
return str;
}
function generateRulesMatcher<T>(
rules?: Record<string, T>,
replacer: (match: T, replacements: Replacements) => T = (match) => match
) {
// TODO: How can you test cross-host rules?
if (!rules) return () => [];
const compiledRules = Object.entries(rules)
.map(([rule, match]) => {
const crossHost = rule.startsWith("https://");
rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
const host_matches = rule.matchAll(
/(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
);
for (const match of host_matches) {
rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
}
const path_matches = rule.matchAll(/:(\w+)/g);
for (const match of path_matches) {
rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
}
rule = "^" + rule + "$";
try {
const regExp = new RegExp(rule);
return [{ crossHost, regExp }, match];
} catch {}
})
.filter((value) => value !== undefined) as [
{ crossHost: boolean; regExp: RegExp },
T
][];
return ({ request }: { request: Request }) => {
const { pathname, host } = new URL(request.url);
return compiledRules
.map(([{ crossHost, regExp }, match]) => {
const test = crossHost ? `https://${host}${pathname}` : pathname;
const result = regExp.exec(test);
if (result) {
return replacer(match, result.groups || {});
}
})
.filter((value) => value !== undefined) as T[];
};
}
function generateHeadersMatcher(headersFile: string) {
if (existsSync(headersFile)) {
const contents = readFileSync(headersFile).toString();
// TODO: Log errors
const lines = contents
.split("\n")
.map((line) => line.trim())
.filter((line) => !line.startsWith("#") && line !== "");
const rules: Record<string, Record<string, string>> = {};
let rule: { path: string; headers: Record<string, string> } | undefined =
undefined;
for (const line of lines) {
if (/^([^\s]+:\/\/|^\/)/.test(line)) {
if (rule && Object.keys(rule.headers).length > 0) {
rules[rule.path] = rule.headers;
}
const path = validateURL(line);
if (path) {
rule = {
path,
headers: {},
};
continue;
}
}
if (!line.includes(":")) continue;
const [rawName, ...rawValue] = line.split(":");
const name = rawName.trim().toLowerCase();
const value = rawValue.join(":").trim();
if (name === "") continue;
if (!rule) continue;
const existingValues = rule.headers[name];
rule.headers[name] = existingValues
? `${existingValues}, ${value}`
: value;
}
if (rule && Object.keys(rule.headers).length > 0) {
rules[rule.path] = rule.headers;
}
const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
Object.fromEntries(
Object.entries(match).map(([name, value]) => [
name,
replacer(value, replacements),
])
)
);
return (request: Request) => {
const matches = rulesMatcher({
request,
});
if (matches) return matches;
};
} else {
return () => undefined;
}
}
function generateRedirectsMatcher(redirectsFile: string) {
if (existsSync(redirectsFile)) {
const contents = readFileSync(redirectsFile).toString();
// TODO: Log errors
const lines = contents
.split("\n")
.map((line) => line.trim())
.filter((line) => !line.startsWith("#") && line !== "");
const rules = Object.fromEntries(
lines
.map((line) => line.split(" "))
.filter((tokens) => tokens.length === 2 || tokens.length === 3)
.map((tokens) => {
const from = validateURL(tokens[0], true, false, false);
const to = validateURL(tokens[1], false, true, true);
let status: number | undefined = parseInt(tokens[2]) || 302;
status = [301, 302, 303, 307, 308].includes(status)
? status
: undefined;
return from && to && status ? [from, { to, status }] : undefined;
})
.filter((rule) => rule !== undefined) as [
string,
{ to: string; status?: number }
][]
);
const rulesMatcher = generateRulesMatcher(
rules,
({ status, to }, replacements) => ({
status,
to: replacer(to, replacements),
})
);
return (request: Request) => {
const match = rulesMatcher({
request,
})[0];
if (match) return match;
};
} else {
return () => undefined;
}
}
function extractPathname(
path = "/",
includeSearch: boolean,
includeHash: boolean
) {
if (!path.startsWith("/")) path = `/${path}`;
const url = new URL(`//${path}`, "relative://");
return `${url.pathname}${includeSearch ? url.search : ""}${
includeHash ? url.hash : ""
}`;
}
function validateURL(
token: string,
onlyRelative = false,
includeSearch = false,
includeHash = false
) {
const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
if (host && host.groups && host.groups.host) {
if (onlyRelative) return;
return `https://${host.groups.host}${extractPathname(
host.groups.path,
includeSearch,
includeHash
)}`;
} else {
if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
const path = /^\//.exec(token);
if (path) {
try {
return extractPathname(token, includeSearch, includeHash);
} catch {}
}
}
return "";
}
function hasFileExtension(pathname: string) {
return /\/.+\.[a-z0-9]+$/i.test(pathname);
}
async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
// Defer importing miniflare until we really need it
const { Headers, Request, Response } = await import("@miniflare/core");
const headersFile = join(directory, "_headers");
const redirectsFile = join(directory, "_redirects");
const workerFile = join(directory, "_worker.js");
const ignoredFiles = [headersFile, redirectsFile, workerFile];
const assetExists = (path: string) => {
path = join(directory, path);
return (
existsSync(path) &&
lstatSync(path).isFile() &&
!ignoredFiles.includes(path)
);
};
const getAsset = (path: string) => {
if (assetExists(path)) {
return join(directory, path);
}
};
let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
let headersMatcher = generateHeadersMatcher(headersFile);
watch([headersFile, redirectsFile], {
persistent: true,
}).on("change", (path) => {
switch (path) {
case headersFile: {
logger.log("_headers modified. Re-evaluating...");
headersMatcher = generateHeadersMatcher(headersFile);
break;
}
case redirectsFile: {
logger.log("_redirects modified. Re-evaluating...");
redirectsMatcher = generateRedirectsMatcher(redirectsFile);
break;
}
}
});
const serveAsset = (file: string) => {
return readFileSync(file);
};
const generateResponse = (request: Request) => {
const url = new URL(request.url);
const deconstructedResponse: {
status: number;
headers: Headers;
body?: Buffer;
} = {
status: 200,
headers: new Headers(),
body: undefined,
};
const match = redirectsMatcher(request);
if (match) {
const { status, to } = match;
let location = to;
let search;
if (to.startsWith("/")) {
search = new URL(location, "http://fakehost").search;
} else {
search = new URL(location).search;
}
location = `${location}${search ? "" : url.search}`;
if (status && [301, 302, 303, 307, 308].includes(status)) {
deconstructedResponse.status = status;
} else {
deconstructedResponse.status = 302;
}
deconstructedResponse.headers.set("Location", location);
return deconstructedResponse;
}
if (!request.method?.match(/^(get|head)$/i)) {
deconstructedResponse.status = 405;
return deconstructedResponse;
}
const notFound = () => {
let cwd = url.pathname;
while (cwd) {
cwd = cwd.slice(0, cwd.lastIndexOf("/"));
if ((asset = getAsset(`${cwd}/404.html`))) {
deconstructedResponse.status = 404;
deconstructedResponse.body = serveAsset(asset);
deconstructedResponse.headers.set(
"Content-Type",
getType(asset) || "application/octet-stream"
);
return deconstructedResponse;
}
}
if ((asset = getAsset(`/index.html`))) {
deconstructedResponse.body = serveAsset(asset);
deconstructedResponse.headers.set(
"Content-Type",
getType(asset) || "application/octet-stream"
);
return deconstructedResponse;
}
deconstructedResponse.status = 404;
return deconstructedResponse;
};
let asset;
if (url.pathname.endsWith("/")) {
if ((asset = getAsset(`${url.pathname}/index.html`))) {
deconstructedResponse.body = serveAsset(asset);
deconstructedResponse.headers.set(
"Content-Type",
getType(asset) || "application/octet-stream"
);
return deconstructedResponse;
} else if (
(asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
) {
deconstructedResponse.status = 301;
deconstructedResponse.headers.set(
"Location",
`${url.pathname.slice(0, -1)}${url.search}`
);
return deconstructedResponse;
}
}
if (url.pathname.endsWith("/index")) {
deconstructedResponse.status = 301;
deconstructedResponse.headers.set(
"Location",
`${url.pathname.slice(0, -"index".length)}${url.search}`
);
return deconstructedResponse;
}
if ((asset = getAsset(url.pathname))) {
if (url.pathname.endsWith(".html")) {
const extensionlessPath = url.pathname.slice(0, -".html".length);
if (getAsset(extensionlessPath) || extensionlessPath === "/") {
deconstructedResponse.body = serveAsset(asset);
deconstructedResponse.headers.set(
"Content-Type",
getType(asset) || "application/octet-stream"
);
return deconstructedResponse;
} else {
deconstructedResponse.status = 301;
deconstructedResponse.headers.set(
"Location",
`${extensionlessPath}${url.search}`
);
return deconstructedResponse;
}
} else {
deconstructedResponse.body = serveAsset(asset);
deconstructedResponse.headers.set(
"Content-Type",
getType(asset) || "application/octet-stream"
);
return deconstructedResponse;
}
} else if (hasFileExtension(url.pathname)) {
notFound();
return deconstructedResponse;
}
if ((asset = getAsset(`${url.pathname}.html`))) {
deconstructedResponse.body = serveAsset(asset);
deconstructedResponse.headers.set(
"Content-Type",
getType(asset) || "application/octet-stream"
);
return deconstructedResponse;
}
if ((asset = getAsset(`${url.pathname}/index.html`))) {
deconstructedResponse.status = 301;
deconstructedResponse.headers.set(
"Location",
`${url.pathname}/${url.search}`
);
return deconstructedResponse;
} else {
notFound();
return deconstructedResponse;
}
};
const attachHeaders = (
request: Request,
deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
) => {
const headers = deconstructedResponse.headers;
const newHeaders = new Headers({});
const matches = headersMatcher(request) || [];
matches.forEach((match) => {
Object.entries(match).forEach(([name, value]) => {
newHeaders.append(name, `${value}`);
});
});
const combinedHeaders = {
...Object.fromEntries(headers.entries()),
...Object.fromEntries(newHeaders.entries()),
};
deconstructedResponse.headers = new Headers({});
Object.entries(combinedHeaders).forEach(([name, value]) => {
if (value) deconstructedResponse.headers.set(name, value);
});
};
return async (input, init) => {
const request = new Request(input, init);
const deconstructedResponse = generateResponse(request);
attachHeaders(request, deconstructedResponse);
const headers = new Headers();
[...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
if (value) headers.set(name, value);
});
return new Response(deconstructedResponse.body, {
headers,
status: deconstructedResponse.status,
});
};
}
const RUNNING_BUILDERS: BuildResult[] = [];
async function buildFunctions({
outfile,
outputConfigPath,
functionsDirectory,
minify = false,
sourcemap = false,
fallbackService = "ASSETS",
watch = false,
onEnd,
plugin = false,
buildOutputDirectory,
}: {
outfile: string;
outputConfigPath?: string;
functionsDirectory: string;
minify?: boolean;
sourcemap?: boolean;
fallbackService?: string;
watch?: boolean;
onEnd?: () => void;
plugin?: boolean;
buildOutputDirectory?: string;
}) {
RUNNING_BUILDERS.forEach(
(runningBuilder) => runningBuilder.stop && runningBuilder.stop()
);
const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
const baseURL = toUrlPath("/");
const config: Config = await generateConfigFromFileTree({
baseDir: functionsDirectory,
baseURL,
});
if (outputConfigPath) {
writeFileSync(
outputConfigPath,
JSON.stringify({ ...config, baseURL }, null, 2)
);
}
await writeRoutesModule({
config,
srcDir: functionsDirectory,
outfile: routesModule,
});
if (plugin) {
RUNNING_BUILDERS.push(
await buildPlugin({
routesModule,
outfile,
minify,
sourcemap,
watch,
onEnd,
})
);
} else {
RUNNING_BUILDERS.push(
await buildWorker({
routesModule,
outfile,
minify,
sourcemap,
fallbackService,
watch,
onEnd,
buildOutputDirectory,
})
);
}
}
interface CreateDeploymentArgs {
directory: string;
projectName?: string;
branch?: string;
commitHash?: string;
commitMessage?: string;
commitDirty?: boolean;
}
const createDeployment: CommandModule<
CreateDeploymentArgs,
CreateDeploymentArgs
> = {
describe: "🆙 Publish a directory of static assets as a Pages deployment",
builder: (yargs) => {
return yargs
.positional("directory", {
type: "string",
demandOption: true,
description: "The directory of static files to upload",
})
.options({
"project-name": {
type: "string",
description: "The name of the project you want to deploy to",
},
branch: {
type: "string",
description: "The name of the branch you want to deploy to",
},
"commit-hash": {
type: "string",
description: "The SHA to attach to this deployment",
},
"commit-message": {
type: "string",
description: "The commit message to attach to this deployment",
},
"commit-dirty": {
type: "boolean",
description:
"Whether or not the workspace should be considered dirty for this deployment",
},
})
.epilogue(pagesBetaWarning);
},
handler: async ({
directory,
projectName,
branch,
commitHash,
commitMessage,
commitDirty,
}) => {
if (!directory) {
throw new FatalError("Must specify a directory.", 1);
}
const config = getConfigCache<PagesConfigCache>(
PAGES_CONFIG_CACHE_FILENAME
);
const accountId = await requireAuth(config);
projectName ??= config.project_name;
const isInteractive = process.stdin.isTTY;
if (!projectName && isInteractive) {
const projects = (await listProjects({ accountId })).filter(
(project) => !project.source
);
let existingOrNew: "existing" | "new" = "new";
if (projects.length > 0) {
existingOrNew = await new Promise<"new" | "existing">((resolve) => {
const { unmount } = render(
<>
<Text>
No project selected. Would you like to create one or use an
existing project?
</Text>
<SelectInput
items={[
{
key: "new",
label: "Create a new project",
value: "new",
},
{
key: "existing",
label: "Use an existing project",
value: "existing",
},
]}
onSelect={async (selected) => {
resolve(selected.value as "new" | "existing");
unmount();
}}
/>
</>
);
});
}
switch (existingOrNew) {
case "existing": {
projectName = await new Promise((resolve) => {
const { unmount } = render(
<>
<Text>Select a project:</Text>
<SelectInput
items={projects.map((project) => ({
key: project.name,
label: project.name,
value: project,
}))}
onSelect={async (selected) => {
resolve(selected.value.name);
unmount();
}}
/>
</>
);
});
break;
}
case "new": {
projectName = await prompt("Enter the name of your new project:");
if (!projectName) {
throw new FatalError("Must specify a project name.", 1);
}
let isGitDir = true;
try {
execSync(`git rev-parse --is-inside-work-tree`, {
stdio: "ignore",
});
} catch (err) {
isGitDir = false;
}
const productionBranch = await prompt(
"Enter the production branch name:",
"text",
isGitDir
? execSync(`git rev-parse --abbrev-ref HEAD`).toString().trim()
: "production"
);
if (!productionBranch) {
throw new FatalError("Must specify a production branch.", 1);
}
await fetchResult<Project>(`/accounts/${accountId}/pages/projects`, {
method: "POST",
body: JSON.stringify({
name: projectName,
production_branch: productionBranch,
}),
});
saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
account_id: accountId,
project_name: projectName,
});
logger.log(`✨ Successfully created the '${projectName}' project.`);
break;
}
}
}
if (!projectName) {
throw new FatalError("Must specify a project name.", 1);
}
// We infer git info by default is not passed in
let isGitDir = true;
try {
execSync(`git rev-parse --is-inside-work-tree`, {
stdio: "ignore",
});
} catch (err) {
isGitDir = false;
}
let isGitDirty = false;
if (isGitDir) {
try {
isGitDirty = Boolean(
execSync(`git status --porcelain`).toString().length
);
if (!branch) {
branch = execSync(`git rev-parse --abbrev-ref HEAD`)
.toString()
.trim();
}
if (!commitHash) {
commitHash = execSync(`git rev-parse HEAD`).toString().trim();
}
if (!commitMessage) {
commitMessage = execSync(`git show -s --format=%B ${commitHash}`)
.toString()
.trim();
}
} catch (err) {}