@joripspace/cli 0.5.0 → 0.5.2
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 +1 -1
- package/bin/joripspace.js +1623 -1610
- package/lib/checkpoint-commands.js +210 -210
- package/lib/deploy-files.js +245 -245
- package/lib/deployment-error.js +14 -14
- package/lib/github-commands.js +185 -0
- package/lib/help.js +138 -137
- package/lib/installer-args.js +28 -28
- package/lib/installer-target.js +134 -134
- package/lib/mcp-config.js +981 -981
- package/lib/project-env.js +198 -198
- package/lib/project-paths.js +257 -257
- package/lib/remote-commands.js +392 -392
- package/lib/start-command.js +123 -123
- package/lib/start.js +1467 -1407
- package/lib/template-commands.js +812 -812
- package/package.json +1 -1
- package/vendor/core/github-workflow.cjs +199 -186
- package/vendor/core/onboarding.cjs +2404 -2403
- package/vendor/core/template-publish-workflow.cjs +169 -169
- package/vendor/templates/index.js +104 -104
- package/vendor/templates/templates/basic-worker/files/worker.js +9 -9
- package/vendor/templates/templates/basic-worker/manifest.json +14 -14
- package/vendor/templates/templates/r2-file-api/files/worker.js +42 -42
- package/vendor/templates/templates/r2-file-api/manifest.json +7 -7
package/lib/template-commands.js
CHANGED
|
@@ -1,812 +1,812 @@
|
|
|
1
|
-
const fs = require('node:fs');
|
|
2
|
-
const crypto = require('node:crypto');
|
|
3
|
-
const os = require('node:os');
|
|
4
|
-
const path = require('node:path');
|
|
5
|
-
const { spawnSync } = require('node:child_process');
|
|
6
|
-
const zlib = require('node:zlib');
|
|
7
|
-
|
|
8
|
-
function createTemplateCommands(deps) {
|
|
9
|
-
async function list(flags) {
|
|
10
|
-
const body = {
|
|
11
|
-
templates: deps.listTemplates().map((template) => ({
|
|
12
|
-
id: template.id,
|
|
13
|
-
name: template.name,
|
|
14
|
-
description: template.description,
|
|
15
|
-
entrypoint: template.entrypoint,
|
|
16
|
-
tags: template.tags ?? [],
|
|
17
|
-
variables: template.variables ?? [],
|
|
18
|
-
})),
|
|
19
|
-
};
|
|
20
|
-
deps.output(flags, body, (value) => {
|
|
21
|
-
for (const template of value.templates)
|
|
22
|
-
console.log(`${template.id}\t${template.name}\t${template.description}`);
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
async function marketplaceList(flags) {
|
|
27
|
-
const project = deps.requireProjectId(flags);
|
|
28
|
-
const cursor = deps.stringFlag(flags, 'cursor');
|
|
29
|
-
const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : '';
|
|
30
|
-
const response = await deps.apiRequest(flags, `/v1/templates${query}`, {
|
|
31
|
-
method: 'GET',
|
|
32
|
-
...deps.projectAuth(flags),
|
|
33
|
-
});
|
|
34
|
-
const body = { ...response, project_id: project };
|
|
35
|
-
deps.output(flags, body, (value) => {
|
|
36
|
-
for (const template of value.templates || []) {
|
|
37
|
-
const name = template.name || template.title || template.slug || template.template_id;
|
|
38
|
-
const slug = template.slug || template.template_id || template.id;
|
|
39
|
-
console.log(`${slug}\t${name}\t${template.description || ''}`);
|
|
40
|
-
}
|
|
41
|
-
if (value.next_cursor || value.cursor) console.log(`Next cursor: ${value.next_cursor || value.cursor}`);
|
|
42
|
-
});
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
async function deploy(flags) {
|
|
46
|
-
const project = deps.requireProjectId(flags);
|
|
47
|
-
const templateId = deps.stringFlag(flags, 'template');
|
|
48
|
-
if (!templateId) throw new Error('deploy-template requires --template');
|
|
49
|
-
const label = deps.stringFlag(flags, 'label').trim();
|
|
50
|
-
if (!label) throw new Error('deploy-template requires --label');
|
|
51
|
-
const { manifest, deployRequest } = deps.buildTemplateDeployRequest(templateId, deps.templateVars(flags));
|
|
52
|
-
const body = await deps.apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/deploy`, {
|
|
53
|
-
method: 'POST',
|
|
54
|
-
...deps.projectAuth(flags),
|
|
55
|
-
body: { ...deployRequest, label },
|
|
56
|
-
});
|
|
57
|
-
deps.output(flags, { ...body, template_id: manifest.id }, (value) => {
|
|
58
|
-
console.log(`Template: ${value.template_id}`);
|
|
59
|
-
console.log(`Deployment: ${value.deployment_id}`);
|
|
60
|
-
console.log(`Status: ${value.status}`);
|
|
61
|
-
console.log(`URL: ${value.url}`);
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
async function install(flags) {
|
|
66
|
-
const project = deps.requireProjectId(flags);
|
|
67
|
-
const templateSlug = deps.stringFlag(flags, 'template');
|
|
68
|
-
if (!templateSlug) throw new Error('install-template requires --template');
|
|
69
|
-
const targetDir = path.resolve(deps.stringFlag(flags, 'dir') || process.cwd());
|
|
70
|
-
const connection = deps.resolveConnection(flags);
|
|
71
|
-
const apiToken = deps.requireApiToken(flags, connection);
|
|
72
|
-
const apiUrl = connection.apiBaseUrl;
|
|
73
|
-
const filesOnly = deps.booleanFlag(flags, 'files-only');
|
|
74
|
-
const headers = { Authorization: `Bearer ${apiToken}`, 'X-Joripspace-Session-Context': 'cli' };
|
|
75
|
-
const claim = await timedFetch(`${apiUrl}/v1/templates/${encodeURIComponent(templateSlug)}/claim`, {
|
|
76
|
-
method: 'POST',
|
|
77
|
-
headers,
|
|
78
|
-
});
|
|
79
|
-
if (!claim.ok && ![404, 409].includes(claim.status)) throw await fetchError(claim);
|
|
80
|
-
const granted = filesOnly ? null : await downloadBundleGrant(apiUrl, headers, templateSlug, project);
|
|
81
|
-
if (granted) {
|
|
82
|
-
const result = applyGitBundle(targetDir, templateSlug, granted.bundle, granted.metadata, false);
|
|
83
|
-
let deployment = null;
|
|
84
|
-
if (deps.booleanFlag(flags, 'deploy')) {
|
|
85
|
-
const entrypoint = deps.stringFlag(flags, 'entrypoint');
|
|
86
|
-
if (!entrypoint) throw new Error('template manifest has no entrypoint. Pass --entrypoint to deploy.');
|
|
87
|
-
deployment = await deps.deployCode(
|
|
88
|
-
{
|
|
89
|
-
...flags,
|
|
90
|
-
dir: targetDir,
|
|
91
|
-
entrypoint,
|
|
92
|
-
label: deps.stringFlag(flags, 'label') || `템플릿 ${templateSlug} 설치`,
|
|
93
|
-
},
|
|
94
|
-
{ output: false }
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
deps.output(
|
|
98
|
-
flags,
|
|
99
|
-
{
|
|
100
|
-
status: 'installed',
|
|
101
|
-
template_id: templateSlug,
|
|
102
|
-
directory: targetDir,
|
|
103
|
-
git_head: result.head,
|
|
104
|
-
deployment,
|
|
105
|
-
},
|
|
106
|
-
(value) => {
|
|
107
|
-
console.log(`Template installed with Git history: ${value.template_id}`);
|
|
108
|
-
console.log(`Directory: ${value.directory}`);
|
|
109
|
-
console.log(`Template HEAD: ${value.git_head}`);
|
|
110
|
-
printDeployment(value.deployment);
|
|
111
|
-
}
|
|
112
|
-
);
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
const response = await timedFetch(
|
|
116
|
-
`${apiUrl}/v1/templates/${encodeURIComponent(templateSlug)}/download?project_id=${encodeURIComponent(project)}`,
|
|
117
|
-
{ method: 'GET', headers }
|
|
118
|
-
);
|
|
119
|
-
if (!response.ok) {
|
|
120
|
-
const text = await response.text();
|
|
121
|
-
let parsed = {};
|
|
122
|
-
try {
|
|
123
|
-
parsed = text ? JSON.parse(text) : {};
|
|
124
|
-
} catch {}
|
|
125
|
-
throw new Error(parsed?.error?.message || parsed?.message || text || `HTTP ${response.status}`);
|
|
126
|
-
}
|
|
127
|
-
const template = parseArchive(Buffer.from(await response.arrayBuffer()));
|
|
128
|
-
writeFiles(targetDir, template.files, deps.booleanFlag(flags, 'force'));
|
|
129
|
-
let deployment = null;
|
|
130
|
-
if (deps.booleanFlag(flags, 'deploy')) {
|
|
131
|
-
const entrypoint = deps.stringFlag(flags, 'entrypoint') || template.manifest.entrypoint;
|
|
132
|
-
if (!entrypoint) throw new Error('template manifest has no entrypoint. Pass --entrypoint to deploy.');
|
|
133
|
-
deployment = await deps.deployCode(
|
|
134
|
-
{
|
|
135
|
-
...flags,
|
|
136
|
-
dir: targetDir,
|
|
137
|
-
entrypoint,
|
|
138
|
-
label: deps.stringFlag(flags, 'label') || `템플릿 ${templateSlug} 설치`,
|
|
139
|
-
},
|
|
140
|
-
{ output: false }
|
|
141
|
-
);
|
|
142
|
-
}
|
|
143
|
-
deps.output(
|
|
144
|
-
flags,
|
|
145
|
-
{
|
|
146
|
-
status: 'installed',
|
|
147
|
-
template_id: templateSlug,
|
|
148
|
-
directory: targetDir,
|
|
149
|
-
files: template.files.length,
|
|
150
|
-
deployment,
|
|
151
|
-
},
|
|
152
|
-
(value) => {
|
|
153
|
-
console.log(`Template installed: ${value.template_id}`);
|
|
154
|
-
console.log(`Directory: ${value.directory}`);
|
|
155
|
-
console.log(`Files: ${value.files}`);
|
|
156
|
-
printDeployment(value.deployment);
|
|
157
|
-
}
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
async function pull(flags) {
|
|
162
|
-
const targetDir = path.resolve(deps.stringFlag(flags, 'dir') || process.cwd());
|
|
163
|
-
const state = readTemplateState(targetDir);
|
|
164
|
-
const templateSlug = deps.stringFlag(flags, 'template') || state?.slug;
|
|
165
|
-
if (!templateSlug) throw new Error('template pull requires --template or .joripspace/template.json');
|
|
166
|
-
const project = deps.requireProjectId(flags);
|
|
167
|
-
const connection = deps.resolveConnection(flags);
|
|
168
|
-
const apiToken = deps.requireApiToken(flags, connection);
|
|
169
|
-
const apiUrl = connection.apiBaseUrl;
|
|
170
|
-
const headers = { Authorization: `Bearer ${apiToken}`, 'X-Joripspace-Session-Context': 'cli' };
|
|
171
|
-
const update = await timedFetch(
|
|
172
|
-
`${apiUrl}/v1/templates/${encodeURIComponent(templateSlug)}/git-update?project_id=${encodeURIComponent(project)}¤t_head=${encodeURIComponent(state.git_head_sha)}`,
|
|
173
|
-
{ method: 'GET', headers }
|
|
174
|
-
);
|
|
175
|
-
if (!update.ok) throw await fetchError(update);
|
|
176
|
-
const updateState = await update.json();
|
|
177
|
-
if (!updateState.update_available) {
|
|
178
|
-
deps.output(
|
|
179
|
-
flags,
|
|
180
|
-
{ status: 'current', template_id: templateSlug, git_head: state.git_head_sha, updated: false },
|
|
181
|
-
(value) => {
|
|
182
|
-
console.log(`Template is already current: ${value.template_id}`);
|
|
183
|
-
console.log(`Template HEAD: ${value.git_head}`);
|
|
184
|
-
}
|
|
185
|
-
);
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
if (!deps.booleanFlag(flags, 'yes'))
|
|
189
|
-
throw new Error(
|
|
190
|
-
`template update ${updateState.version} is available; review the changes and re-run with --yes to download and merge it`
|
|
191
|
-
);
|
|
192
|
-
const granted = await downloadBundleGrant(apiUrl, headers, templateSlug, project);
|
|
193
|
-
if (!granted) throw new Error('template Git history is unavailable');
|
|
194
|
-
const result = applyGitBundle(targetDir, templateSlug, granted.bundle, granted.metadata, true);
|
|
195
|
-
deps.output(
|
|
196
|
-
flags,
|
|
197
|
-
{
|
|
198
|
-
status: result.updated ? 'updated' : 'current',
|
|
199
|
-
template_id: templateSlug,
|
|
200
|
-
git_head: result.head,
|
|
201
|
-
updated: result.updated,
|
|
202
|
-
},
|
|
203
|
-
(value) => {
|
|
204
|
-
console.log(
|
|
205
|
-
value.updated
|
|
206
|
-
? `Template updated: ${value.template_id}`
|
|
207
|
-
: `Template is already current: ${value.template_id}`
|
|
208
|
-
);
|
|
209
|
-
console.log(`Template HEAD: ${value.git_head}`);
|
|
210
|
-
}
|
|
211
|
-
);
|
|
212
|
-
}
|
|
213
|
-
return { list, marketplaceList, deploy, install, pull };
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
function printDeployment(value) {
|
|
217
|
-
if (!value) return;
|
|
218
|
-
console.log(`Deployment: ${value.deployment_id || value.checkpoint_id}`);
|
|
219
|
-
console.log(`Status: ${value.status || 'deployed'}`);
|
|
220
|
-
if (value.url || value.default_url) console.log(`URL: ${value.url || value.default_url}`);
|
|
221
|
-
if (value.transport) console.log(`Transport: ${value.transport}`);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
async function downloadBundleGrant(apiUrl, headers, templateSlug, project) {
|
|
225
|
-
const response = await timedFetch(
|
|
226
|
-
`${apiUrl}/v1/templates/${encodeURIComponent(templateSlug)}/git-bundle-grants?project_id=${encodeURIComponent(project)}`,
|
|
227
|
-
{ method: 'POST', headers }
|
|
228
|
-
);
|
|
229
|
-
if (response.status === 409) return null;
|
|
230
|
-
if (!response.ok) throw await fetchError(response);
|
|
231
|
-
const metadata = await response.json();
|
|
232
|
-
const download = await timedFetch(metadata.download_url, { method: 'GET' }, 45_000);
|
|
233
|
-
if (!download.ok) throw await fetchError(download);
|
|
234
|
-
return { metadata, bundle: Buffer.from(await download.arrayBuffer()) };
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
async function timedFetch(url, options, timeoutMs = 25_000) {
|
|
238
|
-
const controller = new AbortController();
|
|
239
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
240
|
-
try {
|
|
241
|
-
return await fetch(url, { ...options, signal: controller.signal });
|
|
242
|
-
} catch (error) {
|
|
243
|
-
if (error?.name === 'AbortError')
|
|
244
|
-
throw new Error(`template request timed out after ${Math.round(timeoutMs / 1000)} seconds`);
|
|
245
|
-
throw error;
|
|
246
|
-
} finally {
|
|
247
|
-
clearTimeout(timer);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
function applyGitRemote(targetDir, templateSlug, source) {
|
|
252
|
-
const previous = readTemplateState(targetDir);
|
|
253
|
-
if (!previous || previous.slug !== templateSlug)
|
|
254
|
-
throw new Error('template lineage does not match this workspace');
|
|
255
|
-
if (source.template_id && previous.template_id && source.template_id !== previous.template_id)
|
|
256
|
-
throw new Error('template source does not match this workspace');
|
|
257
|
-
if (!isGitRepository(targetDir)) throw new Error('template update requires a Git repository');
|
|
258
|
-
const status = git(targetDir, ['status', '--porcelain']).trim();
|
|
259
|
-
if (status) throw new Error('working tree has changes; commit or stash them before template update');
|
|
260
|
-
const remoteUrl = githubRemoteUrl(source.remote_url);
|
|
261
|
-
const sourceRef = gitBranchRef(source.remote_ref);
|
|
262
|
-
git(targetDir, ['fetch', '--no-tags', remoteUrl, sourceRef]);
|
|
263
|
-
const head = gitSha(git(targetDir, ['rev-parse', 'FETCH_HEAD']).trim());
|
|
264
|
-
const previousHead = gitSha(previous.git_head_sha);
|
|
265
|
-
if (previousHead === head) {
|
|
266
|
-
configureTemplateRemote(targetDir, remoteUrl, sourceRef);
|
|
267
|
-
git(targetDir, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
|
|
268
|
-
return { updated: false, head };
|
|
269
|
-
}
|
|
270
|
-
if (gitResult(targetDir, ['merge-base', '--is-ancestor', previousHead, head]).status !== 0)
|
|
271
|
-
throw new Error('template history was rewritten; automatic update stopped');
|
|
272
|
-
ensureGitIdentity(targetDir);
|
|
273
|
-
const merge = gitResult(targetDir, ['merge', '--no-ff', '--no-commit', head]);
|
|
274
|
-
if (merge.status !== 0) {
|
|
275
|
-
throw new Error(
|
|
276
|
-
`template merge has conflicts; resolve them without force-push\n${String(merge.stderr || merge.stdout).trim()}`
|
|
277
|
-
);
|
|
278
|
-
}
|
|
279
|
-
configureTemplateRemote(targetDir, remoteUrl, sourceRef);
|
|
280
|
-
git(targetDir, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
|
|
281
|
-
writeTemplateStateFromSource(targetDir, previous, source, head);
|
|
282
|
-
git(targetDir, ['add', '.joripspace/template.json']);
|
|
283
|
-
git(targetDir, ['commit', '-m', `조립스페이스 템플릿 업데이트: ${templateSlug}`]);
|
|
284
|
-
return { updated: true, head };
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
function installPublicGitClone(targetDir, templateSlug, source) {
|
|
288
|
-
const remoteUrl = githubRemoteUrl(source.remote_url);
|
|
289
|
-
const remoteRef = gitBranchRef(source.remote_ref);
|
|
290
|
-
const remoteBranch = remoteRef.slice('refs/heads/'.length);
|
|
291
|
-
fs.mkdirSync(targetDir, { recursive: true });
|
|
292
|
-
const existingRepository = isGitRepository(targetDir);
|
|
293
|
-
if (existingRepository) {
|
|
294
|
-
if (gitResult(targetDir, ['rev-parse', '--verify', 'HEAD']).status === 0) return null;
|
|
295
|
-
if (git(targetDir, ['ls-files', '-z']).length) return null;
|
|
296
|
-
}
|
|
297
|
-
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'joripspace-public-template-'));
|
|
298
|
-
const cloneDir = path.join(temp, 'clone');
|
|
299
|
-
try {
|
|
300
|
-
const clone = gitResult(targetDir, [
|
|
301
|
-
...cloneLocalConfigArgs(targetDir),
|
|
302
|
-
'clone',
|
|
303
|
-
'--branch',
|
|
304
|
-
remoteBranch,
|
|
305
|
-
'--single-branch',
|
|
306
|
-
'--no-tags',
|
|
307
|
-
remoteUrl,
|
|
308
|
-
cloneDir,
|
|
309
|
-
]);
|
|
310
|
-
if (clone.status !== 0) return null;
|
|
311
|
-
const head = gitSha(git(cloneDir, ['rev-parse', 'HEAD']).trim());
|
|
312
|
-
const files = git(cloneDir, ['ls-files', '-z']).split('\0').filter(Boolean);
|
|
313
|
-
const allowedCollisions = new Set(['package.json', '.gitignore']);
|
|
314
|
-
const collisions = files.filter(
|
|
315
|
-
(file) => fs.existsSync(path.join(targetDir, ...file.split('/'))) && !allowedCollisions.has(file)
|
|
316
|
-
);
|
|
317
|
-
if (collisions.length) return null;
|
|
318
|
-
const previousPackage = readJson(path.join(targetDir, 'package.json'));
|
|
319
|
-
const previousGitignore = readOptionalText(path.join(targetDir, '.gitignore'));
|
|
320
|
-
if (!existingRepository) git(targetDir, ['init']);
|
|
321
|
-
const branch = gitResult(targetDir, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
322
|
-
const branchName =
|
|
323
|
-
branch.status === 0 && String(branch.stdout || '').trim() ? String(branch.stdout || '').trim() : 'main';
|
|
324
|
-
for (const file of allowedCollisions) {
|
|
325
|
-
const destination = path.join(targetDir, file);
|
|
326
|
-
if (fs.existsSync(destination)) fs.rmSync(destination, { force: true });
|
|
327
|
-
}
|
|
328
|
-
try {
|
|
329
|
-
git(targetDir, ['fetch', '--no-tags', cloneDir, remoteRef]);
|
|
330
|
-
git(targetDir, ['checkout', '-B', branchName, 'FETCH_HEAD']);
|
|
331
|
-
} catch (error) {
|
|
332
|
-
restoreOptionalText(
|
|
333
|
-
path.join(targetDir, 'package.json'),
|
|
334
|
-
previousPackage && `${JSON.stringify(previousPackage, null, 2)}\n`
|
|
335
|
-
);
|
|
336
|
-
restoreOptionalText(path.join(targetDir, '.gitignore'), previousGitignore);
|
|
337
|
-
throw error;
|
|
338
|
-
}
|
|
339
|
-
mergeManagedPackageScripts(path.join(targetDir, 'package.json'), previousPackage);
|
|
340
|
-
mergeGitignore(path.join(targetDir, '.gitignore'), previousGitignore);
|
|
341
|
-
configureTemplateRemote(targetDir, remoteUrl, remoteRef);
|
|
342
|
-
git(targetDir, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
|
|
343
|
-
writeClonedTemplateState(targetDir, templateSlug, source, head);
|
|
344
|
-
return { head };
|
|
345
|
-
} finally {
|
|
346
|
-
fs.rmSync(temp, { recursive: true, force: true });
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
function cloneLocalConfigArgs(targetDir) {
|
|
351
|
-
const result = [];
|
|
352
|
-
const rewrites = gitResult(targetDir, ['config', '--get-regexp', '^url\\..*\\.insteadOf$']);
|
|
353
|
-
if (rewrites.status === 0) {
|
|
354
|
-
for (const line of String(rewrites.stdout || '')
|
|
355
|
-
.split(/\r?\n/)
|
|
356
|
-
.filter(Boolean)) {
|
|
357
|
-
const separator = line.search(/\s/);
|
|
358
|
-
if (separator > 0) result.push('-c', `${line.slice(0, separator)}=${line.slice(separator).trim()}`);
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
const fileProtocol = gitResult(targetDir, ['config', '--get', 'protocol.file.allow']);
|
|
362
|
-
if (fileProtocol.status === 0 && String(fileProtocol.stdout || '').trim()) {
|
|
363
|
-
result.push('-c', `protocol.file.allow=${String(fileProtocol.stdout || '').trim()}`);
|
|
364
|
-
}
|
|
365
|
-
return result;
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
function configureTemplateRemote(targetDir, sourceRef) {
|
|
369
|
-
const remoteUrl = '.git/joripspace/upstream.bundle';
|
|
370
|
-
const current = gitResult(targetDir, ['config', '--get', 'remote.upstream.url']);
|
|
371
|
-
if (current.status === 0) {
|
|
372
|
-
if (String(current.stdout).trim() !== remoteUrl)
|
|
373
|
-
throw new Error('existing upstream remote is not managed by JoripSpace');
|
|
374
|
-
} else {
|
|
375
|
-
git(targetDir, ['remote', 'add', 'upstream', remoteUrl]);
|
|
376
|
-
}
|
|
377
|
-
git(targetDir, [
|
|
378
|
-
'config',
|
|
379
|
-
'--replace-all',
|
|
380
|
-
'remote.upstream.fetch',
|
|
381
|
-
`${sourceRef}:refs/remotes/upstream/main`,
|
|
382
|
-
]);
|
|
383
|
-
git(targetDir, ['config', '--replace-all', 'remote.upstream.tagOpt', '--no-tags']);
|
|
384
|
-
if (gitResult(targetDir, ['remote', 'get-url', 'joripspace-template']).status === 0)
|
|
385
|
-
git(targetDir, ['remote', 'remove', 'joripspace-template']);
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
function applyGitBundle(targetDir, templateSlug, bundle, metadata, updateOnly) {
|
|
389
|
-
const expectedHash = String(metadata.bundle_sha256 || '');
|
|
390
|
-
const actualHash = crypto.createHash('sha256').update(bundle).digest('hex');
|
|
391
|
-
if (!safeEqualHex(actualHash, expectedHash)) throw new Error('template Git bundle integrity check failed');
|
|
392
|
-
const head = gitSha(metadata.git_head_sha);
|
|
393
|
-
const sourceRef = gitBranchRef(metadata.git_ref);
|
|
394
|
-
if (!['refs/heads/main', 'refs/heads/joripspace-template-main'].includes(sourceRef))
|
|
395
|
-
throw new Error('template Git ref is invalid');
|
|
396
|
-
fs.mkdirSync(targetDir, { recursive: true });
|
|
397
|
-
git(targetDir, ['--version'], { withoutC: true });
|
|
398
|
-
if (!isGitRepository(targetDir)) {
|
|
399
|
-
if (updateOnly) throw new Error('template update requires a Git repository');
|
|
400
|
-
git(targetDir, ['init']);
|
|
401
|
-
}
|
|
402
|
-
const status = git(targetDir, ['status', '--porcelain']).trim();
|
|
403
|
-
if (status)
|
|
404
|
-
throw new Error('working tree has changes; commit or stash them before template Git installation/update');
|
|
405
|
-
const gitDirectory = path.resolve(targetDir, git(targetDir, ['rev-parse', '--git-dir']).trim());
|
|
406
|
-
const bundleDirectory = path.join(gitDirectory, 'joripspace');
|
|
407
|
-
fs.mkdirSync(bundleDirectory, { recursive: true });
|
|
408
|
-
const candidatePath = path.join(bundleDirectory, `upstream-${crypto.randomUUID()}.bundle`);
|
|
409
|
-
const bundlePath = path.join(bundleDirectory, 'upstream.bundle');
|
|
410
|
-
const backupPath = path.join(bundleDirectory, 'upstream.bundle.previous');
|
|
411
|
-
fs.writeFileSync(candidatePath, bundle, { flag: 'wx' });
|
|
412
|
-
try {
|
|
413
|
-
git(targetDir, ['bundle', 'verify', candidatePath]);
|
|
414
|
-
git(targetDir, ['fetch', '--no-tags', candidatePath, `${sourceRef}:refs/joripspace/candidate`]);
|
|
415
|
-
const fetchedHead = gitSha(git(targetDir, ['rev-parse', 'refs/joripspace/candidate']).trim());
|
|
416
|
-
if (fetchedHead !== head) throw new Error('template Git HEAD does not match the downloaded bundle');
|
|
417
|
-
const previous = readTemplateState(targetDir);
|
|
418
|
-
if (updateOnly) {
|
|
419
|
-
if (!previous || previous.slug !== templateSlug)
|
|
420
|
-
throw new Error('template lineage does not match this workspace');
|
|
421
|
-
if (previous.template_id && metadata.template_id !== previous.template_id)
|
|
422
|
-
throw new Error('template source does not match this workspace');
|
|
423
|
-
if (
|
|
424
|
-
gitResult(targetDir, ['merge-base', '--is-ancestor', gitSha(previous.git_head_sha), head]).status !==
|
|
425
|
-
0
|
|
426
|
-
)
|
|
427
|
-
throw new Error('template history was rewritten; automatic update stopped');
|
|
428
|
-
}
|
|
429
|
-
const upstream = gitResult(targetDir, ['config', '--get', 'remote.upstream.url']);
|
|
430
|
-
if (upstream.status === 0 && String(upstream.stdout).trim() !== '.git/joripspace/upstream.bundle')
|
|
431
|
-
throw new Error('existing upstream remote is not managed by JoripSpace');
|
|
432
|
-
if (fs.existsSync(backupPath)) fs.rmSync(backupPath, { force: true });
|
|
433
|
-
if (fs.existsSync(bundlePath)) fs.renameSync(bundlePath, backupPath);
|
|
434
|
-
try {
|
|
435
|
-
fs.renameSync(candidatePath, bundlePath);
|
|
436
|
-
} catch (error) {
|
|
437
|
-
if (fs.existsSync(backupPath)) fs.renameSync(backupPath, bundlePath);
|
|
438
|
-
throw error;
|
|
439
|
-
}
|
|
440
|
-
configureTemplateRemote(targetDir, sourceRef);
|
|
441
|
-
git(targetDir, ['fetch', '--no-tags', 'upstream']);
|
|
442
|
-
git(targetDir, ['update-ref', '-d', 'refs/joripspace/candidate']);
|
|
443
|
-
if (updateOnly && previous.git_head_sha === head) {
|
|
444
|
-
writeTemplateState(targetDir, templateSlug, metadata, head);
|
|
445
|
-
git(targetDir, ['add', '.joripspace/template.json']);
|
|
446
|
-
if (gitResult(targetDir, ['diff', '--cached', '--quiet']).status !== 0) {
|
|
447
|
-
ensureGitIdentity(targetDir);
|
|
448
|
-
git(targetDir, ['commit', '-m', `조립스페이스 공식 업데이트 채널 연결: ${templateSlug}`]);
|
|
449
|
-
}
|
|
450
|
-
if (fs.existsSync(backupPath)) fs.rmSync(backupPath, { force: true });
|
|
451
|
-
return { updated: false, head };
|
|
452
|
-
}
|
|
453
|
-
ensureGitIdentity(targetDir);
|
|
454
|
-
const hasHead = gitResult(targetDir, ['rev-parse', '--verify', 'HEAD']).status === 0;
|
|
455
|
-
if (!hasHead) {
|
|
456
|
-
git(targetDir, ['checkout', '-B', 'main', head]);
|
|
457
|
-
writeTemplateState(targetDir, templateSlug, metadata, head);
|
|
458
|
-
git(targetDir, ['add', '.joripspace/template.json']);
|
|
459
|
-
git(targetDir, ['commit', '-m', `조립스페이스 템플릿 연결: ${templateSlug}`]);
|
|
460
|
-
} else {
|
|
461
|
-
const merge = gitResult(targetDir, [
|
|
462
|
-
'merge',
|
|
463
|
-
'--no-ff',
|
|
464
|
-
'--no-commit',
|
|
465
|
-
'--allow-unrelated-histories',
|
|
466
|
-
head,
|
|
467
|
-
]);
|
|
468
|
-
if (merge.status !== 0) {
|
|
469
|
-
throw new Error(
|
|
470
|
-
`template merge has conflicts; resolve them without force-push\n${String(merge.stderr || merge.stdout).trim()}`
|
|
471
|
-
);
|
|
472
|
-
}
|
|
473
|
-
writeTemplateState(targetDir, templateSlug, metadata, head);
|
|
474
|
-
git(targetDir, ['add', '.joripspace/template.json']);
|
|
475
|
-
git(targetDir, [
|
|
476
|
-
'commit',
|
|
477
|
-
'-m',
|
|
478
|
-
`${updateOnly ? '조립스페이스 템플릿 업데이트' : '조립스페이스 템플릿 연결'}: ${templateSlug}`,
|
|
479
|
-
]);
|
|
480
|
-
}
|
|
481
|
-
if (fs.existsSync(backupPath)) fs.rmSync(backupPath, { force: true });
|
|
482
|
-
return { updated: true, head };
|
|
483
|
-
} finally {
|
|
484
|
-
if (fs.existsSync(candidatePath)) fs.rmSync(candidatePath, { force: true });
|
|
485
|
-
gitResult(targetDir, ['update-ref', '-d', 'refs/joripspace/candidate']);
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
function readTemplateState(targetDir) {
|
|
490
|
-
const file = path.join(targetDir, '.joripspace', 'template.json');
|
|
491
|
-
if (!fs.existsSync(file)) return null;
|
|
492
|
-
try {
|
|
493
|
-
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
494
|
-
} catch {
|
|
495
|
-
throw new Error('.joripspace/template.json is invalid');
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
function writeTemplateState(targetDir, slug, metadata, head) {
|
|
500
|
-
const directory = path.join(targetDir, '.joripspace');
|
|
501
|
-
fs.mkdirSync(directory, { recursive: true });
|
|
502
|
-
fs.writeFileSync(
|
|
503
|
-
path.join(directory, 'template.json'),
|
|
504
|
-
`${JSON.stringify(
|
|
505
|
-
{
|
|
506
|
-
schema_version: 3,
|
|
507
|
-
slug,
|
|
508
|
-
template_id: String(metadata.template_id || ''),
|
|
509
|
-
version_id: String(metadata.version_id || ''),
|
|
510
|
-
version: String(metadata.version || ''),
|
|
511
|
-
git_head_sha: head,
|
|
512
|
-
remote_ref: 'refs/remotes/upstream/main',
|
|
513
|
-
},
|
|
514
|
-
null,
|
|
515
|
-
2
|
|
516
|
-
)}\n`
|
|
517
|
-
);
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
function writeTemplateStateFromSource(targetDir, previous, source, head) {
|
|
521
|
-
const directory = path.join(targetDir, '.joripspace');
|
|
522
|
-
fs.mkdirSync(directory, { recursive: true });
|
|
523
|
-
fs.writeFileSync(
|
|
524
|
-
path.join(directory, 'template.json'),
|
|
525
|
-
`${JSON.stringify(
|
|
526
|
-
{
|
|
527
|
-
...previous,
|
|
528
|
-
schema_version: 2,
|
|
529
|
-
git_head_sha: head,
|
|
530
|
-
remote_ref: 'refs/remotes/joripspace-template/main',
|
|
531
|
-
remote_url: githubRemoteUrl(source.remote_url),
|
|
532
|
-
remote_branch_ref: gitBranchRef(source.remote_ref),
|
|
533
|
-
},
|
|
534
|
-
null,
|
|
535
|
-
2
|
|
536
|
-
)}\n`
|
|
537
|
-
);
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
function writeClonedTemplateState(targetDir, slug, source, head) {
|
|
541
|
-
const directory = path.join(targetDir, '.joripspace');
|
|
542
|
-
fs.mkdirSync(directory, { recursive: true });
|
|
543
|
-
fs.writeFileSync(
|
|
544
|
-
path.join(directory, 'template.json'),
|
|
545
|
-
`${JSON.stringify(
|
|
546
|
-
{
|
|
547
|
-
schema_version: 2,
|
|
548
|
-
slug,
|
|
549
|
-
template_id: source.template_id,
|
|
550
|
-
version_id: source.version_id,
|
|
551
|
-
version: source.version,
|
|
552
|
-
git_head_sha: head,
|
|
553
|
-
remote_ref: 'refs/remotes/joripspace-template/main',
|
|
554
|
-
remote_url: githubRemoteUrl(source.remote_url),
|
|
555
|
-
remote_branch_ref: gitBranchRef(source.remote_ref),
|
|
556
|
-
},
|
|
557
|
-
null,
|
|
558
|
-
2
|
|
559
|
-
)}\n`
|
|
560
|
-
);
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
function readJson(file) {
|
|
564
|
-
if (!fs.existsSync(file)) return null;
|
|
565
|
-
try {
|
|
566
|
-
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
567
|
-
} catch {
|
|
568
|
-
return null;
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
function mergeManagedPackageScripts(file, previous) {
|
|
573
|
-
if (!previous || !fs.existsSync(file)) return;
|
|
574
|
-
const current = readJson(file);
|
|
575
|
-
if (!current) return;
|
|
576
|
-
current.scripts = current.scripts && typeof current.scripts === 'object' ? current.scripts : {};
|
|
577
|
-
for (const [name, command] of Object.entries(previous.scripts || {})) {
|
|
578
|
-
if (name.startsWith('joripspace:')) current.scripts[name] = command;
|
|
579
|
-
}
|
|
580
|
-
fs.writeFileSync(file, `${JSON.stringify(current, null, 2)}\n`);
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
function readOptionalText(file) {
|
|
584
|
-
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
function restoreOptionalText(file, value) {
|
|
588
|
-
if (value === null || value === undefined) return;
|
|
589
|
-
fs.writeFileSync(file, value);
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
function mergeGitignore(file, previous) {
|
|
593
|
-
if (previous === null) return;
|
|
594
|
-
const current = readOptionalText(file) || '';
|
|
595
|
-
const lines = current.split(/\r?\n/).filter(Boolean);
|
|
596
|
-
const seen = new Set(lines);
|
|
597
|
-
for (const line of previous.split(/\r?\n/).filter(Boolean)) {
|
|
598
|
-
if (!seen.has(line)) {
|
|
599
|
-
lines.push(line);
|
|
600
|
-
seen.add(line);
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
fs.writeFileSync(file, `${lines.join('\n')}\n`);
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
function isGitRepository(directory) {
|
|
607
|
-
const result = gitResult(directory, ['rev-parse', '--is-inside-work-tree']);
|
|
608
|
-
return result.status === 0 && String(result.stdout).trim() === 'true';
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
function ensureGitIdentity(directory) {
|
|
612
|
-
const name = gitResult(directory, ['config', '--get', 'user.name']);
|
|
613
|
-
const email = gitResult(directory, ['config', '--get', 'user.email']);
|
|
614
|
-
if (
|
|
615
|
-
name.status !== 0 ||
|
|
616
|
-
email.status !== 0 ||
|
|
617
|
-
!String(name.stdout).trim() ||
|
|
618
|
-
!String(email.stdout).trim()
|
|
619
|
-
) {
|
|
620
|
-
throw new Error('Git user.name and user.email must be configured before installing a history template');
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
function git(directory, args, options = {}) {
|
|
625
|
-
const result = gitResult(directory, args, options);
|
|
626
|
-
if (result.error?.code === 'ENOENT') throw new Error('git command not found');
|
|
627
|
-
if (result.status !== 0)
|
|
628
|
-
throw new Error(String(result.stderr || result.stdout || 'git command failed').trim());
|
|
629
|
-
return String(result.stdout || '');
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
function gitResult(directory, args, options = {}) {
|
|
633
|
-
return spawnSync('git', options.withoutC ? args : ['-C', directory, ...args], {
|
|
634
|
-
encoding: 'utf8',
|
|
635
|
-
windowsHide: true,
|
|
636
|
-
});
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
function requiredHeader(headers, name) {
|
|
640
|
-
const value = String(headers.get(name) || '').trim();
|
|
641
|
-
if (!value) throw new Error(`template response is missing ${name}`);
|
|
642
|
-
return value;
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
function optionalHeader(headers, name) {
|
|
646
|
-
return String(headers.get(name) || '').trim();
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
function githubRemoteUrl(value) {
|
|
650
|
-
let url;
|
|
651
|
-
try {
|
|
652
|
-
url = new URL(String(value || ''));
|
|
653
|
-
} catch {
|
|
654
|
-
throw new Error('template Git remote URL is invalid');
|
|
655
|
-
}
|
|
656
|
-
const parts = url.pathname.replace(/^\/+|\/+$/g, '').split('/');
|
|
657
|
-
if (
|
|
658
|
-
url.protocol !== 'https:' ||
|
|
659
|
-
url.hostname.toLowerCase() !== 'github.com' ||
|
|
660
|
-
url.username ||
|
|
661
|
-
url.password ||
|
|
662
|
-
parts.length !== 2 ||
|
|
663
|
-
parts.some((part) => !/^[A-Za-z0-9_.-]+(?:\.git)?$/.test(part))
|
|
664
|
-
) {
|
|
665
|
-
throw new Error('template Git remote URL is invalid');
|
|
666
|
-
}
|
|
667
|
-
return `https://github.com/${parts[0]}/${parts[1].replace(/\.git$/i, '')}.git`;
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
function gitBranchRef(value) {
|
|
671
|
-
const normalized = String(value || '');
|
|
672
|
-
if (!/^refs\/heads\/[A-Za-z0-9][A-Za-z0-9._\/-]*$/.test(normalized) || normalized.includes('..'))
|
|
673
|
-
throw new Error('template Git remote ref is invalid');
|
|
674
|
-
return normalized;
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
function gitSha(value) {
|
|
678
|
-
const normalized = String(value || '').toLowerCase();
|
|
679
|
-
if (!/^[0-9a-f]{40}$/.test(normalized)) throw new Error('template Git SHA is invalid');
|
|
680
|
-
return normalized;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
function safeEqualHex(actual, expected) {
|
|
684
|
-
const normalized = String(expected || '').toLowerCase();
|
|
685
|
-
return (
|
|
686
|
-
/^[0-9a-f]{64}$/.test(normalized) &&
|
|
687
|
-
crypto.timingSafeEqual(Buffer.from(actual, 'hex'), Buffer.from(normalized, 'hex'))
|
|
688
|
-
);
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
async function fetchError(response) {
|
|
692
|
-
const text = await response.text();
|
|
693
|
-
let parsed = {};
|
|
694
|
-
try {
|
|
695
|
-
parsed = text ? JSON.parse(text) : {};
|
|
696
|
-
} catch {}
|
|
697
|
-
return new Error(parsed?.error?.message || parsed?.message || text || `HTTP ${response.status}`);
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
function parseArchive(archive) {
|
|
701
|
-
let tar;
|
|
702
|
-
try {
|
|
703
|
-
tar = zlib.gunzipSync(archive, { maxOutputLength: 100 * 1024 * 1024 });
|
|
704
|
-
} catch {
|
|
705
|
-
throw new Error('template archive is invalid or exceeds 100 MB');
|
|
706
|
-
}
|
|
707
|
-
const entries = [];
|
|
708
|
-
let offset = 0;
|
|
709
|
-
let pendingPath = '';
|
|
710
|
-
while (offset + 512 <= tar.length) {
|
|
711
|
-
const header = tar.subarray(offset, offset + 512);
|
|
712
|
-
if (header.every((byte) => byte === 0)) break;
|
|
713
|
-
const name = tarField(header.subarray(0, 100));
|
|
714
|
-
const prefix = tarField(header.subarray(345, 500));
|
|
715
|
-
const archivePath = pendingPath || [prefix, name].filter(Boolean).join('/');
|
|
716
|
-
pendingPath = '';
|
|
717
|
-
const size = tarOctal(header.subarray(124, 136));
|
|
718
|
-
const mode = tarOctal(header.subarray(100, 108));
|
|
719
|
-
const type = String.fromCharCode(header[156] || 48);
|
|
720
|
-
const dataStart = offset + 512;
|
|
721
|
-
const dataEnd = dataStart + size;
|
|
722
|
-
if (dataEnd > tar.length) throw new Error('template archive is damaged');
|
|
723
|
-
const data = tar.subarray(dataStart, dataEnd);
|
|
724
|
-
if (type === 'L') pendingPath = tarField(data);
|
|
725
|
-
if (type === 'x') pendingPath = paxPath(data) || pendingPath;
|
|
726
|
-
if (type === '0' || type === '\0') {
|
|
727
|
-
const relative = stripRoot(archivePath);
|
|
728
|
-
if (relative) entries.push({ path: safePath(relative), data: Buffer.from(data), mode });
|
|
729
|
-
}
|
|
730
|
-
offset = dataStart + Math.ceil(size / 512) * 512;
|
|
731
|
-
}
|
|
732
|
-
const manifestEntry = entries.find((entry) => entry.path === 'joripspace-template.json');
|
|
733
|
-
if (!manifestEntry) throw new Error('joripspace-template.json is missing');
|
|
734
|
-
let manifest;
|
|
735
|
-
try {
|
|
736
|
-
manifest = JSON.parse(manifestEntry.data.toString('utf8'));
|
|
737
|
-
} catch {
|
|
738
|
-
throw new Error('joripspace-template.json is invalid');
|
|
739
|
-
}
|
|
740
|
-
const sourceRoot = normalizeSourceRoot(manifest.source_root);
|
|
741
|
-
const files = entries
|
|
742
|
-
.filter((entry) => sourceRoot === '.' || entry.path.startsWith(`${sourceRoot}/`))
|
|
743
|
-
.map((entry) => ({
|
|
744
|
-
...entry,
|
|
745
|
-
path: sourceRoot === '.' ? entry.path : safePath(entry.path.slice(sourceRoot.length + 1)),
|
|
746
|
-
}));
|
|
747
|
-
if (!files.length) throw new Error('template source_root contains no files');
|
|
748
|
-
return { manifest, files };
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
function writeFiles(targetDir, files, force) {
|
|
752
|
-
const collisions = files
|
|
753
|
-
.map((file) => path.resolve(targetDir, ...file.path.split('/')))
|
|
754
|
-
.filter(fs.existsSync);
|
|
755
|
-
if (collisions.length && !force)
|
|
756
|
-
throw new Error(`template would overwrite ${collisions.length} existing file(s). Re-run with --force.`);
|
|
757
|
-
fs.mkdirSync(targetDir, { recursive: true });
|
|
758
|
-
for (const file of files) {
|
|
759
|
-
const outputPath = path.resolve(targetDir, ...file.path.split('/'));
|
|
760
|
-
const relative = path.relative(targetDir, outputPath);
|
|
761
|
-
if (!relative || relative.startsWith('..') || path.isAbsolute(relative))
|
|
762
|
-
throw new Error('unsafe template path');
|
|
763
|
-
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
|
764
|
-
fs.writeFileSync(outputPath, file.data, { mode: file.mode & 0o111 ? 0o755 : 0o644 });
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
function tarField(bytes) {
|
|
769
|
-
const end = bytes.indexOf(0);
|
|
770
|
-
return Buffer.from(end >= 0 ? bytes.subarray(0, end) : bytes)
|
|
771
|
-
.toString('utf8')
|
|
772
|
-
.trim();
|
|
773
|
-
}
|
|
774
|
-
function tarOctal(bytes) {
|
|
775
|
-
const value = tarField(bytes).replace(/[^0-7].*$/, '');
|
|
776
|
-
return value ? Number.parseInt(value, 8) : 0;
|
|
777
|
-
}
|
|
778
|
-
function paxPath(bytes) {
|
|
779
|
-
for (const line of Buffer.from(bytes).toString('utf8').split('\n')) {
|
|
780
|
-
const match = line.match(/^\d+ path=(.+)$/);
|
|
781
|
-
if (match) return match[1];
|
|
782
|
-
}
|
|
783
|
-
return '';
|
|
784
|
-
}
|
|
785
|
-
function stripRoot(value) {
|
|
786
|
-
const parts = String(value || '')
|
|
787
|
-
.replace(/^\.?\//, '')
|
|
788
|
-
.split('/');
|
|
789
|
-
return parts.length > 1 ? parts.slice(1).join('/') : '';
|
|
790
|
-
}
|
|
791
|
-
function safePath(value) {
|
|
792
|
-
const normalized = String(value || '')
|
|
793
|
-
.replace(/\\/g, '/')
|
|
794
|
-
.replace(/^\.\//, '');
|
|
795
|
-
const parts = normalized.split('/');
|
|
796
|
-
if (
|
|
797
|
-
!normalized ||
|
|
798
|
-
normalized.startsWith('/') ||
|
|
799
|
-
parts.some((part) => !part || part === '.' || part === '..')
|
|
800
|
-
)
|
|
801
|
-
throw new Error('template contains an unsafe path');
|
|
802
|
-
return normalized;
|
|
803
|
-
}
|
|
804
|
-
function normalizeSourceRoot(value) {
|
|
805
|
-
const normalized = String(value || '.')
|
|
806
|
-
.replace(/\\/g, '/')
|
|
807
|
-
.replace(/^\.\//, '')
|
|
808
|
-
.replace(/\/$/, '');
|
|
809
|
-
return normalized === '' || normalized === '.' ? '.' : safePath(normalized);
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
module.exports = { applyGitBundle, createTemplateCommands };
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
const os = require('node:os');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { spawnSync } = require('node:child_process');
|
|
6
|
+
const zlib = require('node:zlib');
|
|
7
|
+
|
|
8
|
+
function createTemplateCommands(deps) {
|
|
9
|
+
async function list(flags) {
|
|
10
|
+
const body = {
|
|
11
|
+
templates: deps.listTemplates().map((template) => ({
|
|
12
|
+
id: template.id,
|
|
13
|
+
name: template.name,
|
|
14
|
+
description: template.description,
|
|
15
|
+
entrypoint: template.entrypoint,
|
|
16
|
+
tags: template.tags ?? [],
|
|
17
|
+
variables: template.variables ?? [],
|
|
18
|
+
})),
|
|
19
|
+
};
|
|
20
|
+
deps.output(flags, body, (value) => {
|
|
21
|
+
for (const template of value.templates)
|
|
22
|
+
console.log(`${template.id}\t${template.name}\t${template.description}`);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function marketplaceList(flags) {
|
|
27
|
+
const project = deps.requireProjectId(flags);
|
|
28
|
+
const cursor = deps.stringFlag(flags, 'cursor');
|
|
29
|
+
const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : '';
|
|
30
|
+
const response = await deps.apiRequest(flags, `/v1/templates${query}`, {
|
|
31
|
+
method: 'GET',
|
|
32
|
+
...deps.projectAuth(flags),
|
|
33
|
+
});
|
|
34
|
+
const body = { ...response, project_id: project };
|
|
35
|
+
deps.output(flags, body, (value) => {
|
|
36
|
+
for (const template of value.templates || []) {
|
|
37
|
+
const name = template.name || template.title || template.slug || template.template_id;
|
|
38
|
+
const slug = template.slug || template.template_id || template.id;
|
|
39
|
+
console.log(`${slug}\t${name}\t${template.description || ''}`);
|
|
40
|
+
}
|
|
41
|
+
if (value.next_cursor || value.cursor) console.log(`Next cursor: ${value.next_cursor || value.cursor}`);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function deploy(flags) {
|
|
46
|
+
const project = deps.requireProjectId(flags);
|
|
47
|
+
const templateId = deps.stringFlag(flags, 'template');
|
|
48
|
+
if (!templateId) throw new Error('deploy-template requires --template');
|
|
49
|
+
const label = deps.stringFlag(flags, 'label').trim();
|
|
50
|
+
if (!label) throw new Error('deploy-template requires --label');
|
|
51
|
+
const { manifest, deployRequest } = deps.buildTemplateDeployRequest(templateId, deps.templateVars(flags));
|
|
52
|
+
const body = await deps.apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/deploy`, {
|
|
53
|
+
method: 'POST',
|
|
54
|
+
...deps.projectAuth(flags),
|
|
55
|
+
body: { ...deployRequest, label },
|
|
56
|
+
});
|
|
57
|
+
deps.output(flags, { ...body, template_id: manifest.id }, (value) => {
|
|
58
|
+
console.log(`Template: ${value.template_id}`);
|
|
59
|
+
console.log(`Deployment: ${value.deployment_id}`);
|
|
60
|
+
console.log(`Status: ${value.status}`);
|
|
61
|
+
console.log(`URL: ${value.url}`);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function install(flags) {
|
|
66
|
+
const project = deps.requireProjectId(flags);
|
|
67
|
+
const templateSlug = deps.stringFlag(flags, 'template');
|
|
68
|
+
if (!templateSlug) throw new Error('install-template requires --template');
|
|
69
|
+
const targetDir = path.resolve(deps.stringFlag(flags, 'dir') || process.cwd());
|
|
70
|
+
const connection = deps.resolveConnection(flags);
|
|
71
|
+
const apiToken = deps.requireApiToken(flags, connection);
|
|
72
|
+
const apiUrl = connection.apiBaseUrl;
|
|
73
|
+
const filesOnly = deps.booleanFlag(flags, 'files-only');
|
|
74
|
+
const headers = { Authorization: `Bearer ${apiToken}`, 'X-Joripspace-Session-Context': 'cli' };
|
|
75
|
+
const claim = await timedFetch(`${apiUrl}/v1/templates/${encodeURIComponent(templateSlug)}/claim`, {
|
|
76
|
+
method: 'POST',
|
|
77
|
+
headers,
|
|
78
|
+
});
|
|
79
|
+
if (!claim.ok && ![404, 409].includes(claim.status)) throw await fetchError(claim);
|
|
80
|
+
const granted = filesOnly ? null : await downloadBundleGrant(apiUrl, headers, templateSlug, project);
|
|
81
|
+
if (granted) {
|
|
82
|
+
const result = applyGitBundle(targetDir, templateSlug, granted.bundle, granted.metadata, false);
|
|
83
|
+
let deployment = null;
|
|
84
|
+
if (deps.booleanFlag(flags, 'deploy')) {
|
|
85
|
+
const entrypoint = deps.stringFlag(flags, 'entrypoint');
|
|
86
|
+
if (!entrypoint) throw new Error('template manifest has no entrypoint. Pass --entrypoint to deploy.');
|
|
87
|
+
deployment = await deps.deployCode(
|
|
88
|
+
{
|
|
89
|
+
...flags,
|
|
90
|
+
dir: targetDir,
|
|
91
|
+
entrypoint,
|
|
92
|
+
label: deps.stringFlag(flags, 'label') || `템플릿 ${templateSlug} 설치`,
|
|
93
|
+
},
|
|
94
|
+
{ output: false }
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
deps.output(
|
|
98
|
+
flags,
|
|
99
|
+
{
|
|
100
|
+
status: 'installed',
|
|
101
|
+
template_id: templateSlug,
|
|
102
|
+
directory: targetDir,
|
|
103
|
+
git_head: result.head,
|
|
104
|
+
deployment,
|
|
105
|
+
},
|
|
106
|
+
(value) => {
|
|
107
|
+
console.log(`Template installed with Git history: ${value.template_id}`);
|
|
108
|
+
console.log(`Directory: ${value.directory}`);
|
|
109
|
+
console.log(`Template HEAD: ${value.git_head}`);
|
|
110
|
+
printDeployment(value.deployment);
|
|
111
|
+
}
|
|
112
|
+
);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const response = await timedFetch(
|
|
116
|
+
`${apiUrl}/v1/templates/${encodeURIComponent(templateSlug)}/download?project_id=${encodeURIComponent(project)}`,
|
|
117
|
+
{ method: 'GET', headers }
|
|
118
|
+
);
|
|
119
|
+
if (!response.ok) {
|
|
120
|
+
const text = await response.text();
|
|
121
|
+
let parsed = {};
|
|
122
|
+
try {
|
|
123
|
+
parsed = text ? JSON.parse(text) : {};
|
|
124
|
+
} catch {}
|
|
125
|
+
throw new Error(parsed?.error?.message || parsed?.message || text || `HTTP ${response.status}`);
|
|
126
|
+
}
|
|
127
|
+
const template = parseArchive(Buffer.from(await response.arrayBuffer()));
|
|
128
|
+
writeFiles(targetDir, template.files, deps.booleanFlag(flags, 'force'));
|
|
129
|
+
let deployment = null;
|
|
130
|
+
if (deps.booleanFlag(flags, 'deploy')) {
|
|
131
|
+
const entrypoint = deps.stringFlag(flags, 'entrypoint') || template.manifest.entrypoint;
|
|
132
|
+
if (!entrypoint) throw new Error('template manifest has no entrypoint. Pass --entrypoint to deploy.');
|
|
133
|
+
deployment = await deps.deployCode(
|
|
134
|
+
{
|
|
135
|
+
...flags,
|
|
136
|
+
dir: targetDir,
|
|
137
|
+
entrypoint,
|
|
138
|
+
label: deps.stringFlag(flags, 'label') || `템플릿 ${templateSlug} 설치`,
|
|
139
|
+
},
|
|
140
|
+
{ output: false }
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
deps.output(
|
|
144
|
+
flags,
|
|
145
|
+
{
|
|
146
|
+
status: 'installed',
|
|
147
|
+
template_id: templateSlug,
|
|
148
|
+
directory: targetDir,
|
|
149
|
+
files: template.files.length,
|
|
150
|
+
deployment,
|
|
151
|
+
},
|
|
152
|
+
(value) => {
|
|
153
|
+
console.log(`Template installed: ${value.template_id}`);
|
|
154
|
+
console.log(`Directory: ${value.directory}`);
|
|
155
|
+
console.log(`Files: ${value.files}`);
|
|
156
|
+
printDeployment(value.deployment);
|
|
157
|
+
}
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function pull(flags) {
|
|
162
|
+
const targetDir = path.resolve(deps.stringFlag(flags, 'dir') || process.cwd());
|
|
163
|
+
const state = readTemplateState(targetDir);
|
|
164
|
+
const templateSlug = deps.stringFlag(flags, 'template') || state?.slug;
|
|
165
|
+
if (!templateSlug) throw new Error('template pull requires --template or .joripspace/template.json');
|
|
166
|
+
const project = deps.requireProjectId(flags);
|
|
167
|
+
const connection = deps.resolveConnection(flags);
|
|
168
|
+
const apiToken = deps.requireApiToken(flags, connection);
|
|
169
|
+
const apiUrl = connection.apiBaseUrl;
|
|
170
|
+
const headers = { Authorization: `Bearer ${apiToken}`, 'X-Joripspace-Session-Context': 'cli' };
|
|
171
|
+
const update = await timedFetch(
|
|
172
|
+
`${apiUrl}/v1/templates/${encodeURIComponent(templateSlug)}/git-update?project_id=${encodeURIComponent(project)}¤t_head=${encodeURIComponent(state.git_head_sha)}`,
|
|
173
|
+
{ method: 'GET', headers }
|
|
174
|
+
);
|
|
175
|
+
if (!update.ok) throw await fetchError(update);
|
|
176
|
+
const updateState = await update.json();
|
|
177
|
+
if (!updateState.update_available) {
|
|
178
|
+
deps.output(
|
|
179
|
+
flags,
|
|
180
|
+
{ status: 'current', template_id: templateSlug, git_head: state.git_head_sha, updated: false },
|
|
181
|
+
(value) => {
|
|
182
|
+
console.log(`Template is already current: ${value.template_id}`);
|
|
183
|
+
console.log(`Template HEAD: ${value.git_head}`);
|
|
184
|
+
}
|
|
185
|
+
);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (!deps.booleanFlag(flags, 'yes'))
|
|
189
|
+
throw new Error(
|
|
190
|
+
`template update ${updateState.version} is available; review the changes and re-run with --yes to download and merge it`
|
|
191
|
+
);
|
|
192
|
+
const granted = await downloadBundleGrant(apiUrl, headers, templateSlug, project);
|
|
193
|
+
if (!granted) throw new Error('template Git history is unavailable');
|
|
194
|
+
const result = applyGitBundle(targetDir, templateSlug, granted.bundle, granted.metadata, true);
|
|
195
|
+
deps.output(
|
|
196
|
+
flags,
|
|
197
|
+
{
|
|
198
|
+
status: result.updated ? 'updated' : 'current',
|
|
199
|
+
template_id: templateSlug,
|
|
200
|
+
git_head: result.head,
|
|
201
|
+
updated: result.updated,
|
|
202
|
+
},
|
|
203
|
+
(value) => {
|
|
204
|
+
console.log(
|
|
205
|
+
value.updated
|
|
206
|
+
? `Template updated: ${value.template_id}`
|
|
207
|
+
: `Template is already current: ${value.template_id}`
|
|
208
|
+
);
|
|
209
|
+
console.log(`Template HEAD: ${value.git_head}`);
|
|
210
|
+
}
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
return { list, marketplaceList, deploy, install, pull };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function printDeployment(value) {
|
|
217
|
+
if (!value) return;
|
|
218
|
+
console.log(`Deployment: ${value.deployment_id || value.checkpoint_id}`);
|
|
219
|
+
console.log(`Status: ${value.status || 'deployed'}`);
|
|
220
|
+
if (value.url || value.default_url) console.log(`URL: ${value.url || value.default_url}`);
|
|
221
|
+
if (value.transport) console.log(`Transport: ${value.transport}`);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function downloadBundleGrant(apiUrl, headers, templateSlug, project) {
|
|
225
|
+
const response = await timedFetch(
|
|
226
|
+
`${apiUrl}/v1/templates/${encodeURIComponent(templateSlug)}/git-bundle-grants?project_id=${encodeURIComponent(project)}`,
|
|
227
|
+
{ method: 'POST', headers }
|
|
228
|
+
);
|
|
229
|
+
if (response.status === 409) return null;
|
|
230
|
+
if (!response.ok) throw await fetchError(response);
|
|
231
|
+
const metadata = await response.json();
|
|
232
|
+
const download = await timedFetch(metadata.download_url, { method: 'GET' }, 45_000);
|
|
233
|
+
if (!download.ok) throw await fetchError(download);
|
|
234
|
+
return { metadata, bundle: Buffer.from(await download.arrayBuffer()) };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function timedFetch(url, options, timeoutMs = 25_000) {
|
|
238
|
+
const controller = new AbortController();
|
|
239
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
240
|
+
try {
|
|
241
|
+
return await fetch(url, { ...options, signal: controller.signal });
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (error?.name === 'AbortError')
|
|
244
|
+
throw new Error(`template request timed out after ${Math.round(timeoutMs / 1000)} seconds`);
|
|
245
|
+
throw error;
|
|
246
|
+
} finally {
|
|
247
|
+
clearTimeout(timer);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function applyGitRemote(targetDir, templateSlug, source) {
|
|
252
|
+
const previous = readTemplateState(targetDir);
|
|
253
|
+
if (!previous || previous.slug !== templateSlug)
|
|
254
|
+
throw new Error('template lineage does not match this workspace');
|
|
255
|
+
if (source.template_id && previous.template_id && source.template_id !== previous.template_id)
|
|
256
|
+
throw new Error('template source does not match this workspace');
|
|
257
|
+
if (!isGitRepository(targetDir)) throw new Error('template update requires a Git repository');
|
|
258
|
+
const status = git(targetDir, ['status', '--porcelain']).trim();
|
|
259
|
+
if (status) throw new Error('working tree has changes; commit or stash them before template update');
|
|
260
|
+
const remoteUrl = githubRemoteUrl(source.remote_url);
|
|
261
|
+
const sourceRef = gitBranchRef(source.remote_ref);
|
|
262
|
+
git(targetDir, ['fetch', '--no-tags', remoteUrl, sourceRef]);
|
|
263
|
+
const head = gitSha(git(targetDir, ['rev-parse', 'FETCH_HEAD']).trim());
|
|
264
|
+
const previousHead = gitSha(previous.git_head_sha);
|
|
265
|
+
if (previousHead === head) {
|
|
266
|
+
configureTemplateRemote(targetDir, remoteUrl, sourceRef);
|
|
267
|
+
git(targetDir, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
|
|
268
|
+
return { updated: false, head };
|
|
269
|
+
}
|
|
270
|
+
if (gitResult(targetDir, ['merge-base', '--is-ancestor', previousHead, head]).status !== 0)
|
|
271
|
+
throw new Error('template history was rewritten; automatic update stopped');
|
|
272
|
+
ensureGitIdentity(targetDir);
|
|
273
|
+
const merge = gitResult(targetDir, ['merge', '--no-ff', '--no-commit', head]);
|
|
274
|
+
if (merge.status !== 0) {
|
|
275
|
+
throw new Error(
|
|
276
|
+
`template merge has conflicts; resolve them without force-push\n${String(merge.stderr || merge.stdout).trim()}`
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
configureTemplateRemote(targetDir, remoteUrl, sourceRef);
|
|
280
|
+
git(targetDir, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
|
|
281
|
+
writeTemplateStateFromSource(targetDir, previous, source, head);
|
|
282
|
+
git(targetDir, ['add', '.joripspace/template.json']);
|
|
283
|
+
git(targetDir, ['commit', '-m', `조립스페이스 템플릿 업데이트: ${templateSlug}`]);
|
|
284
|
+
return { updated: true, head };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function installPublicGitClone(targetDir, templateSlug, source) {
|
|
288
|
+
const remoteUrl = githubRemoteUrl(source.remote_url);
|
|
289
|
+
const remoteRef = gitBranchRef(source.remote_ref);
|
|
290
|
+
const remoteBranch = remoteRef.slice('refs/heads/'.length);
|
|
291
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
292
|
+
const existingRepository = isGitRepository(targetDir);
|
|
293
|
+
if (existingRepository) {
|
|
294
|
+
if (gitResult(targetDir, ['rev-parse', '--verify', 'HEAD']).status === 0) return null;
|
|
295
|
+
if (git(targetDir, ['ls-files', '-z']).length) return null;
|
|
296
|
+
}
|
|
297
|
+
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'joripspace-public-template-'));
|
|
298
|
+
const cloneDir = path.join(temp, 'clone');
|
|
299
|
+
try {
|
|
300
|
+
const clone = gitResult(targetDir, [
|
|
301
|
+
...cloneLocalConfigArgs(targetDir),
|
|
302
|
+
'clone',
|
|
303
|
+
'--branch',
|
|
304
|
+
remoteBranch,
|
|
305
|
+
'--single-branch',
|
|
306
|
+
'--no-tags',
|
|
307
|
+
remoteUrl,
|
|
308
|
+
cloneDir,
|
|
309
|
+
]);
|
|
310
|
+
if (clone.status !== 0) return null;
|
|
311
|
+
const head = gitSha(git(cloneDir, ['rev-parse', 'HEAD']).trim());
|
|
312
|
+
const files = git(cloneDir, ['ls-files', '-z']).split('\0').filter(Boolean);
|
|
313
|
+
const allowedCollisions = new Set(['package.json', '.gitignore']);
|
|
314
|
+
const collisions = files.filter(
|
|
315
|
+
(file) => fs.existsSync(path.join(targetDir, ...file.split('/'))) && !allowedCollisions.has(file)
|
|
316
|
+
);
|
|
317
|
+
if (collisions.length) return null;
|
|
318
|
+
const previousPackage = readJson(path.join(targetDir, 'package.json'));
|
|
319
|
+
const previousGitignore = readOptionalText(path.join(targetDir, '.gitignore'));
|
|
320
|
+
if (!existingRepository) git(targetDir, ['init']);
|
|
321
|
+
const branch = gitResult(targetDir, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
322
|
+
const branchName =
|
|
323
|
+
branch.status === 0 && String(branch.stdout || '').trim() ? String(branch.stdout || '').trim() : 'main';
|
|
324
|
+
for (const file of allowedCollisions) {
|
|
325
|
+
const destination = path.join(targetDir, file);
|
|
326
|
+
if (fs.existsSync(destination)) fs.rmSync(destination, { force: true });
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
git(targetDir, ['fetch', '--no-tags', cloneDir, remoteRef]);
|
|
330
|
+
git(targetDir, ['checkout', '-B', branchName, 'FETCH_HEAD']);
|
|
331
|
+
} catch (error) {
|
|
332
|
+
restoreOptionalText(
|
|
333
|
+
path.join(targetDir, 'package.json'),
|
|
334
|
+
previousPackage && `${JSON.stringify(previousPackage, null, 2)}\n`
|
|
335
|
+
);
|
|
336
|
+
restoreOptionalText(path.join(targetDir, '.gitignore'), previousGitignore);
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
mergeManagedPackageScripts(path.join(targetDir, 'package.json'), previousPackage);
|
|
340
|
+
mergeGitignore(path.join(targetDir, '.gitignore'), previousGitignore);
|
|
341
|
+
configureTemplateRemote(targetDir, remoteUrl, remoteRef);
|
|
342
|
+
git(targetDir, ['update-ref', 'refs/remotes/joripspace-template/main', head]);
|
|
343
|
+
writeClonedTemplateState(targetDir, templateSlug, source, head);
|
|
344
|
+
return { head };
|
|
345
|
+
} finally {
|
|
346
|
+
fs.rmSync(temp, { recursive: true, force: true });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function cloneLocalConfigArgs(targetDir) {
|
|
351
|
+
const result = [];
|
|
352
|
+
const rewrites = gitResult(targetDir, ['config', '--get-regexp', '^url\\..*\\.insteadOf$']);
|
|
353
|
+
if (rewrites.status === 0) {
|
|
354
|
+
for (const line of String(rewrites.stdout || '')
|
|
355
|
+
.split(/\r?\n/)
|
|
356
|
+
.filter(Boolean)) {
|
|
357
|
+
const separator = line.search(/\s/);
|
|
358
|
+
if (separator > 0) result.push('-c', `${line.slice(0, separator)}=${line.slice(separator).trim()}`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
const fileProtocol = gitResult(targetDir, ['config', '--get', 'protocol.file.allow']);
|
|
362
|
+
if (fileProtocol.status === 0 && String(fileProtocol.stdout || '').trim()) {
|
|
363
|
+
result.push('-c', `protocol.file.allow=${String(fileProtocol.stdout || '').trim()}`);
|
|
364
|
+
}
|
|
365
|
+
return result;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function configureTemplateRemote(targetDir, sourceRef) {
|
|
369
|
+
const remoteUrl = '.git/joripspace/upstream.bundle';
|
|
370
|
+
const current = gitResult(targetDir, ['config', '--get', 'remote.upstream.url']);
|
|
371
|
+
if (current.status === 0) {
|
|
372
|
+
if (String(current.stdout).trim() !== remoteUrl)
|
|
373
|
+
throw new Error('existing upstream remote is not managed by JoripSpace');
|
|
374
|
+
} else {
|
|
375
|
+
git(targetDir, ['remote', 'add', 'upstream', remoteUrl]);
|
|
376
|
+
}
|
|
377
|
+
git(targetDir, [
|
|
378
|
+
'config',
|
|
379
|
+
'--replace-all',
|
|
380
|
+
'remote.upstream.fetch',
|
|
381
|
+
`${sourceRef}:refs/remotes/upstream/main`,
|
|
382
|
+
]);
|
|
383
|
+
git(targetDir, ['config', '--replace-all', 'remote.upstream.tagOpt', '--no-tags']);
|
|
384
|
+
if (gitResult(targetDir, ['remote', 'get-url', 'joripspace-template']).status === 0)
|
|
385
|
+
git(targetDir, ['remote', 'remove', 'joripspace-template']);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function applyGitBundle(targetDir, templateSlug, bundle, metadata, updateOnly) {
|
|
389
|
+
const expectedHash = String(metadata.bundle_sha256 || '');
|
|
390
|
+
const actualHash = crypto.createHash('sha256').update(bundle).digest('hex');
|
|
391
|
+
if (!safeEqualHex(actualHash, expectedHash)) throw new Error('template Git bundle integrity check failed');
|
|
392
|
+
const head = gitSha(metadata.git_head_sha);
|
|
393
|
+
const sourceRef = gitBranchRef(metadata.git_ref);
|
|
394
|
+
if (!['refs/heads/main', 'refs/heads/joripspace-template-main'].includes(sourceRef))
|
|
395
|
+
throw new Error('template Git ref is invalid');
|
|
396
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
397
|
+
git(targetDir, ['--version'], { withoutC: true });
|
|
398
|
+
if (!isGitRepository(targetDir)) {
|
|
399
|
+
if (updateOnly) throw new Error('template update requires a Git repository');
|
|
400
|
+
git(targetDir, ['init']);
|
|
401
|
+
}
|
|
402
|
+
const status = git(targetDir, ['status', '--porcelain']).trim();
|
|
403
|
+
if (status)
|
|
404
|
+
throw new Error('working tree has changes; commit or stash them before template Git installation/update');
|
|
405
|
+
const gitDirectory = path.resolve(targetDir, git(targetDir, ['rev-parse', '--git-dir']).trim());
|
|
406
|
+
const bundleDirectory = path.join(gitDirectory, 'joripspace');
|
|
407
|
+
fs.mkdirSync(bundleDirectory, { recursive: true });
|
|
408
|
+
const candidatePath = path.join(bundleDirectory, `upstream-${crypto.randomUUID()}.bundle`);
|
|
409
|
+
const bundlePath = path.join(bundleDirectory, 'upstream.bundle');
|
|
410
|
+
const backupPath = path.join(bundleDirectory, 'upstream.bundle.previous');
|
|
411
|
+
fs.writeFileSync(candidatePath, bundle, { flag: 'wx' });
|
|
412
|
+
try {
|
|
413
|
+
git(targetDir, ['bundle', 'verify', candidatePath]);
|
|
414
|
+
git(targetDir, ['fetch', '--no-tags', candidatePath, `${sourceRef}:refs/joripspace/candidate`]);
|
|
415
|
+
const fetchedHead = gitSha(git(targetDir, ['rev-parse', 'refs/joripspace/candidate']).trim());
|
|
416
|
+
if (fetchedHead !== head) throw new Error('template Git HEAD does not match the downloaded bundle');
|
|
417
|
+
const previous = readTemplateState(targetDir);
|
|
418
|
+
if (updateOnly) {
|
|
419
|
+
if (!previous || previous.slug !== templateSlug)
|
|
420
|
+
throw new Error('template lineage does not match this workspace');
|
|
421
|
+
if (previous.template_id && metadata.template_id !== previous.template_id)
|
|
422
|
+
throw new Error('template source does not match this workspace');
|
|
423
|
+
if (
|
|
424
|
+
gitResult(targetDir, ['merge-base', '--is-ancestor', gitSha(previous.git_head_sha), head]).status !==
|
|
425
|
+
0
|
|
426
|
+
)
|
|
427
|
+
throw new Error('template history was rewritten; automatic update stopped');
|
|
428
|
+
}
|
|
429
|
+
const upstream = gitResult(targetDir, ['config', '--get', 'remote.upstream.url']);
|
|
430
|
+
if (upstream.status === 0 && String(upstream.stdout).trim() !== '.git/joripspace/upstream.bundle')
|
|
431
|
+
throw new Error('existing upstream remote is not managed by JoripSpace');
|
|
432
|
+
if (fs.existsSync(backupPath)) fs.rmSync(backupPath, { force: true });
|
|
433
|
+
if (fs.existsSync(bundlePath)) fs.renameSync(bundlePath, backupPath);
|
|
434
|
+
try {
|
|
435
|
+
fs.renameSync(candidatePath, bundlePath);
|
|
436
|
+
} catch (error) {
|
|
437
|
+
if (fs.existsSync(backupPath)) fs.renameSync(backupPath, bundlePath);
|
|
438
|
+
throw error;
|
|
439
|
+
}
|
|
440
|
+
configureTemplateRemote(targetDir, sourceRef);
|
|
441
|
+
git(targetDir, ['fetch', '--no-tags', 'upstream']);
|
|
442
|
+
git(targetDir, ['update-ref', '-d', 'refs/joripspace/candidate']);
|
|
443
|
+
if (updateOnly && previous.git_head_sha === head) {
|
|
444
|
+
writeTemplateState(targetDir, templateSlug, metadata, head);
|
|
445
|
+
git(targetDir, ['add', '.joripspace/template.json']);
|
|
446
|
+
if (gitResult(targetDir, ['diff', '--cached', '--quiet']).status !== 0) {
|
|
447
|
+
ensureGitIdentity(targetDir);
|
|
448
|
+
git(targetDir, ['commit', '-m', `조립스페이스 공식 업데이트 채널 연결: ${templateSlug}`]);
|
|
449
|
+
}
|
|
450
|
+
if (fs.existsSync(backupPath)) fs.rmSync(backupPath, { force: true });
|
|
451
|
+
return { updated: false, head };
|
|
452
|
+
}
|
|
453
|
+
ensureGitIdentity(targetDir);
|
|
454
|
+
const hasHead = gitResult(targetDir, ['rev-parse', '--verify', 'HEAD']).status === 0;
|
|
455
|
+
if (!hasHead) {
|
|
456
|
+
git(targetDir, ['checkout', '-B', 'main', head]);
|
|
457
|
+
writeTemplateState(targetDir, templateSlug, metadata, head);
|
|
458
|
+
git(targetDir, ['add', '.joripspace/template.json']);
|
|
459
|
+
git(targetDir, ['commit', '-m', `조립스페이스 템플릿 연결: ${templateSlug}`]);
|
|
460
|
+
} else {
|
|
461
|
+
const merge = gitResult(targetDir, [
|
|
462
|
+
'merge',
|
|
463
|
+
'--no-ff',
|
|
464
|
+
'--no-commit',
|
|
465
|
+
'--allow-unrelated-histories',
|
|
466
|
+
head,
|
|
467
|
+
]);
|
|
468
|
+
if (merge.status !== 0) {
|
|
469
|
+
throw new Error(
|
|
470
|
+
`template merge has conflicts; resolve them without force-push\n${String(merge.stderr || merge.stdout).trim()}`
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
writeTemplateState(targetDir, templateSlug, metadata, head);
|
|
474
|
+
git(targetDir, ['add', '.joripspace/template.json']);
|
|
475
|
+
git(targetDir, [
|
|
476
|
+
'commit',
|
|
477
|
+
'-m',
|
|
478
|
+
`${updateOnly ? '조립스페이스 템플릿 업데이트' : '조립스페이스 템플릿 연결'}: ${templateSlug}`,
|
|
479
|
+
]);
|
|
480
|
+
}
|
|
481
|
+
if (fs.existsSync(backupPath)) fs.rmSync(backupPath, { force: true });
|
|
482
|
+
return { updated: true, head };
|
|
483
|
+
} finally {
|
|
484
|
+
if (fs.existsSync(candidatePath)) fs.rmSync(candidatePath, { force: true });
|
|
485
|
+
gitResult(targetDir, ['update-ref', '-d', 'refs/joripspace/candidate']);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function readTemplateState(targetDir) {
|
|
490
|
+
const file = path.join(targetDir, '.joripspace', 'template.json');
|
|
491
|
+
if (!fs.existsSync(file)) return null;
|
|
492
|
+
try {
|
|
493
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
494
|
+
} catch {
|
|
495
|
+
throw new Error('.joripspace/template.json is invalid');
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function writeTemplateState(targetDir, slug, metadata, head) {
|
|
500
|
+
const directory = path.join(targetDir, '.joripspace');
|
|
501
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
502
|
+
fs.writeFileSync(
|
|
503
|
+
path.join(directory, 'template.json'),
|
|
504
|
+
`${JSON.stringify(
|
|
505
|
+
{
|
|
506
|
+
schema_version: 3,
|
|
507
|
+
slug,
|
|
508
|
+
template_id: String(metadata.template_id || ''),
|
|
509
|
+
version_id: String(metadata.version_id || ''),
|
|
510
|
+
version: String(metadata.version || ''),
|
|
511
|
+
git_head_sha: head,
|
|
512
|
+
remote_ref: 'refs/remotes/upstream/main',
|
|
513
|
+
},
|
|
514
|
+
null,
|
|
515
|
+
2
|
|
516
|
+
)}\n`
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function writeTemplateStateFromSource(targetDir, previous, source, head) {
|
|
521
|
+
const directory = path.join(targetDir, '.joripspace');
|
|
522
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
523
|
+
fs.writeFileSync(
|
|
524
|
+
path.join(directory, 'template.json'),
|
|
525
|
+
`${JSON.stringify(
|
|
526
|
+
{
|
|
527
|
+
...previous,
|
|
528
|
+
schema_version: 2,
|
|
529
|
+
git_head_sha: head,
|
|
530
|
+
remote_ref: 'refs/remotes/joripspace-template/main',
|
|
531
|
+
remote_url: githubRemoteUrl(source.remote_url),
|
|
532
|
+
remote_branch_ref: gitBranchRef(source.remote_ref),
|
|
533
|
+
},
|
|
534
|
+
null,
|
|
535
|
+
2
|
|
536
|
+
)}\n`
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function writeClonedTemplateState(targetDir, slug, source, head) {
|
|
541
|
+
const directory = path.join(targetDir, '.joripspace');
|
|
542
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
543
|
+
fs.writeFileSync(
|
|
544
|
+
path.join(directory, 'template.json'),
|
|
545
|
+
`${JSON.stringify(
|
|
546
|
+
{
|
|
547
|
+
schema_version: 2,
|
|
548
|
+
slug,
|
|
549
|
+
template_id: source.template_id,
|
|
550
|
+
version_id: source.version_id,
|
|
551
|
+
version: source.version,
|
|
552
|
+
git_head_sha: head,
|
|
553
|
+
remote_ref: 'refs/remotes/joripspace-template/main',
|
|
554
|
+
remote_url: githubRemoteUrl(source.remote_url),
|
|
555
|
+
remote_branch_ref: gitBranchRef(source.remote_ref),
|
|
556
|
+
},
|
|
557
|
+
null,
|
|
558
|
+
2
|
|
559
|
+
)}\n`
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function readJson(file) {
|
|
564
|
+
if (!fs.existsSync(file)) return null;
|
|
565
|
+
try {
|
|
566
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
567
|
+
} catch {
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function mergeManagedPackageScripts(file, previous) {
|
|
573
|
+
if (!previous || !fs.existsSync(file)) return;
|
|
574
|
+
const current = readJson(file);
|
|
575
|
+
if (!current) return;
|
|
576
|
+
current.scripts = current.scripts && typeof current.scripts === 'object' ? current.scripts : {};
|
|
577
|
+
for (const [name, command] of Object.entries(previous.scripts || {})) {
|
|
578
|
+
if (name.startsWith('joripspace:')) current.scripts[name] = command;
|
|
579
|
+
}
|
|
580
|
+
fs.writeFileSync(file, `${JSON.stringify(current, null, 2)}\n`);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function readOptionalText(file) {
|
|
584
|
+
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function restoreOptionalText(file, value) {
|
|
588
|
+
if (value === null || value === undefined) return;
|
|
589
|
+
fs.writeFileSync(file, value);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function mergeGitignore(file, previous) {
|
|
593
|
+
if (previous === null) return;
|
|
594
|
+
const current = readOptionalText(file) || '';
|
|
595
|
+
const lines = current.split(/\r?\n/).filter(Boolean);
|
|
596
|
+
const seen = new Set(lines);
|
|
597
|
+
for (const line of previous.split(/\r?\n/).filter(Boolean)) {
|
|
598
|
+
if (!seen.has(line)) {
|
|
599
|
+
lines.push(line);
|
|
600
|
+
seen.add(line);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
fs.writeFileSync(file, `${lines.join('\n')}\n`);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function isGitRepository(directory) {
|
|
607
|
+
const result = gitResult(directory, ['rev-parse', '--is-inside-work-tree']);
|
|
608
|
+
return result.status === 0 && String(result.stdout).trim() === 'true';
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function ensureGitIdentity(directory) {
|
|
612
|
+
const name = gitResult(directory, ['config', '--get', 'user.name']);
|
|
613
|
+
const email = gitResult(directory, ['config', '--get', 'user.email']);
|
|
614
|
+
if (
|
|
615
|
+
name.status !== 0 ||
|
|
616
|
+
email.status !== 0 ||
|
|
617
|
+
!String(name.stdout).trim() ||
|
|
618
|
+
!String(email.stdout).trim()
|
|
619
|
+
) {
|
|
620
|
+
throw new Error('Git user.name and user.email must be configured before installing a history template');
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function git(directory, args, options = {}) {
|
|
625
|
+
const result = gitResult(directory, args, options);
|
|
626
|
+
if (result.error?.code === 'ENOENT') throw new Error('git command not found');
|
|
627
|
+
if (result.status !== 0)
|
|
628
|
+
throw new Error(String(result.stderr || result.stdout || 'git command failed').trim());
|
|
629
|
+
return String(result.stdout || '');
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function gitResult(directory, args, options = {}) {
|
|
633
|
+
return spawnSync('git', options.withoutC ? args : ['-C', directory, ...args], {
|
|
634
|
+
encoding: 'utf8',
|
|
635
|
+
windowsHide: true,
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function requiredHeader(headers, name) {
|
|
640
|
+
const value = String(headers.get(name) || '').trim();
|
|
641
|
+
if (!value) throw new Error(`template response is missing ${name}`);
|
|
642
|
+
return value;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function optionalHeader(headers, name) {
|
|
646
|
+
return String(headers.get(name) || '').trim();
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function githubRemoteUrl(value) {
|
|
650
|
+
let url;
|
|
651
|
+
try {
|
|
652
|
+
url = new URL(String(value || ''));
|
|
653
|
+
} catch {
|
|
654
|
+
throw new Error('template Git remote URL is invalid');
|
|
655
|
+
}
|
|
656
|
+
const parts = url.pathname.replace(/^\/+|\/+$/g, '').split('/');
|
|
657
|
+
if (
|
|
658
|
+
url.protocol !== 'https:' ||
|
|
659
|
+
url.hostname.toLowerCase() !== 'github.com' ||
|
|
660
|
+
url.username ||
|
|
661
|
+
url.password ||
|
|
662
|
+
parts.length !== 2 ||
|
|
663
|
+
parts.some((part) => !/^[A-Za-z0-9_.-]+(?:\.git)?$/.test(part))
|
|
664
|
+
) {
|
|
665
|
+
throw new Error('template Git remote URL is invalid');
|
|
666
|
+
}
|
|
667
|
+
return `https://github.com/${parts[0]}/${parts[1].replace(/\.git$/i, '')}.git`;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function gitBranchRef(value) {
|
|
671
|
+
const normalized = String(value || '');
|
|
672
|
+
if (!/^refs\/heads\/[A-Za-z0-9][A-Za-z0-9._\/-]*$/.test(normalized) || normalized.includes('..'))
|
|
673
|
+
throw new Error('template Git remote ref is invalid');
|
|
674
|
+
return normalized;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function gitSha(value) {
|
|
678
|
+
const normalized = String(value || '').toLowerCase();
|
|
679
|
+
if (!/^[0-9a-f]{40}$/.test(normalized)) throw new Error('template Git SHA is invalid');
|
|
680
|
+
return normalized;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function safeEqualHex(actual, expected) {
|
|
684
|
+
const normalized = String(expected || '').toLowerCase();
|
|
685
|
+
return (
|
|
686
|
+
/^[0-9a-f]{64}$/.test(normalized) &&
|
|
687
|
+
crypto.timingSafeEqual(Buffer.from(actual, 'hex'), Buffer.from(normalized, 'hex'))
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
async function fetchError(response) {
|
|
692
|
+
const text = await response.text();
|
|
693
|
+
let parsed = {};
|
|
694
|
+
try {
|
|
695
|
+
parsed = text ? JSON.parse(text) : {};
|
|
696
|
+
} catch {}
|
|
697
|
+
return new Error(parsed?.error?.message || parsed?.message || text || `HTTP ${response.status}`);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function parseArchive(archive) {
|
|
701
|
+
let tar;
|
|
702
|
+
try {
|
|
703
|
+
tar = zlib.gunzipSync(archive, { maxOutputLength: 100 * 1024 * 1024 });
|
|
704
|
+
} catch {
|
|
705
|
+
throw new Error('template archive is invalid or exceeds 100 MB');
|
|
706
|
+
}
|
|
707
|
+
const entries = [];
|
|
708
|
+
let offset = 0;
|
|
709
|
+
let pendingPath = '';
|
|
710
|
+
while (offset + 512 <= tar.length) {
|
|
711
|
+
const header = tar.subarray(offset, offset + 512);
|
|
712
|
+
if (header.every((byte) => byte === 0)) break;
|
|
713
|
+
const name = tarField(header.subarray(0, 100));
|
|
714
|
+
const prefix = tarField(header.subarray(345, 500));
|
|
715
|
+
const archivePath = pendingPath || [prefix, name].filter(Boolean).join('/');
|
|
716
|
+
pendingPath = '';
|
|
717
|
+
const size = tarOctal(header.subarray(124, 136));
|
|
718
|
+
const mode = tarOctal(header.subarray(100, 108));
|
|
719
|
+
const type = String.fromCharCode(header[156] || 48);
|
|
720
|
+
const dataStart = offset + 512;
|
|
721
|
+
const dataEnd = dataStart + size;
|
|
722
|
+
if (dataEnd > tar.length) throw new Error('template archive is damaged');
|
|
723
|
+
const data = tar.subarray(dataStart, dataEnd);
|
|
724
|
+
if (type === 'L') pendingPath = tarField(data);
|
|
725
|
+
if (type === 'x') pendingPath = paxPath(data) || pendingPath;
|
|
726
|
+
if (type === '0' || type === '\0') {
|
|
727
|
+
const relative = stripRoot(archivePath);
|
|
728
|
+
if (relative) entries.push({ path: safePath(relative), data: Buffer.from(data), mode });
|
|
729
|
+
}
|
|
730
|
+
offset = dataStart + Math.ceil(size / 512) * 512;
|
|
731
|
+
}
|
|
732
|
+
const manifestEntry = entries.find((entry) => entry.path === 'joripspace-template.json');
|
|
733
|
+
if (!manifestEntry) throw new Error('joripspace-template.json is missing');
|
|
734
|
+
let manifest;
|
|
735
|
+
try {
|
|
736
|
+
manifest = JSON.parse(manifestEntry.data.toString('utf8'));
|
|
737
|
+
} catch {
|
|
738
|
+
throw new Error('joripspace-template.json is invalid');
|
|
739
|
+
}
|
|
740
|
+
const sourceRoot = normalizeSourceRoot(manifest.source_root);
|
|
741
|
+
const files = entries
|
|
742
|
+
.filter((entry) => sourceRoot === '.' || entry.path.startsWith(`${sourceRoot}/`))
|
|
743
|
+
.map((entry) => ({
|
|
744
|
+
...entry,
|
|
745
|
+
path: sourceRoot === '.' ? entry.path : safePath(entry.path.slice(sourceRoot.length + 1)),
|
|
746
|
+
}));
|
|
747
|
+
if (!files.length) throw new Error('template source_root contains no files');
|
|
748
|
+
return { manifest, files };
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function writeFiles(targetDir, files, force) {
|
|
752
|
+
const collisions = files
|
|
753
|
+
.map((file) => path.resolve(targetDir, ...file.path.split('/')))
|
|
754
|
+
.filter(fs.existsSync);
|
|
755
|
+
if (collisions.length && !force)
|
|
756
|
+
throw new Error(`template would overwrite ${collisions.length} existing file(s). Re-run with --force.`);
|
|
757
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
758
|
+
for (const file of files) {
|
|
759
|
+
const outputPath = path.resolve(targetDir, ...file.path.split('/'));
|
|
760
|
+
const relative = path.relative(targetDir, outputPath);
|
|
761
|
+
if (!relative || relative.startsWith('..') || path.isAbsolute(relative))
|
|
762
|
+
throw new Error('unsafe template path');
|
|
763
|
+
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
|
764
|
+
fs.writeFileSync(outputPath, file.data, { mode: file.mode & 0o111 ? 0o755 : 0o644 });
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function tarField(bytes) {
|
|
769
|
+
const end = bytes.indexOf(0);
|
|
770
|
+
return Buffer.from(end >= 0 ? bytes.subarray(0, end) : bytes)
|
|
771
|
+
.toString('utf8')
|
|
772
|
+
.trim();
|
|
773
|
+
}
|
|
774
|
+
function tarOctal(bytes) {
|
|
775
|
+
const value = tarField(bytes).replace(/[^0-7].*$/, '');
|
|
776
|
+
return value ? Number.parseInt(value, 8) : 0;
|
|
777
|
+
}
|
|
778
|
+
function paxPath(bytes) {
|
|
779
|
+
for (const line of Buffer.from(bytes).toString('utf8').split('\n')) {
|
|
780
|
+
const match = line.match(/^\d+ path=(.+)$/);
|
|
781
|
+
if (match) return match[1];
|
|
782
|
+
}
|
|
783
|
+
return '';
|
|
784
|
+
}
|
|
785
|
+
function stripRoot(value) {
|
|
786
|
+
const parts = String(value || '')
|
|
787
|
+
.replace(/^\.?\//, '')
|
|
788
|
+
.split('/');
|
|
789
|
+
return parts.length > 1 ? parts.slice(1).join('/') : '';
|
|
790
|
+
}
|
|
791
|
+
function safePath(value) {
|
|
792
|
+
const normalized = String(value || '')
|
|
793
|
+
.replace(/\\/g, '/')
|
|
794
|
+
.replace(/^\.\//, '');
|
|
795
|
+
const parts = normalized.split('/');
|
|
796
|
+
if (
|
|
797
|
+
!normalized ||
|
|
798
|
+
normalized.startsWith('/') ||
|
|
799
|
+
parts.some((part) => !part || part === '.' || part === '..')
|
|
800
|
+
)
|
|
801
|
+
throw new Error('template contains an unsafe path');
|
|
802
|
+
return normalized;
|
|
803
|
+
}
|
|
804
|
+
function normalizeSourceRoot(value) {
|
|
805
|
+
const normalized = String(value || '.')
|
|
806
|
+
.replace(/\\/g, '/')
|
|
807
|
+
.replace(/^\.\//, '')
|
|
808
|
+
.replace(/\/$/, '');
|
|
809
|
+
return normalized === '' || normalized === '.' ? '.' : safePath(normalized);
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
module.exports = { applyGitBundle, createTemplateCommands };
|