@instahost/cli 0.1.2 → 0.3.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.
package/README.md CHANGED
@@ -26,7 +26,7 @@ instahost publish ./dist --json
26
26
 
27
27
  ```text
28
28
  instahost share <file> [--ttl 24h] [--access unlisted|public|private] [--name <filename>] [--content-type <type>]
29
- instahost publish <dir> [--ttl 24h] [--access unlisted|public] [--include-dotfiles] [--concurrency 6]
29
+ instahost publish <dir> [--ttl 24h] [--access unlisted|public] [--include-dotfiles] [--concurrency 6] [--dry-run]
30
30
  instahost delete <id|url> [--token <ihd_...>]
31
31
  ```
32
32
 
@@ -54,6 +54,7 @@ A site is a directory with `index.html` at its root. Its pages must use relative
54
54
  | `--content-type <type>` | share | Declare the media type instead of deriving it from the extension. |
55
55
  | `--include-dotfiles` | publish | Also publish dot-prefixed files and directories. Credentials, VCS data and OS metadata stay excluded. |
56
56
  | `--concurrency <n>` | publish | Parallel uploads, 1 to 16 (default 6). |
57
+ | `--dry-run` | publish | Show which files would be published and which skipped, without contacting InstaHost. |
57
58
  | `--token <ihd_...>` | delete | The artifact's delete token. |
58
59
 
59
60
  An option given to a command it does not belong to is a usage error. `delete` takes an artifact id or any of its URLs. Its credential is the first of `--token`, `--api-key`, `INSTAHOST_DELETE_TOKEN` and `INSTAHOST_API_KEY`; the environment keeps the token out of the process list.
@@ -76,6 +77,21 @@ An option given to a command it does not belong to is a usage error. `delete` ta
76
77
 
77
78
  Detection is by name only: the CLI does not read file contents to find secrets. Publish a build output directory (`dist/`, `build/`, `out/`), never a repository root or home directory.
78
79
 
80
+ ## Preview a publish
81
+
82
+ ```sh
83
+ npx -y @instahost/cli publish ./dist --dry-run --json
84
+ ```
85
+
86
+ The preview runs every local check that `publish` runs: the options, the API key's format and the file checks, including `--include-dotfiles` if set. It then stops without contacting InstaHost, so it cannot create an artifact or confirm server-side limits, quotas or that the API key is accepted. Without `--json`, it prints included paths and sizes to stdout, and skips and warnings to stderr. With `--json`, it prints one document:
87
+
88
+ ```json
89
+ {"ok": true, "dry_run": true, "type": "site", "files": [{"path": "index.html", "size": 42}],
90
+ "file_count": 1, "total_bytes": 42, "skipped": [{"path": ".env", "reason": "sensitive"}], "warnings": []}
91
+ ```
92
+
93
+ Paths are relative to the site root and sizes are in bytes. Warnings can flag root-absolute URLs that may break if the published site is served under a path. Local failures use the usual error document and exit code.
94
+
79
95
  ## Output
80
96
 
81
97
  Without `--json`, the result goes to stdout (URL, access URL, expiry and the delete command, `npx -y @instahost/cli delete <id> --token ...`), and skipped files, warnings and errors go to stderr. With `--json`, `share` and `publish` print:
@@ -91,10 +107,14 @@ Without `--json`, the result goes to stdout (URL, access URL, expiry and the del
91
107
  `access_token` and `access_url` are set for private files. `delete` prints `{"ok": true, "id": "...", "status": "deleted", "deleted_at": "..."}`. Every failure prints one document:
92
108
 
93
109
  ```json
94
- {"ok": false, "error": {"code": "quota_exceeded", "message": "...", "details": {"scope": "client", "resets_at": "..."}, "exit_code": 6}}
110
+ {"ok": false, "error": {"code": "persistent_requires_api_key", "message": "Persistent artifacts need an API key.",
111
+ "fix": "Send an API key as `Authorization: Bearer ihk_…`, or drop `persistent` and set `ttl_seconds`.",
112
+ "docs": "https://instahost.dev/docs/api/#error-persistent_requires_api_key", "exit_code": 4}}
95
113
  ```
96
114
 
97
- When a failure happens after the artifact was created, `error.details.artifact` holds `{id, url, delete_token, access_url}`, because the artifact may exist and its delete token is the only way to remove it.
115
+ `error.fix` says what to do next. Values it refers to, such as paths or a quota reset time, appear in `error.details` when available. API errors can also include an `error.docs` link to the relevant entry. Human output shows the fix and docs link when available. [API error reference](https://instahost.dev/docs/api/#errors)
116
+
117
+ When a failure happens after the artifact was created, `error.details.artifact` holds `{id, url, delete_token, access_url}`. Use the delete token to remove the artifact.
98
118
 
99
119
  ## Exit codes
100
120
 
@@ -114,7 +134,8 @@ When a failure happens after the artifact was created, `error.details.artifact`
114
134
  ## Retries and safety
115
135
 
116
136
  - Each upload is retried up to 3 times (after 1, 2 and 4 s) on network errors, 429 and 5xx. A URL close to expiry is refreshed before use, and a 403 gets a fresh URL once per file.
117
- - The `/uploads` and `complete` calls and `delete` are retried on network errors, 502, 503 and 504, and on 429 `rate_limited` after `Retry-After` (up to 60 s). A 429 `quota_exceeded` is reported at once. Create is never retried, so a quota is never charged twice.
137
+ - API calls retry up to 3 times on network errors, 502, 503 and 504, and on 429 `rate_limited` after `Retry-After` (up to 60 s).
138
+ - `share` and `publish` send the same key and body on every attempt to create an artifact. A retry within the replay window can recover the original response. Create also retries on 500 and can retry a quota refusal after a network error or 5xx. When every request times out, a create can take about two minutes to report failure. [Retrying a create](https://instahost.dev/docs/api/#retry-create)
118
139
  - Credentials are sent only to the API origin. Upload URLs must be `https`, and the API's own follow-up URLs must be on its origin. Redirects are refused.
119
140
 
120
141
  ## Programmatic use
package/bin/instahost.mjs CHANGED
@@ -19,7 +19,8 @@ try {
19
19
  // A damaged or partial install (dist/ missing or unreadable): still exactly one answer.
20
20
  const code = (err && typeof err === "object" && "code" in err && typeof err.code === "string") ? err.code : "unknown";
21
21
  const message = `The CLI could not load its compiled files (${code}); reinstall it: npx -y @instahost/cli@latest, or npm i -g @instahost/cli.`;
22
- if (json) process.stdout.write(`${JSON.stringify({ ok: false, error: { code: "cli_load_failed", message, details: { reason: code }, exit_code: 1 } })}\n`);
22
+ const fix = "Reinstall the CLI with `npx -y @instahost/cli@latest` or `npm i -g @instahost/cli`.";
23
+ if (json) process.stdout.write(`${JSON.stringify({ ok: false, error: { code: "cli_load_failed", message, details: { reason: code }, fix, exit_code: 1 } })}\n`);
23
24
  else process.stderr.write(`instahost: ${message}\n`);
24
25
  process.exit(1);
25
26
  }
@@ -4,13 +4,14 @@
4
4
  // (uploads_url, complete_url) must be on that origin too.
5
5
  // - API calls time out after 30 s. Idempotent calls (uploads, complete, delete) are retried 3
6
6
  // times on network errors and 502/503/504 (1 s, 2 s, 4 s apart) and on 429 after Retry-After.
7
- // Create is never retried automatically.
7
+ // Create retries with one key and body, also on 500 and on quota refusals after a lost
8
+ // or 5xx answer. The key stays internal to this invocation.
8
9
  import { USER_AGENT } from "./config.js";
9
- import { CliError, EXIT, exitCodeForApiError } from "./errors.js";
10
+ import { CliError, EXIT } from "./errors.js";
10
11
  import { describeUrl, redact } from "./redact.js";
11
12
  export const API_TIMEOUT_MS = 30_000;
12
- export const RETRIES = 3;
13
13
  export const BACKOFF_SECONDS = [1, 2, 4];
14
+ export const RETRIES = BACKOFF_SECONDS.length;
14
15
  /** A Retry-After longer than this is not waited for; the 429 is reported instead. */
15
16
  export const MAX_RETRY_AFTER_SECONDS = 60;
16
17
  const RETRYABLE_STATUS = new Set([502, 503, 504]);
@@ -33,7 +34,36 @@ function failureReason(err) {
33
34
  return "unknown";
34
35
  if (err.name === "TimeoutError")
35
36
  return "timeout";
36
- return err.cause?.code ?? err.name;
37
+ const code = err.cause?.code;
38
+ return typeof code === "string" ? code : err.name;
39
+ }
40
+ function createErrorGuidance(code) {
41
+ switch (code) {
42
+ case "internal_error":
43
+ return { fix: "Run the command again later, and report it with the time of the request if the error persists." };
44
+ case "gone":
45
+ return {
46
+ message: "The artifact from the previous create attempt or its upload URLs have expired, or the artifact was deleted or blocked.",
47
+ fix: "Run the command again to create a new artifact.",
48
+ };
49
+ case "artifact_not_pending":
50
+ return {
51
+ message: "The artifact from the previous create attempt is already published or failed.",
52
+ fix: "Run the command again to create a new artifact.",
53
+ };
54
+ }
55
+ }
56
+ function errorDocs(value, apiOrigin) {
57
+ if (typeof value !== "string")
58
+ return;
59
+ try {
60
+ const url = new URL(value);
61
+ if (url.origin === apiOrigin && (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password)
62
+ return value;
63
+ }
64
+ catch {
65
+ // An invalid docs link can be omitted without losing the original error.
66
+ }
37
67
  }
38
68
  export class ApiClient {
39
69
  apiUrl;
@@ -56,7 +86,7 @@ export class ApiClient {
56
86
  resolve(pathOrUrl) {
57
87
  const url = new URL(pathOrUrl, this.apiUrl);
58
88
  if (url.origin !== this.apiUrl) {
59
- throw new CliError("unsafe_url", "The API returned a URL on another origin; refusing to send credentials there.", EXIT.network, { url: describeUrl(url.href) });
89
+ throw CliError.local("unsafe_url", "The API returned a URL on another origin; refusing to send credentials there.", EXIT.network, { url: describeUrl(url.href) });
60
90
  }
61
91
  return url;
62
92
  }
@@ -67,58 +97,76 @@ export class ApiClient {
67
97
  headers["content-type"] = "application/json";
68
98
  if (options.token)
69
99
  headers.authorization = `Bearer ${options.token}`;
100
+ const isCreate = options.phase === "create";
101
+ const key = isCreate ? options.idempotencyKey : undefined;
102
+ if (key)
103
+ headers["idempotency-key"] = key;
70
104
  const body = options.body === undefined ? undefined : JSON.stringify(options.body);
71
- const attempts = options.idempotent ? RETRIES + 1 : 1;
72
- for (let attempt = 1;; attempt++) {
105
+ const redactKey = (value) => key ? value.replaceAll(key, "***") : value;
106
+ let ambiguousCreate = false;
107
+ for (let attempt = 0;; attempt++) {
108
+ const backoff = BACKOFF_SECONDS[attempt];
73
109
  const started = Date.now();
74
110
  let res;
75
111
  let text;
76
112
  try {
77
113
  // The body read is guarded too: a connection cut or the timeout during the body is a
78
- // network failure like any other (retried when the call is idempotent).
114
+ // network failure like any other.
79
115
  res = await this.#fetch(url, { method, headers, body, redirect: "error", signal: AbortSignal.timeout(API_TIMEOUT_MS) });
80
116
  text = await res.text();
81
117
  }
82
118
  catch (err) {
83
- const reason = failureReason(err);
119
+ const reason = redactKey(failureReason(err));
84
120
  this.log(`api ${method} ${url.pathname} failed (${reason})`);
85
- if (attempt < attempts) {
86
- await this.#sleep(BACKOFF_SECONDS[attempt - 1] ?? 4);
121
+ if (backoff !== undefined) {
122
+ ambiguousCreate = isCreate;
123
+ await this.#sleep(backoff);
87
124
  continue;
88
125
  }
89
- throw new CliError("network_error", `Could not reach the API at ${this.apiUrl}.`, EXIT.network, { reason });
126
+ throw CliError.local("network_error", `Could not reach the API at ${this.apiUrl}.`, EXIT.network, { reason });
90
127
  }
91
- this.log(`api ${method} ${url.pathname} -> ${res.status} (${Date.now() - started} ms)`);
128
+ const replayed = isCreate && res.status === 201 && res.headers.get("idempotent-replayed") === "true";
129
+ this.log(`api ${method} ${url.pathname} -> ${res.status} (${Date.now() - started} ms)${replayed ? " (replayed)" : ""}`);
92
130
  let parsed = null;
93
131
  try {
94
- parsed = text ? JSON.parse(text) : null;
132
+ parsed = text ? JSON.parse(res.ok ? text : redactKey(text)) : null;
95
133
  }
96
134
  catch { }
97
135
  if (res.ok) {
98
136
  if (parsed === null || typeof parsed !== "object")
99
- throw new CliError("bad_response", `The API answered ${res.status} without a JSON body.`, EXIT.network, undefined, res.status);
137
+ throw CliError.local("bad_response", `The API answered ${res.status} without a JSON body.`, EXIT.network, undefined, res.status);
100
138
  return parsed;
101
139
  }
102
140
  const envelope = parsed?.error;
103
141
  const code = typeof envelope?.code === "string" ? envelope.code : `http_${res.status}`;
104
- if (attempt < attempts) {
105
- if (RETRYABLE_STATUS.has(res.status)) {
106
- await this.#sleep(BACKOFF_SECONDS[attempt - 1] ?? 4);
142
+ const retryAfter = retryAfterSeconds(res.headers.get("retry-after"));
143
+ if (backoff !== undefined) {
144
+ if (RETRYABLE_STATUS.has(res.status) || (isCreate && res.status === 500)) {
145
+ ambiguousCreate = isCreate;
146
+ await this.#sleep(backoff);
107
147
  continue;
108
148
  }
109
149
  if (res.status === 429 && code === "rate_limited") {
110
- const wait = retryAfterSeconds(res.headers.get("retry-after")) ?? BACKOFF_SECONDS[attempt - 1] ?? 4;
150
+ const wait = retryAfter ?? backoff;
111
151
  if (wait <= MAX_RETRY_AFTER_SECONDS) {
112
152
  this.log(`api rate limited; retrying in ${wait} s`);
113
153
  await this.#sleep(wait);
114
154
  continue;
115
155
  }
116
156
  }
157
+ // The first attempt may have taken the last quota slot before its response arrived.
158
+ // Retry inside the replay window rather than waiting for the daily quota reset.
159
+ if (res.status === 429 && code === "quota_exceeded" && ambiguousCreate) {
160
+ await this.#sleep(backoff);
161
+ continue;
162
+ }
117
163
  }
118
- const message = typeof envelope?.message === "string" ? envelope.message : `The API answered ${res.status}.`;
164
+ const override = isCreate ? createErrorGuidance(code) : undefined;
165
+ const message = override?.message ?? (typeof envelope?.message === "string" ? envelope.message : `The API answered ${res.status}.`);
166
+ const apiFix = envelope?.fix;
167
+ const fix = override?.fix ?? (typeof apiFix === "string" && apiFix.length > 0 && apiFix.length <= 500 ? apiFix : undefined);
119
168
  const details = envelope?.details && typeof envelope.details === "object" ? envelope.details : undefined;
120
- const retryAfter = retryAfterSeconds(res.headers.get("retry-after"));
121
- throw new CliError(code, redact(message), exitCodeForApiError(res.status, code, options.phase), retryAfter === null ? details : { ...details, retry_after_seconds: retryAfter }, res.status);
169
+ throw CliError.api(code, message, res.status, options.phase, retryAfter === null ? details : { ...details, retry_after_seconds: retryAfter }, { fix, docs: errorDocs(envelope?.docs, this.apiUrl) });
122
170
  }
123
171
  }
124
172
  }
@@ -32,10 +32,9 @@ export async function deleteArtifact(ctx, options) {
32
32
  throw usageError("delete needs the artifact's delete token (--token or INSTAHOST_DELETE_TOKEN) or the owner's API key.");
33
33
  const r = await ctx.client.call("DELETE", `/v1/artifacts/${id}`, {
34
34
  token: credential,
35
- idempotent: true,
36
35
  phase: "delete",
37
36
  });
38
37
  if (typeof r?.artifact?.id !== "string" || typeof r.artifact.status !== "string")
39
- throw new CliError("bad_response", "The API's answer to delete has no artifact.", EXIT.network);
38
+ throw CliError.local("bad_response", "The API's answer to delete has no artifact.", EXIT.network);
40
39
  return { ok: true, id: r.artifact.id, status: r.artifact.status, deleted_at: r.artifact.deleted_at ?? null };
41
40
  }
@@ -6,10 +6,10 @@ import { sep } from "node:path";
6
6
  import { inputError } from "../errors.js";
7
7
  import { sensitiveRule } from "../vendor/paths.js";
8
8
  import { lifetimeFields } from "../ttl.js";
9
- import { afterCreate, checkCreated, uploadAndComplete } from "../upload.js";
9
+ import { afterCreate, createArtifact, uploadAndComplete } from "../upload.js";
10
10
  import { findRootAbsoluteReferences, walkSite } from "../walk.js";
11
11
  const MAX_WARNING_PATHS = 20;
12
- export async function publish(ctx, options) {
12
+ async function prepareSite(options) {
13
13
  const display = options.dir;
14
14
  try {
15
15
  if (!(await stat(options.dir)).isDirectory())
@@ -30,14 +30,39 @@ export async function publish(ctx, options) {
30
30
  if (!walked.files.some((f) => f.path === "index.html")) {
31
31
  throw inputError("missing_index", `${display} has no index.html at its root; a site needs one.`, { path: display });
32
32
  }
33
- const rootAbsolute = await findRootAbsoluteReferences(walked.files);
34
- const created = await ctx.client.call("POST", "/v1/artifacts", {
35
- body: { type: "site", access: options.access, ...lifetimeFields(options.lifetime), files: walked.files.map((f) => ({ path: f.path, size: f.size, md5: f.md5 })) },
36
- token: ctx.apiKey,
37
- idempotent: false,
38
- phase: "create",
39
- });
40
- checkCreated(created);
33
+ return { ...walked, rootAbsolute: await findRootAbsoluteReferences(walked.files) };
34
+ }
35
+ function siteWarnings(rootAbsolute, pathname) {
36
+ if (!rootAbsolute.length || pathname === "/")
37
+ return [];
38
+ const impact = pathname ? `break under ${pathname}` : "can break when a site is served under a path";
39
+ return [{
40
+ code: "root_absolute_reference",
41
+ message: `${rootAbsolute.length} file(s) use root-absolute URLs ("/app.js")${rootAbsolute.some((ref) => ref.base) ? " or <base href=\"/\">" : ""}, which ${impact}; use relative URLs (for example Vite base: "./")`,
42
+ paths: rootAbsolute.slice(0, MAX_WARNING_PATHS).map((ref) => ref.path),
43
+ }];
44
+ }
45
+ export async function previewPublish(options) {
46
+ const walked = await prepareSite(options);
47
+ return {
48
+ ok: true,
49
+ dry_run: true,
50
+ type: "site",
51
+ files: walked.files.map(({ path, size }) => ({ path, size })),
52
+ file_count: walked.files.length,
53
+ total_bytes: walked.totalBytes,
54
+ skipped: walked.skipped,
55
+ warnings: siteWarnings(walked.rootAbsolute),
56
+ };
57
+ }
58
+ export async function publish(ctx, options) {
59
+ const walked = await prepareSite(options);
60
+ const created = await createArtifact(ctx.client, {
61
+ type: "site",
62
+ access: options.access,
63
+ ...lifetimeFields(options.lifetime),
64
+ files: walked.files.map((f) => ({ path: f.path, size: f.size, md5: f.md5 })),
65
+ }, ctx.apiKey);
41
66
  const artifact = await afterCreate(created, () => uploadAndComplete({
42
67
  client: ctx.client,
43
68
  created,
@@ -47,16 +72,6 @@ export async function publish(ctx, options) {
47
72
  onProgress: ctx.onProgress,
48
73
  fetch: ctx.fetch,
49
74
  }));
50
- // Root-absolute references only break when the site lives under a path (path mode).
51
- const warnings = [];
52
- if (rootAbsolute.length && new URL(artifact.url).pathname !== "/") {
53
- const paths = rootAbsolute.map((r) => r.path);
54
- warnings.push({
55
- code: "root_absolute_reference",
56
- message: `${paths.length} file(s) use root-absolute URLs ("/app.js")${rootAbsolute.some((r) => r.base) ? " or <base href=\"/\">" : ""}, which break under ${new URL(artifact.url).pathname}; use relative URLs (for example Vite base: "./")`,
57
- paths: paths.slice(0, MAX_WARNING_PATHS),
58
- });
59
- }
60
75
  return {
61
76
  ok: true,
62
77
  id: artifact.id,
@@ -70,6 +85,6 @@ export async function publish(ctx, options) {
70
85
  file_count: artifact.file_count,
71
86
  total_bytes: artifact.total_bytes,
72
87
  skipped: walked.skipped,
73
- warnings,
88
+ warnings: walked.rootAbsolute.length ? siteWarnings(walked.rootAbsolute, new URL(artifact.url).pathname) : [],
74
89
  };
75
90
  }
@@ -6,7 +6,7 @@ import { lstat, realpath } from "node:fs/promises";
6
6
  import { basename, resolve, sep } from "node:path";
7
7
  import { CliError, EXIT, inputError } from "../errors.js";
8
8
  import { lifetimeFields } from "../ttl.js";
9
- import { afterCreate, checkCreated, uploadAndComplete } from "../upload.js";
9
+ import { afterCreate, createArtifact, uploadAndComplete } from "../upload.js";
10
10
  import { sensitiveRule, validatePath } from "../vendor/paths.js";
11
11
  import { hashFile } from "../walk.js";
12
12
  function refuseSensitive(label, path) {
@@ -47,24 +47,22 @@ export async function share(ctx, options) {
47
47
  const file = { path: name, size, md5 };
48
48
  if (options.contentType !== undefined)
49
49
  file.content_type = options.contentType;
50
- const created = await ctx.client.call("POST", "/v1/artifacts", {
51
- body: { type: "file", access: options.access, ...lifetimeFields(options.lifetime), files: [file] },
52
- token: ctx.apiKey,
53
- idempotent: false,
54
- phase: "create",
50
+ const created = await createArtifact(ctx.client, {
51
+ type: "file", access: options.access, ...lifetimeFields(options.lifetime), files: [file],
52
+ }, ctx.apiKey);
53
+ const artifact = await afterCreate(created, async () => {
54
+ if (!created.upload.files.length)
55
+ throw CliError.local("bad_response", "The API returned no upload URL.", EXIT.network);
56
+ return uploadAndComplete({
57
+ client: ctx.client,
58
+ created,
59
+ apiKey: ctx.apiKey,
60
+ files: [{ path: name, absPath: options.file, size, md5, dev, ino }],
61
+ concurrency: 1,
62
+ onProgress: ctx.onProgress,
63
+ fetch: ctx.fetch,
64
+ });
55
65
  });
56
- checkCreated(created);
57
- if (!created.upload.files.length)
58
- throw new CliError("bad_response", "The API returned no upload URL.", EXIT.network);
59
- const artifact = await afterCreate(created, () => uploadAndComplete({
60
- client: ctx.client,
61
- created,
62
- apiKey: ctx.apiKey,
63
- files: [{ path: name, absPath: options.file, size, md5, dev, ino }],
64
- concurrency: 1,
65
- onProgress: ctx.onProgress,
66
- fetch: ctx.fetch,
67
- }));
68
66
  return {
69
67
  ok: true,
70
68
  id: artifact.id,
package/dist/config.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // Precedence: flag, then environment, then DEFAULT_API_URL, the production API origin. Empty
3
3
  // means the CLI asks for an API URL.
4
4
  import { usageError } from "./errors.js";
5
- export const VERSION = "0.1.2";
5
+ export const VERSION = "0.3.0";
6
6
  /**
7
7
  * The production API origin. The service's deploy preflight refuses to deploy an API origin that
8
8
  * differs from this value in the CLI version it pins, so changing the API domain needs a CLI release
package/dist/errors.js CHANGED
@@ -12,32 +12,78 @@ export const EXIT = {
12
12
  publishFailed: 8,
13
13
  notFound: 9,
14
14
  };
15
+ const REPORT_URL = "https://github.com/instahost-dev/instahost/issues";
16
+ const UPDATE_FIX = "Try the latest CLI (`npx -y @instahost/cli@latest`), then report the error at " + REPORT_URL + " if it persists.";
17
+ export const LOCAL_FIX = {
18
+ usage: "Correct the command using the options listed by `npx -y @instahost/cli --help`.",
19
+ internal_error: `Run the command again, then report the error at ${REPORT_URL} with the CLI version if it persists.`,
20
+ file_not_found: "Check the path, then run the command again.",
21
+ not_a_file: "Pass a regular file to `share`, or use `publish` for a directory.",
22
+ not_a_directory: "Pass a directory to `publish`, or share a single file with `share`.",
23
+ unreadable_file: "Make the file readable, then run the command again.",
24
+ unreadable_directory: "Make the directory readable, then run the command again.",
25
+ symlink_refused: "Pass the real file instead of a symbolic link.",
26
+ sensitive_file: "Leave this file out, because its name or location looks like a credential or VCS data.",
27
+ invalid_path: "Rename the files in `details.paths`, or pass `--name` when sharing a single file.",
28
+ duplicate_path: "Rename one of the files in `details.paths` so that the two names differ.",
29
+ missing_index: "Add an `index.html` at the root of the directory, or share a single file with `share`.",
30
+ empty_directory: "Publish the directory that holds the built site and its `index.html`.",
31
+ walk_too_many_files: "Publish a smaller directory, such as the build output only.",
32
+ file_changed: "Run the command again once the file is no longer changing.",
33
+ network_error: "Check the network connection, then run the command again.",
34
+ upload_failed: "Run the command again later.",
35
+ bad_response: UPDATE_FIX,
36
+ unsafe_url: UPDATE_FIX,
37
+ };
38
+ const API_FALLBACK_FIX = {
39
+ [EXIT.internal]: LOCAL_FIX.internal_error,
40
+ [EXIT.usage]: LOCAL_FIX.usage,
41
+ [EXIT.localInput]: "Check the local input described in the message, then run the command again.",
42
+ [EXIT.auth]: "Check the API key or delete token, then run the command again.",
43
+ [EXIT.rejected]: "Change the request as the message says, then run the command again.",
44
+ [EXIT.rateLimited]: "Wait the number of seconds in `details.retry_after_seconds` if set, then run the command again.",
45
+ [EXIT.network]: LOCAL_FIX.upload_failed,
46
+ [EXIT.publishFailed]: "Run the command again to publish a new artifact.",
47
+ [EXIT.notFound]: "Check the artifact id or URL.",
48
+ };
15
49
  export class CliError extends Error {
16
50
  name = "CliError";
17
51
  code;
18
52
  exitCode;
19
53
  details;
54
+ fix;
55
+ docs;
20
56
  /** HTTP status of the API answer behind this error, if any. */
21
57
  status;
22
58
  /** Set when the failure came after create: the artifact may exist (it may even be published). */
23
59
  artifact;
24
- constructor(code, message, exitCode, details, status) {
60
+ constructor(code, message, exitCode, fix, details, status, docs) {
25
61
  super(message);
26
62
  this.code = code;
27
63
  this.exitCode = exitCode;
28
64
  this.details = details;
65
+ this.fix = fix;
66
+ this.docs = docs;
29
67
  this.status = status;
30
68
  }
69
+ static local(code, message, exitCode, details, status) {
70
+ return new CliError(code, message, exitCode, LOCAL_FIX[code], details, status);
71
+ }
72
+ static api(code, message, status, phase, details, guidance) {
73
+ const exitCode = apiFailureExitCode(status, code, phase);
74
+ const fix = status === 429 && code === "rate_limited" ? API_FALLBACK_FIX[EXIT.rateLimited] : guidance.fix;
75
+ return new CliError(code, message, exitCode, fix ?? API_FALLBACK_FIX[exitCode], details, status, guidance.docs);
76
+ }
31
77
  }
32
- export const usageError = (message, details) => new CliError("usage", message, EXIT.usage, details);
33
- export const inputError = (code, message, details) => new CliError(code, message, EXIT.localInput, details);
78
+ export const usageError = (message, details) => CliError.local("usage", message, EXIT.usage, details);
79
+ export const inputError = (code, message, details) => CliError.local(code, message, EXIT.localInput, details);
34
80
  /** API error codes that end a publication (exit 8) wherever they appear in the publish phase. */
35
81
  const PUBLICATION_CODES = new Set(["upload_mismatch", "upload_incomplete", "artifact_failed", "artifact_not_pending", "upload_url_limit", "complete_attempt_limit", "gone"]);
36
82
  /**
37
83
  * Exit code for an error envelope from the API. Order matters: 429 and 401/403 win over the phase,
38
84
  * 404 is not found, 5xx is a server failure.
39
85
  */
40
- export function exitCodeForApiError(status, code, phase) {
86
+ function apiFailureExitCode(status, code, phase) {
41
87
  if (status === 429)
42
88
  return EXIT.rateLimited;
43
89
  if (status === 401 || status === 403)
@@ -52,3 +98,4 @@ export function exitCodeForApiError(status, code, phase) {
52
98
  return EXIT.rejected;
53
99
  return EXIT.internal;
54
100
  }
101
+ export const exitCodeForApiError = apiFailureExitCode;
package/dist/main.js CHANGED
@@ -10,13 +10,13 @@ import { redact } from "./redact.js";
10
10
  import { parseTtl } from "./ttl.js";
11
11
  import { DEFAULT_CONCURRENCY } from "./upload.js";
12
12
  import { deleteArtifact } from "./commands/delete.js";
13
- import { publish } from "./commands/publish.js";
13
+ import { previewPublish, publish } from "./commands/publish.js";
14
14
  import { share } from "./commands/share.js";
15
15
  export const HELP = `instahost ${VERSION}: instant hosting and sharing for AI agents.
16
16
 
17
17
  Usage:
18
18
  instahost share <file> [--ttl 24h] [--access unlisted|public|private] [--name <filename>] [--content-type <type>]
19
- instahost publish <dir> [--ttl 24h] [--access unlisted|public] [--include-dotfiles] [--concurrency 6]
19
+ instahost publish <dir> [--ttl 24h] [--access unlisted|public] [--include-dotfiles] [--concurrency 6] [--dry-run]
20
20
  instahost delete <id|url> [--token <ihd_...>] (or the owner's API key)
21
21
 
22
22
  Options for every command:
@@ -29,8 +29,10 @@ Options for every command:
29
29
  Anonymous artifacts live 24 hours by default and at most 7 days.
30
30
  publish skips dotfiles (except .well-known), credentials (.env*, keys, .git, ...) and OS metadata,
31
31
  and lists them under "skipped". Sites must use relative URLs (Vite: base: "./").
32
+ publish --dry-run lists what would be published or skipped without contacting InstaHost.
32
33
  delete uses --token, else --api-key, else INSTAHOST_DELETE_TOKEN, else INSTAHOST_API_KEY; the
33
34
  environment keeps the token out of the process list.
35
+ On a failure, error.fix in the JSON output says what to do next.
34
36
 
35
37
  Exit codes: 0 ok, 1 internal error, 2 usage, 3 local input (missing file, no index.html, invalid or
36
38
  sensitive name), 4 authentication or authorization (401, 403), 5 rejected by the server (400, 413,
@@ -56,6 +58,7 @@ export const OPTIONS = {
56
58
  "content-type": { type: "string" },
57
59
  "include-dotfiles": { type: "boolean" },
58
60
  concurrency: { type: "string" },
61
+ "dry-run": { type: "boolean" },
59
62
  token: { type: "string" },
60
63
  };
61
64
  /**
@@ -69,7 +72,7 @@ export const GLOBAL = ["json", "api-url", "api-key", "verbose", "help", "version
69
72
  /** Options per command, on top of GLOBAL. */
70
73
  export const PER_COMMAND = {
71
74
  share: ["ttl", "access", "name", "content-type"],
72
- publish: ["ttl", "access", "include-dotfiles", "concurrency"],
75
+ publish: ["ttl", "access", "include-dotfiles", "concurrency", "dry-run"],
73
76
  delete: ["token"],
74
77
  };
75
78
  function defaultStreams() {
@@ -144,13 +147,15 @@ async function run(argv, deps, streams, json) {
144
147
  const concurrency = values.concurrency === undefined ? DEFAULT_CONCURRENCY : Number(values.concurrency);
145
148
  if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
146
149
  throw usageError("--concurrency must be an integer from 1 to 16.");
147
- return publish(ctx, {
150
+ const options = {
148
151
  dir: target,
149
152
  lifetime,
150
153
  access: choice("access", values.access, ["unlisted", "public"], "unlisted"),
151
154
  includeDotfiles: values["include-dotfiles"] ?? false,
152
155
  concurrency,
153
- });
156
+ };
157
+ // A dry run has passed the same option and API key checks as a publish; it stops before any request.
158
+ return values["dry-run"] ? previewPublish(options) : publish(ctx, options);
154
159
  }
155
160
  if (command === "delete") {
156
161
  // Flags before the environment: --token, then --api-key, then
@@ -164,15 +169,15 @@ async function run(argv, deps, streams, json) {
164
169
  const progress = { open: false };
165
170
  /**
166
171
  * Last resort for a real process: an error that escapes main() still ends as one JSON document
167
- * (or one stderr line) and exit code 1, never a Node stack trace on stdout.
172
+ * (or a human-readable error) and exit code 1.
168
173
  */
169
174
  function installCrashHandlers(argv, streams) {
170
175
  const crash = (err) => {
171
- const doc = errorDocument(new CliError("internal_error", `Unexpected error: ${err instanceof Error ? err.name : "unknown"}`, EXIT.internal));
176
+ const error = CliError.local("internal_error", `Unexpected error: ${err instanceof Error ? err.name : "unknown"}`, EXIT.internal);
172
177
  if (argv.includes("--json"))
173
- printJson(streams, doc);
178
+ printJson(streams, errorDocument(error));
174
179
  else
175
- streams.stderr(`instahost: ${doc.error.message}\n`);
180
+ printHumanError(streams, error);
176
181
  process.exit(EXIT.internal);
177
182
  };
178
183
  process.once("uncaughtException", crash);
@@ -190,7 +195,7 @@ export async function main(argv, deps = {}) {
190
195
  streams.stderr("\n");
191
196
  progress.open = false;
192
197
  }
193
- const cliError = err instanceof CliError ? err : new CliError("internal_error", `Unexpected error: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, EXIT.internal);
198
+ const cliError = err instanceof CliError ? err : CliError.local("internal_error", `Unexpected error: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, EXIT.internal);
194
199
  if (json)
195
200
  printJson(streams, errorDocument(cliError));
196
201
  else
package/dist/output.js CHANGED
@@ -1,4 +1,5 @@
1
- import { redact } from "./redact.js";
1
+ import { redact, redactCredentials } from "./redact.js";
2
+ const ARTIFACT_FIX = "The artifact in `details.artifact` may exist: delete it with its `delete_token`.";
2
3
  /** Redacts every string inside a JSON-like value (never the serialised text, which it could corrupt). */
3
4
  export function redactValue(value) {
4
5
  if (typeof value === "string")
@@ -17,7 +18,18 @@ export function errorDocument(err) {
17
18
  let details = err.details && Object.keys(err.details).length ? redactValue(err.details) : undefined;
18
19
  if (err.artifact)
19
20
  details = { ...details, artifact: { ...err.artifact } };
20
- return { ok: false, error: { code: err.code, message: redact(err.message), ...(details ? { details } : {}), exit_code: err.exitCode } };
21
+ const fix = redactCredentials(err.fix) + (err.artifact ? ` ${ARTIFACT_FIX}` : "");
22
+ return {
23
+ ok: false,
24
+ error: {
25
+ code: err.code,
26
+ message: redact(err.message),
27
+ ...(details ? { details } : {}),
28
+ fix,
29
+ ...(err.docs ? { docs: redactCredentials(err.docs) } : {}),
30
+ exit_code: err.exitCode,
31
+ },
32
+ };
21
33
  }
22
34
  /**
23
35
  * The delete command printed in human output. It names the scoped package on purpose: most users run
@@ -44,11 +56,20 @@ const SKIP_LABEL = {
44
56
  // otherwise carry terminal escape sequences (clipboard writes, hidden or rewritten lines).
45
57
  export function printHuman(streams, doc) {
46
58
  const t = terminalSafe;
47
- if ("delete_token" in doc) {
59
+ if ("skipped" in doc) {
48
60
  for (const s of doc.skipped)
49
61
  streams.stderr(`skipped ${t(s.path)} (${SKIP_LABEL[s.reason]})\n`);
50
62
  for (const w of doc.warnings)
51
63
  streams.stderr(`warning ${t(w.message)}${w.paths?.length ? `: ${t(w.paths.join(", "))}` : ""}\n`);
64
+ }
65
+ if ("dry_run" in doc) {
66
+ const lines = [`Dry run: would publish ${doc.file_count} file(s) (${doc.total_bytes} bytes). Nothing uploaded.`];
67
+ for (const file of doc.files)
68
+ lines.push(` ${t(file.path)} (${file.size} bytes)`);
69
+ streams.stdout(`${lines.join("\n")}\n`);
70
+ return;
71
+ }
72
+ if ("delete_token" in doc) {
52
73
  const lines = [`URL ${t(doc.url)}`];
53
74
  if (doc.access_url)
54
75
  lines.push(`Access ${t(doc.access_url)}`);
@@ -71,6 +92,9 @@ export function printHumanError(streams, err) {
71
92
  }
72
93
  if (typeof details.reason === "string" && !paths.length && !err.message.includes(details.reason))
73
94
  lines[0] += ` (${t(details.reason)})`;
95
+ lines.push(` fix: ${terminalSafe(redactCredentials(err.fix))}`);
96
+ if (err.docs)
97
+ lines.push(` docs: ${terminalSafe(redactCredentials(err.docs))}`);
74
98
  if (err.artifact) {
75
99
  const a = err.artifact;
76
100
  lines.push(`instahost: the artifact may exist (${t(a.url)}); delete it with: ${DELETE_COMMAND} ${a.id} --token ${terminalSafe(a.delete_token)}`);
package/dist/redact.js CHANGED
@@ -5,12 +5,15 @@ const TOKEN = /\bih([dak])_[A-Za-z0-9_-]+/g;
5
5
  const SIGNED_PARAM = /\b(X-Amz-(?:Signature|Credential|Security-Token))=[^&\s"']+/gi;
6
6
  const TOKEN_PARAM = /([?&]token=)[^&\s"']+/gi;
7
7
  const BEARER = /\b(Bearer\s+)[^\s"']+/gi;
8
- export function redact(text) {
8
+ /** Masks credentials without swallowing placeholders in guidance such as `Bearer <token>`. */
9
+ export function redactCredentials(text) {
9
10
  return text
10
11
  .replace(TOKEN, (_m, kind) => `ih${kind}_***`)
11
12
  .replace(SIGNED_PARAM, "$1=***")
12
- .replace(TOKEN_PARAM, "$1***")
13
- .replace(BEARER, "$1***");
13
+ .replace(TOKEN_PARAM, "$1***");
14
+ }
15
+ export function redact(text) {
16
+ return redactCredentials(text).replace(BEARER, "$1***");
14
17
  }
15
18
  /** A URL safe for diagnostics: origin and path only (no query string, which may hold a signature). */
16
19
  export function describeUrl(url) {
package/dist/upload.js CHANGED
@@ -13,6 +13,7 @@
13
13
  // (the local R2 emulator); they never get an Authorization header.
14
14
  // - /complete answering 409 upload_incomplete re-uploads details.missing, then completes again, at
15
15
  // most 3 complete calls in all (the server allows MAX_COMPLETE_ATTEMPTS = 4).
16
+ import { randomUUID } from "node:crypto";
16
17
  import { openAsBlob } from "node:fs";
17
18
  import { lstat } from "node:fs/promises";
18
19
  import { BACKOFF_SECONDS, RETRIES } from "./api-client.js";
@@ -39,12 +40,12 @@ export function checkUploadUrl(raw, apiUrl) {
39
40
  url = new URL(raw);
40
41
  }
41
42
  catch {
42
- throw new CliError("unsafe_url", "The API returned an invalid upload URL.", EXIT.network);
43
+ throw CliError.local("unsafe_url", "The API returned an invalid upload URL.", EXIT.network);
43
44
  }
44
45
  const api = new URL(apiUrl);
45
46
  const localHttp = url.protocol === "http:" && isLoopbackHost(url.hostname) && api.protocol === "http:" && isLoopbackHost(api.hostname);
46
47
  if (url.protocol !== "https:" && !localHttp) {
47
- throw new CliError("unsafe_url", "The API returned an upload URL that is not https.", EXIT.network, { url: describeUrl(raw) });
48
+ throw CliError.local("unsafe_url", "The API returned an upload URL that is not https.", EXIT.network, { url: describeUrl(raw) });
48
49
  }
49
50
  return url;
50
51
  }
@@ -56,7 +57,7 @@ export function checkBatch(batch, where) {
56
57
  Array.isArray(b.files) &&
57
58
  b.files.every((f) => f && typeof f.path === "string" && typeof f.url === "string" && f.method === "PUT" && f.headers !== null && typeof f.headers === "object");
58
59
  if (!ok)
59
- throw new CliError("bad_response", `The API's answer to ${where} has no valid upload instructions.`, EXIT.network);
60
+ throw CliError.local("bad_response", `The API's answer to ${where} has no valid upload instructions.`, EXIT.network);
60
61
  }
61
62
  /** The fields read from a create answer (batch_size must be at least 1, or batching never ends). */
62
63
  export function checkCreated(created) {
@@ -70,13 +71,19 @@ export function checkCreated(created) {
70
71
  typeof u.uploads_url === "string" &&
71
72
  typeof u.complete_url === "string";
72
73
  if (!ok)
73
- throw new CliError("bad_response", "The API's answer to create is incomplete.", EXIT.network);
74
+ throw CliError.local("bad_response", "The API's answer to create is incomplete.", EXIT.network);
75
+ }
76
+ /** Give each invocation one create key for the original request and any retries. */
77
+ export async function createArtifact(client, body, token) {
78
+ const created = await client.call("POST", "/v1/artifacts", { body, token, phase: "create", idempotencyKey: randomUUID() });
79
+ checkCreated(created);
80
+ return created;
74
81
  }
75
82
  /** The fields read from a published artifact. */
76
83
  export function checkArtifact(artifact, where) {
77
84
  const a = artifact;
78
85
  if (!a || typeof a.id !== "string" || typeof a.url !== "string")
79
- throw new CliError("bad_response", `The API's answer to ${where} has no artifact.`, EXIT.network);
86
+ throw CliError.local("bad_response", `The API's answer to ${where} has no artifact.`, EXIT.network);
80
87
  }
81
88
  class Uploader {
82
89
  #s;
@@ -121,7 +128,6 @@ class Uploader {
121
128
  const r = await this.#s.client.call("POST", this.#s.created.upload.uploads_url, {
122
129
  body: { paths: paths.slice(i, i + size) },
123
130
  token: this.#token,
124
- idempotent: true,
125
131
  phase: "publish",
126
132
  });
127
133
  checkBatch(r?.upload, "/uploads");
@@ -213,7 +219,7 @@ class Uploader {
213
219
  for (;;) {
214
220
  const cached = this.#cache.get(file.path);
215
221
  if (!cached)
216
- throw new CliError("bad_response", `The API returned no upload URL for ${file.path}.`, EXIT.network, { path: file.path });
222
+ throw CliError.local("bad_response", `The API returned no upload URL for ${file.path}.`, EXIT.network, { path: file.path });
217
223
  // A URL about to expire is replaced before use (once: near the end of the upload window the
218
224
  // server only issues short-lived URLs, which are then used as they are).
219
225
  if (!refreshedBeforeUse && this.#stale(file.path)) {
@@ -264,7 +270,7 @@ class Uploader {
264
270
  throw inputError("file_changed", `${file.path} changed since it was hashed (storage refused its checksum); try again.`, { path: file.path });
265
271
  }
266
272
  const reason = status === 0 ? `network error (${detail})` : `HTTP ${status}${detail ? ` ${detail}` : ""}`;
267
- throw new CliError("upload_failed", `Uploading ${file.path} failed: ${reason}.`, EXIT.network, { path: file.path, status: status || null, s3_code: status ? detail : null });
273
+ throw CliError.local("upload_failed", `Uploading ${file.path} failed: ${reason}.`, EXIT.network, { path: file.path, status: status || null, s3_code: status ? detail : null });
268
274
  }
269
275
  }
270
276
  /** Re-uploads paths the server reported missing (their URLs are re-issued if stale). */
@@ -286,7 +292,7 @@ export async function afterCreate(created, step) {
286
292
  return await step();
287
293
  }
288
294
  catch (err) {
289
- const error = err instanceof CliError ? err : new CliError("internal_error", `Unexpected error: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, EXIT.internal);
295
+ const error = err instanceof CliError ? err : CliError.local("internal_error", `Unexpected error: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, EXIT.internal);
290
296
  error.artifact = { id: created.artifact.id, url: created.artifact.url, delete_token: created.delete_token, access_url: created.access_url ?? null };
291
297
  throw error;
292
298
  }
@@ -303,7 +309,6 @@ export async function uploadAndComplete(session) {
303
309
  try {
304
310
  const r = await session.client.call("POST", session.created.upload.complete_url, {
305
311
  token: manageToken(session),
306
- idempotent: true,
307
312
  phase: "publish",
308
313
  });
309
314
  checkArtifact(r?.artifact, "complete");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instahost/cli",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "description": "Instant hosting and sharing for AI agents: share a file or publish a static site and get an HTTPS URL. The unscoped npm package named instahost is unrelated.",
5
5
  "keywords": [
6
6
  "hosting",
@@ -28,6 +28,7 @@ export function tooOldDocument(version) {
28
28
  code: "node_too_old",
29
29
  message: `Node.js >= ${MIN_NODE[0]} is required (this is ${version}).`,
30
30
  details: { required: `>=${MIN_NODE.join(".")}.0`, found: String(version) },
31
+ fix: `Run the CLI with Node.js ${MIN_NODE[0]} or later.`,
31
32
  exit_code: 2,
32
33
  },
33
34
  };