giget 1.1.1 → 1.1.3

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/README.md CHANGED
@@ -184,7 +184,7 @@ You can define additional [custom registry](#custom-registry) providers using `r
184
184
  import { registryProvider } from "giget";
185
185
 
186
186
  const themes = registryProvider(
187
- "https://raw.githubusercontent.com/unjs/giget/main/templates"
187
+ "https://raw.githubusercontent.com/unjs/giget/main/templates",
188
188
  );
189
189
 
190
190
  const { source, dir } = await downloadRepo("themes:test", {
package/dist/cli.cjs CHANGED
@@ -4,7 +4,7 @@
4
4
  const node_path = require('node:path');
5
5
  const mri = require('mri');
6
6
  const colorette = require('colorette');
7
- const giget = require('./shared/giget.e7e76a83.cjs');
7
+ const index = require('./index.cjs');
8
8
  require('node:fs/promises');
9
9
  require('node:fs');
10
10
  require('tar');
@@ -15,10 +15,13 @@ require('node:child_process');
15
15
  require('node:os');
16
16
  require('node:util');
17
17
  require('node-fetch-native');
18
- require('https-proxy-agent');
18
+
19
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
20
+
21
+ const mri__default = /*#__PURE__*/_interopDefaultCompat(mri);
19
22
 
20
23
  async function main() {
21
- const arguments_ = mri(process.argv.slice(2), {
24
+ const arguments_ = mri__default(process.argv.slice(2), {
22
25
  boolean: [
23
26
  "help",
24
27
  "force",
@@ -41,7 +44,7 @@ async function main() {
41
44
  if (arguments_.verbose) {
42
45
  process.env.DEBUG = process.env.DEBUG || "true";
43
46
  }
44
- const r = await giget.downloadTemplate(input, {
47
+ const r = await index.downloadTemplate(input, {
45
48
  dir,
46
49
  force: arguments_.force,
47
50
  forceClean: arguments_["force-clean"],
@@ -57,7 +60,7 @@ async function main() {
57
60
  `
58
61
  );
59
62
  if (arguments_.shell) {
60
- giget.startShell(r.dir);
63
+ index.startShell(r.dir);
61
64
  }
62
65
  process.exit(0);
63
66
  }
package/dist/cli.d.cts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/cli.d.mts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/cli.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
 
2
- export { }
2
+ export { }
package/dist/cli.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { relative } from 'node:path';
3
3
  import mri from 'mri';
4
4
  import { cyan } from 'colorette';
5
- import { d as downloadTemplate, s as startShell } from './shared/giget.c3d868f5.mjs';
5
+ import { downloadTemplate, startShell } from './index.mjs';
6
6
  import 'node:fs/promises';
7
7
  import 'node:fs';
8
8
  import 'tar';
@@ -13,7 +13,6 @@ import 'node:child_process';
13
13
  import 'node:os';
14
14
  import 'node:util';
15
15
  import 'node-fetch-native';
16
- import 'https-proxy-agent';
17
16
 
18
17
  async function main() {
19
18
  const arguments_ = mri(process.argv.slice(2), {
package/dist/index.cjs CHANGED
@@ -1,20 +1,299 @@
1
1
  'use strict';
2
2
 
3
- const giget = require('./shared/giget.e7e76a83.cjs');
4
- require('node:fs/promises');
5
- require('node:fs');
6
- require('tar');
7
- require('pathe');
8
- require('defu');
9
- require('node:stream');
10
- require('node:child_process');
11
- require('node:os');
12
- require('node:util');
13
- require('node-fetch-native');
14
- require('https-proxy-agent');
3
+ const promises = require('node:fs/promises');
4
+ const node_fs = require('node:fs');
5
+ const tar = require('tar');
6
+ const pathe = require('pathe');
7
+ const defu = require('defu');
8
+ const node_stream = require('node:stream');
9
+ const node_child_process = require('node:child_process');
10
+ const node_os = require('node:os');
11
+ const node_util = require('node:util');
12
+ const nodeFetchNative = require('node-fetch-native');
15
13
 
14
+ async function download(url, filePath, options = {}) {
15
+ const infoPath = filePath + ".json";
16
+ const info = JSON.parse(
17
+ await promises.readFile(infoPath, "utf8").catch(() => "{}")
18
+ );
19
+ const headResponse = await sendFetch(url, {
20
+ method: "HEAD",
21
+ headers: options.headers
22
+ }).catch(() => void 0);
23
+ const etag = headResponse?.headers.get("etag");
24
+ if (info.etag === etag && node_fs.existsSync(filePath)) {
25
+ return;
26
+ }
27
+ if (typeof etag === "string") {
28
+ info.etag = etag;
29
+ }
30
+ const response = await sendFetch(url, { headers: options.headers });
31
+ if (response.status >= 400) {
32
+ throw new Error(
33
+ `Failed to download ${url}: ${response.status} ${response.statusText}`
34
+ );
35
+ }
36
+ const stream = node_fs.createWriteStream(filePath);
37
+ await node_util.promisify(node_stream.pipeline)(response.body, stream);
38
+ await promises.writeFile(infoPath, JSON.stringify(info), "utf8");
39
+ }
40
+ const inputRegex = /^(?<repo>[\w.-]+\/[\w.-]+)(?<subdir>[^#]+)?(?<ref>#[\w./-]+)?/;
41
+ function parseGitURI(input) {
42
+ const m = input.match(inputRegex)?.groups || {};
43
+ return {
44
+ repo: m.repo,
45
+ subdir: m.subdir || "/",
46
+ ref: m.ref ? m.ref.slice(1) : "main"
47
+ };
48
+ }
49
+ function debug(...args) {
50
+ if (process.env.DEBUG) {
51
+ console.debug("[giget]", ...args);
52
+ }
53
+ }
54
+ async function sendFetch(url, options = {}) {
55
+ if (!options.agent) {
56
+ const proxyEnv = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy;
57
+ if (proxyEnv) {
58
+ const HttpsProxyAgent = await import('https-proxy-agent').then(
59
+ (r) => r.HttpsProxyAgent || r.default
60
+ );
61
+ options.agent = new HttpsProxyAgent(proxyEnv);
62
+ }
63
+ }
64
+ return await nodeFetchNative.fetch(url, {
65
+ ...options,
66
+ headers: normalizeHeaders(options.headers)
67
+ });
68
+ }
69
+ function cacheDirectory() {
70
+ return process.env.XDG_CACHE_HOME ? pathe.resolve(process.env.XDG_CACHE_HOME, "giget") : pathe.resolve(node_os.homedir(), ".cache/giget");
71
+ }
72
+ function normalizeHeaders(headers = {}) {
73
+ const normalized = {};
74
+ for (const [key, value] of Object.entries(headers)) {
75
+ if (!value) {
76
+ continue;
77
+ }
78
+ normalized[key.toLowerCase()] = value;
79
+ }
80
+ return normalized;
81
+ }
82
+ function currentShell() {
83
+ if (process.env.SHELL) {
84
+ return process.env.SHELL;
85
+ }
86
+ if (process.platform === "win32") {
87
+ return "cmd.exe";
88
+ }
89
+ return "/bin/bash";
90
+ }
91
+ function startShell(cwd) {
92
+ cwd = pathe.resolve(cwd);
93
+ const shell = currentShell();
94
+ console.info(
95
+ `(experimental) Opening shell in ${pathe.relative(process.cwd(), cwd)}...`
96
+ );
97
+ node_child_process.spawnSync(shell, [], {
98
+ cwd,
99
+ shell: true,
100
+ stdio: "inherit"
101
+ });
102
+ }
16
103
 
104
+ const github = (input, options) => {
105
+ const parsed = parseGitURI(input);
106
+ const githubAPIURL = process.env.GIGET_GITHUB_URL || "https://api.github.com";
107
+ return {
108
+ name: parsed.repo.replace("/", "-"),
109
+ version: parsed.ref,
110
+ subdir: parsed.subdir,
111
+ headers: {
112
+ Authorization: options.auth ? `Bearer ${options.auth}` : void 0,
113
+ Accept: "application/vnd.github+json",
114
+ "X-GitHub-Api-Version": "2022-11-28"
115
+ },
116
+ url: `${githubAPIURL.replace("api.github.com", "github.com")}/${parsed.repo}/tree/${parsed.ref}${parsed.subdir}`,
117
+ tar: `${githubAPIURL}/repos/${parsed.repo}/tarball/${parsed.ref}`
118
+ };
119
+ };
120
+ const gitlab = (input, options) => {
121
+ const parsed = parseGitURI(input);
122
+ const gitlab2 = process.env.GIGET_GITLAB_URL || "https://gitlab.com";
123
+ return {
124
+ name: parsed.repo.replace("/", "-"),
125
+ version: parsed.ref,
126
+ subdir: parsed.subdir,
127
+ headers: {
128
+ authorization: options.auth ? `Bearer ${options.auth}` : void 0
129
+ },
130
+ url: `${gitlab2}/${parsed.repo}/tree/${parsed.ref}${parsed.subdir}`,
131
+ tar: `${gitlab2}/${parsed.repo}/-/archive/${parsed.ref}.tar.gz`
132
+ };
133
+ };
134
+ const bitbucket = (input, options) => {
135
+ const parsed = parseGitURI(input);
136
+ return {
137
+ name: parsed.repo.replace("/", "-"),
138
+ version: parsed.ref,
139
+ subdir: parsed.subdir,
140
+ headers: {
141
+ authorization: options.auth ? `Bearer ${options.auth}` : void 0
142
+ },
143
+ url: `https://bitbucket.com/${parsed.repo}/src/${parsed.ref}${parsed.subdir}`,
144
+ tar: `https://bitbucket.org/${parsed.repo}/get/${parsed.ref}.tar.gz`
145
+ };
146
+ };
147
+ const sourcehut = (input, options) => {
148
+ const parsed = parseGitURI(input);
149
+ return {
150
+ name: parsed.repo.replace("/", "-"),
151
+ version: parsed.ref,
152
+ subdir: parsed.subdir,
153
+ headers: {
154
+ authorization: options.auth ? `Bearer ${options.auth}` : void 0
155
+ },
156
+ url: `https://git.sr.ht/~${parsed.repo}/tree/${parsed.ref}/item${parsed.subdir}`,
157
+ tar: `https://git.sr.ht/~${parsed.repo}/archive/${parsed.ref}.tar.gz`
158
+ };
159
+ };
160
+ const providers = {
161
+ github,
162
+ gh: github,
163
+ gitlab,
164
+ bitbucket,
165
+ sourcehut
166
+ };
17
167
 
18
- exports.downloadTemplate = giget.downloadTemplate;
19
- exports.registryProvider = giget.registryProvider;
20
- exports.startShell = giget.startShell;
168
+ const DEFAULT_REGISTRY = "https://raw.githubusercontent.com/unjs/giget/main/templates";
169
+ const registryProvider = (registryEndpoint = DEFAULT_REGISTRY, options = {}) => {
170
+ return async (input) => {
171
+ const start = Date.now();
172
+ const registryURL = `${registryEndpoint}/${input}.json`;
173
+ const result = await sendFetch(registryURL, {
174
+ headers: {
175
+ authorization: options.auth ? `Bearer ${options.auth}` : void 0
176
+ }
177
+ });
178
+ if (result.status >= 400) {
179
+ throw new Error(
180
+ `Failed to download ${input} template info from ${registryURL}: ${result.status} ${result.statusText}`
181
+ );
182
+ }
183
+ const info = await result.json();
184
+ if (!info.tar || !info.name) {
185
+ throw new Error(
186
+ `Invalid template info from ${registryURL}. name or tar fields are missing!`
187
+ );
188
+ }
189
+ debug(
190
+ `Fetched ${input} template info from ${registryURL} in ${Date.now() - start}ms`
191
+ );
192
+ return info;
193
+ };
194
+ };
195
+
196
+ const sourceProtoRe = /^([\w-.]+):/;
197
+ async function downloadTemplate(input, options = {}) {
198
+ options = defu.defu(
199
+ {
200
+ registry: process.env.GIGET_REGISTRY,
201
+ auth: process.env.GIGET_AUTH
202
+ },
203
+ options
204
+ );
205
+ const registry = options.registry === false ? void 0 : registryProvider(options.registry, { auth: options.auth });
206
+ let providerName = options.provider || (registry ? "registry" : "github");
207
+ let source = input;
208
+ const sourceProvierMatch = input.match(sourceProtoRe);
209
+ if (sourceProvierMatch) {
210
+ providerName = sourceProvierMatch[1];
211
+ source = input.slice(sourceProvierMatch[0].length);
212
+ }
213
+ const provider = options.providers?.[providerName] || providers[providerName] || registry;
214
+ if (!provider) {
215
+ throw new Error(`Unsupported provider: ${providerName}`);
216
+ }
217
+ const template = await Promise.resolve().then(() => provider(source, { auth: options.auth })).catch((error) => {
218
+ throw new Error(
219
+ `Failed to download template from ${providerName}: ${error.message}`
220
+ );
221
+ });
222
+ if (!template) {
223
+ throw new Error(`Failed to resolve template from ${providerName}`);
224
+ }
225
+ template.name = (template.name || "template").replace(/[^\da-z-]/gi, "-");
226
+ template.defaultDir = (template.defaultDir || template.name).replace(
227
+ /[^\da-z-]/gi,
228
+ "-"
229
+ );
230
+ const cwd = pathe.resolve(options.cwd || ".");
231
+ const extractPath = pathe.resolve(cwd, options.dir || template.defaultDir);
232
+ if (options.forceClean) {
233
+ await promises.rm(extractPath, { recursive: true, force: true });
234
+ }
235
+ if (!options.force && node_fs.existsSync(extractPath) && node_fs.readdirSync(extractPath).length > 0) {
236
+ throw new Error(`Destination ${extractPath} already exists.`);
237
+ }
238
+ await promises.mkdir(extractPath, { recursive: true });
239
+ const temporaryDirectory = pathe.resolve(
240
+ cacheDirectory(),
241
+ providerName,
242
+ template.name
243
+ );
244
+ const tarPath = pathe.resolve(
245
+ temporaryDirectory,
246
+ (template.version || template.name) + ".tar.gz"
247
+ );
248
+ if (options.preferOffline && node_fs.existsSync(tarPath)) {
249
+ options.offline = true;
250
+ }
251
+ if (!options.offline) {
252
+ await promises.mkdir(pathe.dirname(tarPath), { recursive: true });
253
+ const s2 = Date.now();
254
+ await download(template.tar, tarPath, {
255
+ headers: {
256
+ Authorization: options.auth ? `Bearer ${options.auth}` : void 0,
257
+ ...normalizeHeaders(template.headers)
258
+ }
259
+ }).catch((error) => {
260
+ if (!node_fs.existsSync(tarPath)) {
261
+ throw error;
262
+ }
263
+ debug("Download error. Using cached version:", error);
264
+ options.offline = true;
265
+ });
266
+ debug(`Downloaded ${template.tar} to ${tarPath} in ${Date.now() - s2}ms`);
267
+ }
268
+ if (!node_fs.existsSync(tarPath)) {
269
+ throw new Error(
270
+ `Tarball not found: ${tarPath} (offline: ${options.offline})`
271
+ );
272
+ }
273
+ const s = Date.now();
274
+ const subdir = template.subdir?.replace(/^\//, "") || "";
275
+ await tar.extract({
276
+ file: tarPath,
277
+ cwd: extractPath,
278
+ onentry(entry) {
279
+ entry.path = entry.path.split("/").splice(1).join("/");
280
+ if (subdir) {
281
+ if (entry.path.startsWith(subdir + "/")) {
282
+ entry.path = entry.path.slice(subdir.length);
283
+ } else {
284
+ entry.path = "";
285
+ }
286
+ }
287
+ }
288
+ });
289
+ debug(`Extracted to ${extractPath} in ${Date.now() - s}ms`);
290
+ return {
291
+ ...template,
292
+ source,
293
+ dir: extractPath
294
+ };
295
+ }
296
+
297
+ exports.downloadTemplate = downloadTemplate;
298
+ exports.registryProvider = registryProvider;
299
+ exports.startShell = startShell;
@@ -0,0 +1,47 @@
1
+ interface GitInfo {
2
+ provider: "github" | "gitlab" | "bitbucket" | "sourcehut";
3
+ repo: string;
4
+ subdir: string;
5
+ ref: string;
6
+ }
7
+ interface TemplateInfo {
8
+ name: string;
9
+ tar: string;
10
+ version?: string;
11
+ subdir?: string;
12
+ url?: string;
13
+ defaultDir?: string;
14
+ headers?: Record<string, string | undefined>;
15
+ source?: never;
16
+ dir?: never;
17
+ [key: string]: any;
18
+ }
19
+ type TemplateProvider = (input: string, options: {
20
+ auth?: string;
21
+ }) => TemplateInfo | Promise<TemplateInfo> | null;
22
+
23
+ interface DownloadTemplateOptions {
24
+ provider?: string;
25
+ force?: boolean;
26
+ forceClean?: boolean;
27
+ offline?: boolean;
28
+ preferOffline?: boolean;
29
+ providers?: Record<string, TemplateProvider>;
30
+ dir?: string;
31
+ registry?: false | string;
32
+ cwd?: string;
33
+ auth?: string;
34
+ }
35
+ type DownloadTemplateResult = Omit<TemplateInfo, "dir" | "source"> & {
36
+ dir: string;
37
+ source: string;
38
+ };
39
+ declare function downloadTemplate(input: string, options?: DownloadTemplateOptions): Promise<DownloadTemplateResult>;
40
+
41
+ declare const registryProvider: (registryEndpoint?: string, options?: {
42
+ auth?: string;
43
+ }) => TemplateProvider;
44
+
45
+ declare function startShell(cwd: string): void;
46
+
47
+ export { type DownloadTemplateOptions, type DownloadTemplateResult, type GitInfo, type TemplateInfo, type TemplateProvider, downloadTemplate, registryProvider, startShell };
@@ -0,0 +1,47 @@
1
+ interface GitInfo {
2
+ provider: "github" | "gitlab" | "bitbucket" | "sourcehut";
3
+ repo: string;
4
+ subdir: string;
5
+ ref: string;
6
+ }
7
+ interface TemplateInfo {
8
+ name: string;
9
+ tar: string;
10
+ version?: string;
11
+ subdir?: string;
12
+ url?: string;
13
+ defaultDir?: string;
14
+ headers?: Record<string, string | undefined>;
15
+ source?: never;
16
+ dir?: never;
17
+ [key: string]: any;
18
+ }
19
+ type TemplateProvider = (input: string, options: {
20
+ auth?: string;
21
+ }) => TemplateInfo | Promise<TemplateInfo> | null;
22
+
23
+ interface DownloadTemplateOptions {
24
+ provider?: string;
25
+ force?: boolean;
26
+ forceClean?: boolean;
27
+ offline?: boolean;
28
+ preferOffline?: boolean;
29
+ providers?: Record<string, TemplateProvider>;
30
+ dir?: string;
31
+ registry?: false | string;
32
+ cwd?: string;
33
+ auth?: string;
34
+ }
35
+ type DownloadTemplateResult = Omit<TemplateInfo, "dir" | "source"> & {
36
+ dir: string;
37
+ source: string;
38
+ };
39
+ declare function downloadTemplate(input: string, options?: DownloadTemplateOptions): Promise<DownloadTemplateResult>;
40
+
41
+ declare const registryProvider: (registryEndpoint?: string, options?: {
42
+ auth?: string;
43
+ }) => TemplateProvider;
44
+
45
+ declare function startShell(cwd: string): void;
46
+
47
+ export { type DownloadTemplateOptions, type DownloadTemplateResult, type GitInfo, type TemplateInfo, type TemplateProvider, downloadTemplate, registryProvider, startShell };
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ interface TemplateInfo {
11
11
  subdir?: string;
12
12
  url?: string;
13
13
  defaultDir?: string;
14
- headers?: Record<string, string>;
14
+ headers?: Record<string, string | undefined>;
15
15
  source?: never;
16
16
  dir?: never;
17
17
  [key: string]: any;
@@ -44,4 +44,4 @@ declare const registryProvider: (registryEndpoint?: string, options?: {
44
44
 
45
45
  declare function startShell(cwd: string): void;
46
46
 
47
- export { DownloadTemplateOptions, DownloadTemplateResult, GitInfo, TemplateInfo, TemplateProvider, downloadTemplate, registryProvider, startShell };
47
+ export { type DownloadTemplateOptions, type DownloadTemplateResult, type GitInfo, type TemplateInfo, type TemplateProvider, downloadTemplate, registryProvider, startShell };