@phnx-labs/artifacts-cli 0.4.7 → 0.5.0

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.
Files changed (122) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +125 -10
  3. package/dist/cli.d.ts +1 -6
  4. package/dist/cli.js +93 -85
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/auth.d.ts +5 -0
  7. package/dist/commands/auth.js +112 -0
  8. package/dist/commands/auth.js.map +1 -0
  9. package/dist/commands/favorite.d.ts +9 -0
  10. package/dist/commands/favorite.js +59 -0
  11. package/dist/commands/favorite.js.map +1 -0
  12. package/dist/commands/share.d.ts +297 -14
  13. package/dist/commands/share.js +1351 -71
  14. package/dist/commands/share.js.map +1 -1
  15. package/dist/lib/browser-detect.d.ts +28 -0
  16. package/dist/lib/browser-detect.js +126 -0
  17. package/dist/lib/browser-detect.js.map +1 -0
  18. package/dist/lib/config.d.ts +14 -0
  19. package/dist/lib/config.js +8 -0
  20. package/dist/lib/config.js.map +1 -1
  21. package/dist/lib/embedded-html.d.ts +1 -1
  22. package/dist/lib/embedded-html.js +12 -0
  23. package/dist/lib/embedded-html.js.map +1 -1
  24. package/dist/lib/excerpt.d.ts +48 -0
  25. package/dist/lib/excerpt.js +167 -0
  26. package/dist/lib/excerpt.js.map +1 -0
  27. package/dist/lib/favorites.d.ts +73 -0
  28. package/dist/lib/favorites.js +180 -0
  29. package/dist/lib/favorites.js.map +1 -0
  30. package/dist/lib/format.d.ts +2 -0
  31. package/dist/lib/format.js +14 -0
  32. package/dist/lib/format.js.map +1 -0
  33. package/dist/lib/github.d.ts +14 -0
  34. package/dist/lib/github.js +36 -0
  35. package/dist/lib/github.js.map +1 -0
  36. package/dist/lib/header-actions.d.ts +44 -0
  37. package/dist/lib/header-actions.js +181 -0
  38. package/dist/lib/header-actions.js.map +1 -0
  39. package/dist/lib/identity/client.d.ts +49 -0
  40. package/dist/lib/identity/client.js +97 -0
  41. package/dist/lib/identity/client.js.map +1 -0
  42. package/dist/lib/identity/index.d.ts +60 -0
  43. package/dist/lib/identity/index.js +69 -0
  44. package/dist/lib/identity/index.js.map +1 -0
  45. package/dist/lib/link-previews.d.ts +67 -0
  46. package/dist/lib/link-previews.js +427 -0
  47. package/dist/lib/link-previews.js.map +1 -0
  48. package/dist/lib/links.d.ts +2 -0
  49. package/dist/lib/links.js +21 -2
  50. package/dist/lib/links.js.map +1 -1
  51. package/dist/lib/math.d.ts +31 -0
  52. package/dist/lib/math.js +122 -0
  53. package/dist/lib/math.js.map +1 -0
  54. package/dist/lib/metadata-menu.d.ts +15 -0
  55. package/dist/lib/metadata-menu.js +23 -0
  56. package/dist/lib/metadata-menu.js.map +1 -1
  57. package/dist/lib/open.d.ts +6 -0
  58. package/dist/lib/open.js +54 -0
  59. package/dist/lib/open.js.map +1 -0
  60. package/dist/lib/render.d.ts +3 -0
  61. package/dist/lib/render.js +158 -35
  62. package/dist/lib/render.js.map +1 -1
  63. package/dist/lib/revisions.d.ts +17 -0
  64. package/dist/lib/revisions.js +6 -1
  65. package/dist/lib/revisions.js.map +1 -1
  66. package/dist/lib/share/analytics.d.ts +13 -0
  67. package/dist/lib/share/analytics.js +46 -0
  68. package/dist/lib/share/analytics.js.map +1 -0
  69. package/dist/lib/share/backend.d.ts +105 -0
  70. package/dist/lib/share/backend.js +161 -0
  71. package/dist/lib/share/backend.js.map +1 -0
  72. package/dist/lib/share/capture.d.ts +31 -0
  73. package/dist/lib/share/capture.js +175 -0
  74. package/dist/lib/share/capture.js.map +1 -0
  75. package/dist/lib/share/config.d.ts +82 -0
  76. package/dist/lib/share/config.js +181 -0
  77. package/dist/lib/share/config.js.map +1 -0
  78. package/dist/lib/share/delete.d.ts +122 -0
  79. package/dist/lib/share/delete.js +174 -0
  80. package/dist/lib/share/delete.js.map +1 -0
  81. package/dist/lib/share/html.d.ts +22 -0
  82. package/dist/lib/share/html.js +89 -0
  83. package/dist/lib/share/html.js.map +1 -0
  84. package/dist/lib/share/http-error.d.ts +52 -0
  85. package/dist/lib/share/http-error.js +66 -0
  86. package/dist/lib/share/http-error.js.map +1 -0
  87. package/dist/lib/share/og.d.ts +25 -0
  88. package/dist/lib/share/og.js +85 -0
  89. package/dist/lib/share/og.js.map +1 -0
  90. package/dist/lib/share/provision.d.ts +99 -0
  91. package/dist/lib/share/provision.js +271 -0
  92. package/dist/lib/share/provision.js.map +1 -0
  93. package/dist/lib/share/publish.d.ts +393 -0
  94. package/dist/lib/share/publish.js +829 -0
  95. package/dist/lib/share/publish.js.map +1 -0
  96. package/dist/lib/share/qr.d.ts +36 -0
  97. package/dist/lib/share/qr.js +102 -0
  98. package/dist/lib/share/qr.js.map +1 -0
  99. package/dist/lib/share/storage-policy.d.ts +9 -0
  100. package/dist/lib/share/storage-policy.js +43 -0
  101. package/dist/lib/share/storage-policy.js.map +1 -0
  102. package/dist/lib/share/visibility.d.ts +92 -0
  103. package/dist/lib/share/visibility.js +108 -0
  104. package/dist/lib/share/visibility.js.map +1 -0
  105. package/dist/lib/share/worker-template.d.ts +29 -0
  106. package/dist/lib/share/worker-template.js +2154 -0
  107. package/dist/lib/share/worker-template.js.map +1 -0
  108. package/dist/lib/status-list.d.ts +49 -0
  109. package/dist/lib/status-list.js +153 -0
  110. package/dist/lib/status-list.js.map +1 -0
  111. package/dist/lib/validate.js +122 -8
  112. package/dist/lib/validate.js.map +1 -1
  113. package/package.json +12 -3
  114. package/dist/lib/share-provision.d.ts +0 -31
  115. package/dist/lib/share-provision.js +0 -83
  116. package/dist/lib/share-provision.js.map +0 -1
  117. package/dist/lib/share-worker.d.ts +0 -1
  118. package/dist/lib/share-worker.js +0 -66
  119. package/dist/lib/share-worker.js.map +0 -1
  120. package/dist/lib/share.d.ts +0 -39
  121. package/dist/lib/share.js +0 -159
  122. package/dist/lib/share.js.map +0 -1
@@ -1,75 +1,1355 @@
1
+ // `artifacts share` — publish a rendered artifact to a shareable link. Signed-in
2
+ // users hit the managed endpoint (share.getrush.ai) with their Phoenix bearer;
3
+ // otherwise the BYO Cloudflare R2 + Worker path.
4
+ import { existsSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { Argument, Option } from 'commander';
1
7
  import chalk from 'chalk';
2
- import { updateConfig, readConfig } from '../lib/config.js';
3
- import { deleteShare, generateWriteToken, joinShare, publishArtifact } from '../lib/share.js';
4
- import { DEFAULT_BUCKET_NAME, DEFAULT_WORKER_NAME, configureBucketLifecycle, createBucket, deployWorker, enableWorkersDev, setWorkerSecret } from '../lib/share-provision.js';
5
- import { renderWorkerScript } from '../lib/share-worker.js';
6
- export async function shareSetup(opts) {
7
- const apiToken = opts.token || process.env.CLOUDFLARE_API_TOKEN;
8
- const accountId = opts.account || process.env.CLOUDFLARE_ACCOUNT_ID;
9
- if (!apiToken)
10
- throw new Error('Cloudflare API token is required. Pass --token or set CLOUDFLARE_API_TOKEN.');
11
- if (!accountId)
12
- throw new Error('Cloudflare account id is required. Pass --account or set CLOUDFLARE_ACCOUNT_ID.');
13
- const workerName = opts.worker || DEFAULT_WORKER_NAME;
14
- const bucketName = opts.bucket || DEFAULT_BUCKET_NAME;
15
- const writeToken = generateWriteToken();
16
- await createBucket(apiToken, accountId, bucketName);
17
- await configureBucketLifecycle(apiToken, accountId, bucketName);
18
- await deployWorker(apiToken, accountId, workerName, renderWorkerScript(), bucketName);
19
- await setWorkerSecret(apiToken, accountId, workerName, writeToken);
20
- const subdomain = await enableWorkersDev(apiToken, accountId, workerName);
21
- const baseUrl = opts.domain ? `https://${opts.domain}` : `https://${workerName}.${subdomain}.workers.dev`;
22
- updateConfig((cfg) => ({
23
- ...cfg,
24
- share: {
25
- baseUrl,
26
- writeToken,
27
- accountId,
28
- workerName,
29
- bucketName,
30
- domain: opts.domain,
31
- analyticsToken: opts.analyticsToken,
32
- },
33
- }));
34
- console.log(`${chalk.bold('share')} ${chalk.green(baseUrl)}`);
35
- }
36
- export async function sharePublish(file, opts) {
37
- const result = await publishArtifact(file, opts);
38
- if (opts.json)
39
- console.log(JSON.stringify(result));
8
+ import { parseUnlimitedStorage } from '../lib/share/storage-policy.js';
9
+ import { formatBytes } from '../lib/format.js';
10
+ import { openPath } from '../lib/open.js';
11
+ import { compileArtifact, slugify } from '../lib/render.js';
12
+ import { DEFAULT_BUCKET_NAME, DEFAULT_CF_BUNDLE, DEFAULT_SHARE_DOMAIN, DEFAULT_WORKER_NAME, generateWriteToken, readCloudflareCreds, readShareConfig, readWriteToken, readWriteTokenEnv, storeWriteToken, writeShareConfig, } from '../lib/share/config.js';
13
+ import { addCustomDomain, configureBucketLifecycle, createBucket, deployWorker, enableWorkersDev, findZoneId, hashWorkerScript, putWorkerSecret, setWorkerSecret, updateWorker, WORKER_PHOENIX_ID_BASE_SECRET, } from '../lib/share/provision.js';
14
+ import { publishFile, resolveShareUsername, parseMetaEntries, sanitizeLabel, scanShareContent, formatSensitiveContentError, unlistedNotPrivateWarning, PUBLISH_VISIBILITY_LEVELS, SHARE_VISIBILITY_LEVELS, } from '../lib/share/publish.js';
15
+ import { deleteShare, resolveDeleteTarget } from '../lib/share/delete.js';
16
+ import { renderWorkerBundle } from '../lib/share/worker-template.js';
17
+ import { analyticsEnabled } from '../lib/share/analytics.js';
18
+ import { extractShareHttpError, formatShareHttpErrorDetail } from '../lib/share/http-error.js';
19
+ import { phoenixIdBaseForDeploy, resolveShareBackend, shareBackendKind, } from '../lib/share/backend.js';
20
+ import { publishVisibility } from '../lib/share/visibility.js';
21
+ import { resolveGitHubUsername } from '../lib/github.js';
22
+ import { refreshSessionAvatar } from '../lib/identity/index.js';
23
+ export function formatSharePublishResult(result, json = false) {
24
+ if (json)
25
+ return JSON.stringify(result, null, 2);
26
+ const lines = [chalk.green(result.url)];
27
+ if (result.slug)
28
+ lines.push(chalk.dim(` slug: ${result.slug}`));
29
+ if (result.label) {
30
+ const hint = result.labelSource === 'derived' ? chalk.dim(' (derived — pass --label to set one)') : '';
31
+ lines.push(chalk.dim(` "${result.label}"`) + hint);
32
+ }
33
+ if (result.coverUrl)
34
+ lines.push(chalk.dim(` cover ${result.coverUrl}`));
35
+ if (result.expiresAt)
36
+ lines.push(chalk.dim(` expires ${new Date(result.expiresAt).toLocaleString()}`));
37
+ else
38
+ lines.push(chalk.dim(' expires never'));
39
+ const visibility = result.visibility ?? (result.unlisted ? 'unlisted' : 'public');
40
+ if (visibility === 'unlisted') {
41
+ lines.push(chalk.dim(' visibility: unlisted (noindex, hidden from gallery — NOT authenticated)'));
42
+ }
43
+ else if (visibility === 'private') {
44
+ lines.push(chalk.dim(' visibility: private (token-gated — 404 without the key; hidden from gallery)'));
45
+ lines.push(chalk.yellow(' the key is in the URL above (?k=…) — treat the whole link as a secret'));
46
+ }
47
+ else if (visibility === 'me' || visibility === 'org') {
48
+ lines.push(chalk.dim(` visibility: ${visibility} (login required, hidden from gallery)`));
49
+ }
40
50
  else {
41
- console.log(result.url);
42
- if (result.expiresAt)
43
- console.log(`${chalk.bold('expires')} ${result.expiresAt}`);
44
- }
45
- }
46
- export function shareJoin(baseUrl, opts) {
47
- const token = opts.token || process.env.ARTIFACTS_SHARE_TOKEN;
48
- if (!token)
49
- throw new Error('Write token is required. Pass --token or set ARTIFACTS_SHARE_TOKEN.');
50
- joinShare(baseUrl, token);
51
- console.log(`${chalk.bold('share')} ${chalk.green(baseUrl.replace(/\/+$/, ''))}`);
52
- }
53
- export function shareStatus() {
54
- const cfg = readConfig();
55
- console.log(`${chalk.bold('endpoint')} ${cfg.share?.baseUrl ?? chalk.dim('not configured')}`);
56
- console.log(`${chalk.bold('worker')} ${cfg.share?.workerName ?? chalk.dim('unknown')}`);
57
- console.log(`${chalk.bold('bucket')} ${cfg.share?.bucketName ?? chalk.dim('unknown')}`);
58
- console.log(`${chalk.bold('token')} ${cfg.share?.writeToken ? chalk.green('stored in ~/.artifacts/config.json') : chalk.dim('not stored')}`);
59
- }
60
- export function shareAnalytics() {
61
- const cfg = readConfig();
62
- if (!cfg.share?.analyticsToken) {
63
- console.log(chalk.dim('Analytics is not configured. Re-run artifacts share setup with --analytics-token.'));
64
- return;
65
- }
66
- const target = cfg.share.accountId
67
- ? `https://dash.cloudflare.com/${cfg.share.accountId}/web-analytics`
68
- : 'https://dash.cloudflare.com/?to=/:account/web-analytics';
69
- console.log(target);
70
- }
71
- export async function shareDelete(slugOrUrl) {
72
- const deleted = await deleteShare(slugOrUrl);
73
- console.log(`${chalk.bold('deleted')} ${deleted}`);
51
+ lines.push(chalk.dim(` visibility: ${visibility}`));
52
+ }
53
+ return lines.join('\n');
54
+ }
55
+ /** Compare the configured endpoint's last-deployed template hash against the
56
+ * hash of the CURRENT `worker-template.ts` render. A config with no recorded
57
+ * hash (every endpoint provisioned before this field existed) is "unknown" —
58
+ * never "current" or "outdated", since there is nothing to compare against. */
59
+ export function shareTemplateStatus(cfg) {
60
+ if (!cfg.templateHash)
61
+ return 'unknown';
62
+ return cfg.templateHash === hashWorkerScript(renderWorkerBundle().script) ? 'current' : 'outdated';
63
+ }
64
+ /**
65
+ * The file that actually gets uploaded for `artifacts share <file>`.
66
+ *
67
+ * A Markdown source is compiled to HTML first — sharing is the last step of
68
+ * rendering, so `artifacts share plan.md` must not upload raw Markdown. The
69
+ * compile is publish-free: this command does its own upload, and letting
70
+ * `compileArtifact` auto-publish would mint a second, unwanted link.
71
+ *
72
+ * A 64-hex artifact id (what `artifacts history` prints, and what the header
73
+ * Share button copies — local absolute paths never enter reader-facing HTML)
74
+ * resolves through the local store: the latest saved, hash-verified snapshot
75
+ * is uploaded as-is; an id with no snapshots but a surviving source recompiles
76
+ * from that source.
77
+ */
78
+ export async function resolveUploadPath(file) {
79
+ if (/^[0-9a-f]{64}$/.test(file)) {
80
+ const { readHistory, revisionSnapshot } = await import('../lib/revisions.js');
81
+ const history = readHistory(file);
82
+ const latest = history.revisions.at(-1);
83
+ if (latest)
84
+ return revisionSnapshot(file, latest.number);
85
+ if (history.sourcePath && existsSync(history.sourcePath))
86
+ return resolveUploadPath(history.sourcePath);
87
+ throw new Error(`No local artifact with id ${file} — nothing rendered on this device matches it.`);
88
+ }
89
+ if (!/\.md$/i.test(file))
90
+ return file;
91
+ const out = join(process.cwd(), '.artifacts', `${slugify(file.replace(/.*\//, '').replace(/\.[^.]+$/, '')) || 'artifact'}.html`);
92
+ const result = await compileArtifact(file, out, { publish: false });
93
+ const errors = result.diagnostics.filter((d) => d.level === 'error');
94
+ if (errors.length) {
95
+ throw new Error(`Artifact did not compile cleanly:\n${errors.map((e) => `- ${e.message}`).join('\n')}`);
96
+ }
97
+ return out;
98
+ }
99
+ export async function runShareEdit(target, opts) {
100
+ // Token-gated `private` can't be set in place: the metadata-edit route carries
101
+ // no viewer token, so re-stamping visibility=private alone would leave the page
102
+ // gated by a hash that doesn't exist — inaccessible to everyone. Fail loud
103
+ // pointing at the publish path, which mints the key.
104
+ if (opts.visibility === 'private') {
105
+ throw new Error("Can't change a page to 'private' in place — a token-gated link needs a fresh viewer key. " +
106
+ "Re-publish it with 'artifacts share <file> --protected' instead.");
107
+ }
108
+ // Same public-listing gate as publish: label + every metadata value are
109
+ // world-readable in the gallery and `share list --list-json`.
110
+ if (opts.force !== true) {
111
+ const hits = [
112
+ ...(typeof opts.label === 'string' ? scanShareContent(opts.label) : []),
113
+ ...Object.values(opts.meta ?? {}).flatMap((value) => scanShareContent(value)),
114
+ ];
115
+ if (hits.length > 0)
116
+ throw new Error(formatSensitiveContentError(hits));
117
+ }
118
+ const backend = resolveShareBackend({ githubUser: opts.githubUser, config: opts.config, writeToken: opts.writeToken, byo: opts.byo, session: opts.session });
119
+ // me/org are Phoenix-only — surface a crisp login hint here rather than the
120
+ // Worker's generic 400 for a signed-out caller (BYO WRITE_TOKEN can only set
121
+ // public/unlisted).
122
+ if ((opts.visibility === 'me' || opts.visibility === 'org') && backend.kind !== 'managed') {
123
+ throw new Error(`Changing visibility to '${opts.visibility}' requires a Phoenix session. Run 'artifacts auth login'.`);
124
+ }
125
+ const { key } = await resolveDeleteTarget(target, { githubUser: backend.kind === 'managed' ? backend.namespace : opts.githubUser || backend.namespace });
126
+ const res = await (opts.fetchEdit ?? fetch)(`${backend.baseUrl.replace(/\/+$/, '')}/${key}`, {
127
+ method: 'PATCH',
128
+ headers: { authorization: `Bearer ${backend.token}`, 'content-type': 'application/json' },
129
+ body: JSON.stringify({
130
+ ...(opts.label !== undefined ? { label: opts.label } : {}),
131
+ ...(opts.visibility !== undefined ? { visibility: opts.visibility } : {}),
132
+ meta: opts.meta ?? {}, metaMode: opts.metaMode ?? 'merge', removeMeta: opts.removeMeta ?? [],
133
+ }),
134
+ });
135
+ const body = await res.text();
136
+ if (!res.ok) {
137
+ let detail = body;
138
+ try {
139
+ detail = String(JSON.parse(body).error ?? body);
140
+ }
141
+ catch { /* keep body */ }
142
+ throw new Error(`Share metadata edit failed (${res.status}): ${detail || 'unknown error'}`);
143
+ }
144
+ const result = JSON.parse(body);
145
+ // A Worker template that predates the visibility edit ignores the `visibility`
146
+ // field and 200s without echoing it back — which would otherwise report a
147
+ // silent success while the page's visibility never changed. Fail loud with the
148
+ // update path instead.
149
+ if (opts.visibility !== undefined && result.visibility === undefined) {
150
+ throw new Error("This share endpoint's Worker doesn't support in-place visibility changes yet — it predates them. " +
151
+ "Run 'artifacts share update' to deploy the current Worker template, then retry " +
152
+ "('artifacts share status' shows whether an update is due).");
153
+ }
154
+ return result;
155
+ }
156
+ /** Shown whenever the deployed Worker has no `?format=json` listing route — an
157
+ * endpoint provisioned before this feature. Points at the update path instead of
158
+ * letting the caller hit a 404 or an HTML body and get a confusing parse error. */
159
+ const OUTDATED_TEMPLATE_HINT = 'Your deployed share Worker has no machine-readable listing route — it predates `artifacts share list`. ' +
160
+ 'Run `artifacts share update` to deploy the current Worker template, then retry (`artifacts share status` shows whether an update is due).';
161
+ async function defaultListingFetch(url, headers) {
162
+ const res = await fetch(url, { headers: { accept: 'application/json', ...(headers || {}) } });
163
+ return { status: res.status, contentType: res.headers.get('content-type') ?? '', body: await res.text() };
164
+ }
165
+ /** Normalize the Worker's `meta` field (arbitrary `--meta key=value` entries)
166
+ * into a plain string record — `{}` for a missing/malformed field (a deployed
167
+ * Worker that predates it, or a non-object value), never throws. */
168
+ function parseMetaField(raw) {
169
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
170
+ return {};
171
+ const out = {};
172
+ for (const [k, v] of Object.entries(raw)) {
173
+ out[k] = String(v);
174
+ }
175
+ return out;
176
+ }
177
+ /** Parse the Worker's listing JSON into a validated result, failing loud (with the
178
+ * outdated-template hint) on any body that isn't the expected shape — an old Worker
179
+ * serves the HTML gallery for a non-empty namespace, which must not be silently
180
+ * accepted as "you have published nothing". */
181
+ export function parseShareListing(user, body) {
182
+ let data;
183
+ try {
184
+ data = JSON.parse(body);
185
+ }
186
+ catch {
187
+ throw new Error(OUTDATED_TEMPLATE_HINT);
188
+ }
189
+ const objectsRaw = data?.objects;
190
+ if (!data || typeof data !== 'object' || !Array.isArray(objectsRaw)) {
191
+ throw new Error(OUTDATED_TEMPLATE_HINT);
192
+ }
193
+ const objects = objectsRaw.map((o) => {
194
+ const item = o;
195
+ return {
196
+ slug: String(item.slug ?? ''),
197
+ url: String(item.url ?? ''),
198
+ size: typeof item.size === 'number' ? item.size : 0,
199
+ contentType: item.contentType == null ? null : String(item.contentType),
200
+ publishedAt: String(item.publishedAt ?? ''),
201
+ expiresAt: item.expiresAt == null ? null : String(item.expiresAt),
202
+ label: item.label == null ? null : String(item.label),
203
+ agent: item.agent == null ? null : String(item.agent),
204
+ session: item.session == null ? null : String(item.session),
205
+ host: item.host == null ? null : String(item.host),
206
+ repo: item.repo == null ? null : String(item.repo),
207
+ revisionCount: typeof item.revisionCount === 'number' ? item.revisionCount : 0,
208
+ visibility: item.visibility === 'unlisted' ||
209
+ item.visibility === 'private' ||
210
+ item.visibility === 'me' ||
211
+ item.visibility === 'org'
212
+ ? item.visibility
213
+ : 'public',
214
+ meta: parseMetaField(item.meta),
215
+ };
216
+ });
217
+ return { user, count: objects.length, objects };
218
+ }
219
+ /** Namespace for list/revisions: managed uses the Phoenix handle (email
220
+ * local-part); BYO resolves the GitHub username (gh / git config / --for-user). */
221
+ async function namespaceForBackend(backend, githubUser) {
222
+ if (backend.kind === 'managed')
223
+ return backend.namespace;
224
+ return resolveShareUsername({ githubUser: githubUser || backend.namespace || undefined });
225
+ }
226
+ /** Fetch and parse the machine-readable listing of the caller's namespace from the
227
+ * Worker's `?format=json` route. Fails loud when share was never configured, when
228
+ * the deployed template is known-outdated, or when the live response proves the
229
+ * route is absent (404 or a non-JSON 200 = the old HTML gallery) — never a silent
230
+ * empty/wrong result. */
231
+ export async function runShareList(opts = {}) {
232
+ const backend = resolveShareBackend({
233
+ githubUser: opts.githubUser,
234
+ config: opts.config,
235
+ writeToken: opts.writeToken,
236
+ byo: opts.byo,
237
+ session: opts.phoenixSession,
238
+ requireToken: false,
239
+ });
240
+ // Managed: the platform Worker is current; skip the BYO template-hash gate.
241
+ // A known-stale BYO template can't have the listing route — say so before any
242
+ // network call. 'unknown' (provisioned before templateHash tracking) is
243
+ // attempted, then caught by the response checks below if the route is absent.
244
+ let templateStatus = 'current';
245
+ if (backend.kind === 'byo') {
246
+ const cfg = opts.config ?? readShareConfig();
247
+ templateStatus = cfg ? shareTemplateStatus(cfg) : 'unknown';
248
+ if (templateStatus === 'outdated') {
249
+ throw new Error(OUTDATED_TEMPLATE_HINT);
250
+ }
251
+ }
252
+ const user = await namespaceForBackend(backend, opts.githubUser);
253
+ const scope = opts.scope ?? 'public';
254
+ const includeHidden = scope !== 'public';
255
+ const query = new URLSearchParams({ format: 'json' });
256
+ if (includeHidden)
257
+ query.set('scope', 'mine');
258
+ const listUrl = `${backend.baseUrl.replace(/\/+$/, '')}/${encodeURIComponent(user)}?${query.toString()}`;
259
+ const listingHeaders = {};
260
+ if (includeHidden) {
261
+ if (!backend.token) {
262
+ throw new Error(`Listing ${scope} shares requires owner authentication. Run 'artifacts auth login' for the managed endpoint, or configure a write token ('artifacts share join') for BYO.`);
263
+ }
264
+ listingHeaders.authorization = `Bearer ${backend.token}`;
265
+ }
266
+ const fetchListing = opts.fetchListing ?? defaultListingFetch;
267
+ const res = await fetchListing(listUrl, listingHeaders);
268
+ if (res.status === 404) {
269
+ // A single-segment path 404s either because the namespace is genuinely empty
270
+ // (current template — the listing route gates on the namespace holding objects,
271
+ // so a namespace with nothing falls through to an object GET) OR because the
272
+ // endpoint predates the listing route entirely. The recorded templateHash
273
+ // disambiguates: a 'current' template HAS the route, so its 404 means an empty
274
+ // namespace ("nothing published"); otherwise the route may be absent, so point
275
+ // at `artifacts share update`. Managed is always 'current'.
276
+ if (templateStatus === 'current') {
277
+ return { user, count: 0, objects: [] };
278
+ }
279
+ throw new Error(OUTDATED_TEMPLATE_HINT);
280
+ }
281
+ if (res.status !== 200) {
282
+ const detail = formatShareHttpErrorDetail(extractShareHttpError({ status: res.status, body: res.body }));
283
+ throw new Error(`Listing failed (${res.status}) for ${listUrl}${detail}. Check the endpoint is reachable, or that 'artifacts share setup' / 'artifacts auth login' completed.`);
284
+ }
285
+ if (!/application\/json/i.test(res.contentType)) {
286
+ // A 200 that isn't JSON means the old Worker ignored ?format=json and served
287
+ // the HTML gallery — the deployed template is outdated. Managed never hits
288
+ // this (platform Worker is current); fail loud if it somehow does.
289
+ if (backend.kind === 'managed') {
290
+ throw new Error(`Managed listing at ${listUrl} did not return JSON (${res.contentType || 'no content-type'}).`);
291
+ }
292
+ throw new Error(OUTDATED_TEMPLATE_HINT);
293
+ }
294
+ const parsed = parseShareListing(user, res.body);
295
+ return applyShareListFilters(parsed, {
296
+ agent: opts.agent,
297
+ session: opts.session,
298
+ label: opts.label,
299
+ meta: opts.meta,
300
+ scope,
301
+ });
302
+ }
303
+ /** Client-side filtering over an already-fetched listing — the Worker has no
304
+ * query surface for this, so it narrows the fetched set instead of a second round
305
+ * trip. `count` reflects the FILTERED set, matching what the caller actually
306
+ * sees. */
307
+ export function applyShareListFilters(result, filters) {
308
+ let objects = result.objects;
309
+ if (filters.scope && filters.scope !== 'all') {
310
+ objects = objects.filter((o) => o.visibility === filters.scope);
311
+ }
312
+ if (filters.agent) {
313
+ const needle = filters.agent.toLowerCase();
314
+ objects = objects.filter((o) => (o.agent ?? '').toLowerCase() === needle);
315
+ }
316
+ if (filters.session) {
317
+ objects = objects.filter((o) => o.session === filters.session);
318
+ }
319
+ if (filters.label) {
320
+ const needle = filters.label.toLowerCase();
321
+ objects = objects.filter((o) => (o.label ?? '').toLowerCase().includes(needle));
322
+ }
323
+ if (filters.meta) {
324
+ const wanted = filters.meta;
325
+ objects = objects.filter((o) => Object.entries(wanted).every(([key, value]) => o.meta[key] === value));
326
+ }
327
+ return { user: result.user, count: objects.length, objects };
328
+ }
329
+ /** Render an arbitrary `--meta` map as `k=v k2=v2` for a human table row, or
330
+ * undefined when there's nothing to show. */
331
+ function formatMetaPairs(meta) {
332
+ if (!meta)
333
+ return undefined;
334
+ const entries = Object.entries(meta);
335
+ if (entries.length === 0)
336
+ return undefined;
337
+ return entries.map(([k, v]) => `${k}=${v}`).join(' ');
338
+ }
339
+ export function formatShareList(result, json = false) {
340
+ if (json)
341
+ return JSON.stringify(result, null, 2);
342
+ if (result.count === 0) {
343
+ return chalk.dim(`No active pages published under @${result.user}.`);
344
+ }
345
+ const header = chalk.bold(`@${result.user}`) +
346
+ chalk.dim(` ${result.count} published ${result.count === 1 ? 'page' : 'pages'}`);
347
+ const rows = result.objects.map((o) => {
348
+ const when = o.publishedAt ? o.publishedAt.slice(0, 10) : 'unknown';
349
+ const visibility = o.visibility ?? 'public';
350
+ const visibilityBit = visibility === 'public' ? chalk.green('public') : chalk.yellow(visibility);
351
+ const bits = [visibilityBit, when, formatBytes(o.size)];
352
+ if (o.agent)
353
+ bits.push(o.agent);
354
+ if (o.revisionCount > 0)
355
+ bits.push(`${o.revisionCount} ${o.revisionCount === 1 ? 'revision' : 'revisions'}`);
356
+ if (o.expiresAt)
357
+ bits.push(`expires ${o.expiresAt.slice(0, 10)}`);
358
+ const metaPairs = formatMetaPairs(o.meta);
359
+ if (metaPairs)
360
+ bits.push(metaPairs);
361
+ const line = bits.join(' · ');
362
+ const title = o.label ? `${chalk.bold(o.label)}\n ` : '';
363
+ return `${title}${chalk.cyan(o.slug)} ${chalk.dim(line)}\n ${chalk.green(o.url)}`;
364
+ });
365
+ return [header, ...rows].join('\n');
366
+ }
367
+ /** Parse the Worker's `?revisions=json` payload, failing loud (with the same
368
+ * outdated-template hint as {@link parseShareListing}) on an unexpected shape. */
369
+ export function parseShareRevisions(key, body) {
370
+ let data;
371
+ try {
372
+ data = JSON.parse(body);
373
+ }
374
+ catch {
375
+ throw new Error(OUTDATED_TEMPLATE_HINT);
376
+ }
377
+ const revisionsRaw = data?.revisions;
378
+ if (!data || typeof data !== 'object' || !Array.isArray(revisionsRaw)) {
379
+ throw new Error(OUTDATED_TEMPLATE_HINT);
380
+ }
381
+ const revisions = revisionsRaw.map((o) => {
382
+ const item = o;
383
+ return {
384
+ key: String(item.key ?? ''),
385
+ url: String(item.url ?? ''),
386
+ size: typeof item.size === 'number' ? item.size : 0,
387
+ contentType: item.contentType == null ? null : String(item.contentType),
388
+ uploadedAt: String(item.uploadedAt ?? ''),
389
+ expiresAt: item.expiresAt == null ? null : String(item.expiresAt),
390
+ label: item.label == null ? null : String(item.label),
391
+ agent: item.agent == null ? null : String(item.agent),
392
+ session: item.session == null ? null : String(item.session),
393
+ host: item.host == null ? null : String(item.host),
394
+ repo: item.repo == null ? null : String(item.repo),
395
+ meta: parseMetaField(item.meta),
396
+ };
397
+ });
398
+ return { key, count: revisions.length, revisions };
399
+ }
400
+ /** Fetch and parse the retained prior versions of one published slug. `target`
401
+ * accepts the same three forms as `artifacts unshare` (a full URL, `<user>/<slug>`,
402
+ * or a bare slug resolved against the caller's own namespace) — reuses
403
+ * {@link resolveDeleteTarget} rather than re-deriving the key. */
404
+ export async function runShareRevisions(target, opts = {}) {
405
+ const backend = resolveShareBackend({
406
+ githubUser: opts.githubUser,
407
+ config: opts.config,
408
+ writeToken: opts.writeToken,
409
+ byo: opts.byo,
410
+ session: opts.session,
411
+ requireToken: false,
412
+ });
413
+ if (backend.kind === 'byo') {
414
+ const cfg = opts.config ?? readShareConfig();
415
+ if (cfg && shareTemplateStatus(cfg) === 'outdated') {
416
+ throw new Error(OUTDATED_TEMPLATE_HINT);
417
+ }
418
+ }
419
+ const githubUser = backend.kind === 'managed'
420
+ ? backend.namespace
421
+ : opts.githubUser || backend.namespace || undefined;
422
+ const { key } = await resolveDeleteTarget(target, { githubUser });
423
+ const revUrl = `${backend.baseUrl.replace(/\/+$/, '')}/${key}?revisions=json`;
424
+ const fetchListing = opts.fetchListing ?? defaultListingFetch;
425
+ const res = await fetchListing(revUrl);
426
+ if (res.status !== 200) {
427
+ const detail = formatShareHttpErrorDetail(extractShareHttpError({ status: res.status, body: res.body }));
428
+ throw new Error(`Revisions lookup failed (${res.status}) for ${revUrl}${detail}. Check the endpoint is reachable, or that 'artifacts share setup' / 'artifacts auth login' completed.`);
429
+ }
430
+ if (!/application\/json/i.test(res.contentType)) {
431
+ if (backend.kind === 'managed') {
432
+ throw new Error(`Managed revisions at ${revUrl} did not return JSON (${res.contentType || 'no content-type'}).`);
433
+ }
434
+ throw new Error(OUTDATED_TEMPLATE_HINT);
435
+ }
436
+ return parseShareRevisions(key, res.body);
437
+ }
438
+ /** Mint a one-time login ticket for the signed-in owner and build the URL that
439
+ * opens their own published page **as the owner**, so the inline visibility
440
+ * control is live in the browser. Managed backend only — the control is gated on
441
+ * the Phoenix identity, and BYO (WRITE_TOKEN) endpoints have no per-viewer login. */
442
+ export async function runShareOpen(target, opts = {}) {
443
+ const backend = resolveShareBackend({
444
+ githubUser: opts.githubUser,
445
+ config: opts.config,
446
+ session: opts.session,
447
+ requireToken: false,
448
+ });
449
+ if (backend.kind !== 'managed') {
450
+ throw new Error("'artifacts share open' needs a managed (Phoenix) endpoint — the page's inline " +
451
+ "visibility control is gated on your signed-in identity. Run 'artifacts auth login' first.");
452
+ }
453
+ const baseUrl = backend.baseUrl.replace(/\/+$/, '');
454
+ const { key } = await resolveDeleteTarget(target, { githubUser: backend.namespace });
455
+ const url = `${baseUrl}/${key}`;
456
+ const doFetch = opts.fetchTicket ??
457
+ (async (u, bearer) => {
458
+ const res = await fetch(u, { method: 'POST', headers: { authorization: `Bearer ${bearer}` } });
459
+ return { status: res.status, body: await res.text() };
460
+ });
461
+ const res = await doFetch(`${baseUrl}/__ticket`, backend.token);
462
+ if (res.status !== 200) {
463
+ throw new Error(`Could not mint a login ticket (${res.status}) from ${baseUrl}/__ticket. ` +
464
+ "The endpoint may predate this feature — run 'artifacts share update' to redeploy the Worker.");
465
+ }
466
+ let ticket;
467
+ try {
468
+ const parsed = JSON.parse(res.body);
469
+ if (typeof parsed.ticket !== 'string' || !parsed.ticket)
470
+ throw new Error('no ticket in response');
471
+ ticket = parsed.ticket;
472
+ }
473
+ catch {
474
+ throw new Error(`Ticket endpoint at ${baseUrl}/__ticket did not return a usable ticket.`);
475
+ }
476
+ const ownerUrl = `${url}?phoenix_ticket=${encodeURIComponent(ticket)}`;
477
+ return { key, url, ownerUrl };
478
+ }
479
+ export function formatShareRevisions(result, json = false) {
480
+ if (json)
481
+ return JSON.stringify(result, null, 2);
482
+ if (result.count === 0) {
483
+ return chalk.dim(`No retained revisions for ${result.key} (only the current version exists).`);
484
+ }
485
+ const header = chalk.bold(result.key) + chalk.dim(` ${result.count} retained ${result.count === 1 ? 'revision' : 'revisions'}`);
486
+ const rows = result.revisions.map((r) => {
487
+ const bits = [r.uploadedAt ? r.uploadedAt.slice(0, 10) : 'unknown', formatBytes(r.size)];
488
+ if (r.agent)
489
+ bits.push(r.agent);
490
+ if (r.label)
491
+ bits.push(r.label);
492
+ const metaPairs = formatMetaPairs(r.meta);
493
+ if (metaPairs)
494
+ bits.push(metaPairs);
495
+ return `${chalk.cyan(r.uploadedAt || r.key)} ${chalk.dim(bits.join(' · '))}\n ${chalk.green(r.url)}`;
496
+ });
497
+ return [header, ...rows].join('\n');
498
+ }
499
+ export function formatShareDeleteResult(result, json = false) {
500
+ if (json)
501
+ return JSON.stringify(result, null, 2);
502
+ if (result.skipped)
503
+ return chalk.dim(`skipped — ${result.url} was already gone`);
504
+ const lines = [chalk.green(`deleted ${result.url}`)];
505
+ if (result.cover) {
506
+ lines.push(result.cover.existedBefore
507
+ ? chalk.dim(` cover deleted ${result.cover.url}`)
508
+ : chalk.dim(` cover (none) ${result.cover.url}`));
509
+ }
510
+ if (result.revisions?.length) {
511
+ lines.push(chalk.dim(` ${result.revisions.length} retained ${result.revisions.length === 1 ? 'revision' : 'revisions'} deleted`));
512
+ }
513
+ return lines.join('\n');
514
+ }
515
+ /** Human summary of an in-place visibility change. */
516
+ function formatShareVisibilityResult(result, requested) {
517
+ const now = result.visibility ?? requested;
518
+ const from = result.previousVisibility && result.previousVisibility !== now
519
+ ? `${chalk.dim(result.previousVisibility)} → `
520
+ : '';
521
+ return [
522
+ `${chalk.green('✓')} visibility ${from}${chalk.bold(now)}`,
523
+ chalk.dim(` ${result.url}`),
524
+ chalk.dim(' body unchanged — no revision created'),
525
+ ].join('\n');
526
+ }
527
+ /** Shared handler for `artifacts share delete <targets...>` and the top-level
528
+ * `artifacts unshare <targets...>` alias. Deletes each target independently and
529
+ * continues past a failed one (rm-style), reporting all results and exiting
530
+ * non-zero if any target failed to verify as gone.
531
+ *
532
+ * `deleteFn` is a DI seam for tests (defaults to the real `deleteShare`) — it is
533
+ * never exposed as a CLI flag, only used to inject a fake config/checker/deleter
534
+ * without touching a live endpoint. */
535
+ export async function runShareDelete(targets, opts, deleteFn = deleteShare) {
536
+ const results = [];
537
+ for (const target of targets) {
538
+ try {
539
+ const result = await deleteFn(target, {
540
+ keepCover: opts.keepCover === true,
541
+ keepRevisions: opts.keepRevisions === true,
542
+ ifExists: opts.ifExists === true,
543
+ githubUser: opts.forUser,
544
+ });
545
+ results.push({ target, result });
546
+ if (!opts.deleteJson)
547
+ console.log(formatShareDeleteResult(result));
548
+ }
549
+ catch (e) {
550
+ results.push({ target, error: e.message });
551
+ if (!opts.deleteJson)
552
+ console.error(chalk.red(`${target}: ${e.message}`));
553
+ }
554
+ }
555
+ if (opts.deleteJson) {
556
+ console.log(JSON.stringify(results, null, 2));
557
+ }
558
+ if (results.some((r) => r.error)) {
559
+ process.exitCode = 1;
560
+ }
561
+ }
562
+ function registerShareDeleteOptions(cmd) {
563
+ return cmd
564
+ .option('--keep-cover', 'leave the sibling <slug>.png OG cover in place (default: delete it too)')
565
+ .option('--keep-revisions', 'leave retained revisions (<slug>/rev-*) in place (default: delete them too)')
566
+ .option('--if-exists', 'treat an already-missing target as a no-op success instead of an error')
567
+ // Named --for-user / --delete-json, not --github-user / --json: `share
568
+ // <file>` (the parent of the nested `share delete`) already owns both
569
+ // those long names, and commander resolves an option's long name against
570
+ // the WHOLE ancestor chain — a same-named child option is silently
571
+ // dropped at parse time even when it parses alone. Matches the
572
+ // `revisions`/`list` precedents below, and applies equally to the top-level
573
+ // `unshare` alias so both spellings stay identical.
574
+ .option('--for-user <user>', 'GitHub username for resolving a bare-slug target (default: resolved from gh/git config)')
575
+ .option('--delete-json', 'emit machine-readable results');
576
+ }
577
+ const SHARE_DELETE_HELP = `
578
+ Examples:
579
+ # Delete by full URL — also takes down the sibling OG cover and any retained revisions
580
+ $ artifacts share delete https://share.getrush.ai/octocat/my-plan-a1b2
581
+
582
+ # Delete by <user>/<slug>, or a bare slug in your own namespace
583
+ $ artifacts share delete octocat/my-plan-a1b2
584
+ $ artifacts unshare my-plan-a1b2
585
+
586
+ # Several at once, keep the cover, or don't error when it's already gone
587
+ $ artifacts unshare my-plan-a1b2 old-report-9f3c
588
+ $ artifacts unshare my-plan-a1b2 --keep-cover
589
+ $ artifacts unshare my-plan-a1b2 --if-exists
590
+
591
+ Notes:
592
+ A follow-up GET must resolve 404 before this reports success — the Worker's
593
+ DELETE is idempotent and returns {"ok":true} even for a key that was never
594
+ there, so that response alone is never proof of a takedown.
595
+
596
+ Retained revisions of the target go too: a share that was republished at least
597
+ once leaves its prior version(s) live at their own URL, so leaving them up would
598
+ defeat the point of taking the page down. --keep-revisions leaves them (they
599
+ still expire via the bucket's lifecycle rule either way).
600
+
601
+ artifacts share delete === artifacts unshare (same command, different name).
602
+ `;
603
+ /**
604
+ * Register the `share` subtree on the root program, plus the top-level
605
+ * `artifacts unshare` alias (see {@link registerUnshareCommand}).
606
+ */
607
+ export function registerShareCommands(program) {
608
+ const shareCmd = program
609
+ .command('share')
610
+ // Child task commands intentionally reuse publish vocabulary (`edit --label`,
611
+ // `list --meta`). Keep option ownership positional within this subtree so
612
+ // Commander does not silently resolve those flags to the parent publisher.
613
+ .enablePositionalOptions()
614
+ .description('Publish an artifact to a shareable link — managed if signed in, otherwise your Cloudflare R2.')
615
+ .argument('[file]', 'file to publish (Markdown, HTML, any static asset, or a local artifact id from `artifacts history`/`artifacts list`)')
616
+ .option('--slug <slug>', 'URL slug override (default: stable slug of the artifact title, then filename)')
617
+ .option('--github-user <user>', 'GitHub username for the share namespace (default: resolved from gh/git config; ignored on the managed endpoint)')
618
+ .option('--handle <name>', 'managed only: publish under an alternate public handle instead of your email local-part. The escape hatch when your derived handle is taken, or for a vanity namespace — the Worker binds it with the same first-writer claim')
619
+ .option('--expire <spec>', "auto-expire (default 30d). e.g. 12h, 30d, 2026-08-01, or 'never'")
620
+ .addOption(new Option('--visibility <level>', 'public (default) | unlisted | private | me | org. public is listed in the gallery and gets an OG cover; me is owner-only and org is your whole email domain (both need a Phoenix session); unlisted is an UNAUTHENTICATED capability URL; private is token-gated (404 without the key)')
621
+ .choices([...PUBLISH_VISIBILITY_LEVELS]))
622
+ .addOption(new Option('--protected', 'token-gated link (= --visibility private): the URL carries a secret key and returns 404 without it — the authenticated alternative to --unlisted'))
623
+ .option('--unlisted', 'alias of --visibility unlisted: hidden from the gallery, noindex, no OG cover (obscurity, NOT authentication)')
624
+ .addOption(new Option('--private', 'alias of --unlisted (obscurity, NOT authentication — for real read-auth use --protected)').hideHelp())
625
+ .option('--force', 'publish even when the file contains emails or credential-shaped strings')
626
+ .option('--no-cover', 'skip the OG preview image (public HTML pages get one by default)')
627
+ .option('--no-analytics', 'skip injecting the Cloudflare Web Analytics beacon')
628
+ .option('--no-qr', 'skip the footer QR of the share URL (embedded in published HTML pages by default)')
629
+ .option('--label <text>', 'human display title, shown in the gallery and `share list` (default: derived from the HTML <title>, frontmatter title, or filename)')
630
+ .option('--title <text>', 'alias of --label')
631
+ .option('--meta <key=value>', 'structured metadata (repeatable), e.g. --meta kind=plan --meta ticket=PHNX-3992. Reserved (set automatically, not settable): agent, session, host, repo, date, label', (val, prev) => [...prev, val], [])
632
+ .option('--no-revision', "overwrite an existing slug in place — skip keeping the prior version as a <slug>/rev-<ts> backup (default: keep it, see 'artifacts share revisions')")
633
+ .option('--json', 'emit the machine-readable publish result')
634
+ .action(async (file, opts) => {
635
+ if (!file) {
636
+ shareCmd.help();
637
+ return;
638
+ }
639
+ // A 64-hex artifact id resolves through the local store inside
640
+ // resolveUploadPath (latest saved snapshot), so it skips the file check.
641
+ if (!/^[0-9a-f]{64}$/.test(file) && !existsSync(file)) {
642
+ console.error(chalk.red(`No such file: ${file}`));
643
+ process.exitCode = 1;
644
+ return;
645
+ }
646
+ try {
647
+ const meta = parseMetaEntries(opts.meta);
648
+ // Public by default: an explicit flag wins; otherwise the backend-aware
649
+ // default. `shareBackendKind` reads the same session/BYO signals
650
+ // `publishFile` will resolve, so the default matches the backend the
651
+ // publish actually uses.
652
+ const visibility = publishVisibility({
653
+ visibility: opts.visibility,
654
+ unlisted: opts.unlisted === true || opts.private === true,
655
+ protected: opts.protected === true,
656
+ }, shareBackendKind({}));
657
+ // unlisted (incl. its --private alias) is obscurity, not read-auth — warn
658
+ // loudly before the publish so a "private" link is never mistaken for a
659
+ // gated one. Skipped for --json so machine output stays clean.
660
+ if (visibility === 'unlisted' && !opts.json) {
661
+ console.error(chalk.yellow(`⚠ ${unlistedNotPrivateWarning()}`));
662
+ }
663
+ const managed = shareBackendKind({}) === 'managed';
664
+ // Managed publish: fill the session's hosted avatar (one /auth/me call,
665
+ // no-op when already known) so the attribution bar can show the OAuth
666
+ // profile image.
667
+ if (managed)
668
+ await refreshSessionAvatar();
669
+ const uploadPath = await resolveUploadPath(file);
670
+ const result = await publishFile(uploadPath, {
671
+ slug: opts.slug,
672
+ githubUser: opts.githubUser,
673
+ handle: opts.handle,
674
+ expire: opts.expire,
675
+ visibility,
676
+ unlisted: visibility === 'unlisted',
677
+ protected: visibility === 'private',
678
+ force: opts.force,
679
+ // A capability URL is only as private as its obscurity, and a gallery
680
+ // OG cover is a second world-readable object under a derivable key.
681
+ // Public pages get a cover; anything hidden does not, unless the author
682
+ // has already opted out with --no-cover (in which case honour that).
683
+ cover: opts.cover === false ? false : visibility === 'public',
684
+ analytics: opts.analytics,
685
+ qr: opts.qr,
686
+ label: opts.label ?? opts.title,
687
+ meta,
688
+ noRevision: opts.revision === false,
689
+ });
690
+ console.log(formatSharePublishResult(result, Boolean(opts.json)));
691
+ }
692
+ catch (e) {
693
+ console.error(chalk.red(e.message));
694
+ process.exitCode = 1;
695
+ }
696
+ })
697
+ .addHelpText('after', `
698
+ Examples:
699
+ # Signed in? Just publish — no Cloudflare setup (managed endpoint).
700
+ # The default is public: listed in your gallery with an OG preview card.
701
+ $ artifacts auth login
702
+ $ artifacts share ./out/plan.html
703
+
704
+ # Markdown is rendered first, then published
705
+ $ artifacts share plan.md
706
+
707
+ # Owner-only, or your whole email domain (no org setup — the domain is it)
708
+ $ artifacts share ./out/plan.html --visibility me
709
+ $ artifacts share ./out/plan.html --visibility org
710
+
711
+ # Hide from the gallery (direct URL still works, noindex, no card), expire sooner
712
+ $ artifacts share ./out/report.html --unlisted --no-cover --expire 7d
713
+
714
+ # Token-gated link — GET returns 404 without the secret ?k= key
715
+ $ artifacts share ./out/secret.html --protected
716
+
717
+ # Permanent link, explicit slug, human title + structured metadata
718
+ $ artifacts share ./out/landing.html --expire never --slug q3-landing
719
+ $ artifacts share ./out/plan.html --label "Q3 fleet plan" --meta kind=plan
720
+ ${SHARE_DELETE_HELP}
721
+ # One-time BYO setup (or join an existing endpoint)
722
+ $ artifacts share setup --token <cf-token> --account <cf-account>
723
+ $ artifacts share join https://share.getrush.ai --token <write-token>
724
+
725
+ # Push a worker-template.ts change out to an already-provisioned endpoint
726
+ $ artifacts share update
727
+
728
+ Notes:
729
+ Signed-in users publish to the managed endpoint (share.getrush.ai/<handle>/…)
730
+ with the Phoenix session — no Cloudflare account, bucket, or write token. The
731
+ handle is the local-part of the signed-in email; --handle publishes under an
732
+ alternate public namespace instead (first-writer-claimed like the derived one).
733
+ Without a session, the BYO Cloudflare path applies (setup / join).
734
+
735
+ The default slug is derived deterministically from the HTML <title> or Markdown
736
+ frontmatter title, then the filename, so republishing the same title updates the
737
+ same URL. --slug is an exact override. HTML is stored as one object: local
738
+ images are inlined and Chrome-saved file:// TOC links become in-page hashes.
739
+
740
+ Public by default: a bare publish is listed in your gallery and carries an OG
741
+ cover, so the link unfurls into a preview card in Slack/iMessage/Twitter/
742
+ Discord. --visibility me is owner-only and --visibility org covers everyone at
743
+ your email domain (both require a Phoenix session, both hidden from the gallery
744
+ with no cover). --unlisted (alias --private) is an UNAUTHENTICATED capability
745
+ URL: hidden and noindex, but world-readable by anyone holding it. --protected
746
+ is the real read-auth — the URL carries a secret ?k= key and GET returns 404
747
+ without it.
748
+
749
+ Default expiry is 30d so an accidental publish decays; --expire never for a
750
+ permanent link. A pre-publish scan refuses emails and credential-shaped strings
751
+ unless --force is passed — it covers the file body, the label, and every --meta
752
+ value, all of which are world-readable on a public page.
753
+
754
+ Every publish carries provenance auto-captured from the exec env/git/clock
755
+ (agent, session, host, repo, date) — never invented, only sent when present.
756
+ Republishing an existing slug keeps the prior version as a retained revision by
757
+ default; see 'artifacts share revisions'.
758
+ `);
759
+ const shareDeleteCmd = registerShareDeleteOptions(shareCmd
760
+ .command('delete <targets...>')
761
+ .description('Take down a published page (and by default its OG cover). Verifies the page 404s before reporting success. Alias: artifacts unshare.'));
762
+ shareDeleteCmd.addHelpText('after', SHARE_DELETE_HELP);
763
+ shareDeleteCmd.action(async (targets, opts) => {
764
+ await runShareDelete(targets, opts);
765
+ });
766
+ // `artifacts share visibility <target> <level>` — change an already-published
767
+ // page's visibility in place. It reuses the delete target parser and the same
768
+ // PATCH metadata-edit route as `share edit` (visibility is metadata), so it
769
+ // re-stamps the stored object rather than re-publishing. --for-user /
770
+ // --visibility-json (not --github-user / --json): the parent `share <file>`
771
+ // already owns both long names, and commander resolves a child option's long
772
+ // name against the whole ancestor chain, silently dropping a same-named child.
773
+ const shareVisibilityCmd = shareCmd
774
+ .command('visibility')
775
+ .description("Change an already-published page's visibility in place (public | unlisted | me | org). The slug/URL is preserved; the body is untouched, so no revision is created.")
776
+ .addArgument(new Argument('<target>', 'the published page: a full URL, <user>/<slug>, or a bare slug in your namespace'))
777
+ .addArgument(new Argument('<level>', 'new visibility').choices([...SHARE_VISIBILITY_LEVELS]))
778
+ .option('--for-user <user>', 'GitHub username for resolving a bare-slug target (default: resolved from gh/git config)')
779
+ .option('--visibility-json', 'emit a machine-readable result')
780
+ .action(async (target, level, opts) => {
781
+ try {
782
+ const visibility = level;
783
+ const result = await runShareEdit(target, { visibility, githubUser: opts.forUser });
784
+ if (opts.visibilityJson) {
785
+ console.log(JSON.stringify(result, null, 2));
786
+ return;
787
+ }
788
+ console.log(formatShareVisibilityResult(result, visibility));
789
+ }
790
+ catch (e) {
791
+ console.error(chalk.red(e.message));
792
+ process.exitCode = 1;
793
+ }
794
+ })
795
+ .addHelpText('after', `
796
+ Examples:
797
+ $ artifacts share visibility https://share.getrush.ai/octocat/q3-plan me
798
+ $ artifacts share visibility octocat/q3-plan public
799
+ $ artifacts share visibility q3-plan unlisted
800
+ $ artifacts share visibility q3-plan org
801
+ $ artifacts share visibility q3-plan me --visibility-json
802
+
803
+ Notes:
804
+ Re-stamps only the visibility on the stored object; the body, provenance,
805
+ label, and --meta are untouched, so — like 'artifacts share edit' — this is a
806
+ metadata-only rewrite and creates no revision. The slug, and so the URL, is
807
+ preserved.
808
+
809
+ me and org require a Phoenix session ('artifacts auth login'), and org is
810
+ refused on a public-inbox email domain (gmail.com, outlook.com, …). Changing to
811
+ 'private' is not possible in place — token-gating needs a fresh viewer key,
812
+ which only a re-publish with --protected mints.
813
+ `);
814
+ const shareOpenCmd = shareCmd
815
+ .command('open')
816
+ .description("Open your own published page in the browser signed in as the owner, so the page's inline visibility control is live. Mints a one-time login ticket and appends it to the URL.")
817
+ .addArgument(new Argument('<target>', 'the published page: a full URL, <user>/<slug>, or a bare slug in your namespace'))
818
+ .option('--for-user <user>', 'namespace for resolving a bare-slug target (default: your Phoenix handle)')
819
+ .option('--no-open', 'print the owner URL instead of opening a browser')
820
+ .option('--open-json', 'emit a machine-readable result (includes the ticketed owner URL)')
821
+ .action(async (target, opts) => {
822
+ try {
823
+ const result = await runShareOpen(target, { githubUser: opts.forUser });
824
+ if (opts.openJson) {
825
+ console.log(JSON.stringify(result, null, 2));
826
+ return;
827
+ }
828
+ if (opts.open === false) {
829
+ console.log(chalk.green(result.ownerUrl));
830
+ console.log(chalk.dim(' open this to land on the page as the owner (the visibility chip becomes a control)'));
831
+ return;
832
+ }
833
+ openPath(result.ownerUrl);
834
+ console.log(chalk.green(`Opened ${result.url} as owner — the visibility chip is now a live control.`));
835
+ }
836
+ catch (e) {
837
+ console.error(chalk.red(e.message));
838
+ process.exitCode = 1;
839
+ }
840
+ })
841
+ .addHelpText('after', `
842
+ Examples:
843
+ $ artifacts share open q3-plan
844
+ $ artifacts share open octocat/q3-plan
845
+ $ artifacts share open https://share.getrush.ai/octocat/q3-plan --no-open
846
+
847
+ Notes:
848
+ The shared page's visibility chip is an interactive control only for the
849
+ signed-in owner; a plain link has no login, so the chip renders as a static
850
+ cue. This mints a short-lived, single-use login ticket (self-signed by the
851
+ share Worker) and opens the page with it, so the chip becomes a dropdown you
852
+ can switch in place.
853
+
854
+ Managed (Phoenix) endpoints only — run 'artifacts auth login' first. If the
855
+ mint 501s/404s, the Worker predates the feature: run 'artifacts share update'.
856
+ Prefer no browser? Use 'artifacts share visibility <target> <level>'.
857
+ `);
858
+ void shareOpenCmd;
859
+ shareCmd
860
+ .command('setup')
861
+ .description('Provision your own Cloudflare R2 bucket + Worker and save the endpoint config.')
862
+ .option('--bundle <name>', 'secrets bundle holding the Cloudflare API token', DEFAULT_CF_BUNDLE)
863
+ .option('--token <token>', 'Cloudflare API token (else CLOUDFLARE_API_TOKEN, else --bundle)')
864
+ .option('--account <id>', 'Cloudflare account id (else CLOUDFLARE_ACCOUNT_ID, else --bundle)')
865
+ .option('--worker <name>', 'Worker name', DEFAULT_WORKER_NAME)
866
+ .option('--bucket <name>', 'R2 bucket name', DEFAULT_BUCKET_NAME)
867
+ .option('--domain <host>', 'custom hostname to map, when your token owns the zone')
868
+ .option('--analytics-token <token>', 'Cloudflare Web Analytics token to inject into published pages')
869
+ .option('--unlimited-storage <json>', 'operator allowlist: JSON with exact emails and domains arrays; persisted for future updates')
870
+ .option('--managed', 'bind PHOENIX_ID_BASE so this Worker also accepts Phoenix bearers')
871
+ .action(async (opts) => {
872
+ try {
873
+ await runShareProvision(opts);
874
+ }
875
+ catch (e) {
876
+ console.error(chalk.red(e.message));
877
+ process.exitCode = 1;
878
+ }
879
+ });
880
+ shareCmd
881
+ .command('join')
882
+ .description('Use an existing share endpoint and write token (no provisioning).')
883
+ .argument('<baseUrl>', 'base URL of the endpoint, e.g. https://share.getrush.ai')
884
+ .option('--token <token>', 'write token (else ARTIFACTS_SHARE_TOKEN / SHARE_WRITE_TOKEN)')
885
+ .option('--worker <name>', 'Worker name behind the endpoint', DEFAULT_WORKER_NAME)
886
+ .option('--bucket <name>', 'R2 bucket behind the endpoint', DEFAULT_BUCKET_NAME)
887
+ .option('--account <id>', 'Cloudflare account id (needed later by `artifacts share update`)')
888
+ .action((baseUrl, opts) => {
889
+ try {
890
+ runShareJoin(baseUrl, opts);
891
+ }
892
+ catch (e) {
893
+ console.error(chalk.red(e.message));
894
+ process.exitCode = 1;
895
+ }
896
+ });
897
+ const shareUpdateCmd = shareCmd
898
+ .command('update')
899
+ .description('Re-deploy the Worker script to the current template on an already-provisioned endpoint (idempotent).')
900
+ .option('--bundle <name>', 'secrets bundle holding the Cloudflare API token', DEFAULT_CF_BUNDLE)
901
+ .option('--account <id>', "Cloudflare account id override (default: the configured endpoint's account)")
902
+ .option('--token <t>', 'Cloudflare API token (else CLOUDFLARE_API_TOKEN, else --bundle)')
903
+ .option('--force', 're-deploy even if the deployed template already matches')
904
+ .option('--check', 'report whether a deploy is needed and exit without deploying (needs no Cloudflare credentials)')
905
+ .option('--unlimited-storage <json>', 'operator allowlist: JSON with exact emails and domains arrays; persisted for future updates')
906
+ .option('--managed', 'bind PHOENIX_ID_BASE even when the configured hostname is not the managed domain')
907
+ // Named --update-json, not --json: `share <file>` (the parent) already owns
908
+ // --json for its own publish result, and commander resolves an option's long
909
+ // name against the WHOLE ancestor chain, so a same-named child option is
910
+ // silently dropped at parse time.
911
+ .option('--update-json', 'emit a machine-readable result')
912
+ .action(async (opts) => {
913
+ try {
914
+ const result = await runShareUpdate(opts);
915
+ if (opts.updateJson) {
916
+ console.log(JSON.stringify(result, null, 2));
917
+ return;
918
+ }
919
+ if (result.checked) {
920
+ console.log(result.deployNeeded
921
+ ? chalk.yellow(`Worker '${result.workerName}' needs an update (current render ${result.templateHash.slice(0, 12)}…).`)
922
+ : chalk.dim(`Worker '${result.workerName}' already matches the current template — no deploy needed.`));
923
+ return;
924
+ }
925
+ if (result.updated) {
926
+ console.log(chalk.green(`Worker '${result.workerName}' updated → template ${result.templateHash.slice(0, 12)}…`));
927
+ }
928
+ else {
929
+ console.log(chalk.dim(`Worker '${result.workerName}' already matches the current template — no-op.`));
930
+ }
931
+ }
932
+ catch (e) {
933
+ console.error(chalk.red(e.message));
934
+ process.exitCode = 1;
935
+ }
936
+ })
937
+ .addHelpText('after', `
938
+ Examples:
939
+ $ artifacts share update # deploy if the template changed
940
+ $ artifacts share update --force # deploy regardless
941
+ $ artifacts share update --check --update-json # is a deploy due? (no CF creds needed)
942
+
943
+ Notes:
944
+ Reuses the existing account/worker/bucket and write token — it never
945
+ re-provisions a bucket, touches routes, or regenerates the token. See
946
+ 'artifacts share status' for whether an update is due.
947
+
948
+ --check renders the current template and compares its hash to what the endpoint
949
+ last deployed, then exits — deploying nothing and reading no Cloudflare
950
+ credentials. The release script uses it to decide, after publish, whether the
951
+ shipped template changed.
952
+
953
+ The Cloudflare API token comes from --token, then the environment, then the
954
+ named --bundle. Under a secrets manager the usual form is:
955
+ agents secrets exec cloudflare -- artifacts share update
956
+ `);
957
+ void shareUpdateCmd;
958
+ shareCmd
959
+ .command('status')
960
+ .description('Show the configured share endpoint and namespace.')
961
+ .action(async () => {
962
+ let backend;
963
+ try {
964
+ backend = resolveShareBackend({ requireToken: false });
965
+ }
966
+ catch (e) {
967
+ console.log(chalk.dim(e.message));
968
+ return;
969
+ }
970
+ if (backend.kind === 'managed') {
971
+ console.log(`${chalk.bold('backend')} ${chalk.green('managed')}`);
972
+ console.log(`${chalk.bold('endpoint')} ${chalk.green(backend.baseUrl)}`);
973
+ console.log(`${chalk.bold('namespace')} ${chalk.cyan(`${backend.baseUrl}/${backend.namespace}`)}`);
974
+ console.log(chalk.dim('Phoenix session — no Cloudflare setup. Force BYO with ARTIFACTS_SHARE_BACKEND=byo.'));
975
+ return;
976
+ }
977
+ const cfg = readShareConfig();
978
+ if (!cfg) {
979
+ console.log(chalk.dim("Not configured. Run 'artifacts auth login', 'artifacts share setup', or 'artifacts share join'."));
980
+ return;
981
+ }
982
+ console.log(`${chalk.bold('backend')} ${chalk.green('byo')}`);
983
+ console.log(`${chalk.bold('endpoint')} ${chalk.green(cfg.baseUrl)}`);
984
+ console.log(chalk.dim(`worker ${cfg.workerName} · bucket ${cfg.bucketName} · account ${cfg.accountId || 'missing'}`));
985
+ if (!cfg.accountId) {
986
+ console.log(chalk.dim('account id empty — publish still uses baseUrl + the write token; `artifacts share update` needs --account or a re-join'));
987
+ }
988
+ const user = await resolveGitHubUsername();
989
+ console.log(`${chalk.bold('namespace')} ${user ? chalk.cyan(`${cfg.baseUrl}/${user}`) : chalk.yellow('unknown — set gh auth or github.user')}`);
990
+ console.log(`${chalk.bold('analytics')} ${analyticsEnabled(cfg) ? chalk.green('enabled') : chalk.dim('not configured')}`);
991
+ const templateStatus = shareTemplateStatus(cfg);
992
+ const templateLabel = templateStatus === 'current'
993
+ ? chalk.green('current')
994
+ : templateStatus === 'outdated'
995
+ ? chalk.yellow('outdated — run `artifacts share update`')
996
+ : chalk.dim('unknown — provisioned before version tracking; run `artifacts share update` to adopt it');
997
+ console.log(`${chalk.bold('template')} ${templateLabel}`);
998
+ });
999
+ const shareListCmd = shareCmd
1000
+ .command('list')
1001
+ .description("List the pages you've published to your share namespace (human table; --list-json for scripts).")
1002
+ // Named --for-user / --list-json / --scope, not --github-user / --json /
1003
+ // --visibility: `share <file>` (the parent) owns all three of those long
1004
+ // names, and commander resolves a child option's long name against the WHOLE
1005
+ // ancestor chain — a same-named child option is silently dropped at parse
1006
+ // time even when it parses alone.
1007
+ .option('--for-user <user>', 'GitHub username whose namespace to list (default: resolved from gh/git config)')
1008
+ .addOption(new Option('--scope <level>', 'visibility filter: public (default), unlisted, private, me, org, or all')
1009
+ .choices(['public', 'unlisted', 'private', 'me', 'org', 'all'])
1010
+ .default('public'))
1011
+ .option('--all', 'list every page including hidden unlisted/private/me/org shares (alias for --scope all)')
1012
+ .option('--agent <name>', 'filter to shares published by this agent/harness (case-insensitive)')
1013
+ .option('--session <id>', 'filter to shares published from this session id')
1014
+ // Named --label-contains, not --label: the parent already owns --label/--title.
1015
+ .option('--label-contains <substr>', 'filter to shares whose label contains this text (case-insensitive)')
1016
+ .option('--meta <key=value>', 'filter by an exact arbitrary metadata entry (repeatable)', (v, p) => [...p, v], [])
1017
+ .option('--list-json', 'emit the machine-readable listing')
1018
+ .action(async (opts) => {
1019
+ try {
1020
+ const scope = opts.all ? 'all' : (opts.scope ?? 'public');
1021
+ const parentMeta = shareCmd.opts().meta ?? [];
1022
+ const result = await runShareList({
1023
+ githubUser: opts.forUser,
1024
+ scope,
1025
+ agent: opts.agent,
1026
+ session: opts.session,
1027
+ label: opts.labelContains,
1028
+ meta: parseMetaEntries(opts.meta.length ? opts.meta : parentMeta),
1029
+ });
1030
+ console.log(formatShareList(result, Boolean(opts.listJson)));
1031
+ }
1032
+ catch (e) {
1033
+ console.error(chalk.red(e.message));
1034
+ process.exitCode = 1;
1035
+ }
1036
+ })
1037
+ .addHelpText('after', `
1038
+ Examples:
1039
+ $ artifacts share list # your public pages, as the gallery shows them
1040
+ $ artifacts share list --all # include hidden unlisted/private/me/org pages
1041
+ $ artifacts share list --scope me
1042
+ $ artifacts share list --list-json | jq -r '.objects[].url'
1043
+ $ artifacts share list --for-user octocat
1044
+ $ artifacts share list --agent claude --label-contains "fleet plan" --meta kind=plan
1045
+
1046
+ Notes:
1047
+ Lists the ACTIVE pages in your namespace — expired links and the sibling .png
1048
+ OG covers are omitted. By default this mirrors the public gallery. --scope
1049
+ unlisted|private|me|org or --all include your hidden pages; those scopes send
1050
+ the owner's bearer and a 'scope=mine' hint, which the Worker honours only after
1051
+ verifying the caller owns the namespace.
1052
+
1053
+ --agent/--session/--label-contains/--meta filter the fetched listing
1054
+ client-side; --list-json's count reflects the filtered set.
1055
+ `);
1056
+ void shareListCmd;
1057
+ const shareEditCmd = shareCmd
1058
+ .command('edit <target>')
1059
+ .description("Edit a published share's label or arbitrary metadata without republishing its body.")
1060
+ .option('--for-user <user>', 'namespace for resolving a bare slug (default: your namespace)')
1061
+ .option('--label <text>', 'set or replace the display label')
1062
+ .option('--remove-label', 'remove the display label')
1063
+ .option('--meta <key=value>', 'merge a metadata entry (repeatable)', (v, p) => [...p, v], [])
1064
+ .option('--replace-meta <key=value>', 'replace all arbitrary metadata with these entries (repeatable)', (v, p) => [...p, v], [])
1065
+ .option('--remove-meta <key>', 'remove an arbitrary metadata key (repeatable)', (v, p) => [...p, v], [])
1066
+ .option('--edit-json', 'emit the machine-readable edit result')
1067
+ .action(async (target, opts) => {
1068
+ try {
1069
+ const parent = shareCmd.opts();
1070
+ const label = opts.label ?? parent.label;
1071
+ const mergeMeta = opts.meta.length ? opts.meta : (parent.meta ?? []);
1072
+ if (label !== undefined && opts.removeLabel)
1073
+ throw new Error('--label and --remove-label are mutually exclusive.');
1074
+ if (mergeMeta.length && opts.replaceMeta.length)
1075
+ throw new Error('--meta and --replace-meta are mutually exclusive.');
1076
+ if (opts.replaceMeta.length && opts.removeMeta.length)
1077
+ throw new Error('--replace-meta and --remove-meta are mutually exclusive.');
1078
+ if (label === undefined && !opts.removeLabel && !mergeMeta.length && !opts.replaceMeta.length && !opts.removeMeta.length) {
1079
+ throw new Error('Nothing to edit. Pass --label, --remove-label, --meta, --replace-meta, or --remove-meta.');
1080
+ }
1081
+ const removeMeta = opts.removeMeta.map((key) => Object.keys(parseMetaEntries([`${key}=x`]))[0]);
1082
+ const result = await runShareEdit(target, {
1083
+ githubUser: opts.forUser,
1084
+ label: opts.removeLabel ? null : label === undefined ? undefined : sanitizeLabel(label),
1085
+ meta: parseMetaEntries(opts.replaceMeta.length ? opts.replaceMeta : mergeMeta),
1086
+ metaMode: opts.replaceMeta.length ? 'replace' : 'merge',
1087
+ removeMeta,
1088
+ // Parent `share --force`: a child --force would be silently dropped.
1089
+ force: parent.force,
1090
+ });
1091
+ console.log(opts.editJson ? JSON.stringify(result, null, 2) : chalk.green(`updated ${result.url}`));
1092
+ }
1093
+ catch (e) {
1094
+ console.error(chalk.red(e.message));
1095
+ process.exitCode = 1;
1096
+ }
1097
+ })
1098
+ .addHelpText('after', `
1099
+ Examples:
1100
+ $ artifacts share edit q3-plan --label "Q3 fleet plan"
1101
+ $ artifacts share edit q3-plan --meta status=final --meta ticket=PHNX-3992
1102
+ $ artifacts share edit q3-plan --replace-meta kind=plan --replace-meta status=final
1103
+ $ artifacts share edit q3-plan --remove-meta status
1104
+
1105
+ Notes:
1106
+ Metadata edits preserve the exact published body, content type, publication
1107
+ time, visibility, expiry, provenance, cover, and retained revisions. --meta
1108
+ merges; --replace-meta replaces all arbitrary metadata; --remove-meta deletes
1109
+ named keys. Reserved Worker/provenance keys cannot be changed this way.
1110
+ Edited labels and metadata values are scanned for emails and credential-shaped
1111
+ strings the same way publish is — pass --force to write them anyway.
1112
+ `);
1113
+ void shareEditCmd;
1114
+ const shareRevisionsCmd = shareCmd
1115
+ .command('revisions <target>')
1116
+ .description('Show the retained prior versions of a published slug, newest first (human table; --revisions-json for scripts).')
1117
+ .option('--for-user <user>', 'GitHub username for resolving a bare-slug target (default: resolved from gh/git config)')
1118
+ .option('--revisions-json', 'emit the machine-readable revision list')
1119
+ .action(async (target, opts) => {
1120
+ try {
1121
+ const result = await runShareRevisions(target, { githubUser: opts.forUser });
1122
+ console.log(formatShareRevisions(result, Boolean(opts.revisionsJson)));
1123
+ }
1124
+ catch (e) {
1125
+ console.error(chalk.red(e.message));
1126
+ process.exitCode = 1;
1127
+ }
1128
+ })
1129
+ .addHelpText('after', `
1130
+ Examples:
1131
+ $ artifacts share revisions q3-report
1132
+ $ artifacts share revisions octocat/q3-report
1133
+ $ artifacts share revisions https://share.getrush.ai/octocat/q3-report
1134
+ $ artifacts share revisions q3-report --revisions-json --for-user octocat
1135
+
1136
+ Notes:
1137
+ A revision is created automatically on every republish of an existing slug
1138
+ (pass --no-revision at publish time to skip it) — this is history, never shown
1139
+ on the public gallery or in 'artifacts share list' beyond its count. Each
1140
+ revision's own URL is still directly reachable and honors its own recorded
1141
+ expiry.
1142
+ `);
1143
+ void shareRevisionsCmd;
1144
+ shareCmd
1145
+ .command('analytics')
1146
+ .description('Show the Cloudflare Web Analytics status for this share endpoint.')
1147
+ .action(async () => {
1148
+ let backend;
1149
+ try {
1150
+ backend = resolveShareBackend({ requireToken: false });
1151
+ }
1152
+ catch (e) {
1153
+ console.log(chalk.dim(e.message));
1154
+ return;
1155
+ }
1156
+ if (backend.kind === 'managed') {
1157
+ console.log(chalk.yellow('Cloudflare Web Analytics is a BYO feature.'));
1158
+ console.log(chalk.dim(`You're on the managed endpoint (${backend.baseUrl}). Provision your own Cloudflare with 'artifacts share setup --analytics-token <token>', or force BYO with ARTIFACTS_SHARE_BACKEND=byo.`));
1159
+ return;
1160
+ }
1161
+ const cfg = readShareConfig();
1162
+ if (!cfg) {
1163
+ console.log(chalk.dim("Not configured. Run 'artifacts share setup' or 'artifacts share join'."));
1164
+ return;
1165
+ }
1166
+ if (!analyticsEnabled(cfg)) {
1167
+ console.log(chalk.yellow('Cloudflare Web Analytics is not configured.'));
1168
+ console.log(chalk.dim("Re-run 'artifacts share setup --analytics-token <token>'."));
1169
+ return;
1170
+ }
1171
+ const dashboard = cfg.domain
1172
+ ? `https://dash.cloudflare.com/${cfg.accountId}/web-analytics/${cfg.domain}`
1173
+ : `https://dash.cloudflare.com/${cfg.accountId}/web-analytics`;
1174
+ console.log(`${chalk.bold('analytics')} ${chalk.green('enabled')}`);
1175
+ console.log(`${chalk.bold('token')} ${chalk.dim(cfg.analyticsToken.slice(0, 8) + '…')}`);
1176
+ console.log(`${chalk.bold('dashboard')} ${chalk.cyan(dashboard)}`);
1177
+ const user = await resolveGitHubUsername();
1178
+ if (user) {
1179
+ console.log(chalk.dim(`Per-page breakdown is available under Paths in the dashboard (filter by /${user}/).`));
1180
+ }
1181
+ });
1182
+ }
1183
+ /**
1184
+ * Register `artifacts unshare <targets...>` as the top-level alias of
1185
+ * `artifacts share delete`.
1186
+ */
1187
+ export function registerUnshareCommand(program) {
1188
+ const unshareCmd = registerShareDeleteOptions(program
1189
+ .command('unshare <targets...>')
1190
+ .description('Alias of `artifacts share delete` — take down a published page (and by default its OG cover).'));
1191
+ unshareCmd.addHelpText('after', SHARE_DELETE_HELP);
1192
+ unshareCmd.action(async (targets, opts) => {
1193
+ await runShareDelete(targets, opts);
1194
+ });
1195
+ }
1196
+ /** Provision a fresh R2 bucket + Worker on the caller's Cloudflare and persist
1197
+ * the endpoint config + write token. */
1198
+ export async function runShareProvision(opts) {
1199
+ const { apiToken, accountId: acctFromBundle } = readCloudflareCreds(opts.bundle ?? DEFAULT_CF_BUNDLE, {
1200
+ apiToken: opts.token,
1201
+ accountId: opts.account,
1202
+ });
1203
+ const accountId = opts.account || acctFromBundle;
1204
+ if (!accountId) {
1205
+ throw new Error('A Cloudflare account id is required. Pass --account <id>, or set CLOUDFLARE_ACCOUNT_ID in the environment.');
1206
+ }
1207
+ const workerName = opts.worker;
1208
+ const bucketName = opts.bucket;
1209
+ const token = generateWriteToken();
1210
+ // Default to the product hostname: when the caller's token owns the zone this
1211
+ // is the platform provisioning path; when it doesn't, findZoneId returns null
1212
+ // and the endpoint simply stays on workers.dev.
1213
+ const requestedDomain = cleanHostname(opts.domain) ?? DEFAULT_SHARE_DOMAIN;
1214
+ const worker = renderWorkerBundle();
1215
+ const existing = readShareConfig();
1216
+ const unlimitedStorage = opts.unlimitedStorage === undefined
1217
+ ? (existing?.accountId === accountId && existing.workerName === workerName ? existing.unlimitedStorage : undefined)
1218
+ : parseUnlimitedStorage(opts.unlimitedStorage);
1219
+ const provisionOpts = { ...(opts.request ? { request: opts.request } : {}), unlimitedStorage };
1220
+ await createBucket(apiToken, accountId, bucketName, provisionOpts);
1221
+ console.log(chalk.dim(`R2 bucket '${bucketName}' ready`));
1222
+ await configureBucketLifecycle(apiToken, accountId, bucketName, provisionOpts);
1223
+ await deployWorker(apiToken, accountId, workerName, worker, bucketName, provisionOpts);
1224
+ console.log(chalk.dim(`Worker '${workerName}' deployed`));
1225
+ await setWorkerSecret(apiToken, accountId, workerName, token, provisionOpts);
1226
+ const subdomain = await enableWorkersDev(apiToken, accountId, workerName, provisionOpts);
1227
+ let baseUrl = `https://${workerName}.${subdomain}.workers.dev`;
1228
+ let domain;
1229
+ if (requestedDomain) {
1230
+ const zoneId = await findZoneId(apiToken, requestedDomain, provisionOpts);
1231
+ if (zoneId) {
1232
+ await addCustomDomain(apiToken, accountId, workerName, zoneId, requestedDomain, provisionOpts);
1233
+ baseUrl = `https://${requestedDomain}`;
1234
+ domain = requestedDomain;
1235
+ }
1236
+ else {
1237
+ console.error(chalk.yellow(`Zone for ${requestedDomain} is not visible to this token — staying on workers.dev`));
1238
+ }
1239
+ }
1240
+ const phoenixIdBase = phoenixIdBaseForDeploy({ managed: opts.managed }, { baseUrl, domain });
1241
+ if (phoenixIdBase) {
1242
+ await putWorkerSecret(apiToken, accountId, workerName, WORKER_PHOENIX_ID_BASE_SECRET, phoenixIdBase, provisionOpts);
1243
+ console.log(chalk.dim(`Worker '${workerName}' Phoenix ID base set`));
1244
+ }
1245
+ writeShareConfig({
1246
+ baseUrl,
1247
+ accountId,
1248
+ workerName,
1249
+ bucketName,
1250
+ domain,
1251
+ analyticsToken: opts.analyticsToken,
1252
+ unlimitedStorage,
1253
+ templateHash: hashWorkerScript(worker.script),
1254
+ });
1255
+ storeWriteToken(token);
1256
+ console.log(chalk.green(`\nShare endpoint ready → ${chalk.bold(baseUrl)}`));
1257
+ console.log(chalk.dim('Publish with: ') + chalk.cyan('artifacts share <file>'));
1258
+ }
1259
+ /** Re-deploy the Worker script on an ALREADY-provisioned endpoint to match the
1260
+ * current `worker-template.ts`. Reuses the existing account/worker/bucket and
1261
+ * write token — never creates a bucket, touches routes/domains, or regenerates
1262
+ * the token (see `updateWorker` in `lib/share/provision.ts` for how the token —
1263
+ * and, on a managed endpoint, `PHOENIX_ID_BASE` — survives the re-upload).
1264
+ * Idempotent: no-ops the script upload when the deployed hash already matches
1265
+ * unless `force`; a managed endpoint still re-applies `PHOENIX_ID_BASE`. */
1266
+ export async function runShareUpdate(opts = {}) {
1267
+ const cfg = readShareConfig();
1268
+ if (!cfg) {
1269
+ throw new Error("Not configured. Run 'artifacts share setup' (to provision) or 'artifacts share join' first.");
1270
+ }
1271
+ const unlimitedStorage = opts.unlimitedStorage === undefined ? cfg.unlimitedStorage : parseUnlimitedStorage(opts.unlimitedStorage);
1272
+ const policyChanged = JSON.stringify(unlimitedStorage) !== JSON.stringify(cfg.unlimitedStorage);
1273
+ // Change detection is a pure local computation (render + sha256), so it needs
1274
+ // no Cloudflare credentials. The release script calls this in `--check` mode
1275
+ // to decide whether the release changes the Worker at all.
1276
+ const worker = renderWorkerBundle();
1277
+ const templateHash = hashWorkerScript(worker.script);
1278
+ const deployNeeded = opts.force === true || policyChanged || shareTemplateStatus(cfg) !== 'current';
1279
+ if (opts.check) {
1280
+ return {
1281
+ updated: false,
1282
+ checked: true,
1283
+ deployNeeded,
1284
+ templateHash,
1285
+ deployedHash: cfg.templateHash,
1286
+ baseUrl: cfg.baseUrl,
1287
+ workerName: cfg.workerName,
1288
+ };
1289
+ }
1290
+ const { apiToken, accountId: acctFromBundle } = readCloudflareCreds(opts.bundle ?? DEFAULT_CF_BUNDLE, {
1291
+ apiToken: opts.token,
1292
+ accountId: opts.account,
1293
+ });
1294
+ const accountId = opts.account || acctFromBundle || cfg.accountId;
1295
+ if (!accountId) {
1296
+ throw new Error("Share endpoint has no Cloudflare account id — `artifacts share update` cannot call the API. Pass --account <id>, or re-run 'artifacts share join --account <id>'.");
1297
+ }
1298
+ const writeToken = readWriteToken();
1299
+ const phoenixIdBase = phoenixIdBaseForDeploy({ managed: opts.managed }, cfg);
1300
+ const provisionOpts = {
1301
+ ...(opts.request ? { request: opts.request } : {}),
1302
+ force: opts.force,
1303
+ unlimitedStorage,
1304
+ ...(phoenixIdBase !== undefined ? { phoenixIdBase } : {}),
1305
+ };
1306
+ const result = await updateWorker(apiToken, accountId, cfg.workerName, cfg.bucketName, worker, writeToken, cfg.templateHash, provisionOpts);
1307
+ if (!result.skipped || policyChanged) {
1308
+ writeShareConfig({ ...cfg, accountId, unlimitedStorage, templateHash: result.templateHash });
1309
+ }
1310
+ return {
1311
+ updated: !result.skipped || policyChanged,
1312
+ templateHash: result.templateHash,
1313
+ deployNeeded,
1314
+ deployedHash: cfg.templateHash,
1315
+ baseUrl: cfg.baseUrl,
1316
+ workerName: cfg.workerName,
1317
+ };
1318
+ }
1319
+ function cleanHostname(domain) {
1320
+ const raw = domain?.trim().replace(/\/+$/, '');
1321
+ if (!raw)
1322
+ return undefined;
1323
+ try {
1324
+ const url = new URL(raw.includes('://') ? raw : `https://${raw}`);
1325
+ return url.hostname || undefined;
1326
+ }
1327
+ catch {
1328
+ return raw;
1329
+ }
1330
+ }
1331
+ /** Join an existing share endpoint (no provisioning): persist the endpoint
1332
+ * details + write token. */
1333
+ export function runShareJoin(baseUrl, opts = {}) {
1334
+ const clean = baseUrl.trim().replace(/\/+$/, '');
1335
+ if (!clean)
1336
+ throw new Error('Share endpoint URL is required.');
1337
+ const token = opts.token?.trim() || readWriteTokenEnv();
1338
+ if (!token) {
1339
+ throw new Error('A write token is required to join. Pass --token <t>, or set ARTIFACTS_SHARE_TOKEN in the environment.');
1340
+ }
1341
+ const host = cleanHostname(clean);
1342
+ const domain = host && !host.endsWith('.workers.dev') ? host : undefined;
1343
+ writeShareConfig({
1344
+ baseUrl: clean,
1345
+ accountId: opts.account ?? '',
1346
+ workerName: opts.worker ?? DEFAULT_WORKER_NAME,
1347
+ bucketName: opts.bucket ?? DEFAULT_BUCKET_NAME,
1348
+ domain,
1349
+ });
1350
+ storeWriteToken(token);
1351
+ console.log(chalk.green(`Joined ${chalk.bold(clean)} — publish with `) + chalk.cyan('artifacts share <file>'));
74
1352
  }
1353
+ /** The managed endpoint's public base, e.g. for a `join` default. */
1354
+ export const MANAGED_SHARE_BASE_URL = `https://${DEFAULT_SHARE_DOMAIN}`;
75
1355
  //# sourceMappingURL=share.js.map