@artifactshare/cli 0.0.0-reserved.0 → 0.1.1
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/LICENSE +202 -0
- package/README.md +61 -3
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3153 -3
- package/package.json +34 -6
- package/skills/artifactshare/SKILL.md +59 -0
- package/skills/artifactshare/artifactshare.mdc +23 -0
package/dist/index.js
CHANGED
|
@@ -1,5 +1,3155 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { cli, define, lazy } from "gunshi";
|
|
4
|
+
import { Agent } from "undici";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { createReadStream } from "node:fs";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { setTimeout } from "node:timers/promises";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
const DEVICE_CLIENT_ID = "artifactshare-cli";
|
|
12
|
+
const IGNORED_FILENAMES = new Set([
|
|
13
|
+
".DS_Store",
|
|
14
|
+
"Thumbs.db",
|
|
15
|
+
"desktop.ini"
|
|
16
|
+
]);
|
|
17
|
+
const EXCLUDED_DIR_NAMES = new Set([
|
|
18
|
+
"node_modules",
|
|
19
|
+
".git",
|
|
20
|
+
".artifactshare",
|
|
21
|
+
".turbo"
|
|
22
|
+
]);
|
|
23
|
+
const BOOLEAN_FLAGS = new Set([
|
|
24
|
+
"allow-plaintext-token-store",
|
|
25
|
+
"dry-run",
|
|
26
|
+
"force",
|
|
27
|
+
"json",
|
|
28
|
+
"help",
|
|
29
|
+
"home",
|
|
30
|
+
"insecure-localhost"
|
|
31
|
+
]);
|
|
32
|
+
const VALUE_FLAGS = new Set([
|
|
33
|
+
"base-url",
|
|
34
|
+
"body",
|
|
35
|
+
"grant-email",
|
|
36
|
+
"include",
|
|
37
|
+
"key",
|
|
38
|
+
"note",
|
|
39
|
+
"offset",
|
|
40
|
+
"output",
|
|
41
|
+
"profile",
|
|
42
|
+
"project",
|
|
43
|
+
"project-id",
|
|
44
|
+
"quote",
|
|
45
|
+
"quote-after",
|
|
46
|
+
"quote-before",
|
|
47
|
+
"reply-to",
|
|
48
|
+
"scope",
|
|
49
|
+
"token",
|
|
50
|
+
"tool",
|
|
51
|
+
"visibility"
|
|
52
|
+
]);
|
|
53
|
+
const COMMAND_NAMES = new Set([
|
|
54
|
+
"login",
|
|
55
|
+
"publish",
|
|
56
|
+
"update",
|
|
57
|
+
"resolve",
|
|
58
|
+
"download",
|
|
59
|
+
"artifacts",
|
|
60
|
+
"comments",
|
|
61
|
+
"request-access",
|
|
62
|
+
"whoami",
|
|
63
|
+
"doctor",
|
|
64
|
+
"profiles",
|
|
65
|
+
"projects",
|
|
66
|
+
"skills",
|
|
67
|
+
"init"
|
|
68
|
+
]);
|
|
69
|
+
const SUBCOMMANDS = {
|
|
70
|
+
artifacts: ["get"],
|
|
71
|
+
comments: ["list", "post"],
|
|
72
|
+
profiles: ["list", "use"],
|
|
73
|
+
projects: ["list"],
|
|
74
|
+
skills: [
|
|
75
|
+
"install",
|
|
76
|
+
"list",
|
|
77
|
+
"update",
|
|
78
|
+
"remove"
|
|
79
|
+
]
|
|
80
|
+
};
|
|
81
|
+
const UPDATE_OPTION_KEYS = new Set([
|
|
82
|
+
"baseUrl",
|
|
83
|
+
"help",
|
|
84
|
+
"insecureLocalhost",
|
|
85
|
+
"json",
|
|
86
|
+
"profile",
|
|
87
|
+
"token"
|
|
88
|
+
]);
|
|
89
|
+
//#endregion
|
|
90
|
+
//#region src/errors.ts
|
|
91
|
+
const REQUEST_ACCESS_COMMAND$1 = "npx @artifactshare/cli request-access --json";
|
|
92
|
+
const PROJECTS_LIST_COMMAND = "npx @artifactshare/cli projects list --json";
|
|
93
|
+
function apiError(body) {
|
|
94
|
+
const error = body?.error;
|
|
95
|
+
if (typeof error === "string") return {
|
|
96
|
+
code: error,
|
|
97
|
+
message: void 0
|
|
98
|
+
};
|
|
99
|
+
return {
|
|
100
|
+
code: normalizeApiCode(error?.code),
|
|
101
|
+
message: error?.message
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function mapApiError(status, body, options = {}) {
|
|
105
|
+
const { code: apiCode, message: apiMessage } = apiError(body);
|
|
106
|
+
if (status === 401) return options.authenticated ? tokenInvalidError() : authRequiredError();
|
|
107
|
+
if (apiCode === "upload-not-allowed") return cliError({
|
|
108
|
+
code: "upload_not_allowed",
|
|
109
|
+
message: "This account cannot publish yet.",
|
|
110
|
+
why: "Artifact Share is currently limiting who can publish.",
|
|
111
|
+
hint: `Run ${REQUEST_ACCESS_COMMAND$1} to join the early-access waitlist; an operator opens publishing afterwards.`,
|
|
112
|
+
agentRecoverable: false,
|
|
113
|
+
requiresHuman: true,
|
|
114
|
+
recovery: {
|
|
115
|
+
kind: "run_command",
|
|
116
|
+
command: REQUEST_ACCESS_COMMAND$1
|
|
117
|
+
},
|
|
118
|
+
details: {
|
|
119
|
+
limit: "upload_access",
|
|
120
|
+
suggested_command: REQUEST_ACCESS_COMMAND$1
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
if (apiCode === "upload-suspended") return cliError({
|
|
124
|
+
code: "upload_suspended",
|
|
125
|
+
message: apiMessage ?? "Your upload permission is suspended.",
|
|
126
|
+
why: "Artifact Share suspended upload access for this account.",
|
|
127
|
+
hint: "Ask an operator to restore upload access, then retry publish.",
|
|
128
|
+
agentRecoverable: false,
|
|
129
|
+
requiresHuman: true,
|
|
130
|
+
recovery: { kind: "ask_human" }
|
|
131
|
+
});
|
|
132
|
+
if (apiCode === "contributor-limit-exceeded") return cliError({
|
|
133
|
+
code: "contributor_limit_exceeded",
|
|
134
|
+
message: apiMessage ?? "Contributor limit exceeded.",
|
|
135
|
+
why: "This workspace reached the contributor limit for uploads.",
|
|
136
|
+
hint: "Ask an administrator to adjust workspace limits, then retry.",
|
|
137
|
+
agentRecoverable: false,
|
|
138
|
+
requiresHuman: true,
|
|
139
|
+
recovery: { kind: "ask_human" }
|
|
140
|
+
});
|
|
141
|
+
if (apiCode === "quota-exceeded") return cliError({
|
|
142
|
+
code: "storage_limit_exceeded",
|
|
143
|
+
message: "Storage quota is exceeded.",
|
|
144
|
+
why: "The workspace does not have enough remaining storage for this upload.",
|
|
145
|
+
hint: "Reduce the artifact size or ask an administrator to increase storage.",
|
|
146
|
+
agentRecoverable: false,
|
|
147
|
+
requiresHuman: true,
|
|
148
|
+
recovery: { kind: "ask_human" }
|
|
149
|
+
});
|
|
150
|
+
if (apiCode !== null && ["too-large", "file-too-large"].includes(apiCode)) return cliError({
|
|
151
|
+
code: "file_too_large",
|
|
152
|
+
message: apiMessage ?? "The upload is too large.",
|
|
153
|
+
why: "The selected file or directory exceeds the current upload limit.",
|
|
154
|
+
hint: "Reduce generated files and retry.",
|
|
155
|
+
agentRecoverable: true,
|
|
156
|
+
requiresHuman: false,
|
|
157
|
+
recovery: { kind: "change_input" }
|
|
158
|
+
});
|
|
159
|
+
if (apiCode === "too-many-files") return cliError({
|
|
160
|
+
code: "file_count_exceeded",
|
|
161
|
+
message: apiMessage ?? "Too many files in the static site bundle.",
|
|
162
|
+
why: "The directory exceeds the static site file count limit.",
|
|
163
|
+
hint: "Remove generated assets and retry with fewer files.",
|
|
164
|
+
agentRecoverable: true,
|
|
165
|
+
requiresHuman: false,
|
|
166
|
+
recovery: { kind: "change_input" }
|
|
167
|
+
});
|
|
168
|
+
if (apiCode !== null && ["invalid-container"].includes(apiCode)) return cliError({
|
|
169
|
+
code: "project_not_found",
|
|
170
|
+
message: apiMessage ?? "The publish destination is invalid.",
|
|
171
|
+
why: "The project ID does not exist or is not available in this workspace.",
|
|
172
|
+
hint: "Retry with a valid --project-id or use --home.",
|
|
173
|
+
agentRecoverable: true,
|
|
174
|
+
requiresHuman: false,
|
|
175
|
+
recovery: { kind: "change_input" }
|
|
176
|
+
});
|
|
177
|
+
if (apiCode === "thread-not-found") return cliError({
|
|
178
|
+
code: "thread_not_found",
|
|
179
|
+
message: apiMessage ?? "Comment thread was not found.",
|
|
180
|
+
why: "No comment thread with that ID exists on this artifact.",
|
|
181
|
+
hint: "Run npx @artifactshare/cli comments list <artifact-id> --json and retry with a listed thread id.",
|
|
182
|
+
agentRecoverable: true,
|
|
183
|
+
requiresHuman: false,
|
|
184
|
+
recovery: { kind: "change_input" }
|
|
185
|
+
});
|
|
186
|
+
if (apiCode === "thread-resolved") return cliError({
|
|
187
|
+
code: "thread_resolved",
|
|
188
|
+
message: apiMessage ?? "Comment thread is resolved.",
|
|
189
|
+
why: "Resolved threads do not accept new replies.",
|
|
190
|
+
hint: "Reopen the thread in the viewer first, or start a new thread without --reply-to.",
|
|
191
|
+
agentRecoverable: true,
|
|
192
|
+
requiresHuman: false,
|
|
193
|
+
recovery: { kind: "change_input" }
|
|
194
|
+
});
|
|
195
|
+
if (apiCode === "quote-unsupported") return cliError({
|
|
196
|
+
code: "quote_unsupported",
|
|
197
|
+
message: apiMessage ?? "This artifact does not support quoted comments.",
|
|
198
|
+
why: "Quoted-text comments work only on single-file Markdown or HTML artifacts.",
|
|
199
|
+
hint: "Retry without --quote to comment on the whole artifact.",
|
|
200
|
+
agentRecoverable: true,
|
|
201
|
+
requiresHuman: false,
|
|
202
|
+
recovery: { kind: "change_input" }
|
|
203
|
+
});
|
|
204
|
+
if (apiCode === "quote-not-found") return cliError({
|
|
205
|
+
code: "quote_not_found",
|
|
206
|
+
message: apiMessage ?? "The quoted text was not found in the artifact.",
|
|
207
|
+
why: "The --quote value must match the artifact text exactly.",
|
|
208
|
+
hint: "Copy the exact text from npx @artifactshare/cli artifacts get <artifact-id>, or add --quote-before / --quote-after to pick the right occurrence.",
|
|
209
|
+
agentRecoverable: true,
|
|
210
|
+
requiresHuman: false,
|
|
211
|
+
recovery: { kind: "change_input" }
|
|
212
|
+
});
|
|
213
|
+
if (options.artifactTarget && (apiCode === "not-found" || status === 404)) return cliError({
|
|
214
|
+
code: "target_not_found",
|
|
215
|
+
message: apiMessage ?? "Artifact target was not found.",
|
|
216
|
+
why: "The specified artifact does not exist or is not available in the current workspace.",
|
|
217
|
+
hint: "Retry with an artifact ID or share URL that this account can access.",
|
|
218
|
+
agentRecoverable: true,
|
|
219
|
+
requiresHuman: false,
|
|
220
|
+
recovery: { kind: "change_input" }
|
|
221
|
+
});
|
|
222
|
+
if (options.artifactTarget && apiCode === "unsupported-kind") return cliError({
|
|
223
|
+
code: "unsupported_kind",
|
|
224
|
+
message: apiMessage ?? "This artifact cannot be read as a single source file.",
|
|
225
|
+
why: "Static sites and other multi-file artifacts do not have one Markdown or HTML source to read back.",
|
|
226
|
+
hint: "Open the share URL in a browser, or use a supported artifact kind.",
|
|
227
|
+
agentRecoverable: true,
|
|
228
|
+
requiresHuman: false,
|
|
229
|
+
recovery: { kind: "change_input" }
|
|
230
|
+
});
|
|
231
|
+
if (options.artifactTarget && apiCode === "source-unavailable") return cliError({
|
|
232
|
+
code: "source_unavailable",
|
|
233
|
+
message: apiMessage ?? "Artifact source is unavailable.",
|
|
234
|
+
why: "The current version exists but its stored source could not be read.",
|
|
235
|
+
hint: "Retry later. If this repeats, open the share URL and check the artifact.",
|
|
236
|
+
agentRecoverable: true,
|
|
237
|
+
requiresHuman: false,
|
|
238
|
+
recovery: { kind: "retry_later" }
|
|
239
|
+
});
|
|
240
|
+
if (options.artifactTarget && apiCode === "copy-forbidden") return cliError({
|
|
241
|
+
code: "artifact_kind_mismatch",
|
|
242
|
+
message: apiMessage ?? "The selected artifact cannot be updated with this input.",
|
|
243
|
+
why: "Single-file artifacts must be updated with a file, and static-site artifacts must be updated with a directory.",
|
|
244
|
+
hint: "Retry with the same kind of input that was used to create the artifact.",
|
|
245
|
+
agentRecoverable: true,
|
|
246
|
+
requiresHuman: false,
|
|
247
|
+
recovery: { kind: "change_input" }
|
|
248
|
+
});
|
|
249
|
+
if (apiCode === "key-target-moved") return cliError({
|
|
250
|
+
code: "key_target_moved",
|
|
251
|
+
message: apiMessage ?? "The artifact for this key moved.",
|
|
252
|
+
why: "The artifact this key points to now lives in a different destination, so the key no longer updates it.",
|
|
253
|
+
hint: "Find the artifact with resolve --json, then update it by ID or publish with a new key.",
|
|
254
|
+
agentRecoverable: true,
|
|
255
|
+
requiresHuman: false,
|
|
256
|
+
recovery: { kind: "change_input" }
|
|
257
|
+
});
|
|
258
|
+
if (apiCode === "key-kind-mismatch") return cliError({
|
|
259
|
+
code: "key_kind_mismatch",
|
|
260
|
+
message: apiMessage ?? "The artifact for this key is a different kind.",
|
|
261
|
+
why: "The key points to an artifact whose kind (single file or static site) does not match this input.",
|
|
262
|
+
hint: "Check the existing artifact by ID, or publish with a new key.",
|
|
263
|
+
agentRecoverable: true,
|
|
264
|
+
requiresHuman: false,
|
|
265
|
+
recovery: { kind: "change_input" }
|
|
266
|
+
});
|
|
267
|
+
if (apiCode === "key-conflict") return cliError({
|
|
268
|
+
code: "key_conflict",
|
|
269
|
+
message: apiMessage ?? "Another publish created this key first.",
|
|
270
|
+
why: "Two publishes raced to create the same key, and the other one won.",
|
|
271
|
+
hint: "Retry the same command; it will update the artifact the other publish created.",
|
|
272
|
+
agentRecoverable: true,
|
|
273
|
+
requiresHuman: false,
|
|
274
|
+
recovery: { kind: "retry_later" }
|
|
275
|
+
});
|
|
276
|
+
if (apiCode !== null && [
|
|
277
|
+
"unsupported-type",
|
|
278
|
+
"invalid-key",
|
|
279
|
+
"invalid-path",
|
|
280
|
+
"missing-entrypoint",
|
|
281
|
+
"invalid-form-data",
|
|
282
|
+
"invalid-visibility",
|
|
283
|
+
"invalid-grants",
|
|
284
|
+
"missing-file",
|
|
285
|
+
"invalid-artifact-kind",
|
|
286
|
+
"unknown-artifact-kind",
|
|
287
|
+
"too-many-parts",
|
|
288
|
+
"workspace-unavailable"
|
|
289
|
+
].includes(apiCode)) return cliError({
|
|
290
|
+
code: "validation_failed",
|
|
291
|
+
message: apiMessage ?? "The upload input is invalid.",
|
|
292
|
+
why: "The file, directory, or publish options failed server-side validation.",
|
|
293
|
+
hint: "Check the path, file types, and visibility options, then retry.",
|
|
294
|
+
agentRecoverable: true,
|
|
295
|
+
requiresHuman: false,
|
|
296
|
+
recovery: { kind: "change_input" }
|
|
297
|
+
});
|
|
298
|
+
if (status === 400) return cliError({
|
|
299
|
+
code: "validation_failed",
|
|
300
|
+
message: apiMessage ?? "The request input is invalid.",
|
|
301
|
+
why: "Artifact Share rejected the request as invalid.",
|
|
302
|
+
hint: "Check the command input and retry.",
|
|
303
|
+
agentRecoverable: true,
|
|
304
|
+
requiresHuman: false,
|
|
305
|
+
recovery: { kind: "change_input" }
|
|
306
|
+
});
|
|
307
|
+
if (apiCode === "upload-policy-unavailable") return cliError({
|
|
308
|
+
code: "service_unavailable",
|
|
309
|
+
message: apiMessage ?? "Upload permission could not be checked.",
|
|
310
|
+
why: "Artifact Share could not verify upload permission right now.",
|
|
311
|
+
hint: "Retry later with the same command.",
|
|
312
|
+
agentRecoverable: true,
|
|
313
|
+
requiresHuman: false,
|
|
314
|
+
recovery: { kind: "retry_later" }
|
|
315
|
+
});
|
|
316
|
+
return cliError({
|
|
317
|
+
code: "service_error",
|
|
318
|
+
message: apiMessage ?? `Artifact Share returned HTTP ${status}.`,
|
|
319
|
+
why: `The API request failed with status ${status}.`,
|
|
320
|
+
hint: "Check the input and retry. If this repeats, report the response code.",
|
|
321
|
+
agentRecoverable: status >= 500,
|
|
322
|
+
requiresHuman: status >= 500 ? false : status !== 400,
|
|
323
|
+
recovery: { kind: status >= 500 ? "retry_later" : "change_input" },
|
|
324
|
+
details: {
|
|
325
|
+
status,
|
|
326
|
+
api_code: apiCode ?? null
|
|
327
|
+
}
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function serviceError(message) {
|
|
331
|
+
return cliError({
|
|
332
|
+
code: "service_error",
|
|
333
|
+
message,
|
|
334
|
+
why: "Artifact Share returned a success response without required fields.",
|
|
335
|
+
hint: "Retry with --json. If this repeats, report the response.",
|
|
336
|
+
agentRecoverable: true,
|
|
337
|
+
requiresHuman: false,
|
|
338
|
+
recovery: { kind: "retry_later" }
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
function authRequiredError() {
|
|
342
|
+
return cliError({
|
|
343
|
+
code: "auth_required",
|
|
344
|
+
message: "Login is required.",
|
|
345
|
+
why: "No ARTIFACTSHARE_TOKEN or --token value was provided.",
|
|
346
|
+
hint: "Run npx @artifactshare/cli login --profile default, or set ARTIFACTSHARE_TOKEN.",
|
|
347
|
+
agentRecoverable: false,
|
|
348
|
+
requiresHuman: true,
|
|
349
|
+
recovery: { kind: "ask_human" }
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
function tokenInvalidError() {
|
|
353
|
+
return cliError({
|
|
354
|
+
code: "token_invalid",
|
|
355
|
+
message: "The bearer token is invalid or expired.",
|
|
356
|
+
why: "Artifact Share rejected the Authorization bearer token.",
|
|
357
|
+
hint: "Refresh ARTIFACTSHARE_TOKEN or sign in again, then retry.",
|
|
358
|
+
agentRecoverable: false,
|
|
359
|
+
requiresHuman: true,
|
|
360
|
+
recovery: { kind: "ask_human" }
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
function authDeniedError(profile) {
|
|
364
|
+
return cliError({
|
|
365
|
+
code: "auth_denied",
|
|
366
|
+
message: "Login was denied.",
|
|
367
|
+
why: "The device login request was denied in the browser.",
|
|
368
|
+
hint: `Run npx @artifactshare/cli login --profile ${profile} again if you want to sign in.`,
|
|
369
|
+
agentRecoverable: false,
|
|
370
|
+
requiresHuman: true,
|
|
371
|
+
recovery: { kind: "ask_human" },
|
|
372
|
+
details: {
|
|
373
|
+
profile,
|
|
374
|
+
suggested_command: `npx @artifactshare/cli login --profile ${profile}`
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
function authExpiredError(profile) {
|
|
379
|
+
return cliError({
|
|
380
|
+
code: "auth_expired",
|
|
381
|
+
message: "Login expired.",
|
|
382
|
+
why: "The device login was not completed before the code expired.",
|
|
383
|
+
hint: `Run npx @artifactshare/cli login --profile ${profile} again.`,
|
|
384
|
+
agentRecoverable: false,
|
|
385
|
+
requiresHuman: true,
|
|
386
|
+
recovery: { kind: "ask_human" },
|
|
387
|
+
details: {
|
|
388
|
+
profile,
|
|
389
|
+
suggested_command: `npx @artifactshare/cli login --profile ${profile}`
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
function authAccountMismatchError(profile, expectedEmail, actualEmail) {
|
|
394
|
+
return cliError({
|
|
395
|
+
code: "auth_account_mismatch",
|
|
396
|
+
message: "Login used a different account than this profile expects.",
|
|
397
|
+
why: `Profile "${profile}" is already associated with ${expectedEmail}, but the browser approved ${actualEmail}.`,
|
|
398
|
+
hint: "Choose the expected Google account in the browser, or use another --profile name.",
|
|
399
|
+
agentRecoverable: false,
|
|
400
|
+
requiresHuman: true,
|
|
401
|
+
recovery: { kind: "ask_human" },
|
|
402
|
+
details: {
|
|
403
|
+
profile,
|
|
404
|
+
expected_email: expectedEmail,
|
|
405
|
+
actual_email: actualEmail
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
function profileNotFoundError(profile) {
|
|
410
|
+
return cliError({
|
|
411
|
+
code: "profile_not_found",
|
|
412
|
+
message: `Profile "${profile}" was not found.`,
|
|
413
|
+
why: "No saved CLI profile has that name.",
|
|
414
|
+
hint: `Run npx @artifactshare/cli profiles list to see saved profiles, or npx @artifactshare/cli login --profile ${profile} to create it.`,
|
|
415
|
+
agentRecoverable: true,
|
|
416
|
+
requiresHuman: false,
|
|
417
|
+
recovery: { kind: "change_input" },
|
|
418
|
+
details: { profile }
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
function tokenStoreUnavailableError(profile) {
|
|
422
|
+
return cliError({
|
|
423
|
+
code: "token_store_unavailable",
|
|
424
|
+
message: "No safe token store is available.",
|
|
425
|
+
why: "Artifact Share could not find an OS credential store for this environment.",
|
|
426
|
+
hint: `Configure an OS credential store, or rerun login with --allow-plaintext-token-store only if this machine is trusted.`,
|
|
427
|
+
agentRecoverable: false,
|
|
428
|
+
requiresHuman: true,
|
|
429
|
+
recovery: { kind: "ask_human" },
|
|
430
|
+
...profile ? { details: { profile } } : {}
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
function skillUpdateConflictError(path) {
|
|
434
|
+
return cliError({
|
|
435
|
+
code: "skill_update_conflict",
|
|
436
|
+
message: `The file at ${path} is not managed by Artifact Share CLI.`,
|
|
437
|
+
why: "Artifact Share only rewrites or removes skill files it created with a managed marker comment.",
|
|
438
|
+
hint: "Inspect the file and resolve it yourself, or rerun skills install with --force to overwrite it.",
|
|
439
|
+
agentRecoverable: false,
|
|
440
|
+
requiresHuman: true,
|
|
441
|
+
recovery: { kind: "ask_human" },
|
|
442
|
+
details: { path }
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
function unknownCommandError(command) {
|
|
446
|
+
return cliError({
|
|
447
|
+
code: "unknown_command",
|
|
448
|
+
message: `Unknown command: ${command}`,
|
|
449
|
+
why: "The command is not part of Artifact Share CLI.",
|
|
450
|
+
hint: "Run npx @artifactshare/cli --help.",
|
|
451
|
+
agentRecoverable: true,
|
|
452
|
+
requiresHuman: false,
|
|
453
|
+
recovery: {
|
|
454
|
+
kind: "run_command",
|
|
455
|
+
command: "npx @artifactshare/cli --help"
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
function normalizeApiCode(value) {
|
|
460
|
+
return typeof value === "string" ? value : null;
|
|
461
|
+
}
|
|
462
|
+
function uploadBlockedHint(code) {
|
|
463
|
+
if (code === "upload-not-allowed") return `Run ${REQUEST_ACCESS_COMMAND$1} to join the waitlist, then retry publish once an operator opens publishing.`;
|
|
464
|
+
if (code === "upload-policy-unavailable") return "Retry doctor later; upload permission could not be checked.";
|
|
465
|
+
return "Resolve the upload issue, then retry publish.";
|
|
466
|
+
}
|
|
467
|
+
function projectNotFoundByNameError() {
|
|
468
|
+
return cliError({
|
|
469
|
+
code: "project_not_found",
|
|
470
|
+
message: "The publish destination project was not found.",
|
|
471
|
+
why: "No project in the current workspace matches the given project name exactly.",
|
|
472
|
+
hint: `Run ${PROJECTS_LIST_COMMAND}, then retry with --project-id <id>.`,
|
|
473
|
+
agentRecoverable: true,
|
|
474
|
+
requiresHuman: false,
|
|
475
|
+
recovery: {
|
|
476
|
+
kind: "run_command",
|
|
477
|
+
command: PROJECTS_LIST_COMMAND
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
function projectAmbiguousError(candidates) {
|
|
482
|
+
return cliError({
|
|
483
|
+
code: "project_ambiguous",
|
|
484
|
+
message: "The publish destination project is ambiguous.",
|
|
485
|
+
why: "Multiple projects in the current workspace match the given project name exactly.",
|
|
486
|
+
hint: "Retry with --project-id <id> from the candidates.",
|
|
487
|
+
agentRecoverable: true,
|
|
488
|
+
requiresHuman: false,
|
|
489
|
+
recovery: { kind: "change_input" },
|
|
490
|
+
details: { candidates }
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
function validationError(message, hint, code = "validation_failed") {
|
|
494
|
+
return cliError({
|
|
495
|
+
code,
|
|
496
|
+
message,
|
|
497
|
+
why: "The command input is not valid.",
|
|
498
|
+
hint,
|
|
499
|
+
agentRecoverable: true,
|
|
500
|
+
requiresHuman: false,
|
|
501
|
+
recovery: { kind: "change_input" }
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
function networkError(error) {
|
|
505
|
+
return cliError({
|
|
506
|
+
code: "network_failed",
|
|
507
|
+
message: "Network request failed.",
|
|
508
|
+
why: error instanceof Error ? error.message : "Artifact Share could not be reached.",
|
|
509
|
+
hint: "Check the base URL and network connection, then retry.",
|
|
510
|
+
agentRecoverable: true,
|
|
511
|
+
requiresHuman: false,
|
|
512
|
+
recovery: { kind: "retry_later" }
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
function unexpectedError(error) {
|
|
516
|
+
return cliError({
|
|
517
|
+
code: "unexpected_error",
|
|
518
|
+
message: "Unexpected error.",
|
|
519
|
+
why: error instanceof Error ? error.message : String(error),
|
|
520
|
+
hint: "Retry with --json and report the error if it repeats.",
|
|
521
|
+
agentRecoverable: false,
|
|
522
|
+
requiresHuman: true,
|
|
523
|
+
recovery: { kind: "report_issue" }
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
function cliError(args) {
|
|
527
|
+
return {
|
|
528
|
+
code: args.code,
|
|
529
|
+
message: args.message,
|
|
530
|
+
why: args.why,
|
|
531
|
+
hint: args.hint,
|
|
532
|
+
agent_recoverable: args.agentRecoverable,
|
|
533
|
+
requires_human: args.requiresHuman,
|
|
534
|
+
recovery: args.recovery,
|
|
535
|
+
...args.details ? { details: args.details } : {}
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
//#endregion
|
|
539
|
+
//#region src/shared.ts
|
|
540
|
+
function arrayOption(value) {
|
|
541
|
+
if (value === void 0) return [];
|
|
542
|
+
return Array.isArray(value) ? value : [value];
|
|
543
|
+
}
|
|
544
|
+
function parseOffsetOption(value) {
|
|
545
|
+
if (value === void 0) return { value: void 0 };
|
|
546
|
+
if (!/^\d+$/.test(value)) return { error: validationError("--offset must be a non-negative integer.", "Retry with --offset set to next_offset from the previous response.") };
|
|
547
|
+
return { value };
|
|
548
|
+
}
|
|
549
|
+
function parseIncludeOptions(value) {
|
|
550
|
+
const values = [];
|
|
551
|
+
for (const raw of arrayOption(value)) for (const item of raw.split(",")) {
|
|
552
|
+
const trimmed = item.trim();
|
|
553
|
+
if (!trimmed) continue;
|
|
554
|
+
if (trimmed !== "versions" && trimmed !== "comments") return { error: validationError(`Unsupported include value: ${trimmed}`, "Use --include versions or --include comments.") };
|
|
555
|
+
values.push(trimmed);
|
|
556
|
+
}
|
|
557
|
+
return { values: [...new Set(values)] };
|
|
558
|
+
}
|
|
559
|
+
function unsupportedUpdateOption(options) {
|
|
560
|
+
for (const key of Object.keys(options)) if (!UPDATE_OPTION_KEYS.has(key)) return kebabCase(key);
|
|
561
|
+
return null;
|
|
562
|
+
}
|
|
563
|
+
function resolveArtifactId(input) {
|
|
564
|
+
const trimmed = input.trim();
|
|
565
|
+
if (/^[A-Za-z0-9]+$/.test(trimmed)) return trimmed;
|
|
566
|
+
let url;
|
|
567
|
+
try {
|
|
568
|
+
url = new URL(trimmed);
|
|
569
|
+
} catch {
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
const sandboxMatch = url.hostname.match(/^([A-Za-z0-9]+)\.sandbox\./);
|
|
573
|
+
if (sandboxMatch?.[1]) return sandboxMatch[1];
|
|
574
|
+
const shareMatch = url.pathname.match(/^\/a\/([A-Za-z0-9]+)(?:\.data)?\/?$/);
|
|
575
|
+
if (shareMatch?.[1]) return shareMatch[1];
|
|
576
|
+
return null;
|
|
577
|
+
}
|
|
578
|
+
const TARGET_COMMAND_LABELS = {
|
|
579
|
+
update: "Update",
|
|
580
|
+
"artifacts get": "Artifacts get",
|
|
581
|
+
download: "Download",
|
|
582
|
+
"comments list": "Comments list",
|
|
583
|
+
"comments post": "Comments post"
|
|
584
|
+
};
|
|
585
|
+
function targetResolutionError(input, command) {
|
|
586
|
+
return cliError({
|
|
587
|
+
code: "target_not_found",
|
|
588
|
+
message: "Artifact target could not be resolved.",
|
|
589
|
+
why: `${TARGET_COMMAND_LABELS[command]} only accepts an artifact ID, share URL, or sandbox URL.`,
|
|
590
|
+
hint: "Retry with an artifact ID, /a/<id> share URL, or sandbox URL. If you only have a title, resolve it to an ID first.",
|
|
591
|
+
agentRecoverable: true,
|
|
592
|
+
requiresHuman: false,
|
|
593
|
+
recovery: { kind: "change_input" },
|
|
594
|
+
details: { input }
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
function parseArtifactTarget(input, command, missingHint) {
|
|
598
|
+
if (!input) return { error: validationError("Artifact is required.", missingHint) };
|
|
599
|
+
const artifactId = resolveArtifactId(input);
|
|
600
|
+
if (!artifactId) return { error: targetResolutionError(input, command) };
|
|
601
|
+
return { artifactId };
|
|
602
|
+
}
|
|
603
|
+
function camelCase(value) {
|
|
604
|
+
return value.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
|
|
605
|
+
}
|
|
606
|
+
function kebabCase(value) {
|
|
607
|
+
return value.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);
|
|
608
|
+
}
|
|
609
|
+
//#endregion
|
|
610
|
+
//#region src/args.ts
|
|
611
|
+
function parsedArgsFromContext(command, ctx) {
|
|
612
|
+
const options = optionsFromContext(ctx);
|
|
613
|
+
if (command === "update") for (const token of ctx.tokens) {
|
|
614
|
+
if (token.kind !== "option") continue;
|
|
615
|
+
const rawName = token.name ?? token.rawName?.replace(/^--?/, "");
|
|
616
|
+
if (!rawName) continue;
|
|
617
|
+
const name = camelCase(rawName);
|
|
618
|
+
if (options[name] === void 0 && !UPDATE_OPTION_KEYS.has(name)) options[name] = true;
|
|
619
|
+
}
|
|
620
|
+
return {
|
|
621
|
+
command,
|
|
622
|
+
options,
|
|
623
|
+
positionals: ctx.positionals.slice(command.includes(" ") ? 2 : 1)
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
function optionsFromContext(ctx) {
|
|
627
|
+
const options = {};
|
|
628
|
+
for (const [key, value] of Object.entries(ctx.values)) {
|
|
629
|
+
if (ctx.args[key]?.type === "positional") continue;
|
|
630
|
+
if (value === void 0) continue;
|
|
631
|
+
if (typeof value === "boolean" || typeof value === "string" || Array.isArray(value) && value.every((item) => typeof item === "string")) options[key] = value;
|
|
632
|
+
}
|
|
633
|
+
return options;
|
|
634
|
+
}
|
|
635
|
+
function joinLeadingDashValues(argv) {
|
|
636
|
+
const result = [];
|
|
637
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
638
|
+
const arg = argv[i] ?? "";
|
|
639
|
+
const next = argv[i + 1];
|
|
640
|
+
if (arg.startsWith("--") && !arg.includes("=") && VALUE_FLAGS.has(arg.slice(2)) && next !== void 0 && next.startsWith("-") && !isKnownFlagToken(next)) {
|
|
641
|
+
result.push(`${arg}=${next}`);
|
|
642
|
+
i += 1;
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
result.push(arg);
|
|
646
|
+
}
|
|
647
|
+
return result;
|
|
648
|
+
}
|
|
649
|
+
function isKnownFlagToken(token) {
|
|
650
|
+
if (token === "--") return true;
|
|
651
|
+
if (!token.startsWith("--")) return false;
|
|
652
|
+
const eqIndex = token.indexOf("=");
|
|
653
|
+
const name = eqIndex === -1 ? token.slice(2) : token.slice(2, eqIndex);
|
|
654
|
+
return BOOLEAN_FLAGS.has(name) || VALUE_FLAGS.has(name) || name === "help" || name === "version";
|
|
655
|
+
}
|
|
656
|
+
function validateRawArgs(argv) {
|
|
657
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
658
|
+
const arg = argv[i] ?? "";
|
|
659
|
+
if (!arg.startsWith("--")) continue;
|
|
660
|
+
const eqIndex = arg.indexOf("=");
|
|
661
|
+
if (eqIndex === -1) {
|
|
662
|
+
const rawName = arg.slice(2);
|
|
663
|
+
if (VALUE_FLAGS.has(rawName) && (argv[i + 1] === void 0 || argv[i + 1] === "")) return validationError(`--${rawName} requires a value.`, `Pass --${rawName} <value> and retry.`);
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
const rawName = arg.slice(2, eqIndex);
|
|
667
|
+
const value = arg.slice(eqIndex + 1);
|
|
668
|
+
if (BOOLEAN_FLAGS.has(rawName)) return validationError(`--${rawName} does not accept a value.`, `Use --${rawName} without =value.`);
|
|
669
|
+
if (VALUE_FLAGS.has(rawName) && value === "") return validationError(`--${rawName} requires a value.`, `Pass --${rawName} <value> and retry.`);
|
|
670
|
+
}
|
|
671
|
+
return null;
|
|
672
|
+
}
|
|
673
|
+
function commandNameFromArgv(argv) {
|
|
674
|
+
const found = findCommandCandidate(argv);
|
|
675
|
+
const command = found?.command;
|
|
676
|
+
if (found && command !== void 0 && SUBCOMMANDS[command]) {
|
|
677
|
+
const sub = nextPositional(argv, found.index);
|
|
678
|
+
if (sub !== void 0 && SUBCOMMANDS[command].includes(sub)) return `${command} ${sub}`;
|
|
679
|
+
}
|
|
680
|
+
return command !== void 0 && COMMAND_NAMES.has(command) ? command : void 0;
|
|
681
|
+
}
|
|
682
|
+
function firstCommandCandidate(argv) {
|
|
683
|
+
return findCommandCandidate(argv)?.command;
|
|
684
|
+
}
|
|
685
|
+
function findCommandCandidate(argv) {
|
|
686
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
687
|
+
const arg = argv[i] ?? "";
|
|
688
|
+
if (arg === "--") {
|
|
689
|
+
const command = argv[i + 1];
|
|
690
|
+
return command === void 0 ? void 0 : {
|
|
691
|
+
command,
|
|
692
|
+
index: i + 1
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
if (!arg.startsWith("--")) return {
|
|
696
|
+
command: arg,
|
|
697
|
+
index: i
|
|
698
|
+
};
|
|
699
|
+
const eqIndex = arg.indexOf("=");
|
|
700
|
+
const rawName = eqIndex === -1 ? arg.slice(2) : arg.slice(2, eqIndex);
|
|
701
|
+
if (eqIndex === -1 && VALUE_FLAGS.has(rawName)) i += 1;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
function nextPositional(argv, afterIndex) {
|
|
705
|
+
const index = nextPositionalIndex(argv, afterIndex);
|
|
706
|
+
return index === void 0 ? void 0 : argv[index];
|
|
707
|
+
}
|
|
708
|
+
function nextPositionalIndex(argv, afterIndex) {
|
|
709
|
+
for (let i = afterIndex + 1; i < argv.length; i += 1) {
|
|
710
|
+
const arg = argv[i] ?? "";
|
|
711
|
+
if (arg === "--") return i + 1 < argv.length ? i + 1 : void 0;
|
|
712
|
+
if (!arg.startsWith("--")) return i;
|
|
713
|
+
const eqIndex = arg.indexOf("=");
|
|
714
|
+
const rawName = eqIndex === -1 ? arg.slice(2) : arg.slice(2, eqIndex);
|
|
715
|
+
if (eqIndex === -1 && VALUE_FLAGS.has(rawName)) i += 1;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
function normalizeArgvForGunshi(argv, commandCandidate) {
|
|
719
|
+
if (commandCandidate === void 0) return argv;
|
|
720
|
+
const found = findCommandCandidate(argv);
|
|
721
|
+
if (!found) return argv;
|
|
722
|
+
const subIndex = SUBCOMMANDS[found.command] ? nextPositionalIndex(argv, found.index) : void 0;
|
|
723
|
+
const sub = subIndex === void 0 ? void 0 : argv[subIndex];
|
|
724
|
+
const hoistSub = sub !== void 0 && SUBCOMMANDS[found.command]?.includes(sub);
|
|
725
|
+
if (found.index === 0 && (!hoistSub || subIndex === found.index + 1)) return argv;
|
|
726
|
+
const rest = argv.filter((_, index) => index !== found.index && !(hoistSub && index === subIndex));
|
|
727
|
+
const head = argv[found.index] ?? commandCandidate;
|
|
728
|
+
return hoistSub && sub !== void 0 ? [
|
|
729
|
+
head,
|
|
730
|
+
sub,
|
|
731
|
+
...rest
|
|
732
|
+
] : [head, ...rest];
|
|
733
|
+
}
|
|
734
|
+
//#endregion
|
|
735
|
+
//#region src/validators.ts
|
|
736
|
+
function isRecord(value) {
|
|
737
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
738
|
+
}
|
|
739
|
+
function nonEmpty(value) {
|
|
740
|
+
if (typeof value !== "string") return void 0;
|
|
741
|
+
const trimmed = value.trim();
|
|
742
|
+
return trimmed ? trimmed : void 0;
|
|
743
|
+
}
|
|
744
|
+
//#endregion
|
|
745
|
+
//#region src/output.ts
|
|
746
|
+
function outputModeFromArgv(argv) {
|
|
747
|
+
return outputMode({ json: argv.includes("--json") });
|
|
748
|
+
}
|
|
749
|
+
function outputMode(options) {
|
|
750
|
+
return { json: Boolean(options.json) || process.env.CI === "true" || !process.stdout.isTTY };
|
|
751
|
+
}
|
|
752
|
+
function writeSuccess(command, data, mode) {
|
|
753
|
+
if (!mode.json && command === "publish" && !publishSuccessFields(data)) return writeFailure(command, serviceError("Publish succeeded but the response did not include an artifact id and URL."), mode, 1);
|
|
754
|
+
const payload = {
|
|
755
|
+
schema_version: 1,
|
|
756
|
+
ok: true,
|
|
757
|
+
command,
|
|
758
|
+
data
|
|
759
|
+
};
|
|
760
|
+
if (mode.json) {
|
|
761
|
+
process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
process.stdout.write(humanSuccess(command, data));
|
|
765
|
+
}
|
|
766
|
+
function writeFailure(command, error, mode, exitCode) {
|
|
767
|
+
const payload = {
|
|
768
|
+
schema_version: 1,
|
|
769
|
+
ok: false,
|
|
770
|
+
command,
|
|
771
|
+
error
|
|
772
|
+
};
|
|
773
|
+
if (mode.json) process.stderr.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
774
|
+
else process.stderr.write(`Error: ${error.message}\nWhy: ${error.why}\nHint: ${error.hint}\n`);
|
|
775
|
+
process.exitCode = exitCode;
|
|
776
|
+
}
|
|
777
|
+
function writeText(text) {
|
|
778
|
+
process.stdout.write(text);
|
|
779
|
+
}
|
|
780
|
+
function writeEvent(data) {
|
|
781
|
+
process.stderr.write(`${JSON.stringify(data)}\n`);
|
|
782
|
+
}
|
|
783
|
+
function humanSuccess(command, data) {
|
|
784
|
+
if (command === "publish") {
|
|
785
|
+
const fields = publishSuccessFields(data);
|
|
786
|
+
if (!fields) return `${JSON.stringify(data, null, 2)}\n`;
|
|
787
|
+
return [
|
|
788
|
+
"Published",
|
|
789
|
+
`Artifact ID: ${fields.artifactId}`,
|
|
790
|
+
`URL: ${fields.url}`,
|
|
791
|
+
`Destination: ${fields.destinationType}${fields.projectId ? ` (${fields.projectId})` : ""}`,
|
|
792
|
+
`Visibility: ${fields.visibility}`,
|
|
793
|
+
""
|
|
794
|
+
].join("\n");
|
|
795
|
+
}
|
|
796
|
+
if (command === "doctor") return doctorHumanOutput(data);
|
|
797
|
+
return `${JSON.stringify(data, null, 2)}\n`;
|
|
798
|
+
}
|
|
799
|
+
function doctorHumanOutput(data) {
|
|
800
|
+
const nextCommand = doctorNextCommand(data);
|
|
801
|
+
const body = `${JSON.stringify(data, null, 2)}`;
|
|
802
|
+
if (!nextCommand) return `${body}\n`;
|
|
803
|
+
return `${body}\n${nextCommand}\n`;
|
|
804
|
+
}
|
|
805
|
+
function doctorNextCommand(data) {
|
|
806
|
+
if (!isRecord(data) || !("next_command" in data)) return null;
|
|
807
|
+
return typeof data.next_command === "string" ? data.next_command : null;
|
|
808
|
+
}
|
|
809
|
+
function publishSuccessFields(data) {
|
|
810
|
+
if (!isRecord(data)) return null;
|
|
811
|
+
const artifact = data.artifact;
|
|
812
|
+
const destination = data.destination;
|
|
813
|
+
const share = data.share;
|
|
814
|
+
if (!isRecord(artifact) || !isRecord(destination) || !isRecord(share)) return null;
|
|
815
|
+
if (typeof artifact.id !== "string" || typeof artifact.url !== "string" || typeof destination.type !== "string" || typeof share.visibility !== "string") return null;
|
|
816
|
+
return {
|
|
817
|
+
artifactId: artifact.id,
|
|
818
|
+
url: artifact.url,
|
|
819
|
+
destinationType: destination.type,
|
|
820
|
+
projectId: typeof destination.project_id === "string" ? destination.project_id : null,
|
|
821
|
+
visibility: share.visibility
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
function updateSuccessFields(data) {
|
|
825
|
+
if (!isRecord(data)) return null;
|
|
826
|
+
const artifact = data.artifact;
|
|
827
|
+
const version = data.version;
|
|
828
|
+
if (!isRecord(artifact) || !isRecord(version)) return null;
|
|
829
|
+
if (typeof artifact.id !== "string" || typeof artifact.url !== "string" || typeof version.id !== "string") return null;
|
|
830
|
+
return {
|
|
831
|
+
artifactId: artifact.id,
|
|
832
|
+
url: artifact.url,
|
|
833
|
+
versionId: version.id
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
function resolveSuccessFields(data) {
|
|
837
|
+
if (!isRecord(data)) return false;
|
|
838
|
+
return typeof data.query === "string" && Array.isArray(data.candidates) && typeof data.has_more === "boolean";
|
|
839
|
+
}
|
|
840
|
+
function artifactGetSuccessFields(data) {
|
|
841
|
+
if (!isRecord(data)) return false;
|
|
842
|
+
return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && (data.format === "html" || data.format === "markdown") && typeof data.content === "string" && typeof data.size_bytes === "number" && typeof data.truncated === "boolean" && (typeof data.next_offset === "number" || data.next_offset === null);
|
|
843
|
+
}
|
|
844
|
+
function downloadManifestFields(data) {
|
|
845
|
+
if (!isRecord(data)) return false;
|
|
846
|
+
return typeof data.id === "string" && typeof data.share_url === "string" && typeof data.version_id === "string" && typeof data.artifact_kind === "string" && Array.isArray(data.files) && data.files.every(downloadManifestFileFields) && typeof data.total_size_bytes === "number";
|
|
847
|
+
}
|
|
848
|
+
function downloadManifestFileFields(data) {
|
|
849
|
+
if (!isRecord(data)) return false;
|
|
850
|
+
return typeof data.path === "string" && typeof data.size_bytes === "number" && typeof data.content_type === "string" && typeof data.sha256 === "string";
|
|
851
|
+
}
|
|
852
|
+
//#endregion
|
|
853
|
+
//#region src/api.ts
|
|
854
|
+
let insecureLocalhostDispatcher;
|
|
855
|
+
function baseUrlOf(options) {
|
|
856
|
+
return String(options.baseUrl ?? process.env.ARTIFACTSHARE_BASE_URL ?? "https://artifactshare.com").replace(/\/$/, "");
|
|
857
|
+
}
|
|
858
|
+
function requestConfig(options) {
|
|
859
|
+
if (!insecureLocalhostEnabled(options)) return { init: {} };
|
|
860
|
+
const baseUrl = baseUrlOf(options);
|
|
861
|
+
const url = new URL(baseUrl);
|
|
862
|
+
if (url.protocol !== "https:" || !isLocalHostname(url.hostname)) return { error: validationError("--insecure-localhost only works with local HTTPS base URLs.", "Use it only with https://localhost, https://127.0.0.1, or https://[::1].") };
|
|
863
|
+
return { init: { dispatcher: insecureLocalhostDispatcher ??= new Agent({ connect: { rejectUnauthorized: false } }) } };
|
|
864
|
+
}
|
|
865
|
+
function insecureLocalhostEnabled(options) {
|
|
866
|
+
return Boolean(options.insecureLocalhost) || process.env.ARTIFACTSHARE_INSECURE_LOCALHOST === "1";
|
|
867
|
+
}
|
|
868
|
+
function isLocalHostname(hostname) {
|
|
869
|
+
return [
|
|
870
|
+
"localhost",
|
|
871
|
+
"127.0.0.1",
|
|
872
|
+
"::1",
|
|
873
|
+
"[::1]"
|
|
874
|
+
].includes(hostname.toLowerCase());
|
|
875
|
+
}
|
|
876
|
+
function apiUrl(path, baseUrl) {
|
|
877
|
+
const url = new URL(baseUrl);
|
|
878
|
+
url.pathname = `${url.pathname.replace(/\/$/, "")}${path}`;
|
|
879
|
+
url.search = "";
|
|
880
|
+
url.hash = "";
|
|
881
|
+
return url;
|
|
882
|
+
}
|
|
883
|
+
function downloadFileUrl(baseUrl, artifactId, filePath) {
|
|
884
|
+
const encodedPath = filePath.split("/").filter(Boolean).map((segment) => encodeURIComponent(segment)).join("/");
|
|
885
|
+
return apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/download/${encodedPath}`, baseUrl);
|
|
886
|
+
}
|
|
887
|
+
async function readJson(response) {
|
|
888
|
+
return await response.json().catch(() => null);
|
|
889
|
+
}
|
|
890
|
+
async function apiGet(path, token, options, init, errorOptions = {}) {
|
|
891
|
+
return await apiRequest(path, options, {
|
|
892
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
893
|
+
...init
|
|
894
|
+
}, errorOptions);
|
|
895
|
+
}
|
|
896
|
+
async function apiPost(path, token, payload, options, init, errorOptions = {}) {
|
|
897
|
+
return await apiRequest(path, options, {
|
|
898
|
+
method: "POST",
|
|
899
|
+
headers: {
|
|
900
|
+
Authorization: `Bearer ${token}`,
|
|
901
|
+
"content-type": "application/json"
|
|
902
|
+
},
|
|
903
|
+
body: JSON.stringify(payload),
|
|
904
|
+
...init
|
|
905
|
+
}, errorOptions);
|
|
906
|
+
}
|
|
907
|
+
async function apiRequest(path, options, init, errorOptions) {
|
|
908
|
+
const response = await fetch(apiUrl(path, baseUrlOf(options)), init).catch((error) => ({ networkError: error }));
|
|
909
|
+
if ("networkError" in response) return { error: networkError(response.networkError) };
|
|
910
|
+
const body = await readJson(response);
|
|
911
|
+
if (!response.ok) return { error: mapApiError(response.status, body, {
|
|
912
|
+
authenticated: true,
|
|
913
|
+
...errorOptions
|
|
914
|
+
}) };
|
|
915
|
+
return { body };
|
|
916
|
+
}
|
|
917
|
+
//#endregion
|
|
918
|
+
//#region src/process.ts
|
|
919
|
+
function spawnFile(command, args, input) {
|
|
920
|
+
return new Promise((resolve) => {
|
|
921
|
+
const child = spawn(command, args, { stdio: [
|
|
922
|
+
"pipe",
|
|
923
|
+
"pipe",
|
|
924
|
+
"pipe"
|
|
925
|
+
] });
|
|
926
|
+
let stdout = "";
|
|
927
|
+
let stderr = "";
|
|
928
|
+
child.stdout.setEncoding("utf8");
|
|
929
|
+
child.stderr.setEncoding("utf8");
|
|
930
|
+
child.stdout.on("data", (chunk) => {
|
|
931
|
+
stdout += chunk;
|
|
932
|
+
});
|
|
933
|
+
child.stderr.on("data", (chunk) => {
|
|
934
|
+
stderr += chunk;
|
|
935
|
+
});
|
|
936
|
+
child.on("error", (error) => {
|
|
937
|
+
resolve({
|
|
938
|
+
status: 127,
|
|
939
|
+
stdout,
|
|
940
|
+
stderr: error.message
|
|
941
|
+
});
|
|
942
|
+
});
|
|
943
|
+
child.on("close", (status) => {
|
|
944
|
+
resolve({
|
|
945
|
+
status,
|
|
946
|
+
stdout,
|
|
947
|
+
stderr
|
|
948
|
+
});
|
|
949
|
+
});
|
|
950
|
+
if (input) child.stdin.end(input);
|
|
951
|
+
else child.stdin.end();
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
//#endregion
|
|
955
|
+
//#region src/destination.ts
|
|
956
|
+
function destinationConflictError(options) {
|
|
957
|
+
const projectName = nonEmpty(options.project);
|
|
958
|
+
if (options.home && (options.projectId || projectName)) return validationError("Choose either --home or a project destination.", "Remove one destination option and retry.", "destination_conflict");
|
|
959
|
+
if (projectName && options.projectId) return validationError("Choose either --project or --project-id.", "Remove one destination option and retry.", "destination_conflict");
|
|
960
|
+
return null;
|
|
961
|
+
}
|
|
962
|
+
function resolveDestination(options, config) {
|
|
963
|
+
const conflict = destinationConflictError(options);
|
|
964
|
+
if (conflict) return { error: conflict };
|
|
965
|
+
if (options.home) return { containerId: null };
|
|
966
|
+
const containerId = options.projectId ?? config?.default_project_id ?? null;
|
|
967
|
+
if (containerId) return { containerId };
|
|
968
|
+
return { error: cliError({
|
|
969
|
+
code: "destination_required",
|
|
970
|
+
message: "A publish destination is required.",
|
|
971
|
+
why: "Non-interactive publish never guesses a project or home destination.",
|
|
972
|
+
hint: "Retry with --project-id <id>, configure .artifactshare/config.json, or pass --home.",
|
|
973
|
+
agentRecoverable: true,
|
|
974
|
+
requiresHuman: false,
|
|
975
|
+
recovery: { kind: "change_input" }
|
|
976
|
+
}) };
|
|
977
|
+
}
|
|
978
|
+
const PROJECT_CONFIG_PATH = ".artifactshare/config.json";
|
|
979
|
+
function projectConfigPath() {
|
|
980
|
+
return resolve(process.cwd(), PROJECT_CONFIG_PATH);
|
|
981
|
+
}
|
|
982
|
+
async function readProjectConfig() {
|
|
983
|
+
return await readJsonFile(projectConfigPath());
|
|
984
|
+
}
|
|
985
|
+
async function readRawProjectConfig() {
|
|
986
|
+
return await readJsonFile(projectConfigPath());
|
|
987
|
+
}
|
|
988
|
+
function configString(value) {
|
|
989
|
+
return nonEmpty(typeof value === "string" ? value : void 0) ?? null;
|
|
990
|
+
}
|
|
991
|
+
async function readJsonFile(path) {
|
|
992
|
+
const text = await readFile(path, "utf8").catch(() => null);
|
|
993
|
+
if (!text) return null;
|
|
994
|
+
try {
|
|
995
|
+
return JSON.parse(text);
|
|
996
|
+
} catch {
|
|
997
|
+
return null;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
//#endregion
|
|
1001
|
+
//#region src/token-store.ts
|
|
1002
|
+
const SERVICE = "artifactshare-cli";
|
|
1003
|
+
async function readProfileToken(profile, options) {
|
|
1004
|
+
const account = accountName(profile, baseUrlOf(options));
|
|
1005
|
+
const native = await nativeStore();
|
|
1006
|
+
if (native) {
|
|
1007
|
+
const token = await native.read(account);
|
|
1008
|
+
if (token) return {
|
|
1009
|
+
ok: true,
|
|
1010
|
+
token,
|
|
1011
|
+
store: native.kind
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
const plaintext = await readPlaintextToken(account);
|
|
1015
|
+
if (plaintext) return {
|
|
1016
|
+
ok: true,
|
|
1017
|
+
token: plaintext,
|
|
1018
|
+
store: "plaintext_file"
|
|
1019
|
+
};
|
|
1020
|
+
return {
|
|
1021
|
+
ok: false,
|
|
1022
|
+
reason: native || options.allowPlaintextTokenStore ? "missing" : "unavailable"
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
async function saveProfileToken(profile, token, options) {
|
|
1026
|
+
const account = accountName(profile, baseUrlOf(options));
|
|
1027
|
+
const native = await nativeStore();
|
|
1028
|
+
if (native && await native.write(account, token)) return {
|
|
1029
|
+
ok: true,
|
|
1030
|
+
store: native.kind
|
|
1031
|
+
};
|
|
1032
|
+
if (options.allowPlaintextTokenStore && await writePlaintextToken(account, token)) return {
|
|
1033
|
+
ok: true,
|
|
1034
|
+
store: "plaintext_file"
|
|
1035
|
+
};
|
|
1036
|
+
return {
|
|
1037
|
+
ok: false,
|
|
1038
|
+
reason: "unavailable"
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
async function readGlobalConfig() {
|
|
1042
|
+
const home = configHome();
|
|
1043
|
+
if (!home) return null;
|
|
1044
|
+
return await readJsonFile(join(home, "config.json"));
|
|
1045
|
+
}
|
|
1046
|
+
async function writeGlobalConfig(config) {
|
|
1047
|
+
const home = configHome();
|
|
1048
|
+
if (!home) return false;
|
|
1049
|
+
await mkdir(home, {
|
|
1050
|
+
recursive: true,
|
|
1051
|
+
mode: 448
|
|
1052
|
+
});
|
|
1053
|
+
await writeFile(join(home, "config.json"), `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
|
|
1054
|
+
return true;
|
|
1055
|
+
}
|
|
1056
|
+
function accountName(profile, baseUrl) {
|
|
1057
|
+
return `${baseUrl}:${profile}`;
|
|
1058
|
+
}
|
|
1059
|
+
let nativeStorePromise;
|
|
1060
|
+
function nativeStore() {
|
|
1061
|
+
if (process.env.ARTIFACTSHARE_DISABLE_NATIVE_TOKEN_STORE === "1") return Promise.resolve(null);
|
|
1062
|
+
return nativeStorePromise ??= detectNativeStore();
|
|
1063
|
+
}
|
|
1064
|
+
async function detectNativeStore() {
|
|
1065
|
+
if (process.platform === "darwin") return macosKeychain();
|
|
1066
|
+
if (process.platform === "linux") return await linuxSecretService();
|
|
1067
|
+
return null;
|
|
1068
|
+
}
|
|
1069
|
+
function macosKeychain() {
|
|
1070
|
+
return {
|
|
1071
|
+
kind: "macos_keychain",
|
|
1072
|
+
read: async (account) => {
|
|
1073
|
+
const result = await spawnFile("security", [
|
|
1074
|
+
"find-generic-password",
|
|
1075
|
+
"-s",
|
|
1076
|
+
SERVICE,
|
|
1077
|
+
"-a",
|
|
1078
|
+
account,
|
|
1079
|
+
"-w"
|
|
1080
|
+
]);
|
|
1081
|
+
return result.status === 0 ? result.stdout.trim() || null : null;
|
|
1082
|
+
},
|
|
1083
|
+
write: async (account, token) => {
|
|
1084
|
+
return (await spawnFile("security", ["-i"], `${[
|
|
1085
|
+
"add-generic-password",
|
|
1086
|
+
"-U",
|
|
1087
|
+
"-s",
|
|
1088
|
+
securityQuote(SERVICE),
|
|
1089
|
+
"-a",
|
|
1090
|
+
securityQuote(account),
|
|
1091
|
+
"-w",
|
|
1092
|
+
securityQuote(token)
|
|
1093
|
+
].join(" ")}\n`)).status === 0;
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
function securityQuote(value) {
|
|
1098
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
1099
|
+
}
|
|
1100
|
+
async function linuxSecretService() {
|
|
1101
|
+
if ((await spawnFile("secret-tool", ["--version"])).status !== 0) return null;
|
|
1102
|
+
return {
|
|
1103
|
+
kind: "linux_secret_service",
|
|
1104
|
+
read: async (account) => {
|
|
1105
|
+
const result = await spawnFile("secret-tool", [
|
|
1106
|
+
"lookup",
|
|
1107
|
+
"service",
|
|
1108
|
+
SERVICE,
|
|
1109
|
+
"account",
|
|
1110
|
+
account
|
|
1111
|
+
]);
|
|
1112
|
+
return result.status === 0 ? result.stdout.trim() || null : null;
|
|
1113
|
+
},
|
|
1114
|
+
write: async (account, token) => {
|
|
1115
|
+
return (await spawnFile("secret-tool", [
|
|
1116
|
+
"store",
|
|
1117
|
+
"--label",
|
|
1118
|
+
`Artifact Share ${account}`,
|
|
1119
|
+
"service",
|
|
1120
|
+
SERVICE,
|
|
1121
|
+
"account",
|
|
1122
|
+
account
|
|
1123
|
+
], token)).status === 0;
|
|
1124
|
+
}
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
async function readPlaintextToken(account) {
|
|
1128
|
+
const token = (await readPlaintextTokens())?.[account];
|
|
1129
|
+
return typeof token === "string" && token ? token : null;
|
|
1130
|
+
}
|
|
1131
|
+
async function writePlaintextToken(account, token) {
|
|
1132
|
+
const home = configHome();
|
|
1133
|
+
if (!home) return false;
|
|
1134
|
+
const tokens = await readPlaintextTokens() ?? {};
|
|
1135
|
+
tokens[account] = token;
|
|
1136
|
+
await mkdir(home, {
|
|
1137
|
+
recursive: true,
|
|
1138
|
+
mode: 448
|
|
1139
|
+
});
|
|
1140
|
+
const path = plaintextTokensPath(home);
|
|
1141
|
+
await writeFile(path, `${JSON.stringify(tokens, null, 2)}\n`, { mode: 384 });
|
|
1142
|
+
await chmod(path, 384);
|
|
1143
|
+
return true;
|
|
1144
|
+
}
|
|
1145
|
+
async function readPlaintextTokens() {
|
|
1146
|
+
const home = configHome();
|
|
1147
|
+
if (!home) return null;
|
|
1148
|
+
const raw = await readFile(plaintextTokensPath(home), "utf8").catch(() => null);
|
|
1149
|
+
if (!raw) return null;
|
|
1150
|
+
try {
|
|
1151
|
+
const parsed = JSON.parse(raw);
|
|
1152
|
+
return isRecord(parsed) ? parsed : null;
|
|
1153
|
+
} catch {
|
|
1154
|
+
return null;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
function plaintextTokensPath(home) {
|
|
1158
|
+
return join(home, "tokens.json");
|
|
1159
|
+
}
|
|
1160
|
+
function configHome() {
|
|
1161
|
+
const override = nonEmpty(process.env.ARTIFACTSHARE_CONFIG_HOME);
|
|
1162
|
+
if (override) return override;
|
|
1163
|
+
const xdgConfigHome = nonEmpty(process.env.XDG_CONFIG_HOME);
|
|
1164
|
+
if (xdgConfigHome) return join(xdgConfigHome, "artifactshare");
|
|
1165
|
+
const home = nonEmpty(process.env.HOME);
|
|
1166
|
+
if (home) return join(home, ".config/artifactshare");
|
|
1167
|
+
return null;
|
|
1168
|
+
}
|
|
1169
|
+
//#endregion
|
|
1170
|
+
//#region src/credentials.ts
|
|
1171
|
+
async function resolveCredential(options, projectConfig = null) {
|
|
1172
|
+
const envToken = nonEmpty(process.env.ARTIFACTSHARE_TOKEN);
|
|
1173
|
+
const optionToken = nonEmpty(options.token);
|
|
1174
|
+
const profile = nonEmpty(options.profile);
|
|
1175
|
+
if (profile && (envToken || optionToken)) return {
|
|
1176
|
+
ok: false,
|
|
1177
|
+
source: envToken ? "env" : "token_option",
|
|
1178
|
+
profile,
|
|
1179
|
+
error: validationError("Choose either --profile or a bearer token.", "Remove --profile, unset ARTIFACTSHARE_TOKEN, or remove --token before retrying.")
|
|
1180
|
+
};
|
|
1181
|
+
if (optionToken) return {
|
|
1182
|
+
ok: true,
|
|
1183
|
+
source: "token_option",
|
|
1184
|
+
token: optionToken
|
|
1185
|
+
};
|
|
1186
|
+
if (envToken) return {
|
|
1187
|
+
ok: true,
|
|
1188
|
+
source: "env",
|
|
1189
|
+
token: envToken
|
|
1190
|
+
};
|
|
1191
|
+
const globalConfig = await readGlobalConfig();
|
|
1192
|
+
if (profile) return await resolveProfileCredential("profile", profile, options, globalConfig);
|
|
1193
|
+
const projectProfile = nonEmpty(projectConfig?.default_profile);
|
|
1194
|
+
if (projectProfile) return await resolveProfileCredential("project_config", projectProfile, options, globalConfig);
|
|
1195
|
+
const globalProfile = nonEmpty(globalConfig?.default_profile);
|
|
1196
|
+
if (globalProfile) return await resolveProfileCredential("global_profile", globalProfile, options, globalConfig);
|
|
1197
|
+
return {
|
|
1198
|
+
ok: false,
|
|
1199
|
+
source: "none",
|
|
1200
|
+
error: authRequiredError()
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
async function resolveProfileCredential(source, profile, options, globalConfig) {
|
|
1204
|
+
const profileBaseUrl = nonEmpty(globalConfig?.profiles?.[profile]?.base_url);
|
|
1205
|
+
if (profileBaseUrl && !nonEmpty(options.baseUrl) && !nonEmpty(process.env.ARTIFACTSHARE_BASE_URL)) options.baseUrl = profileBaseUrl;
|
|
1206
|
+
const stored = await readProfileToken(profile, options);
|
|
1207
|
+
if (stored.ok) return {
|
|
1208
|
+
ok: true,
|
|
1209
|
+
source: "profile",
|
|
1210
|
+
profile,
|
|
1211
|
+
token: stored.token
|
|
1212
|
+
};
|
|
1213
|
+
return profileAuthRequired(source, profile, stored.reason);
|
|
1214
|
+
}
|
|
1215
|
+
function profileAuthRequired(source, profile, reason) {
|
|
1216
|
+
const error = authRequiredError();
|
|
1217
|
+
const why = reason === "unavailable" ? `No safe token store is available for profile "${profile}".` : `No saved credential was found for profile "${profile}".`;
|
|
1218
|
+
return {
|
|
1219
|
+
ok: false,
|
|
1220
|
+
source,
|
|
1221
|
+
profile,
|
|
1222
|
+
error: {
|
|
1223
|
+
...error,
|
|
1224
|
+
why,
|
|
1225
|
+
hint: `Run npx @artifactshare/cli login --profile ${profile}, or set ARTIFACTSHARE_TOKEN.`,
|
|
1226
|
+
details: {
|
|
1227
|
+
credential_source: source,
|
|
1228
|
+
profile
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
//#endregion
|
|
1234
|
+
//#region src/command-runners/artifacts-get.ts
|
|
1235
|
+
async function runArtifactsGet(parsed, mode) {
|
|
1236
|
+
const command = "artifacts get";
|
|
1237
|
+
const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL to read.");
|
|
1238
|
+
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
1239
|
+
const artifactId = target.artifactId;
|
|
1240
|
+
const offset = parseOffsetOption(parsed.options.offset);
|
|
1241
|
+
if (offset.error) return writeFailure(command, offset.error, mode, 1);
|
|
1242
|
+
const include = parseIncludeOptions(parsed.options.include);
|
|
1243
|
+
if (include.error) return writeFailure(command, include.error, mode, 1);
|
|
1244
|
+
const credential = await resolveCredential(parsed.options, await readProjectConfig());
|
|
1245
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
1246
|
+
const request = requestConfig(parsed.options);
|
|
1247
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1248
|
+
const url = apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}`, baseUrlOf(parsed.options));
|
|
1249
|
+
if (offset.value !== void 0) url.searchParams.set("offset", offset.value);
|
|
1250
|
+
for (const item of include.values) url.searchParams.append("include", item);
|
|
1251
|
+
const response = await fetch(url, {
|
|
1252
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
1253
|
+
...request.init
|
|
1254
|
+
}).catch((error) => ({ networkError: error }));
|
|
1255
|
+
if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
|
|
1256
|
+
const body = await readJson(response);
|
|
1257
|
+
if (!response.ok) return writeFailure(command, mapApiError(response.status, body, {
|
|
1258
|
+
authenticated: true,
|
|
1259
|
+
artifactTarget: true
|
|
1260
|
+
}), mode, 1);
|
|
1261
|
+
if (!artifactGetSuccessFields(body)) return writeFailure(command, serviceError("Artifact read succeeded but the response did not include source metadata."), mode, 1);
|
|
1262
|
+
return writeSuccess(command, body, mode);
|
|
1263
|
+
}
|
|
1264
|
+
//#endregion
|
|
1265
|
+
//#region src/command-runners/comments.ts
|
|
1266
|
+
async function runCommentsList(parsed, mode) {
|
|
1267
|
+
const command = "comments list";
|
|
1268
|
+
const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
|
|
1269
|
+
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
1270
|
+
const artifactId = target.artifactId;
|
|
1271
|
+
const credential = await resolveCredential(parsed.options, await readProjectConfig());
|
|
1272
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
1273
|
+
const request = requestConfig(parsed.options);
|
|
1274
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1275
|
+
const result = await apiGet(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, parsed.options, request.init, { artifactTarget: true });
|
|
1276
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
1277
|
+
const comments = Array.isArray(result.body?.comments) ? result.body.comments : [];
|
|
1278
|
+
writeSuccess(command, {
|
|
1279
|
+
artifact_id: artifactId,
|
|
1280
|
+
share_url: configString(result.body?.share_url),
|
|
1281
|
+
comments,
|
|
1282
|
+
has_more: result.body?.has_more === true
|
|
1283
|
+
}, mode);
|
|
1284
|
+
if (!mode.json && comments.length === 0) writeText("No comments yet.\n");
|
|
1285
|
+
}
|
|
1286
|
+
async function runCommentsPost(parsed, mode) {
|
|
1287
|
+
const command = "comments post";
|
|
1288
|
+
const target = parseArtifactTarget(parsed.positionals[0], command, "Pass an artifact ID or share URL.");
|
|
1289
|
+
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
1290
|
+
const artifactId = target.artifactId;
|
|
1291
|
+
const body = parsed.options.body;
|
|
1292
|
+
if (!body || !body.trim()) return writeFailure(command, validationError("A comment body is required.", "Retry with --body <text>."), mode, 1);
|
|
1293
|
+
const replyTo = parsed.options.replyTo;
|
|
1294
|
+
const quote = parsed.options.quote;
|
|
1295
|
+
if (quote !== void 0 && replyTo !== void 0) return writeFailure(command, validationError("Choose either --quote or --reply-to.", "A quote anchors a new thread; a reply joins an existing thread. Remove one and retry."), mode, 1);
|
|
1296
|
+
if (quote === void 0 && (parsed.options.quoteBefore !== void 0 || parsed.options.quoteAfter !== void 0)) return writeFailure(command, validationError("--quote-before and --quote-after require --quote.", "Add --quote <text>, or remove the context options."), mode, 1);
|
|
1297
|
+
const credential = await resolveCredential(parsed.options, await readProjectConfig());
|
|
1298
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
1299
|
+
const request = requestConfig(parsed.options);
|
|
1300
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1301
|
+
const result = await apiPost(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/comments`, credential.token, {
|
|
1302
|
+
body,
|
|
1303
|
+
reply_to: replyTo,
|
|
1304
|
+
quote,
|
|
1305
|
+
quote_before: parsed.options.quoteBefore,
|
|
1306
|
+
quote_after: parsed.options.quoteAfter
|
|
1307
|
+
}, parsed.options, request.init, { artifactTarget: true });
|
|
1308
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
1309
|
+
const threadId = configString(result.body?.thread_id);
|
|
1310
|
+
if (!threadId) return writeFailure(command, serviceError("Comment was saved but the response had no thread id."), mode, 1);
|
|
1311
|
+
writeSuccess(command, {
|
|
1312
|
+
artifact_id: artifactId,
|
|
1313
|
+
share_url: configString(result.body?.share_url),
|
|
1314
|
+
thread_id: threadId,
|
|
1315
|
+
reply: result.body?.reply === true,
|
|
1316
|
+
thread: result.body?.thread ?? null
|
|
1317
|
+
}, mode);
|
|
1318
|
+
}
|
|
1319
|
+
//#endregion
|
|
1320
|
+
//#region src/command-runners/doctor.ts
|
|
1321
|
+
const LOGIN_COMMAND = "npx @artifactshare/cli login";
|
|
1322
|
+
const REQUEST_ACCESS_COMMAND = "npx @artifactshare/cli request-access";
|
|
1323
|
+
function bearerTokenBlocksLogin(data) {
|
|
1324
|
+
return data.auth.credential_source === "env" || data.auth.credential_source === "token_option";
|
|
1325
|
+
}
|
|
1326
|
+
function resolveDoctorNextCommand(data) {
|
|
1327
|
+
if (data.config.project.code === "token_store_unsafe") {
|
|
1328
|
+
if (bearerTokenBlocksLogin(data)) return null;
|
|
1329
|
+
return LOGIN_COMMAND;
|
|
1330
|
+
}
|
|
1331
|
+
if ((data.auth.code === "auth_required" || data.auth.code === "token_invalid") && !bearerTokenBlocksLogin(data)) return data.auth.profile ? `${LOGIN_COMMAND} --profile ${data.auth.profile}` : LOGIN_COMMAND;
|
|
1332
|
+
if (!data.network.ok) return null;
|
|
1333
|
+
if (data.upload.checked && !data.upload.ok) {
|
|
1334
|
+
if (data.upload.code === "upload-not-allowed") return REQUEST_ACCESS_COMMAND;
|
|
1335
|
+
return null;
|
|
1336
|
+
}
|
|
1337
|
+
return null;
|
|
1338
|
+
}
|
|
1339
|
+
function doctorDataWithNextCommand(data) {
|
|
1340
|
+
return {
|
|
1341
|
+
...data,
|
|
1342
|
+
next_command: resolveDoctorNextCommand(data)
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
async function runDoctor(parsed, mode) {
|
|
1346
|
+
const command = "doctor";
|
|
1347
|
+
const rawProjectConfig = await readRawProjectConfig();
|
|
1348
|
+
const config = rawProjectConfig;
|
|
1349
|
+
const credential = await resolveCredential(parsed.options, config);
|
|
1350
|
+
const destination = resolveDestination(parsed.options, config);
|
|
1351
|
+
const data = {
|
|
1352
|
+
next_command: null,
|
|
1353
|
+
base_url: baseUrlOf(parsed.options),
|
|
1354
|
+
config: await configDiagnostics(rawProjectConfig),
|
|
1355
|
+
auth: {
|
|
1356
|
+
credential_source: credential.source,
|
|
1357
|
+
...credential.profile ? { profile: credential.profile } : {},
|
|
1358
|
+
token_present: credential.ok,
|
|
1359
|
+
ok: false
|
|
1360
|
+
},
|
|
1361
|
+
destination: destination.error ? {
|
|
1362
|
+
ok: false,
|
|
1363
|
+
code: destination.error.code,
|
|
1364
|
+
hint: destination.error.hint
|
|
1365
|
+
} : {
|
|
1366
|
+
ok: true,
|
|
1367
|
+
type: destination.containerId ? "project" : "home",
|
|
1368
|
+
project_id: destination.containerId ?? null
|
|
1369
|
+
},
|
|
1370
|
+
network: { ok: false },
|
|
1371
|
+
upload: {
|
|
1372
|
+
ok: false,
|
|
1373
|
+
checked: false
|
|
1374
|
+
}
|
|
1375
|
+
};
|
|
1376
|
+
if (!credential.ok) {
|
|
1377
|
+
if (credential.error.code !== "auth_required") return writeFailure(command, credential.error, mode, 1);
|
|
1378
|
+
data.auth.code = credential.error.code;
|
|
1379
|
+
data.auth.hint = credential.error.hint;
|
|
1380
|
+
return writeSuccess(command, doctorDataWithNextCommand(data), mode);
|
|
1381
|
+
}
|
|
1382
|
+
const request = requestConfig(parsed.options);
|
|
1383
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1384
|
+
const response = await fetch(apiUrl("/api/cli/doctor", baseUrlOf(parsed.options)), {
|
|
1385
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
1386
|
+
...request.init
|
|
1387
|
+
}).catch((error) => ({ networkError: error }));
|
|
1388
|
+
if ("networkError" in response) {
|
|
1389
|
+
data.network = {
|
|
1390
|
+
ok: false,
|
|
1391
|
+
code: "network_failed",
|
|
1392
|
+
hint: networkError(response.networkError).hint
|
|
1393
|
+
};
|
|
1394
|
+
return writeSuccess(command, doctorDataWithNextCommand(data), mode);
|
|
1395
|
+
}
|
|
1396
|
+
data.network.ok = true;
|
|
1397
|
+
const body = await readJson(response);
|
|
1398
|
+
if (!response.ok) {
|
|
1399
|
+
const error = mapApiError(response.status, body, { authenticated: true });
|
|
1400
|
+
data.auth.code = error.code;
|
|
1401
|
+
data.auth.hint = error.hint;
|
|
1402
|
+
return writeSuccess(command, doctorDataWithNextCommand(data), mode);
|
|
1403
|
+
}
|
|
1404
|
+
if (!body) throw new Error("Doctor response was not valid JSON.");
|
|
1405
|
+
data.auth.ok = body.auth?.ok ?? true;
|
|
1406
|
+
data.auth.email = body.user?.email ?? null;
|
|
1407
|
+
data.upload.checked = true;
|
|
1408
|
+
data.upload.ok = body.upload?.ok ?? false;
|
|
1409
|
+
if (!data.upload.ok) {
|
|
1410
|
+
data.upload.code = normalizeApiCode(body.upload?.code);
|
|
1411
|
+
data.upload.hint = uploadBlockedHint(data.upload.code);
|
|
1412
|
+
}
|
|
1413
|
+
return writeSuccess(command, doctorDataWithNextCommand(data), mode);
|
|
1414
|
+
}
|
|
1415
|
+
async function configDiagnostics(rawProjectConfig) {
|
|
1416
|
+
const globalConfig = await readGlobalConfig();
|
|
1417
|
+
const unsafeKey = Object.keys(rawProjectConfig ?? {}).find((key) => key.toLowerCase().includes("token"));
|
|
1418
|
+
return {
|
|
1419
|
+
project: {
|
|
1420
|
+
present: rawProjectConfig !== null,
|
|
1421
|
+
default_profile: configString(rawProjectConfig?.default_profile),
|
|
1422
|
+
default_project_id: configString(rawProjectConfig?.default_project_id),
|
|
1423
|
+
...unsafeKey ? {
|
|
1424
|
+
code: "token_store_unsafe",
|
|
1425
|
+
hint: `Remove "${unsafeKey}" from ${PROJECT_CONFIG_PATH} and run npx @artifactshare/cli login instead; the working-directory config must never hold secrets.`
|
|
1426
|
+
} : {}
|
|
1427
|
+
},
|
|
1428
|
+
global: {
|
|
1429
|
+
present: globalConfig !== null,
|
|
1430
|
+
default_profile: configString(globalConfig?.default_profile),
|
|
1431
|
+
profile_count: Object.keys(globalConfig?.profiles ?? {}).length
|
|
1432
|
+
}
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
//#endregion
|
|
1436
|
+
//#region src/files.ts
|
|
1437
|
+
async function prepareUploadPayload(targetPath, fileStat, initialForm = new FormData()) {
|
|
1438
|
+
if (fileStat.isDirectory()) {
|
|
1439
|
+
let files;
|
|
1440
|
+
try {
|
|
1441
|
+
files = await collectDirectoryFiles(resolve(targetPath));
|
|
1442
|
+
} catch (error) {
|
|
1443
|
+
if (error instanceof CollectDirectoryFilesError) return { error: validationError(error.message, error.hint) };
|
|
1444
|
+
throw error;
|
|
1445
|
+
}
|
|
1446
|
+
if (files.length === 0) return { error: validationError("Directory has no publishable files.", "Add index.html or index.md and retry.") };
|
|
1447
|
+
for (const file of files) initialForm.append("file", await blobFor(file.path), file.relativePath);
|
|
1448
|
+
return { payload: {
|
|
1449
|
+
form: initialForm,
|
|
1450
|
+
kind: "static_site"
|
|
1451
|
+
} };
|
|
1452
|
+
}
|
|
1453
|
+
if (fileStat.isFile()) {
|
|
1454
|
+
initialForm.append("file", await blobFor(targetPath), basename(targetPath));
|
|
1455
|
+
return { payload: {
|
|
1456
|
+
form: initialForm,
|
|
1457
|
+
kind: artifactKindForFile(targetPath)
|
|
1458
|
+
} };
|
|
1459
|
+
}
|
|
1460
|
+
return { error: validationError("Path must be a file or directory.", "Pass a regular file or directory.") };
|
|
1461
|
+
}
|
|
1462
|
+
async function prepareDownloadPlan(manifest, outputPath, force) {
|
|
1463
|
+
if (manifest.files.length === 0) return { error: validationError("Download manifest contains no files.", "Check the artifact and retry.") };
|
|
1464
|
+
if (outputPath === "") return { error: validationError("--output requires a non-empty directory.", "Pass --output <path> or omit --output to use the artifact ID.") };
|
|
1465
|
+
const root = resolve(outputPath);
|
|
1466
|
+
const existing = await lstat(root).catch(() => null);
|
|
1467
|
+
if (existing?.isSymbolicLink()) return { error: validationError("Output path must not be a symbolic link.", "Choose a regular directory path and retry.") };
|
|
1468
|
+
if (existing && !force) return { error: cliError({
|
|
1469
|
+
code: "output_exists",
|
|
1470
|
+
message: "Output path already exists.",
|
|
1471
|
+
why: "Download will not write into an existing path unless --force is set.",
|
|
1472
|
+
hint: "Choose a different --output path or retry with --force.",
|
|
1473
|
+
agentRecoverable: true,
|
|
1474
|
+
requiresHuman: false,
|
|
1475
|
+
recovery: { kind: "change_input" }
|
|
1476
|
+
}) };
|
|
1477
|
+
if (existing && !existing.isDirectory()) return { error: validationError("Output path is not a directory.", "Choose a directory path or remove the existing file.") };
|
|
1478
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1479
|
+
const relativeFiles = [];
|
|
1480
|
+
for (const file of manifest.files) {
|
|
1481
|
+
const relativePath = downloadRelativePath(file.path);
|
|
1482
|
+
if (relativePath.error) return { error: relativePath.error };
|
|
1483
|
+
if (seen.has(relativePath.value)) return { error: validationError("Download manifest contains duplicate file paths.", "Retry later. If this repeats, report the artifact ID.") };
|
|
1484
|
+
seen.add(relativePath.value);
|
|
1485
|
+
relativeFiles.push({
|
|
1486
|
+
...file,
|
|
1487
|
+
relativePath: relativePath.value
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
const parent = dirname(root);
|
|
1491
|
+
await mkdir(parent, { recursive: true });
|
|
1492
|
+
const tempRoot = await mkdtemp(join(parent, `.${basename(root)}.tmp-`));
|
|
1493
|
+
const files = [];
|
|
1494
|
+
for (const file of relativeFiles) {
|
|
1495
|
+
const targetPath = resolve(tempRoot, file.relativePath);
|
|
1496
|
+
files.push({
|
|
1497
|
+
...file,
|
|
1498
|
+
targetPath
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
return { value: {
|
|
1502
|
+
root,
|
|
1503
|
+
tempRoot,
|
|
1504
|
+
replaceExisting: Boolean(existing),
|
|
1505
|
+
files
|
|
1506
|
+
} };
|
|
1507
|
+
}
|
|
1508
|
+
function downloadRelativePath(path) {
|
|
1509
|
+
if (!path.startsWith("/") || path.includes("\0") || path.includes("\\")) return { error: validationError("Download manifest contains an invalid file path.", "Retry later. If this repeats, report the artifact ID.") };
|
|
1510
|
+
const segments = path.split("/").slice(1);
|
|
1511
|
+
if (segments.length === 0 || segments.some((segment) => segment === "" || segment === "." || segment === "..")) return { error: validationError("Download manifest contains an unsafe file path.", "Retry later. If this repeats, report the artifact ID.") };
|
|
1512
|
+
return { value: segments.join("/") };
|
|
1513
|
+
}
|
|
1514
|
+
function verifyDownloadedBytes(file, bytes) {
|
|
1515
|
+
if (bytes.byteLength !== file.size_bytes) return { error: downloadIntegrityError(file.path, "size mismatch") };
|
|
1516
|
+
if (file.sha256) {
|
|
1517
|
+
if (createHash("sha256").update(bytes).digest("base64url") !== file.sha256) return { error: downloadIntegrityError(file.path, "sha256 mismatch") };
|
|
1518
|
+
}
|
|
1519
|
+
return { ok: true };
|
|
1520
|
+
}
|
|
1521
|
+
function downloadIntegrityError(path, reason) {
|
|
1522
|
+
return cliError({
|
|
1523
|
+
code: "download_integrity_failed",
|
|
1524
|
+
message: "Downloaded file did not match the manifest.",
|
|
1525
|
+
why: `The downloaded file ${path} failed integrity verification: ${reason}.`,
|
|
1526
|
+
hint: "Retry the download. If this repeats, report the artifact ID.",
|
|
1527
|
+
agentRecoverable: true,
|
|
1528
|
+
requiresHuman: false,
|
|
1529
|
+
recovery: { kind: "retry_later" }
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
function backupPathFor(root) {
|
|
1533
|
+
return join(dirname(root), `.${basename(root)}.old-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
|
|
1534
|
+
}
|
|
1535
|
+
async function pathExists(path) {
|
|
1536
|
+
return Boolean(await lstat(path).catch(() => null));
|
|
1537
|
+
}
|
|
1538
|
+
function downloadFileSystemError(error) {
|
|
1539
|
+
return cliError({
|
|
1540
|
+
code: "download_failed",
|
|
1541
|
+
message: "Could not write downloaded files.",
|
|
1542
|
+
why: error instanceof Error ? error.message : "The local filesystem rejected a download operation.",
|
|
1543
|
+
hint: "Check --output permissions and available disk space, then retry.",
|
|
1544
|
+
agentRecoverable: true,
|
|
1545
|
+
requiresHuman: false,
|
|
1546
|
+
recovery: { kind: "change_input" }
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
async function collectDirectoryFiles(root) {
|
|
1550
|
+
const results = [];
|
|
1551
|
+
async function visit(dir) {
|
|
1552
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
1553
|
+
if (entry.name === "__MACOSX") continue;
|
|
1554
|
+
const fullPath = join(dir, entry.name);
|
|
1555
|
+
if (entry.isSymbolicLink()) throw new CollectDirectoryFilesError("Directory contains a symbolic link.", "Remove or replace symlinked files and directories before publishing.");
|
|
1556
|
+
if (entry.isDirectory()) {
|
|
1557
|
+
if (EXCLUDED_DIR_NAMES.has(entry.name) || entry.name.startsWith(".")) continue;
|
|
1558
|
+
await visit(fullPath);
|
|
1559
|
+
continue;
|
|
1560
|
+
}
|
|
1561
|
+
if (!entry.isFile() || IGNORED_FILENAMES.has(entry.name) || entry.name.startsWith(".")) continue;
|
|
1562
|
+
const relativePath = relative(root, fullPath).split(sep).join("/");
|
|
1563
|
+
results.push({
|
|
1564
|
+
path: fullPath,
|
|
1565
|
+
relativePath
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
await visit(root);
|
|
1570
|
+
results.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
|
1571
|
+
return results;
|
|
1572
|
+
}
|
|
1573
|
+
var CollectDirectoryFilesError = class extends Error {
|
|
1574
|
+
hint;
|
|
1575
|
+
constructor(message, hint) {
|
|
1576
|
+
super(message);
|
|
1577
|
+
this.name = "CollectDirectoryFilesError";
|
|
1578
|
+
this.hint = hint;
|
|
1579
|
+
}
|
|
1580
|
+
};
|
|
1581
|
+
async function blobFor(path) {
|
|
1582
|
+
const chunks = [];
|
|
1583
|
+
for await (const chunk of createReadStream(path)) chunks.push(chunk);
|
|
1584
|
+
return new Blob(chunks, { type: contentTypeFor(path) });
|
|
1585
|
+
}
|
|
1586
|
+
function contentTypeFor(path) {
|
|
1587
|
+
if (path.endsWith(".html")) return "text/html";
|
|
1588
|
+
if (path.endsWith(".md")) return "text/markdown";
|
|
1589
|
+
if (path.endsWith(".css")) return "text/css";
|
|
1590
|
+
if (path.endsWith(".js")) return "text/javascript";
|
|
1591
|
+
if (path.endsWith(".json")) return "application/json";
|
|
1592
|
+
if (path.endsWith(".svg")) return "image/svg+xml";
|
|
1593
|
+
if (path.endsWith(".png")) return "image/png";
|
|
1594
|
+
if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
|
|
1595
|
+
return "application/octet-stream";
|
|
1596
|
+
}
|
|
1597
|
+
function artifactKindForFile(path) {
|
|
1598
|
+
return path.endsWith(".md") ? "markdown_page" : "html_page";
|
|
1599
|
+
}
|
|
1600
|
+
//#endregion
|
|
1601
|
+
//#region src/command-runners/login.ts
|
|
1602
|
+
async function performDeviceLogin(profile, options, mode) {
|
|
1603
|
+
const request = requestConfig(options);
|
|
1604
|
+
if (request.error) return {
|
|
1605
|
+
ok: false,
|
|
1606
|
+
error: request.error
|
|
1607
|
+
};
|
|
1608
|
+
const code = await requestDeviceCode(options, request.init);
|
|
1609
|
+
if ("error" in code) return {
|
|
1610
|
+
ok: false,
|
|
1611
|
+
error: code.error
|
|
1612
|
+
};
|
|
1613
|
+
const deadline = Date.now() + code.expires_in * 1e3;
|
|
1614
|
+
if (mode.json) writeEvent({
|
|
1615
|
+
status: "pending",
|
|
1616
|
+
verification_uri: code.verification_uri,
|
|
1617
|
+
verification_uri_complete: code.verification_uri_complete ?? null,
|
|
1618
|
+
user_code: code.user_code,
|
|
1619
|
+
expires_at: new Date(deadline).toISOString(),
|
|
1620
|
+
interval_seconds: code.interval
|
|
1621
|
+
});
|
|
1622
|
+
else writeText([
|
|
1623
|
+
"Open this URL in a browser to sign in:",
|
|
1624
|
+
code.verification_uri_complete ?? code.verification_uri,
|
|
1625
|
+
"",
|
|
1626
|
+
`Code: ${code.user_code}`,
|
|
1627
|
+
`Waiting for approval for profile "${profile}"...`,
|
|
1628
|
+
""
|
|
1629
|
+
].join("\n"));
|
|
1630
|
+
const token = await pollForToken(options, code, request.init, profile, deadline);
|
|
1631
|
+
if ("error" in token) return {
|
|
1632
|
+
ok: false,
|
|
1633
|
+
error: token.error
|
|
1634
|
+
};
|
|
1635
|
+
const sessionExpiresAt = token.expires_in === void 0 ? null : new Date(Date.now() + token.expires_in * 1e3).toISOString();
|
|
1636
|
+
const config = await readGlobalConfig() ?? {};
|
|
1637
|
+
const whoamiResult = await apiGet("/api/cli/whoami", token.access_token, options, request.init);
|
|
1638
|
+
if (whoamiResult.error) return {
|
|
1639
|
+
ok: false,
|
|
1640
|
+
error: whoamiResult.error
|
|
1641
|
+
};
|
|
1642
|
+
const whoami = whoamiProfile(whoamiResult.body);
|
|
1643
|
+
const expectedEmail = config.profiles?.[profile]?.email;
|
|
1644
|
+
if (expectedEmail && whoami.email && expectedEmail !== whoami.email) return {
|
|
1645
|
+
ok: false,
|
|
1646
|
+
error: authAccountMismatchError(profile, expectedEmail, whoami.email)
|
|
1647
|
+
};
|
|
1648
|
+
const saved = await saveProfileToken(profile, token.access_token, options);
|
|
1649
|
+
if (!saved.ok) return {
|
|
1650
|
+
ok: false,
|
|
1651
|
+
error: tokenStoreUnavailableError(profile)
|
|
1652
|
+
};
|
|
1653
|
+
await writeProfileConfig(profile, options, saved.store, whoami);
|
|
1654
|
+
return {
|
|
1655
|
+
ok: true,
|
|
1656
|
+
data: {
|
|
1657
|
+
profile,
|
|
1658
|
+
status: "completed",
|
|
1659
|
+
credential_source: "profile",
|
|
1660
|
+
token_store: saved.store,
|
|
1661
|
+
user: { email: whoami.email },
|
|
1662
|
+
workspace: {
|
|
1663
|
+
id: whoami.workspace_id,
|
|
1664
|
+
hosted_domain: whoami.hosted_domain
|
|
1665
|
+
},
|
|
1666
|
+
verification_uri: code.verification_uri,
|
|
1667
|
+
verification_uri_complete: code.verification_uri_complete ?? null,
|
|
1668
|
+
user_code: code.user_code,
|
|
1669
|
+
expires_at: sessionExpiresAt,
|
|
1670
|
+
interval_seconds: code.interval
|
|
1671
|
+
}
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
async function runLogin(parsed, mode) {
|
|
1675
|
+
const command = "login";
|
|
1676
|
+
const profile = nonEmpty(parsed.options.profile) ?? "default";
|
|
1677
|
+
if (nonEmpty(process.env.ARTIFACTSHARE_TOKEN) || nonEmpty(parsed.options.token)) return writeFailure(command, validationError("Login cannot run with a bearer token already selected.", "Unset ARTIFACTSHARE_TOKEN and remove --token before running login."), mode, 1);
|
|
1678
|
+
const result = await performDeviceLogin(profile, parsed.options, mode);
|
|
1679
|
+
if (!result.ok) return writeFailure(command, result.error, mode, 1);
|
|
1680
|
+
return writeSuccess(command, result.data, mode);
|
|
1681
|
+
}
|
|
1682
|
+
async function requestDeviceCode(options, init) {
|
|
1683
|
+
const response = await fetch(apiUrl("/api/auth/device/code", baseUrlOf(options)), {
|
|
1684
|
+
method: "POST",
|
|
1685
|
+
headers: { "content-type": "application/json" },
|
|
1686
|
+
body: JSON.stringify({ client_id: DEVICE_CLIENT_ID }),
|
|
1687
|
+
...init
|
|
1688
|
+
}).catch((error) => ({ networkError: error }));
|
|
1689
|
+
if ("networkError" in response) return { error: networkError(response.networkError) };
|
|
1690
|
+
const body = await readJson(response);
|
|
1691
|
+
if (!response.ok) return { error: mapApiError(response.status, body) };
|
|
1692
|
+
if (!isDeviceCodeResponse(body)) return { error: validationError("Device login response was invalid.", "Retry login. If this repeats, report the response shape.", "service_error") };
|
|
1693
|
+
return body;
|
|
1694
|
+
}
|
|
1695
|
+
async function pollForToken(options, code, init, profile, deadline) {
|
|
1696
|
+
let intervalMs = Math.max(code.interval, 1) * 1e3;
|
|
1697
|
+
let networkFailures = 0;
|
|
1698
|
+
while (Date.now() < deadline) {
|
|
1699
|
+
await setTimeout(intervalMs);
|
|
1700
|
+
const response = await fetch(apiUrl("/api/auth/device/token", baseUrlOf(options)), {
|
|
1701
|
+
method: "POST",
|
|
1702
|
+
headers: { "content-type": "application/json" },
|
|
1703
|
+
body: JSON.stringify({
|
|
1704
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
1705
|
+
device_code: code.device_code,
|
|
1706
|
+
client_id: DEVICE_CLIENT_ID
|
|
1707
|
+
}),
|
|
1708
|
+
...init
|
|
1709
|
+
}).catch((error) => ({ networkError: error }));
|
|
1710
|
+
if ("networkError" in response) {
|
|
1711
|
+
networkFailures += 1;
|
|
1712
|
+
if (networkFailures >= 5) return { error: networkError(response.networkError) };
|
|
1713
|
+
continue;
|
|
1714
|
+
}
|
|
1715
|
+
networkFailures = 0;
|
|
1716
|
+
const body = await readJson(response);
|
|
1717
|
+
if (response.ok && isDeviceTokenResponse(body)) return body;
|
|
1718
|
+
const authError = deviceTokenError(body);
|
|
1719
|
+
if (authError === "authorization_pending") continue;
|
|
1720
|
+
if (authError === "slow_down") {
|
|
1721
|
+
intervalMs += 5e3;
|
|
1722
|
+
continue;
|
|
1723
|
+
}
|
|
1724
|
+
if (authError === "access_denied") return { error: authDeniedError(profile) };
|
|
1725
|
+
if (authError === "expired_token") return { error: authExpiredError(profile) };
|
|
1726
|
+
return { error: mapApiError(response.status, body) };
|
|
1727
|
+
}
|
|
1728
|
+
return { error: authExpiredError(profile) };
|
|
1729
|
+
}
|
|
1730
|
+
async function writeProfileConfig(profile, options, tokenStore, whoami) {
|
|
1731
|
+
const config = await readGlobalConfig() ?? {};
|
|
1732
|
+
await writeGlobalConfig({
|
|
1733
|
+
...config,
|
|
1734
|
+
default_profile: nonEmpty(config.default_profile) ?? profile,
|
|
1735
|
+
profiles: {
|
|
1736
|
+
...config.profiles,
|
|
1737
|
+
[profile]: {
|
|
1738
|
+
...config.profiles?.[profile],
|
|
1739
|
+
base_url: baseUrlOf(options),
|
|
1740
|
+
email: whoami.email,
|
|
1741
|
+
workspace_id: whoami.workspace_id,
|
|
1742
|
+
token_store: tokenStore,
|
|
1743
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
});
|
|
1747
|
+
}
|
|
1748
|
+
function isDeviceCodeResponse(body) {
|
|
1749
|
+
if (!isRecord(body)) return false;
|
|
1750
|
+
return typeof body.device_code === "string" && typeof body.user_code === "string" && typeof body.verification_uri === "string" && (typeof body.verification_uri_complete === "string" || body.verification_uri_complete === void 0) && typeof body.expires_in === "number" && typeof body.interval === "number";
|
|
1751
|
+
}
|
|
1752
|
+
function isDeviceTokenResponse(body) {
|
|
1753
|
+
if (!isRecord(body)) return false;
|
|
1754
|
+
return typeof body.access_token === "string" && typeof body.token_type === "string" && body.token_type.toLowerCase() === "bearer" && (typeof body.expires_in === "number" || body.expires_in === void 0);
|
|
1755
|
+
}
|
|
1756
|
+
function deviceTokenError(body) {
|
|
1757
|
+
if (!isRecord(body)) return null;
|
|
1758
|
+
return typeof body.error === "string" ? body.error : null;
|
|
1759
|
+
}
|
|
1760
|
+
function whoamiProfile(body) {
|
|
1761
|
+
const record = isRecord(body) ? body : null;
|
|
1762
|
+
const user = record && isRecord(record.user) ? record.user : null;
|
|
1763
|
+
const workspace = record && isRecord(record.workspace) ? record.workspace : null;
|
|
1764
|
+
return {
|
|
1765
|
+
email: typeof user?.email === "string" ? user.email : null,
|
|
1766
|
+
workspace_id: typeof workspace?.id === "string" ? workspace.id : null,
|
|
1767
|
+
hosted_domain: typeof workspace?.hosted_domain === "string" ? workspace.hosted_domain : null
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
//#endregion
|
|
1771
|
+
//#region src/command-runners/auto-login.ts
|
|
1772
|
+
function isInteractiveTerminal(mode) {
|
|
1773
|
+
return !mode.json && process.stdin.isTTY === true;
|
|
1774
|
+
}
|
|
1775
|
+
function profileForAutoLogin(credential) {
|
|
1776
|
+
return credential.source === "none" ? "default" : credential.profile ?? "default";
|
|
1777
|
+
}
|
|
1778
|
+
async function handleCredentialFailure(command, credential, options, mode, rerun, isRetry = false, deps = {}) {
|
|
1779
|
+
if (credential.error.code !== "auth_required" || !isInteractiveTerminal(mode) || isRetry) return writeFailure(command, credential.error, mode, 1);
|
|
1780
|
+
const performLogin = deps.performLogin ?? performDeviceLogin;
|
|
1781
|
+
const profile = profileForAutoLogin(credential);
|
|
1782
|
+
writeText("Not signed in. Starting device login to continue...\n");
|
|
1783
|
+
const loginResult = await performLogin(profile, options, mode);
|
|
1784
|
+
if (!loginResult.ok) return writeFailure(command, loginResult.error, mode, 1);
|
|
1785
|
+
return rerun();
|
|
1786
|
+
}
|
|
1787
|
+
//#endregion
|
|
1788
|
+
//#region src/command-runners/download.ts
|
|
1789
|
+
async function runDownload(parsed, mode, isRetry = false) {
|
|
1790
|
+
const command = "download";
|
|
1791
|
+
const target = parseArtifactTarget(parsed.positionals[0], "download", "Pass an artifact ID or share URL to download.");
|
|
1792
|
+
if (target.error) return writeFailure(command, target.error, mode, 1);
|
|
1793
|
+
const artifactId = target.artifactId;
|
|
1794
|
+
const credential = await resolveCredential(parsed.options, await readProjectConfig());
|
|
1795
|
+
if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runDownload(parsed, mode, true), isRetry);
|
|
1796
|
+
const request = requestConfig(parsed.options);
|
|
1797
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1798
|
+
const baseUrl = baseUrlOf(parsed.options);
|
|
1799
|
+
const manifestUrl = apiUrl(`/api/cli/artifacts/${encodeURIComponent(artifactId)}/download`, baseUrl);
|
|
1800
|
+
const manifestResponse = await fetch(manifestUrl, {
|
|
1801
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
1802
|
+
...request.init
|
|
1803
|
+
}).catch((error) => ({ networkError: error }));
|
|
1804
|
+
if ("networkError" in manifestResponse) return writeFailure(command, networkError(manifestResponse.networkError), mode, 1);
|
|
1805
|
+
const body = await readJson(manifestResponse);
|
|
1806
|
+
if (!manifestResponse.ok) return writeFailure(command, mapApiError(manifestResponse.status, body, {
|
|
1807
|
+
authenticated: true,
|
|
1808
|
+
artifactTarget: true
|
|
1809
|
+
}), mode, 1);
|
|
1810
|
+
if (!downloadManifestFields(body)) return writeFailure(command, serviceError("Download manifest succeeded but the response did not include file metadata."), mode, 1);
|
|
1811
|
+
const plan = await prepareDownloadPlan(body, parsed.options.output ?? artifactId, Boolean(parsed.options.force));
|
|
1812
|
+
if (plan.error) return writeFailure(command, plan.error, mode, 1);
|
|
1813
|
+
let completed = false;
|
|
1814
|
+
let backupRoot = null;
|
|
1815
|
+
try {
|
|
1816
|
+
for (const file of plan.value.files) {
|
|
1817
|
+
const fileUrl = downloadFileUrl(baseUrl, artifactId, file.path);
|
|
1818
|
+
const fileResponse = await fetch(fileUrl, {
|
|
1819
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
1820
|
+
...request.init
|
|
1821
|
+
}).catch((error) => ({ networkError: error }));
|
|
1822
|
+
if ("networkError" in fileResponse) return writeFailure(command, networkError(fileResponse.networkError), mode, 1);
|
|
1823
|
+
if (!fileResponse.ok) return writeFailure(command, mapApiError(fileResponse.status, await readJson(fileResponse), {
|
|
1824
|
+
authenticated: true,
|
|
1825
|
+
artifactTarget: true
|
|
1826
|
+
}), mode, 1);
|
|
1827
|
+
const bytes = Buffer.from(await fileResponse.arrayBuffer());
|
|
1828
|
+
const verified = verifyDownloadedBytes(file, bytes);
|
|
1829
|
+
if (verified.error) return writeFailure(command, verified.error, mode, 1);
|
|
1830
|
+
await mkdir(dirname(file.targetPath), { recursive: true });
|
|
1831
|
+
await writeFile(file.targetPath, bytes);
|
|
1832
|
+
}
|
|
1833
|
+
if (plan.value.replaceExisting) {
|
|
1834
|
+
backupRoot = backupPathFor(plan.value.root);
|
|
1835
|
+
await rename(plan.value.root, backupRoot);
|
|
1836
|
+
}
|
|
1837
|
+
await rename(plan.value.tempRoot, plan.value.root);
|
|
1838
|
+
completed = true;
|
|
1839
|
+
if (backupRoot) await rm(backupRoot, {
|
|
1840
|
+
recursive: true,
|
|
1841
|
+
force: true
|
|
1842
|
+
}).catch(() => {});
|
|
1843
|
+
} catch (error) {
|
|
1844
|
+
if (backupRoot && !await pathExists(plan.value.root) && await pathExists(backupRoot)) await rename(backupRoot, plan.value.root).catch(() => {});
|
|
1845
|
+
return writeFailure(command, downloadFileSystemError(error), mode, 1);
|
|
1846
|
+
} finally {
|
|
1847
|
+
if (!completed) await rm(plan.value.tempRoot, {
|
|
1848
|
+
recursive: true,
|
|
1849
|
+
force: true
|
|
1850
|
+
}).catch(() => {});
|
|
1851
|
+
}
|
|
1852
|
+
return writeSuccess(command, {
|
|
1853
|
+
artifact: {
|
|
1854
|
+
id: body.id,
|
|
1855
|
+
url: body.share_url,
|
|
1856
|
+
kind: body.artifact_kind
|
|
1857
|
+
},
|
|
1858
|
+
version: { id: body.version_id },
|
|
1859
|
+
destination: { path: plan.value.root },
|
|
1860
|
+
files: {
|
|
1861
|
+
count: plan.value.files.length,
|
|
1862
|
+
total_size_bytes: body.total_size_bytes
|
|
1863
|
+
}
|
|
1864
|
+
}, mode);
|
|
1865
|
+
}
|
|
1866
|
+
//#endregion
|
|
1867
|
+
//#region src/command-runners/init.ts
|
|
1868
|
+
async function runInit(parsed, mode) {
|
|
1869
|
+
const command = "init";
|
|
1870
|
+
const profile = nonEmpty(parsed.options.profile);
|
|
1871
|
+
const projectId = nonEmpty(parsed.options.projectId);
|
|
1872
|
+
const existing = await readRawProjectConfig() ?? {};
|
|
1873
|
+
if (!profile && !projectId) return writeSuccess(command, initData(false, existing), mode);
|
|
1874
|
+
if (profile) {
|
|
1875
|
+
if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(profile), mode, 1);
|
|
1876
|
+
const globalConfig = await readGlobalConfig();
|
|
1877
|
+
if (!Object.hasOwn(globalConfig?.profiles ?? {}, profile)) return writeFailure(command, profileNotFoundError(profile), mode, 1);
|
|
1878
|
+
}
|
|
1879
|
+
const next = {
|
|
1880
|
+
...existing,
|
|
1881
|
+
...profile ? { default_profile: profile } : {},
|
|
1882
|
+
...projectId ? { default_project_id: projectId } : {}
|
|
1883
|
+
};
|
|
1884
|
+
const path = projectConfigPath();
|
|
1885
|
+
await mkdir(dirname(path), { recursive: true });
|
|
1886
|
+
await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
|
|
1887
|
+
return writeSuccess(command, initData(true, next), mode);
|
|
1888
|
+
}
|
|
1889
|
+
function initData(written, config) {
|
|
1890
|
+
return {
|
|
1891
|
+
path: PROJECT_CONFIG_PATH,
|
|
1892
|
+
written,
|
|
1893
|
+
config: {
|
|
1894
|
+
default_profile: configString(config.default_profile),
|
|
1895
|
+
default_project_id: configString(config.default_project_id)
|
|
1896
|
+
}
|
|
1897
|
+
};
|
|
1898
|
+
}
|
|
1899
|
+
//#endregion
|
|
1900
|
+
//#region src/command-runners/profiles.ts
|
|
1901
|
+
async function runProfilesList(parsed, mode) {
|
|
1902
|
+
const command = "profiles list";
|
|
1903
|
+
if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
|
|
1904
|
+
const config = await readGlobalConfig() ?? {};
|
|
1905
|
+
const defaultProfile = nonEmpty(config.default_profile) ?? null;
|
|
1906
|
+
const profiles = await Promise.all(Object.entries(config.profiles ?? {}).map(async ([name, rawEntry]) => {
|
|
1907
|
+
const entry = isRecord(rawEntry) ? rawEntry : {};
|
|
1908
|
+
const stored = await readProfileToken(name, {
|
|
1909
|
+
...parsed.options,
|
|
1910
|
+
baseUrl: nonEmpty(entry.base_url) ?? "https://artifactshare.com"
|
|
1911
|
+
});
|
|
1912
|
+
return {
|
|
1913
|
+
name,
|
|
1914
|
+
base_url: nonEmpty(entry.base_url) ?? null,
|
|
1915
|
+
email: nonEmpty(entry.email) ?? null,
|
|
1916
|
+
workspace_id: nonEmpty(entry.workspace_id) ?? null,
|
|
1917
|
+
token_store: entry.token_store ?? null,
|
|
1918
|
+
updated_at: nonEmpty(entry.updated_at) ?? null,
|
|
1919
|
+
is_default: name === defaultProfile,
|
|
1920
|
+
token_present: stored.ok
|
|
1921
|
+
};
|
|
1922
|
+
}));
|
|
1923
|
+
writeSuccess(command, {
|
|
1924
|
+
default_profile: defaultProfile,
|
|
1925
|
+
profiles
|
|
1926
|
+
}, mode);
|
|
1927
|
+
if (!mode.json && profiles.length === 0) writeText("No profiles yet. Run npx @artifactshare/cli login --profile default to create one.\n");
|
|
1928
|
+
}
|
|
1929
|
+
async function runProfilesUse(parsed, mode) {
|
|
1930
|
+
const command = "profiles use";
|
|
1931
|
+
const name = nonEmpty(parsed.positionals[0]);
|
|
1932
|
+
if (!name) return writeFailure(command, validationError("A profile name is required.", "Run npx @artifactshare/cli profiles use <name>."), mode, 1);
|
|
1933
|
+
if (!configHome()) return writeFailure(command, tokenStoreUnavailableError(), mode, 1);
|
|
1934
|
+
const config = await readGlobalConfig() ?? {};
|
|
1935
|
+
if (!Object.hasOwn(config.profiles ?? {}, name)) return writeFailure(command, profileNotFoundError(name), mode, 1);
|
|
1936
|
+
const previous = nonEmpty(config.default_profile) ?? null;
|
|
1937
|
+
await writeGlobalConfig({
|
|
1938
|
+
...config,
|
|
1939
|
+
default_profile: name
|
|
1940
|
+
});
|
|
1941
|
+
return writeSuccess(command, {
|
|
1942
|
+
default_profile: name,
|
|
1943
|
+
previous_default: previous
|
|
1944
|
+
}, mode);
|
|
1945
|
+
}
|
|
1946
|
+
//#endregion
|
|
1947
|
+
//#region src/command-runners/projects.ts
|
|
1948
|
+
async function fetchProjects(token, options, init) {
|
|
1949
|
+
const result = await apiGet("/api/cli/projects", token, options, init);
|
|
1950
|
+
if (result.error) return { error: result.error };
|
|
1951
|
+
return { projects: (Array.isArray(result.body?.projects) ? result.body.projects : []).filter(isRecord).flatMap((project) => {
|
|
1952
|
+
const id = configString(project.id);
|
|
1953
|
+
if (!id) return [];
|
|
1954
|
+
return [{
|
|
1955
|
+
id,
|
|
1956
|
+
name: configString(project.name),
|
|
1957
|
+
description: configString(project.description),
|
|
1958
|
+
base_visibility: configString(project.base_visibility),
|
|
1959
|
+
file_count: typeof project.file_count === "number" ? project.file_count : null,
|
|
1960
|
+
updated_at: configString(project.updated_at)
|
|
1961
|
+
}];
|
|
1962
|
+
}) };
|
|
1963
|
+
}
|
|
1964
|
+
async function runProjectsList(parsed, mode) {
|
|
1965
|
+
const command = "projects list";
|
|
1966
|
+
const config = await readProjectConfig();
|
|
1967
|
+
const credential = await resolveCredential(parsed.options, config);
|
|
1968
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
1969
|
+
const request = requestConfig(parsed.options);
|
|
1970
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
1971
|
+
const result = await fetchProjects(credential.token, parsed.options, request.init);
|
|
1972
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
1973
|
+
const defaultProjectId = configString(config?.default_project_id);
|
|
1974
|
+
const projects = result.projects.map((project) => ({
|
|
1975
|
+
...project,
|
|
1976
|
+
is_default: project.id === defaultProjectId
|
|
1977
|
+
}));
|
|
1978
|
+
writeSuccess(command, {
|
|
1979
|
+
default_project_id: defaultProjectId,
|
|
1980
|
+
projects
|
|
1981
|
+
}, mode);
|
|
1982
|
+
if (!mode.json && projects.length === 0) writeText("No projects yet. Create one on the web, then publish with --project-id.\n");
|
|
1983
|
+
}
|
|
1984
|
+
//#endregion
|
|
1985
|
+
//#region src/command-runners/publish.ts
|
|
1986
|
+
const MAX_PUBLISH_KEY_LENGTH = 128;
|
|
1987
|
+
async function runPublish(parsed, mode, isRetry = false) {
|
|
1988
|
+
const command = "publish";
|
|
1989
|
+
const targetPath = parsed.positionals[0];
|
|
1990
|
+
if (!targetPath) return writeFailure(command, validationError("Path is required.", "Pass a file or directory to publish."), mode, 1);
|
|
1991
|
+
let publishKey = null;
|
|
1992
|
+
if ("key" in parsed.options) {
|
|
1993
|
+
publishKey = (typeof parsed.options.key === "string" ? parsed.options.key : "").trim();
|
|
1994
|
+
if (publishKey.length === 0 || publishKey.length > MAX_PUBLISH_KEY_LENGTH) return writeFailure(command, validationError(`--key must be 1-${MAX_PUBLISH_KEY_LENGTH} characters after trimming.`, "Pass a short stable identifier, like a job name or PR number."), mode, 1);
|
|
1995
|
+
}
|
|
1996
|
+
const config = await readProjectConfig();
|
|
1997
|
+
const credential = await resolveCredential(parsed.options, config);
|
|
1998
|
+
if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runPublish(parsed, mode, true), isRetry);
|
|
1999
|
+
const baseUrl = baseUrlOf(parsed.options);
|
|
2000
|
+
const hasProjectFlag = "project" in parsed.options;
|
|
2001
|
+
let destinationOptions = parsed.options;
|
|
2002
|
+
let projectName;
|
|
2003
|
+
if (hasProjectFlag) {
|
|
2004
|
+
projectName = nonEmpty(typeof parsed.options.project === "string" ? parsed.options.project : "");
|
|
2005
|
+
if (!projectName) return writeFailure(command, validationError("--project requires a value.", "Pass --project <name> and retry."), mode, 1);
|
|
2006
|
+
const conflict = destinationConflictError(parsed.options);
|
|
2007
|
+
if (conflict) return writeFailure(command, conflict, mode, 1);
|
|
2008
|
+
} else {
|
|
2009
|
+
const earlyDestination = resolveDestination(parsed.options, config);
|
|
2010
|
+
if (earlyDestination.error) return writeFailure(command, earlyDestination.error, mode, 1);
|
|
2011
|
+
}
|
|
2012
|
+
const fileStat = await stat(targetPath).catch(() => null);
|
|
2013
|
+
if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
|
|
2014
|
+
const request = requestConfig(parsed.options);
|
|
2015
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2016
|
+
if (hasProjectFlag && projectName) {
|
|
2017
|
+
const resolved = await resolveProjectIdByName(projectName, credential.token, parsed.options, request.init);
|
|
2018
|
+
if (resolved.error) return writeFailure(command, resolved.error, mode, 1);
|
|
2019
|
+
const { project: _project, ...rest } = parsed.options;
|
|
2020
|
+
destinationOptions = {
|
|
2021
|
+
...rest,
|
|
2022
|
+
projectId: resolved.projectId
|
|
2023
|
+
};
|
|
2024
|
+
}
|
|
2025
|
+
const destination = resolveDestination(destinationOptions, config);
|
|
2026
|
+
if (destination.error) return writeFailure(command, destination.error, mode, 1);
|
|
2027
|
+
const initialForm = new FormData();
|
|
2028
|
+
const grantEmails = arrayOption(parsed.options.grantEmail);
|
|
2029
|
+
const requestedVisibility = parsed.options.visibility ?? (destination.containerId && grantEmails.length === 0 ? "project" : "private");
|
|
2030
|
+
initialForm.set("visibility", requestedVisibility);
|
|
2031
|
+
for (const email of grantEmails) initialForm.append("grant_email", email);
|
|
2032
|
+
if (destination.containerId) initialForm.set("container_id", destination.containerId);
|
|
2033
|
+
const uploadUrl = apiUrl("/api/shareables/uploads", baseUrl);
|
|
2034
|
+
if (publishKey !== null) uploadUrl.searchParams.set("publish_key", publishKey);
|
|
2035
|
+
const upload = await prepareUploadPayload(targetPath, fileStat, initialForm);
|
|
2036
|
+
if (upload.error) return writeFailure(command, upload.error, mode, 1);
|
|
2037
|
+
if (upload.payload.kind === "static_site") {
|
|
2038
|
+
uploadUrl.searchParams.set("artifact_kind", "static_site");
|
|
2039
|
+
if (destination.containerId) uploadUrl.searchParams.set("container_id", destination.containerId);
|
|
2040
|
+
}
|
|
2041
|
+
const response = await fetch(uploadUrl, {
|
|
2042
|
+
method: "POST",
|
|
2043
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
2044
|
+
body: upload.payload.form,
|
|
2045
|
+
...request.init
|
|
2046
|
+
}).catch((error) => ({ networkError: error }));
|
|
2047
|
+
if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
|
|
2048
|
+
const body = await readJson(response);
|
|
2049
|
+
if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
|
|
2050
|
+
const id = body?.id ?? null;
|
|
2051
|
+
return writeSuccess(command, {
|
|
2052
|
+
artifact: {
|
|
2053
|
+
id,
|
|
2054
|
+
url: body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
|
|
2055
|
+
kind: body?.artifactKind ?? upload.payload.kind
|
|
2056
|
+
},
|
|
2057
|
+
version: { id: body?.versionId ?? null },
|
|
2058
|
+
result: { created: body?.created ?? true },
|
|
2059
|
+
...publishKey !== null ? { key: publishKey } : {},
|
|
2060
|
+
destination: destination.containerId ? {
|
|
2061
|
+
type: "project",
|
|
2062
|
+
project_id: destination.containerId
|
|
2063
|
+
} : { type: "home" },
|
|
2064
|
+
share: {
|
|
2065
|
+
visibility: body?.visibility ?? requestedVisibility,
|
|
2066
|
+
grant_emails: grantEmails
|
|
2067
|
+
}
|
|
2068
|
+
}, mode);
|
|
2069
|
+
}
|
|
2070
|
+
async function resolveProjectIdByName(projectName, token, options, init) {
|
|
2071
|
+
const result = await fetchProjects(token, options, init);
|
|
2072
|
+
if (result.error) return { error: result.error };
|
|
2073
|
+
const candidates = result.projects.flatMap((project) => {
|
|
2074
|
+
if (project.name !== projectName) return [];
|
|
2075
|
+
return [{
|
|
2076
|
+
project_id: project.id,
|
|
2077
|
+
name: project.name,
|
|
2078
|
+
updated_at: project.updated_at
|
|
2079
|
+
}];
|
|
2080
|
+
});
|
|
2081
|
+
if (candidates.length === 0) return { error: projectNotFoundByNameError() };
|
|
2082
|
+
if (candidates.length > 1) return { error: projectAmbiguousError(candidates) };
|
|
2083
|
+
return { projectId: candidates[0].project_id };
|
|
2084
|
+
}
|
|
2085
|
+
//#endregion
|
|
2086
|
+
//#region src/command-runners/request-access.ts
|
|
2087
|
+
const NOTE_MAX = 2e3;
|
|
2088
|
+
async function runRequestAccess(parsed, mode) {
|
|
2089
|
+
const command = "request-access";
|
|
2090
|
+
const note = parsed.options.note;
|
|
2091
|
+
if (note !== void 0 && note.length > NOTE_MAX) return writeFailure(command, validationError(`A note can be at most ${NOTE_MAX} characters.`, "Shorten --note and retry."), mode, 1);
|
|
2092
|
+
const credential = await resolveCredential(parsed.options, await readProjectConfig());
|
|
2093
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
2094
|
+
const request = requestConfig(parsed.options);
|
|
2095
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2096
|
+
const result = await apiPost("/api/cli/request-access", credential.token, { note }, parsed.options, request.init);
|
|
2097
|
+
if (result.error) return writeFailure(command, result.error, mode, 1);
|
|
2098
|
+
const body = result.body;
|
|
2099
|
+
const data = {
|
|
2100
|
+
requested: body?.requested === true,
|
|
2101
|
+
already_enabled: body?.already_enabled === true,
|
|
2102
|
+
status: typeof body?.status === "string" ? body.status : null,
|
|
2103
|
+
created: body?.created === true,
|
|
2104
|
+
requires_operator_action: body?.requires_operator_action === true,
|
|
2105
|
+
message: typeof body?.message === "string" ? body.message : ""
|
|
2106
|
+
};
|
|
2107
|
+
writeSuccess(command, data, mode);
|
|
2108
|
+
if (!mode.json && data.message) writeText(`${data.message}\n`);
|
|
2109
|
+
}
|
|
2110
|
+
//#endregion
|
|
2111
|
+
//#region src/command-runners/resolve.ts
|
|
2112
|
+
async function runResolve(parsed, mode) {
|
|
2113
|
+
const command = "resolve";
|
|
2114
|
+
const value = parsed.positionals[0]?.trim();
|
|
2115
|
+
if (!value) return writeFailure(command, validationError("Resolve value is required.", "Pass a URL, ID, title, or project name to resolve."), mode, 1);
|
|
2116
|
+
const credential = await resolveCredential(parsed.options, await readProjectConfig());
|
|
2117
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
2118
|
+
const request = requestConfig(parsed.options);
|
|
2119
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2120
|
+
const url = apiUrl("/api/cli/resolve", baseUrlOf(parsed.options));
|
|
2121
|
+
url.searchParams.set("q", value);
|
|
2122
|
+
const response = await fetch(url, {
|
|
2123
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
2124
|
+
...request.init
|
|
2125
|
+
}).catch((error) => ({ networkError: error }));
|
|
2126
|
+
if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
|
|
2127
|
+
const body = await readJson(response);
|
|
2128
|
+
if (!response.ok) return writeFailure(command, mapApiError(response.status, body, { authenticated: true }), mode, 1);
|
|
2129
|
+
if (!resolveSuccessFields(body)) return writeFailure(command, serviceError("Resolve succeeded but the response did not include query, candidates, and has_more."), mode, 1);
|
|
2130
|
+
return writeSuccess(command, body, mode);
|
|
2131
|
+
}
|
|
2132
|
+
//#endregion
|
|
2133
|
+
//#region src/command-runners/skills.ts
|
|
2134
|
+
const SKILL_TOOLS = [
|
|
2135
|
+
"codex",
|
|
2136
|
+
"claude",
|
|
2137
|
+
"cursor"
|
|
2138
|
+
];
|
|
2139
|
+
const SKILL_FILE_PATH = join("skills", "artifactshare", "SKILL.md");
|
|
2140
|
+
const TOOL_CONFIG = {
|
|
2141
|
+
codex: {
|
|
2142
|
+
relativePath: join(".agents", SKILL_FILE_PATH),
|
|
2143
|
+
scopes: ["project", "user"],
|
|
2144
|
+
detectDirs: [".codex", ".agents"],
|
|
2145
|
+
bundledFile: "SKILL.md",
|
|
2146
|
+
pruneDirs: ["artifactshare", "skills"]
|
|
2147
|
+
},
|
|
2148
|
+
claude: {
|
|
2149
|
+
relativePath: join(".claude", SKILL_FILE_PATH),
|
|
2150
|
+
scopes: ["project", "user"],
|
|
2151
|
+
detectDirs: [".claude"],
|
|
2152
|
+
bundledFile: "SKILL.md",
|
|
2153
|
+
pruneDirs: ["artifactshare", "skills"]
|
|
2154
|
+
},
|
|
2155
|
+
cursor: {
|
|
2156
|
+
relativePath: join(".cursor", "rules", "artifactshare.mdc"),
|
|
2157
|
+
scopes: ["project"],
|
|
2158
|
+
detectDirs: [".cursor"],
|
|
2159
|
+
bundledFile: "artifactshare.mdc",
|
|
2160
|
+
pruneDirs: []
|
|
2161
|
+
}
|
|
2162
|
+
};
|
|
2163
|
+
function skillTarget(tool, scope) {
|
|
2164
|
+
const relative = TOOL_CONFIG[tool].relativePath;
|
|
2165
|
+
const path = scope === "project" ? relative : join(homedir(), relative);
|
|
2166
|
+
return {
|
|
2167
|
+
tool,
|
|
2168
|
+
scope,
|
|
2169
|
+
path,
|
|
2170
|
+
absolutePath: resolve(path)
|
|
2171
|
+
};
|
|
2172
|
+
}
|
|
2173
|
+
function allTargets() {
|
|
2174
|
+
return SKILL_TOOLS.flatMap((tool) => TOOL_CONFIG[tool].scopes.map((scope) => skillTarget(tool, scope)));
|
|
2175
|
+
}
|
|
2176
|
+
function managedState(content) {
|
|
2177
|
+
if (content === null) return { kind: "missing" };
|
|
2178
|
+
if (!content.includes("artifactshare-skill")) return { kind: "unmanaged" };
|
|
2179
|
+
const block = content.match(/<!--\s*artifactshare-skill([\s\S]*?)-->/)?.[1];
|
|
2180
|
+
const version = block?.match(/(?:^|\n)\s*version:\s*(\d+)\s*(?:\n|$)/)?.[1];
|
|
2181
|
+
const managed = block !== void 0 && /(?:^|\n)\s*managed:\s*true\s*(?:\n|$)/.test(block);
|
|
2182
|
+
if (version === void 0 || !managed) return { kind: "broken" };
|
|
2183
|
+
return {
|
|
2184
|
+
kind: "managed",
|
|
2185
|
+
version: Number(version)
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
async function readTarget(target) {
|
|
2189
|
+
return managedState(await readFile(target.absolutePath, "utf8").catch(() => null));
|
|
2190
|
+
}
|
|
2191
|
+
async function loadBundledSkills() {
|
|
2192
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
2193
|
+
const contents = {};
|
|
2194
|
+
let version;
|
|
2195
|
+
for (const tool of SKILL_TOOLS) {
|
|
2196
|
+
const file = TOOL_CONFIG[tool].bundledFile;
|
|
2197
|
+
let content = byFile.get(file);
|
|
2198
|
+
if (content === void 0) {
|
|
2199
|
+
content = await readFile(new URL(`../skills/artifactshare/${file}`, import.meta.url), "utf8");
|
|
2200
|
+
const state = managedState(content);
|
|
2201
|
+
if (state.kind !== "managed" || (version ?? state.version) !== state.version) throw new Error(`The bundled ${file} has a missing or mismatched managed marker.`);
|
|
2202
|
+
version = state.version;
|
|
2203
|
+
byFile.set(file, content);
|
|
2204
|
+
}
|
|
2205
|
+
contents[tool] = content;
|
|
2206
|
+
}
|
|
2207
|
+
return {
|
|
2208
|
+
contents,
|
|
2209
|
+
version
|
|
2210
|
+
};
|
|
2211
|
+
}
|
|
2212
|
+
function parseTools(value) {
|
|
2213
|
+
const raws = arrayOption(value);
|
|
2214
|
+
const tools = [];
|
|
2215
|
+
for (const raw of raws) for (const item of raw.split(",")) {
|
|
2216
|
+
const trimmed = item.trim();
|
|
2217
|
+
if (!trimmed) continue;
|
|
2218
|
+
if (!SKILL_TOOLS.includes(trimmed)) return { error: validationError(`Unknown --tool value: ${trimmed}`, "Pass --tool codex, --tool claude, or --tool cursor.") };
|
|
2219
|
+
tools.push(trimmed);
|
|
2220
|
+
}
|
|
2221
|
+
if (raws.length > 0 && tools.length === 0) return { error: validationError("--tool has no value.", "Pass --tool codex, --tool claude, or --tool cursor.") };
|
|
2222
|
+
return { tools: [...new Set(tools)] };
|
|
2223
|
+
}
|
|
2224
|
+
function parseScope(value) {
|
|
2225
|
+
const trimmed = nonEmpty(value);
|
|
2226
|
+
if (trimmed === void 0) return { scope: void 0 };
|
|
2227
|
+
if (trimmed === "project" || trimmed === "user") return { scope: trimmed };
|
|
2228
|
+
return { error: validationError(`Unknown --scope value: ${trimmed}`, "Pass --scope project or --scope user.") };
|
|
2229
|
+
}
|
|
2230
|
+
function parseFilters(parsed) {
|
|
2231
|
+
const tools = parseTools(parsed.options.tool);
|
|
2232
|
+
if (tools.error) return { error: tools.error };
|
|
2233
|
+
const scope = parseScope(parsed.options.scope);
|
|
2234
|
+
if (scope.error) return { error: scope.error };
|
|
2235
|
+
const unsupported = scope.scope === void 0 ? void 0 : tools.tools.find((tool) => !TOOL_CONFIG[tool].scopes.includes(scope.scope));
|
|
2236
|
+
if (unsupported) return { error: validationError(`The ${unsupported} tool does not support --scope ${scope.scope}.`, `Use --tool ${unsupported} --scope project.`) };
|
|
2237
|
+
return {
|
|
2238
|
+
tools: tools.tools,
|
|
2239
|
+
scope: scope.scope
|
|
2240
|
+
};
|
|
2241
|
+
}
|
|
2242
|
+
function filteredTargets(tools, scope) {
|
|
2243
|
+
return allTargets().filter((target) => (tools.length === 0 || tools.includes(target.tool)) && (scope === void 0 || target.scope === scope));
|
|
2244
|
+
}
|
|
2245
|
+
async function applyAction({ target, action, content }) {
|
|
2246
|
+
if (content !== void 0) {
|
|
2247
|
+
await mkdir(dirname(target.absolutePath), { recursive: true });
|
|
2248
|
+
await writeFile(target.absolutePath, content);
|
|
2249
|
+
return;
|
|
2250
|
+
}
|
|
2251
|
+
if (action === "removed") {
|
|
2252
|
+
await rm(target.absolutePath, { force: true });
|
|
2253
|
+
await cleanupSkillDirs(target);
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
async function cleanupSkillDirs(target) {
|
|
2257
|
+
let dir = dirname(target.absolutePath);
|
|
2258
|
+
for (const expected of TOOL_CONFIG[target.tool].pruneDirs) {
|
|
2259
|
+
if (basename(dir) !== expected) return;
|
|
2260
|
+
try {
|
|
2261
|
+
await rmdir(dir);
|
|
2262
|
+
} catch {
|
|
2263
|
+
return;
|
|
2264
|
+
}
|
|
2265
|
+
dir = dirname(dir);
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
async function finishActions(command, planned, dryRun, mode) {
|
|
2269
|
+
if (!dryRun) try {
|
|
2270
|
+
for (const item of planned) await applyAction(item);
|
|
2271
|
+
} catch (error) {
|
|
2272
|
+
return writeFailure(command, unexpectedError(error), mode, 1);
|
|
2273
|
+
}
|
|
2274
|
+
return writeSuccess(command, {
|
|
2275
|
+
dry_run: dryRun,
|
|
2276
|
+
targets: planned.map(({ target, action }) => ({
|
|
2277
|
+
tool: target.tool,
|
|
2278
|
+
scope: target.scope,
|
|
2279
|
+
path: target.path,
|
|
2280
|
+
action
|
|
2281
|
+
}))
|
|
2282
|
+
}, mode);
|
|
2283
|
+
}
|
|
2284
|
+
async function bundledOrFailure(command, mode) {
|
|
2285
|
+
try {
|
|
2286
|
+
return await loadBundledSkills();
|
|
2287
|
+
} catch (error) {
|
|
2288
|
+
writeFailure(command, unexpectedError(error), mode, 1);
|
|
2289
|
+
return;
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
2292
|
+
async function runSkillsInstall(parsed, mode) {
|
|
2293
|
+
const command = "skills install";
|
|
2294
|
+
const filters = parseFilters(parsed);
|
|
2295
|
+
if (filters.error) return writeFailure(command, filters.error, mode, 1);
|
|
2296
|
+
const { tools } = filters;
|
|
2297
|
+
if (tools.length === 0) return writeFailure(command, validationError("--tool is required.", "Pass --tool codex, --tool claude, or --tool cursor; repeat for multiple tools."), mode, 1);
|
|
2298
|
+
const scope = filters.scope ?? "project";
|
|
2299
|
+
const force = parsed.options.force === true;
|
|
2300
|
+
const bundled = await bundledOrFailure(command, mode);
|
|
2301
|
+
if (!bundled) return;
|
|
2302
|
+
const planned = [];
|
|
2303
|
+
for (const tool of tools) {
|
|
2304
|
+
const target = skillTarget(tool, scope);
|
|
2305
|
+
const state = await readTarget(target);
|
|
2306
|
+
if ((state.kind === "unmanaged" || state.kind === "broken") && !force) return writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
|
|
2307
|
+
if (state.kind === "managed" && state.version === bundled.version && !force) {
|
|
2308
|
+
planned.push({
|
|
2309
|
+
target,
|
|
2310
|
+
action: "unchanged"
|
|
2311
|
+
});
|
|
2312
|
+
continue;
|
|
2313
|
+
}
|
|
2314
|
+
planned.push({
|
|
2315
|
+
target,
|
|
2316
|
+
action: state.kind === "missing" ? "installed" : "updated",
|
|
2317
|
+
content: bundled.contents[tool]
|
|
2318
|
+
});
|
|
2319
|
+
}
|
|
2320
|
+
return finishActions(command, planned, parsed.options.dryRun === true, mode);
|
|
2321
|
+
}
|
|
2322
|
+
async function runSkillsList(parsed, mode) {
|
|
2323
|
+
const bundled = await bundledOrFailure("skills list", mode);
|
|
2324
|
+
if (!bundled) return;
|
|
2325
|
+
const targets = [];
|
|
2326
|
+
for (const target of allTargets()) {
|
|
2327
|
+
const base = target.scope === "project" ? process.cwd() : homedir();
|
|
2328
|
+
let detected = false;
|
|
2329
|
+
for (const dir of TOOL_CONFIG[target.tool].detectDirs) if ((await stat(join(base, dir)).catch(() => null))?.isDirectory()) detected = true;
|
|
2330
|
+
const state = await readTarget(target);
|
|
2331
|
+
targets.push({
|
|
2332
|
+
tool: target.tool,
|
|
2333
|
+
scope: target.scope,
|
|
2334
|
+
path: target.path,
|
|
2335
|
+
detected,
|
|
2336
|
+
installed: state.kind !== "missing",
|
|
2337
|
+
managed: state.kind === "managed",
|
|
2338
|
+
installed_version: state.kind === "managed" ? state.version : null,
|
|
2339
|
+
update_available: state.kind === "managed" && state.version !== bundled.version
|
|
2340
|
+
});
|
|
2341
|
+
}
|
|
2342
|
+
return writeSuccess("skills list", {
|
|
2343
|
+
bundled_version: bundled.version,
|
|
2344
|
+
targets
|
|
2345
|
+
}, mode);
|
|
2346
|
+
}
|
|
2347
|
+
async function runSkillsUpdate(parsed, mode) {
|
|
2348
|
+
const command = "skills update";
|
|
2349
|
+
const filters = parseFilters(parsed);
|
|
2350
|
+
if (filters.error) return writeFailure(command, filters.error, mode, 1);
|
|
2351
|
+
const force = parsed.options.force === true;
|
|
2352
|
+
const bundled = await bundledOrFailure(command, mode);
|
|
2353
|
+
if (!bundled) return;
|
|
2354
|
+
const planned = [];
|
|
2355
|
+
for (const target of filteredTargets(filters.tools, filters.scope)) {
|
|
2356
|
+
const state = await readTarget(target);
|
|
2357
|
+
if (state.kind === "broken") return writeFailure(command, skillUpdateConflictError(target.path), mode, 1);
|
|
2358
|
+
if (state.kind === "missing") planned.push({
|
|
2359
|
+
target,
|
|
2360
|
+
action: "not_installed"
|
|
2361
|
+
});
|
|
2362
|
+
else if (state.kind === "unmanaged") planned.push({
|
|
2363
|
+
target,
|
|
2364
|
+
action: "skipped_unmanaged"
|
|
2365
|
+
});
|
|
2366
|
+
else if (state.version !== bundled.version || force) planned.push({
|
|
2367
|
+
target,
|
|
2368
|
+
action: "updated",
|
|
2369
|
+
content: bundled.contents[target.tool]
|
|
2370
|
+
});
|
|
2371
|
+
else planned.push({
|
|
2372
|
+
target,
|
|
2373
|
+
action: "unchanged"
|
|
2374
|
+
});
|
|
2375
|
+
}
|
|
2376
|
+
return finishActions(command, planned, parsed.options.dryRun === true, mode);
|
|
2377
|
+
}
|
|
2378
|
+
async function runSkillsRemove(parsed, mode) {
|
|
2379
|
+
const command = "skills remove";
|
|
2380
|
+
const filters = parseFilters(parsed);
|
|
2381
|
+
if (filters.error) return writeFailure(command, filters.error, mode, 1);
|
|
2382
|
+
const planned = [];
|
|
2383
|
+
for (const target of filteredTargets(filters.tools, filters.scope)) {
|
|
2384
|
+
const state = await readTarget(target);
|
|
2385
|
+
const action = state.kind === "missing" ? "not_installed" : state.kind === "managed" ? "removed" : "skipped_unmanaged";
|
|
2386
|
+
planned.push({
|
|
2387
|
+
target,
|
|
2388
|
+
action
|
|
2389
|
+
});
|
|
2390
|
+
}
|
|
2391
|
+
return finishActions(command, planned, parsed.options.dryRun === true, mode);
|
|
2392
|
+
}
|
|
2393
|
+
//#endregion
|
|
2394
|
+
//#region src/command-runners/update.ts
|
|
2395
|
+
async function runUpdate(parsed, mode, isRetry = false) {
|
|
2396
|
+
const command = "update";
|
|
2397
|
+
const artifactInput = parsed.positionals[0];
|
|
2398
|
+
const targetPath = parsed.positionals[1];
|
|
2399
|
+
if (!artifactInput) return writeFailure(command, validationError("Artifact is required.", "Pass an artifact ID or share URL to update."), mode, 1);
|
|
2400
|
+
if (!targetPath) return writeFailure(command, validationError("Path is required.", "Pass a file or directory to add as the new version."), mode, 1);
|
|
2401
|
+
const unsupportedOption = unsupportedUpdateOption(parsed.options);
|
|
2402
|
+
if (unsupportedOption) return writeFailure(command, validationError(`Update does not accept --${unsupportedOption}.`, "Update only adds a new version. Remove unsupported options and retry."), mode, 1);
|
|
2403
|
+
const artifactId = resolveArtifactId(artifactInput);
|
|
2404
|
+
if (!artifactId) return writeFailure(command, targetResolutionError(artifactInput, "update"), mode, 1);
|
|
2405
|
+
const credential = await resolveCredential(parsed.options, await readProjectConfig());
|
|
2406
|
+
if (!credential.ok) return handleCredentialFailure(command, credential, parsed.options, mode, () => runUpdate(parsed, mode, true), isRetry);
|
|
2407
|
+
const fileStat = await stat(targetPath).catch(() => null);
|
|
2408
|
+
if (!fileStat) return writeFailure(command, validationError("Path was not found.", `Check the path and retry: ${targetPath}`), mode, 1);
|
|
2409
|
+
const baseUrl = baseUrlOf(parsed.options);
|
|
2410
|
+
const request = requestConfig(parsed.options);
|
|
2411
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2412
|
+
const upload = await prepareUploadPayload(targetPath, fileStat);
|
|
2413
|
+
if (upload.error) return writeFailure(command, upload.error, mode, 1);
|
|
2414
|
+
const updateUrl = apiUrl(`/api/shareables/${encodeURIComponent(artifactId)}/versions`, baseUrl);
|
|
2415
|
+
if (upload.payload.kind === "static_site") updateUrl.searchParams.set("artifact_kind", "static_site");
|
|
2416
|
+
const response = await fetch(updateUrl, {
|
|
2417
|
+
method: "POST",
|
|
2418
|
+
headers: { Authorization: `Bearer ${credential.token}` },
|
|
2419
|
+
body: upload.payload.form,
|
|
2420
|
+
...request.init
|
|
2421
|
+
}).catch((error) => ({ networkError: error }));
|
|
2422
|
+
if ("networkError" in response) return writeFailure(command, networkError(response.networkError), mode, 1);
|
|
2423
|
+
const body = await readJson(response);
|
|
2424
|
+
if (!response.ok) return writeFailure(command, mapApiError(response.status, body, {
|
|
2425
|
+
authenticated: true,
|
|
2426
|
+
artifactTarget: true
|
|
2427
|
+
}), mode, 1);
|
|
2428
|
+
const id = body?.id ?? artifactId;
|
|
2429
|
+
const result = {
|
|
2430
|
+
artifact: {
|
|
2431
|
+
id,
|
|
2432
|
+
url: body?.shareUrl ?? (id ? `${baseUrl.replace(/\/$/, "")}/a/${id}` : null),
|
|
2433
|
+
kind: body?.artifactKind ?? upload.payload.kind
|
|
2434
|
+
},
|
|
2435
|
+
version: { id: body?.versionId ?? null },
|
|
2436
|
+
result: { updated: true }
|
|
2437
|
+
};
|
|
2438
|
+
if (!updateSuccessFields(result)) return writeFailure(command, serviceError("Update succeeded but the response did not include an artifact id, URL, and version id."), mode, 1);
|
|
2439
|
+
return writeSuccess(command, result, mode);
|
|
2440
|
+
}
|
|
2441
|
+
//#endregion
|
|
2442
|
+
//#region src/command-runners/whoami.ts
|
|
2443
|
+
async function runWhoami(parsed, mode) {
|
|
2444
|
+
const command = "whoami";
|
|
2445
|
+
const credential = await resolveCredential(parsed.options, await readProjectConfig());
|
|
2446
|
+
if (!credential.ok) return writeFailure(command, credential.error, mode, 1);
|
|
2447
|
+
const request = requestConfig(parsed.options);
|
|
2448
|
+
if (request.error) return writeFailure(command, request.error, mode, 1);
|
|
2449
|
+
const whoami = await apiGet("/api/cli/whoami", credential.token, parsed.options, request.init);
|
|
2450
|
+
if (whoami.error) return writeFailure(command, whoami.error, mode, 1);
|
|
2451
|
+
return writeSuccess(command, isRecord(whoami.body) ? {
|
|
2452
|
+
...whoami.body,
|
|
2453
|
+
credential_source: credential.source
|
|
2454
|
+
} : { credential_source: credential.source }, mode);
|
|
2455
|
+
}
|
|
2456
|
+
//#endregion
|
|
2457
|
+
//#region src/commands.ts
|
|
2458
|
+
async function publishRunner(ctx) {
|
|
2459
|
+
const parsed = parsedArgsFromContext("publish", ctx);
|
|
2460
|
+
return await runPublish(parsed, outputMode(parsed.options));
|
|
2461
|
+
}
|
|
2462
|
+
async function loginRunner(ctx) {
|
|
2463
|
+
const parsed = parsedArgsFromContext("login", ctx);
|
|
2464
|
+
return await runLogin(parsed, outputMode(parsed.options));
|
|
2465
|
+
}
|
|
2466
|
+
async function updateRunner(ctx) {
|
|
2467
|
+
const parsed = parsedArgsFromContext("update", ctx);
|
|
2468
|
+
return await runUpdate(parsed, outputMode(parsed.options));
|
|
2469
|
+
}
|
|
2470
|
+
async function resolveRunner(ctx) {
|
|
2471
|
+
const parsed = parsedArgsFromContext("resolve", ctx);
|
|
2472
|
+
return await runResolve(parsed, outputMode(parsed.options));
|
|
2473
|
+
}
|
|
2474
|
+
async function downloadRunner(ctx) {
|
|
2475
|
+
const parsed = parsedArgsFromContext("download", ctx);
|
|
2476
|
+
return await runDownload(parsed, outputMode(parsed.options));
|
|
2477
|
+
}
|
|
2478
|
+
async function artifactsGetRunner(ctx) {
|
|
2479
|
+
const parsed = parsedArgsFromContext("artifacts get", ctx);
|
|
2480
|
+
return await runArtifactsGet(parsed, outputMode(parsed.options));
|
|
2481
|
+
}
|
|
2482
|
+
async function commentsListRunner(ctx) {
|
|
2483
|
+
const parsed = parsedArgsFromContext("comments list", ctx);
|
|
2484
|
+
return await runCommentsList(parsed, outputMode(parsed.options));
|
|
2485
|
+
}
|
|
2486
|
+
async function commentsPostRunner(ctx) {
|
|
2487
|
+
const parsed = parsedArgsFromContext("comments post", ctx);
|
|
2488
|
+
return await runCommentsPost(parsed, outputMode(parsed.options));
|
|
2489
|
+
}
|
|
2490
|
+
async function requestAccessRunner(ctx) {
|
|
2491
|
+
const parsed = parsedArgsFromContext("request-access", ctx);
|
|
2492
|
+
return await runRequestAccess(parsed, outputMode(parsed.options));
|
|
2493
|
+
}
|
|
2494
|
+
async function whoamiRunner(ctx) {
|
|
2495
|
+
const parsed = parsedArgsFromContext("whoami", ctx);
|
|
2496
|
+
return await runWhoami(parsed, outputMode(parsed.options));
|
|
2497
|
+
}
|
|
2498
|
+
async function profilesListRunner(ctx) {
|
|
2499
|
+
const parsed = parsedArgsFromContext("profiles list", ctx);
|
|
2500
|
+
return await runProfilesList(parsed, outputMode(parsed.options));
|
|
2501
|
+
}
|
|
2502
|
+
async function profilesUseRunner(ctx) {
|
|
2503
|
+
const parsed = parsedArgsFromContext("profiles use", ctx);
|
|
2504
|
+
return await runProfilesUse(parsed, outputMode(parsed.options));
|
|
2505
|
+
}
|
|
2506
|
+
async function projectsListRunner(ctx) {
|
|
2507
|
+
const parsed = parsedArgsFromContext("projects list", ctx);
|
|
2508
|
+
return await runProjectsList(parsed, outputMode(parsed.options));
|
|
2509
|
+
}
|
|
2510
|
+
async function initRunner(ctx) {
|
|
2511
|
+
const parsed = parsedArgsFromContext("init", ctx);
|
|
2512
|
+
return await runInit(parsed, outputMode(parsed.options));
|
|
2513
|
+
}
|
|
2514
|
+
async function skillsInstallRunner(ctx) {
|
|
2515
|
+
const parsed = parsedArgsFromContext("skills install", ctx);
|
|
2516
|
+
return await runSkillsInstall(parsed, outputMode(parsed.options));
|
|
2517
|
+
}
|
|
2518
|
+
async function skillsListRunner(ctx) {
|
|
2519
|
+
const parsed = parsedArgsFromContext("skills list", ctx);
|
|
2520
|
+
return await runSkillsList(parsed, outputMode(parsed.options));
|
|
2521
|
+
}
|
|
2522
|
+
async function skillsUpdateRunner(ctx) {
|
|
2523
|
+
const parsed = parsedArgsFromContext("skills update", ctx);
|
|
2524
|
+
return await runSkillsUpdate(parsed, outputMode(parsed.options));
|
|
2525
|
+
}
|
|
2526
|
+
async function skillsRemoveRunner(ctx) {
|
|
2527
|
+
const parsed = parsedArgsFromContext("skills remove", ctx);
|
|
2528
|
+
return await runSkillsRemove(parsed, outputMode(parsed.options));
|
|
2529
|
+
}
|
|
2530
|
+
async function doctorRunner(ctx) {
|
|
2531
|
+
const parsed = parsedArgsFromContext("doctor", ctx);
|
|
2532
|
+
return await runDoctor(parsed, outputMode(parsed.options));
|
|
2533
|
+
}
|
|
2534
|
+
function parentCommandRunner(command) {
|
|
2535
|
+
return (ctx) => {
|
|
2536
|
+
const parsed = parsedArgsFromContext(command, ctx);
|
|
2537
|
+
writeFailure(command, validationError("A subcommand is required.", `Run npx @artifactshare/cli ${command} <${(SUBCOMMANDS[command] ?? []).join(" | ")}>.`), outputMode(parsed.options), 1);
|
|
2538
|
+
};
|
|
2539
|
+
}
|
|
2540
|
+
//#endregion
|
|
2541
|
+
//#region src/index.ts
|
|
2542
|
+
async function main(rawArgv) {
|
|
2543
|
+
const argv = joinLeadingDashValues(rawArgv);
|
|
2544
|
+
const command = commandNameFromArgv(argv);
|
|
2545
|
+
const commandCandidate = firstCommandCandidate(argv);
|
|
2546
|
+
const rawError = validateRawArgs(argv);
|
|
2547
|
+
if (rawError) return writeFailure(command ?? "unknown", rawError, outputModeFromArgv(argv), 1);
|
|
2548
|
+
if (command === void 0 && commandCandidate !== void 0) return writeFailure("unknown", unknownCommandError(commandCandidate), outputModeFromArgv(argv), 1);
|
|
2549
|
+
const usage = await runGunshi(command === void 0 ? ["--help"] : normalizeArgvForGunshi(argv, commandCandidate)).catch((error) => {
|
|
2550
|
+
if (error instanceof AggregateError) {
|
|
2551
|
+
writeFailure(command ?? "unknown", validationError("Arguments are invalid.", error.errors.map((item) => item instanceof Error ? item.message : String(item)).join(" ")), outputModeFromArgv(argv), 1);
|
|
2552
|
+
return;
|
|
2553
|
+
}
|
|
2554
|
+
throw error;
|
|
2555
|
+
});
|
|
2556
|
+
if (usage) writeText(usage);
|
|
2557
|
+
}
|
|
2558
|
+
async function loadCliVersion() {
|
|
2559
|
+
try {
|
|
2560
|
+
const content = await readFile(new URL("../package.json", import.meta.url), "utf8");
|
|
2561
|
+
const pkg = JSON.parse(content);
|
|
2562
|
+
return typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
2563
|
+
} catch {
|
|
2564
|
+
return "0.0.0";
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
async function runGunshi(argv) {
|
|
2568
|
+
return cli(argv, entryCommand, {
|
|
2569
|
+
name: "artifactshare",
|
|
2570
|
+
description: "Artifact Share CLI",
|
|
2571
|
+
version: await loadCliVersion(),
|
|
2572
|
+
subCommands: {
|
|
2573
|
+
login: lazyCommand(loginDefinition, loginRunner),
|
|
2574
|
+
publish: lazyCommand(publishDefinition, publishRunner),
|
|
2575
|
+
update: lazyCommand(updateDefinition, updateRunner),
|
|
2576
|
+
resolve: lazyCommand(resolveDefinition, resolveRunner),
|
|
2577
|
+
download: lazyCommand(downloadDefinition, downloadRunner),
|
|
2578
|
+
artifacts: artifactsDefinition,
|
|
2579
|
+
comments: commentsDefinition,
|
|
2580
|
+
"request-access": lazyCommand(requestAccessDefinition, requestAccessRunner),
|
|
2581
|
+
whoami: lazyCommand(whoamiDefinition, whoamiRunner),
|
|
2582
|
+
doctor: lazyCommand(doctorDefinition, doctorRunner),
|
|
2583
|
+
profiles: profilesDefinition,
|
|
2584
|
+
projects: projectsDefinition,
|
|
2585
|
+
skills: skillsDefinition,
|
|
2586
|
+
init: lazyCommand(initDefinition, initRunner)
|
|
2587
|
+
},
|
|
2588
|
+
usageSilent: true
|
|
2589
|
+
});
|
|
2590
|
+
}
|
|
2591
|
+
function lazyCommand(definition, runner) {
|
|
2592
|
+
return lazy(() => Promise.resolve(async (ctx) => {
|
|
2593
|
+
await runner(ctx);
|
|
2594
|
+
}), definition);
|
|
2595
|
+
}
|
|
2596
|
+
const commonArgs = {
|
|
2597
|
+
json: {
|
|
2598
|
+
type: "boolean",
|
|
2599
|
+
toKebab: true,
|
|
2600
|
+
description: "Print stable JSON output"
|
|
2601
|
+
},
|
|
2602
|
+
baseUrl: {
|
|
2603
|
+
type: "string",
|
|
2604
|
+
toKebab: true,
|
|
2605
|
+
description: "Artifact Share base URL (default: ARTIFACTSHARE_BASE_URL or https://artifactshare.com)"
|
|
2606
|
+
},
|
|
2607
|
+
token: {
|
|
2608
|
+
type: "string",
|
|
2609
|
+
toKebab: true,
|
|
2610
|
+
description: "Bearer token (default: ARTIFACTSHARE_TOKEN)"
|
|
2611
|
+
},
|
|
2612
|
+
profile: {
|
|
2613
|
+
type: "string",
|
|
2614
|
+
toKebab: true,
|
|
2615
|
+
description: "Profile name for saved CLI credentials"
|
|
2616
|
+
},
|
|
2617
|
+
allowPlaintextTokenStore: {
|
|
2618
|
+
type: "boolean",
|
|
2619
|
+
toKebab: true,
|
|
2620
|
+
description: "Allow a 0600 file token store when no OS credential store is available"
|
|
2621
|
+
},
|
|
2622
|
+
insecureLocalhost: {
|
|
2623
|
+
type: "boolean",
|
|
2624
|
+
toKebab: true,
|
|
2625
|
+
description: "Allow self-signed HTTPS only for localhost dev servers"
|
|
2626
|
+
}
|
|
2627
|
+
};
|
|
2628
|
+
const entryCommand = define({
|
|
2629
|
+
name: "artifactshare",
|
|
2630
|
+
description: "Artifact Share CLI",
|
|
2631
|
+
toKebab: true,
|
|
2632
|
+
args: commonArgs,
|
|
2633
|
+
examples: `npx @artifactshare/cli publish <path> --project-id <id> --json
|
|
2634
|
+
npx @artifactshare/cli update <artifact-id-or-url> <path> --json
|
|
2635
|
+
npx @artifactshare/cli resolve <url-id-or-title> --json
|
|
2636
|
+
npx @artifactshare/cli artifacts get <artifact-id-or-url> --json
|
|
2637
|
+
npx @artifactshare/cli comments list <artifact-id-or-url> --json
|
|
2638
|
+
npx @artifactshare/cli comments post <artifact-id-or-url> --body "<text>" --json
|
|
2639
|
+
npx @artifactshare/cli download <artifact-id-or-url> --output ./artifact --json
|
|
2640
|
+
npx @artifactshare/cli login --profile default
|
|
2641
|
+
npx @artifactshare/cli profiles list --json
|
|
2642
|
+
npx @artifactshare/cli profiles use <name> --json
|
|
2643
|
+
npx @artifactshare/cli projects list --json
|
|
2644
|
+
npx @artifactshare/cli skills install --tool codex --json
|
|
2645
|
+
npx @artifactshare/cli skills list --json
|
|
2646
|
+
npx @artifactshare/cli init --profile <name> --project-id <id> --json
|
|
2647
|
+
npx @artifactshare/cli publish <path> --home --json
|
|
2648
|
+
npx @artifactshare/cli request-access --json
|
|
2649
|
+
npx @artifactshare/cli whoami --json
|
|
2650
|
+
npx @artifactshare/cli doctor --json
|
|
2
2651
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2652
|
+
Common failures:
|
|
2653
|
+
auth_required Set ARTIFACTSHARE_TOKEN or pass --token
|
|
2654
|
+
destination_required Add --project-id, configure .artifactshare/config.json, or pass --home
|
|
2655
|
+
target_not_found Use an artifact ID, share URL, or sandbox URL
|
|
2656
|
+
upload_not_allowed Upload access is limited; run request-access to join the waitlist`,
|
|
2657
|
+
run: () => {}
|
|
2658
|
+
});
|
|
2659
|
+
const loginDefinition = define({
|
|
2660
|
+
name: "login",
|
|
2661
|
+
description: "Sign in with device authorization and save a CLI profile.",
|
|
2662
|
+
toKebab: true,
|
|
2663
|
+
args: commonArgs,
|
|
2664
|
+
examples: `npx @artifactshare/cli login --profile default
|
|
2665
|
+
npx @artifactshare/cli login --profile client-a --json
|
|
2666
|
+
|
|
2667
|
+
Common failures:
|
|
2668
|
+
auth_denied The browser approval was denied
|
|
2669
|
+
auth_expired The device code expired before approval
|
|
2670
|
+
token_store_unavailable Configure an OS credential store or use the explicit plaintext fallback`
|
|
2671
|
+
});
|
|
2672
|
+
const publishDefinition = define({
|
|
2673
|
+
name: "publish",
|
|
2674
|
+
description: "Publish a file or directory.",
|
|
2675
|
+
toKebab: true,
|
|
2676
|
+
args: {
|
|
2677
|
+
...commonArgs,
|
|
2678
|
+
path: {
|
|
2679
|
+
type: "positional",
|
|
2680
|
+
description: "File or directory to publish"
|
|
2681
|
+
},
|
|
2682
|
+
projectId: {
|
|
2683
|
+
type: "string",
|
|
2684
|
+
toKebab: true,
|
|
2685
|
+
description: "Publish into a project"
|
|
2686
|
+
},
|
|
2687
|
+
project: {
|
|
2688
|
+
type: "string",
|
|
2689
|
+
toKebab: true,
|
|
2690
|
+
description: "Publish into a project by exact name"
|
|
2691
|
+
},
|
|
2692
|
+
home: {
|
|
2693
|
+
type: "boolean",
|
|
2694
|
+
toKebab: true,
|
|
2695
|
+
description: "Publish into your unfiled home destination"
|
|
2696
|
+
},
|
|
2697
|
+
visibility: {
|
|
2698
|
+
type: "string",
|
|
2699
|
+
toKebab: true,
|
|
2700
|
+
description: "private, workspace, or project (default: project for a project destination, private otherwise or with --grant-email)"
|
|
2701
|
+
},
|
|
2702
|
+
grantEmail: {
|
|
2703
|
+
type: "string",
|
|
2704
|
+
multiple: true,
|
|
2705
|
+
toKebab: true,
|
|
2706
|
+
description: "Add an explicit viewer; repeat for multiple viewers"
|
|
2707
|
+
},
|
|
2708
|
+
key: {
|
|
2709
|
+
type: "string",
|
|
2710
|
+
toKebab: true,
|
|
2711
|
+
description: "Stable key for create-or-update: the first publish creates the artifact, repeats add versions. Not a secret; it appears in logs and JSON"
|
|
2712
|
+
}
|
|
2713
|
+
},
|
|
2714
|
+
examples: `npx @artifactshare/cli publish report.html --project-id <id> --key nightly-report --json
|
|
2715
|
+
|
|
2716
|
+
Common failures:
|
|
2717
|
+
auth_required Set ARTIFACTSHARE_TOKEN before publish
|
|
2718
|
+
destination_required Non-interactive publish needs --project-id, config default, or --home
|
|
2719
|
+
upload_not_allowed Your account cannot publish yet; request access from an operator
|
|
2720
|
+
file_too_large Reduce file or directory size and retry
|
|
2721
|
+
validation_failed Check file type (.html / .md for single files) and directory layout
|
|
2722
|
+
key_target_moved The artifact for --key moved; update it by ID or use a new key
|
|
2723
|
+
key_kind_mismatch The artifact for --key is a different kind; use a new key`
|
|
2724
|
+
});
|
|
2725
|
+
const updateDefinition = define({
|
|
2726
|
+
name: "update",
|
|
2727
|
+
description: "Add a new version to an existing artifact.",
|
|
2728
|
+
toKebab: true,
|
|
2729
|
+
args: {
|
|
2730
|
+
...commonArgs,
|
|
2731
|
+
artifactIdOrUrl: {
|
|
2732
|
+
type: "positional",
|
|
2733
|
+
toKebab: true,
|
|
2734
|
+
description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
|
|
2735
|
+
},
|
|
2736
|
+
path: {
|
|
2737
|
+
type: "positional",
|
|
2738
|
+
description: "File or directory to add as the new version"
|
|
2739
|
+
}
|
|
2740
|
+
},
|
|
2741
|
+
examples: `Target:
|
|
2742
|
+
Accepts an artifact ID, /a/<id> share URL, or <id>.sandbox.* URL.
|
|
2743
|
+
Titles and project names are not updated directly; resolve them to an ID first.
|
|
2744
|
+
|
|
2745
|
+
Common failures:
|
|
2746
|
+
auth_required Set ARTIFACTSHARE_TOKEN before update
|
|
2747
|
+
target_not_found Retry with an artifact ID, share URL, or sandbox URL
|
|
2748
|
+
artifact_kind_mismatch Use a file for single-file artifacts or a directory for static sites
|
|
2749
|
+
upload_not_allowed Your account cannot publish yet; request access from an operator
|
|
2750
|
+
file_too_large Reduce file or directory size and retry
|
|
2751
|
+
validation_failed Check file type (.html / .md for single files) and directory layout`
|
|
2752
|
+
});
|
|
2753
|
+
const resolveDefinition = define({
|
|
2754
|
+
name: "resolve",
|
|
2755
|
+
description: "Find artifact, version, and project candidates before writing.",
|
|
2756
|
+
toKebab: true,
|
|
2757
|
+
args: {
|
|
2758
|
+
...commonArgs,
|
|
2759
|
+
value: {
|
|
2760
|
+
type: "positional",
|
|
2761
|
+
description: "Share URL, sandbox URL, ID, title, or project name"
|
|
2762
|
+
}
|
|
2763
|
+
},
|
|
2764
|
+
examples: `npx @artifactshare/cli resolve "Weekly report" --json
|
|
2765
|
+
npx @artifactshare/cli resolve https://artifactshare.com/a/abc123def4 --json
|
|
2766
|
+
|
|
2767
|
+
Use resolve before write commands when a user gives a title or project name.
|
|
2768
|
+
Pass the returned artifact id or project id to the next command.
|
|
2769
|
+
|
|
2770
|
+
Common failures:
|
|
2771
|
+
auth_required Set ARTIFACTSHARE_TOKEN before resolve
|
|
2772
|
+
validation_failed Pass a non-empty URL, ID, title, or project name
|
|
2773
|
+
network_failed Check --base-url and network access`
|
|
2774
|
+
});
|
|
2775
|
+
const downloadDefinition = define({
|
|
2776
|
+
name: "download",
|
|
2777
|
+
description: "Save an artifact source or static site bundle locally.",
|
|
2778
|
+
toKebab: true,
|
|
2779
|
+
args: {
|
|
2780
|
+
...commonArgs,
|
|
2781
|
+
artifactIdOrUrl: {
|
|
2782
|
+
type: "positional",
|
|
2783
|
+
toKebab: true,
|
|
2784
|
+
description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
|
|
2785
|
+
},
|
|
2786
|
+
output: {
|
|
2787
|
+
type: "string",
|
|
2788
|
+
toKebab: true,
|
|
2789
|
+
description: "Output directory (default: artifact ID)"
|
|
2790
|
+
},
|
|
2791
|
+
force: {
|
|
2792
|
+
type: "boolean",
|
|
2793
|
+
toKebab: true,
|
|
2794
|
+
description: "Allow writing into an existing output directory"
|
|
2795
|
+
}
|
|
2796
|
+
},
|
|
2797
|
+
examples: `npx @artifactshare/cli download abc123def4 --json
|
|
2798
|
+
npx @artifactshare/cli download https://artifactshare.com/a/abc123def4 --output ./artifact --json
|
|
2799
|
+
|
|
2800
|
+
Use resolve first when a user gives a title or project name, then pass the id here.
|
|
2801
|
+
Download writes files to a directory so the result can be inspected or passed to update.
|
|
2802
|
+
|
|
2803
|
+
Common failures:
|
|
2804
|
+
auth_required Set ARTIFACTSHARE_TOKEN before download
|
|
2805
|
+
target_not_found Retry with an artifact ID, share URL, or sandbox URL
|
|
2806
|
+
output_exists Choose another --output path or pass --force
|
|
2807
|
+
validation_failed Check --output and downloaded file paths`
|
|
2808
|
+
});
|
|
2809
|
+
const artifactsDefinition = define({
|
|
2810
|
+
name: "artifacts",
|
|
2811
|
+
description: "Read Artifact Share artifacts.",
|
|
2812
|
+
toKebab: true,
|
|
2813
|
+
args: commonArgs,
|
|
2814
|
+
subCommands: { get: lazyCommand(define({
|
|
2815
|
+
name: "get",
|
|
2816
|
+
description: "Read a single-file artifact source and metadata.",
|
|
2817
|
+
toKebab: true,
|
|
2818
|
+
args: {
|
|
2819
|
+
...commonArgs,
|
|
2820
|
+
artifactIdOrUrl: {
|
|
2821
|
+
type: "positional",
|
|
2822
|
+
toKebab: true,
|
|
2823
|
+
description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
|
|
2824
|
+
},
|
|
2825
|
+
offset: {
|
|
2826
|
+
type: "string",
|
|
2827
|
+
toKebab: true,
|
|
2828
|
+
description: "Character offset for continuing a truncated read"
|
|
2829
|
+
},
|
|
2830
|
+
include: {
|
|
2831
|
+
type: "string",
|
|
2832
|
+
multiple: true,
|
|
2833
|
+
toKebab: true,
|
|
2834
|
+
description: "Extra data to include: versions or comments"
|
|
2835
|
+
}
|
|
2836
|
+
},
|
|
2837
|
+
examples: `npx @artifactshare/cli artifacts get abc123def4 --json
|
|
2838
|
+
npx @artifactshare/cli artifacts get https://artifactshare.com/a/abc123def4 --include versions --include comments --json
|
|
2839
|
+
npx @artifactshare/cli artifacts get abc123def4 --offset 200000 --json
|
|
2840
|
+
|
|
2841
|
+
Use resolve first when a user gives a title or project name, then pass the id here.
|
|
2842
|
+
If truncated is true, call again with --offset set to next_offset before updating.
|
|
2843
|
+
|
|
2844
|
+
Common failures:
|
|
2845
|
+
auth_required Set ARTIFACTSHARE_TOKEN before artifacts get
|
|
2846
|
+
target_not_found Retry with an artifact ID, share URL, or sandbox URL
|
|
2847
|
+
unsupported_kind Use download for static sites or other multi-file artifacts
|
|
2848
|
+
validation_failed Check --offset and --include values`
|
|
2849
|
+
}), artifactsGetRunner) },
|
|
2850
|
+
examples: `npx @artifactshare/cli artifacts get <artifact-id-or-url> --json
|
|
2851
|
+
|
|
2852
|
+
Use artifacts get to read back Markdown or HTML before update.`,
|
|
2853
|
+
run: parentCommandRunner("artifacts")
|
|
2854
|
+
});
|
|
2855
|
+
const commentsListDefinition = define({
|
|
2856
|
+
name: "list",
|
|
2857
|
+
description: "Read the comments on an artifact.",
|
|
2858
|
+
toKebab: true,
|
|
2859
|
+
args: {
|
|
2860
|
+
...commonArgs,
|
|
2861
|
+
artifactIdOrUrl: {
|
|
2862
|
+
type: "positional",
|
|
2863
|
+
toKebab: true,
|
|
2864
|
+
description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
|
|
2865
|
+
}
|
|
2866
|
+
},
|
|
2867
|
+
examples: `npx @artifactshare/cli comments list abc123def4 --json
|
|
2868
|
+
|
|
2869
|
+
Returns up to 50 threads (open threads first); has_more reports whether more exist.
|
|
2870
|
+
Each thread carries its messages, status, and quoted-text anchor when present.
|
|
2871
|
+
|
|
2872
|
+
Common failures:
|
|
2873
|
+
auth_required Set ARTIFACTSHARE_TOKEN before comments list
|
|
2874
|
+
target_not_found Retry with an artifact ID, share URL, or sandbox URL`
|
|
2875
|
+
});
|
|
2876
|
+
const commentsPostDefinition = define({
|
|
2877
|
+
name: "post",
|
|
2878
|
+
description: "Comment on an artifact, reply, or anchor a quoted span.",
|
|
2879
|
+
toKebab: true,
|
|
2880
|
+
args: {
|
|
2881
|
+
...commonArgs,
|
|
2882
|
+
artifactIdOrUrl: {
|
|
2883
|
+
type: "positional",
|
|
2884
|
+
toKebab: true,
|
|
2885
|
+
description: "Artifact ID, /a/<id> share URL, or <id>.sandbox.* URL"
|
|
2886
|
+
},
|
|
2887
|
+
body: {
|
|
2888
|
+
type: "string",
|
|
2889
|
+
toKebab: true,
|
|
2890
|
+
description: "Comment text (required)"
|
|
2891
|
+
},
|
|
2892
|
+
replyTo: {
|
|
2893
|
+
type: "string",
|
|
2894
|
+
toKebab: true,
|
|
2895
|
+
description: "Reply to this thread id from comments list"
|
|
2896
|
+
},
|
|
2897
|
+
quote: {
|
|
2898
|
+
type: "string",
|
|
2899
|
+
toKebab: true,
|
|
2900
|
+
description: "Anchor the comment to this exact text from the artifact (new threads only)"
|
|
2901
|
+
},
|
|
2902
|
+
quoteBefore: {
|
|
2903
|
+
type: "string",
|
|
2904
|
+
toKebab: true,
|
|
2905
|
+
description: "Text just before the quote, to pick the right occurrence"
|
|
2906
|
+
},
|
|
2907
|
+
quoteAfter: {
|
|
2908
|
+
type: "string",
|
|
2909
|
+
toKebab: true,
|
|
2910
|
+
description: "Text just after the quote, to pick the right occurrence"
|
|
2911
|
+
}
|
|
2912
|
+
},
|
|
2913
|
+
examples: `npx @artifactshare/cli comments post abc123def4 --body "Looks good" --json
|
|
2914
|
+
npx @artifactshare/cli comments post abc123def4 --body "Done" --reply-to <thread-id> --json
|
|
2915
|
+
npx @artifactshare/cli comments post abc123def4 --body "Fix this" --quote "exact text" --json
|
|
2916
|
+
|
|
2917
|
+
Copy quote text from artifacts get so it matches the artifact exactly.
|
|
2918
|
+
|
|
2919
|
+
Common failures:
|
|
2920
|
+
auth_required Set ARTIFACTSHARE_TOKEN before comments post
|
|
2921
|
+
target_not_found Retry with an artifact ID, share URL, or sandbox URL
|
|
2922
|
+
thread_not_found Run comments list and retry with a listed thread id
|
|
2923
|
+
thread_resolved Reopen the thread in the viewer, or start a new thread
|
|
2924
|
+
quote_not_found Copy the exact text from artifacts get
|
|
2925
|
+
validation_failed Pass --body, and do not combine --quote with --reply-to`
|
|
2926
|
+
});
|
|
2927
|
+
const commentsDefinition = define({
|
|
2928
|
+
name: "comments",
|
|
2929
|
+
description: "Read and write artifact comments.",
|
|
2930
|
+
toKebab: true,
|
|
2931
|
+
args: commonArgs,
|
|
2932
|
+
subCommands: {
|
|
2933
|
+
list: lazyCommand(commentsListDefinition, commentsListRunner),
|
|
2934
|
+
post: lazyCommand(commentsPostDefinition, commentsPostRunner)
|
|
2935
|
+
},
|
|
2936
|
+
examples: `npx @artifactshare/cli comments list <artifact-id-or-url> --json
|
|
2937
|
+
npx @artifactshare/cli comments post <artifact-id-or-url> --body "<text>" --json`,
|
|
2938
|
+
run: parentCommandRunner("comments")
|
|
2939
|
+
});
|
|
2940
|
+
const profilesListDefinition = define({
|
|
2941
|
+
name: "list",
|
|
2942
|
+
description: "List saved CLI profiles and the default profile.",
|
|
2943
|
+
toKebab: true,
|
|
2944
|
+
args: commonArgs,
|
|
2945
|
+
examples: `npx @artifactshare/cli profiles list --json
|
|
2946
|
+
|
|
2947
|
+
token_present shows whether a saved credential exists; token values are never printed.`
|
|
2948
|
+
});
|
|
2949
|
+
const profilesUseDefinition = define({
|
|
2950
|
+
name: "use",
|
|
2951
|
+
description: "Switch the default CLI profile.",
|
|
2952
|
+
toKebab: true,
|
|
2953
|
+
args: {
|
|
2954
|
+
...commonArgs,
|
|
2955
|
+
name: {
|
|
2956
|
+
type: "positional",
|
|
2957
|
+
description: "Profile name to make the default"
|
|
2958
|
+
}
|
|
2959
|
+
},
|
|
2960
|
+
examples: `npx @artifactshare/cli profiles use client-a --json
|
|
2961
|
+
|
|
2962
|
+
Common failures:
|
|
2963
|
+
profile_not_found Run profiles list to see saved profiles, or login --profile <name>`
|
|
2964
|
+
});
|
|
2965
|
+
const profilesDefinition = define({
|
|
2966
|
+
name: "profiles",
|
|
2967
|
+
description: "Manage saved CLI profiles.",
|
|
2968
|
+
toKebab: true,
|
|
2969
|
+
args: commonArgs,
|
|
2970
|
+
subCommands: {
|
|
2971
|
+
list: lazyCommand(profilesListDefinition, profilesListRunner),
|
|
2972
|
+
use: lazyCommand(profilesUseDefinition, profilesUseRunner)
|
|
2973
|
+
},
|
|
2974
|
+
examples: `npx @artifactshare/cli profiles list --json
|
|
2975
|
+
npx @artifactshare/cli profiles use client-a --json`,
|
|
2976
|
+
run: parentCommandRunner("profiles")
|
|
2977
|
+
});
|
|
2978
|
+
const projectsDefinition = define({
|
|
2979
|
+
name: "projects",
|
|
2980
|
+
description: "Find publish destinations.",
|
|
2981
|
+
toKebab: true,
|
|
2982
|
+
args: commonArgs,
|
|
2983
|
+
subCommands: { list: lazyCommand(define({
|
|
2984
|
+
name: "list",
|
|
2985
|
+
description: "List projects you can publish into.",
|
|
2986
|
+
toKebab: true,
|
|
2987
|
+
args: commonArgs,
|
|
2988
|
+
examples: `npx @artifactshare/cli projects list --json
|
|
2989
|
+
|
|
2990
|
+
is_default marks the working-directory default project from .artifactshare/config.json.
|
|
2991
|
+
Use a project id with publish --project-id or init --project-id.`
|
|
2992
|
+
}), projectsListRunner) },
|
|
2993
|
+
examples: `npx @artifactshare/cli projects list --json`,
|
|
2994
|
+
run: parentCommandRunner("projects")
|
|
2995
|
+
});
|
|
2996
|
+
const skillsToolArgs = {
|
|
2997
|
+
tool: {
|
|
2998
|
+
type: "string",
|
|
2999
|
+
multiple: true,
|
|
3000
|
+
toKebab: true,
|
|
3001
|
+
description: "Agent tool: codex, claude, or cursor; repeat for multiple"
|
|
3002
|
+
},
|
|
3003
|
+
scope: {
|
|
3004
|
+
type: "string",
|
|
3005
|
+
toKebab: true,
|
|
3006
|
+
description: "Install scope: project (default) or user"
|
|
3007
|
+
},
|
|
3008
|
+
dryRun: {
|
|
3009
|
+
type: "boolean",
|
|
3010
|
+
toKebab: true,
|
|
3011
|
+
description: "Show planned file changes without writing"
|
|
3012
|
+
}
|
|
3013
|
+
};
|
|
3014
|
+
const skillsInstallDefinition = define({
|
|
3015
|
+
name: "install",
|
|
3016
|
+
description: "Install the bundled Artifact Share skill for an agent tool.",
|
|
3017
|
+
toKebab: true,
|
|
3018
|
+
args: {
|
|
3019
|
+
...commonArgs,
|
|
3020
|
+
...skillsToolArgs,
|
|
3021
|
+
force: {
|
|
3022
|
+
type: "boolean",
|
|
3023
|
+
toKebab: true,
|
|
3024
|
+
description: "Overwrite an existing unmanaged file or reinstall the same version"
|
|
3025
|
+
}
|
|
3026
|
+
},
|
|
3027
|
+
examples: `npx @artifactshare/cli skills install --tool codex --scope project --json
|
|
3028
|
+
npx @artifactshare/cli skills install --tool claude --tool cursor --dry-run --json
|
|
3029
|
+
|
|
3030
|
+
Writes a managed SKILL.md (codex, claude) or Cursor rule (cursor).
|
|
3031
|
+
Files without the Artifact Share managed marker are never overwritten without --force.
|
|
3032
|
+
|
|
3033
|
+
Common failures:
|
|
3034
|
+
validation_failed Pass --tool codex|claude|cursor; cursor supports --scope project only
|
|
3035
|
+
skill_update_conflict An unmanaged file exists at the target path; inspect it or pass --force`
|
|
3036
|
+
});
|
|
3037
|
+
const skillsListDefinition = define({
|
|
3038
|
+
name: "list",
|
|
3039
|
+
description: "Show skill install status for each supported agent tool.",
|
|
3040
|
+
toKebab: true,
|
|
3041
|
+
args: commonArgs,
|
|
3042
|
+
examples: `npx @artifactshare/cli skills list --json
|
|
3043
|
+
|
|
3044
|
+
Reports each tool and scope with detection, install state, and update availability.
|
|
3045
|
+
Runs locally; no network or authentication is used.`
|
|
3046
|
+
});
|
|
3047
|
+
const skillsUpdateDefinition = define({
|
|
3048
|
+
name: "update",
|
|
3049
|
+
description: "Update installed Artifact Share skills to the bundled version.",
|
|
3050
|
+
toKebab: true,
|
|
3051
|
+
args: {
|
|
3052
|
+
...commonArgs,
|
|
3053
|
+
...skillsToolArgs,
|
|
3054
|
+
force: {
|
|
3055
|
+
type: "boolean",
|
|
3056
|
+
toKebab: true,
|
|
3057
|
+
description: "Rewrite managed files even when the version already matches"
|
|
3058
|
+
}
|
|
3059
|
+
},
|
|
3060
|
+
examples: `npx @artifactshare/cli skills update --json
|
|
3061
|
+
npx @artifactshare/cli skills update --tool codex --scope user --json
|
|
3062
|
+
|
|
3063
|
+
Only files created by skills install (managed marker present) are updated.
|
|
3064
|
+
|
|
3065
|
+
Common failures:
|
|
3066
|
+
skill_update_conflict A managed marker is broken; inspect the file or reinstall with --force`
|
|
3067
|
+
});
|
|
3068
|
+
const skillsRemoveDefinition = define({
|
|
3069
|
+
name: "remove",
|
|
3070
|
+
description: "Remove Artifact Share skills installed by this CLI.",
|
|
3071
|
+
toKebab: true,
|
|
3072
|
+
args: {
|
|
3073
|
+
...commonArgs,
|
|
3074
|
+
...skillsToolArgs
|
|
3075
|
+
},
|
|
3076
|
+
examples: `npx @artifactshare/cli skills remove --json
|
|
3077
|
+
npx @artifactshare/cli skills remove --tool cursor --json
|
|
3078
|
+
|
|
3079
|
+
Only files created by skills install are deleted; unmanaged files are skipped.`
|
|
3080
|
+
});
|
|
3081
|
+
const skillsDefinition = define({
|
|
3082
|
+
name: "skills",
|
|
3083
|
+
description: "Install agent skills for Codex, Claude Code, and Cursor.",
|
|
3084
|
+
toKebab: true,
|
|
3085
|
+
args: commonArgs,
|
|
3086
|
+
subCommands: {
|
|
3087
|
+
install: lazyCommand(skillsInstallDefinition, skillsInstallRunner),
|
|
3088
|
+
list: lazyCommand(skillsListDefinition, skillsListRunner),
|
|
3089
|
+
update: lazyCommand(skillsUpdateDefinition, skillsUpdateRunner),
|
|
3090
|
+
remove: lazyCommand(skillsRemoveDefinition, skillsRemoveRunner)
|
|
3091
|
+
},
|
|
3092
|
+
examples: `npx @artifactshare/cli skills install --tool codex --json
|
|
3093
|
+
npx @artifactshare/cli skills list --json`,
|
|
3094
|
+
run: parentCommandRunner("skills")
|
|
3095
|
+
});
|
|
3096
|
+
const initDefinition = define({
|
|
3097
|
+
name: "init",
|
|
3098
|
+
description: "Save working-directory defaults to .artifactshare/config.json.",
|
|
3099
|
+
toKebab: true,
|
|
3100
|
+
args: {
|
|
3101
|
+
...commonArgs,
|
|
3102
|
+
projectId: {
|
|
3103
|
+
type: "string",
|
|
3104
|
+
toKebab: true,
|
|
3105
|
+
description: "Default project for publish in this directory"
|
|
3106
|
+
}
|
|
3107
|
+
},
|
|
3108
|
+
examples: `npx @artifactshare/cli init --profile client-a --project-id <id> --json
|
|
3109
|
+
npx @artifactshare/cli init --json
|
|
3110
|
+
|
|
3111
|
+
Without flags, init reports the current config and writes nothing.
|
|
3112
|
+
Secrets are never written to .artifactshare/config.json.
|
|
3113
|
+
|
|
3114
|
+
Common failures:
|
|
3115
|
+
profile_not_found Run profiles list to see saved profiles, or login --profile <name>`
|
|
3116
|
+
});
|
|
3117
|
+
const requestAccessDefinition = define({
|
|
3118
|
+
name: "request-access",
|
|
3119
|
+
description: "Join the early-access waitlist for publishing.",
|
|
3120
|
+
toKebab: true,
|
|
3121
|
+
args: {
|
|
3122
|
+
...commonArgs,
|
|
3123
|
+
note: {
|
|
3124
|
+
type: "string",
|
|
3125
|
+
toKebab: true,
|
|
3126
|
+
description: "Optional message for the Artifact Share team (max 2000 characters)"
|
|
3127
|
+
}
|
|
3128
|
+
},
|
|
3129
|
+
examples: `npx @artifactshare/cli request-access --json
|
|
3130
|
+
npx @artifactshare/cli request-access --note "Publishing weekly reports for my team" --json
|
|
3131
|
+
|
|
3132
|
+
Joining the waitlist does not enable publishing immediately; an operator opens it.
|
|
3133
|
+
Re-running updates your note without creating a duplicate entry.
|
|
3134
|
+
|
|
3135
|
+
Common failures:
|
|
3136
|
+
auth_required Set ARTIFACTSHARE_TOKEN, pass --token, or login --profile <name>`
|
|
3137
|
+
});
|
|
3138
|
+
const whoamiDefinition = define({
|
|
3139
|
+
name: "whoami",
|
|
3140
|
+
description: "Show the authenticated CLI user.",
|
|
3141
|
+
toKebab: true,
|
|
3142
|
+
args: commonArgs
|
|
3143
|
+
});
|
|
3144
|
+
const doctorDefinition = define({
|
|
3145
|
+
name: "doctor",
|
|
3146
|
+
description: "Check authentication, destination, network, and upload access.",
|
|
3147
|
+
toKebab: true,
|
|
3148
|
+
args: commonArgs
|
|
3149
|
+
});
|
|
3150
|
+
const cliArgv = process.argv.slice(2);
|
|
3151
|
+
main(cliArgv).catch((error) => {
|
|
3152
|
+
writeFailure("unknown", unexpectedError(error), outputModeFromArgv(cliArgv), 1);
|
|
3153
|
+
});
|
|
3154
|
+
//#endregion
|
|
3155
|
+
export {};
|