-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
102 lines (84 loc) · 2.53 KB
/
index.ts
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
import "dotenv/config";
import { getEnv, post, zipFiles } from "./utils.ts";
import { randomUUID } from "crypto";
import { createReadStream, createWriteStream, read, readFileSync } from "fs";
import jwt from 'jsonwebtoken'
interface Props {
user: {
sessionId: string;
},
netlify: {
team: {
slug: string;
};
site: {
name: string;
publishDir: string;
env?: Record<string, string>;
zipPath: string;
};
};
}
const { NETLIFY_ADMIN_PAT, NETLIFY_TEAM_SLUG, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET } = process.env;
export const netlifyHeaders = {
Authorization: `Bearer ${NETLIFY_ADMIN_PAT}`,
"Content-Type": "application/json",
};
async function createClaimableSite({ netlify,user }: Props) {
console.log("Creating claimable site...");
const site = await post("https://api.netlify.com/api/v1/sites", {
headers: netlifyHeaders,
body: JSON.stringify({
// initially the site will be connected to your team
// then it will be able to be claimed/transferred to another user
account_slug: netlify.team.slug,
name: netlify.site.name,
// arbitrary value
created_via: "deploy-and-claim",
// what env vars should be set on the site?
env: getEnv(netlify.site.env),
// This session id is what will be used to link the current user
// with their claim url.
session_id: user.sessionId,
}),
});
console.log("");
console.log("Site created successfully!");
console.log("Site ID: ", site.id);
console.log("Admin URL:", site.admin_url);
console.log('Zipping site files...')
await zipFiles({zipPath: netlify.site.zipPath, glob:'public/**/*'})
console.log("Deploying site...");
const deploy = await post(`https://api.netlify.com/api/v1/sites/${site.id}/deploys`, {
headers: {
...netlifyHeaders,
"Content-Type": "application/zip",
},
body: createReadStream(netlify.site.zipPath),
//@ts-ignore
duplex: "half",
});
console.log("Creating claim url...");
const token = jwt.sign({ client_id: OAUTH_CLIENT_ID, session_id: user.sessionId }, OAUTH_CLIENT_SECRET);
console.log("Link to claim the site:")
console.log("https://app.netlify.com/claim?#" + token)
}
// Example usage...
createClaimableSite({
user: {
sessionId: randomUUID()
},
netlify: {
team: {
slug: NETLIFY_TEAM_SLUG || '',
},
site: {
name: `b-and-c-${randomUUID()}`.slice(0, 16),
publishDir: "/public",
env: {
MY_API_KEY: "my-api-key-value",
},
zipPath: "site.zip",
},
},
});