-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathcreate-repo.ts
78 lines (74 loc) · 2.31 KB
/
create-repo.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
import { HUB_URL } from "../consts";
import { createApiError } from "../error";
import type { ApiCreateRepoPayload } from "../types/api/api-create-repo";
import type { CredentialsParams, RepoDesignation, SpaceSdk } from "../types/public";
import { base64FromBytes } from "../utils/base64FromBytes";
import { checkCredentials } from "../utils/checkCredentials";
import { toRepoId } from "../utils/toRepoId";
export async function createRepo(
params: {
repo: RepoDesignation;
/**
* If unset, will follow the organization's default setting. (typically public, except for some Enterprise organizations)
*/
private?: boolean;
license?: string;
/**
* Only a few lightweight files are supported at repo creation
*/
files?: Array<{ content: ArrayBuffer | Blob; path: string }>;
/** @required for when {@link repo.type} === "space" */
sdk?: SpaceSdk;
hubUrl?: string;
/**
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
*/
fetch?: typeof fetch;
} & CredentialsParams
): Promise<{ repoUrl: string }> {
const accessToken = checkCredentials(params);
const repoId = toRepoId(params.repo);
const [namespace, repoName] = repoId.name.split("/");
if (!namespace || !repoName) {
throw new TypeError(
`"${repoId.name}" is not a fully qualified repo name. It should be of the form "{namespace}/{repoName}".`
);
}
const res = await (params.fetch ?? fetch)(`${params.hubUrl ?? HUB_URL}/api/repos/create`, {
method: "POST",
body: JSON.stringify({
name: repoName,
private: params.private,
organization: namespace,
license: params.license,
...(repoId.type === "space"
? {
type: "space",
sdk: "static",
}
: {
type: repoId.type,
}),
files: params.files
? await Promise.all(
params.files.map(async (file) => ({
encoding: "base64",
path: file.path,
content: base64FromBytes(
new Uint8Array(file.content instanceof Blob ? await file.content.arrayBuffer() : file.content)
),
}))
)
: undefined,
} satisfies ApiCreateRepoPayload),
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
if (!res.ok) {
throw await createApiError(res);
}
const output = await res.json();
return { repoUrl: output.url };
}