-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli-program.test.ts
More file actions
406 lines (361 loc) · 13.5 KB
/
cli-program.test.ts
File metadata and controls
406 lines (361 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import { test, expect, describe, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { createProgram, formatApiBody } from "./cli-program.ts";
import { ApiError } from "./lib/errors.ts";
import { STANDARD_AGENT_DIRS, EXTRA_REL_PATHS } from "./lib/skill-detection.ts";
test("registers users as a top-level command", () => {
const program = createProgram();
const users = program.commands.find((command) => command.name() === "users");
expect(users).toBeDefined();
});
test("registers users create and list as subcommands", () => {
const program = createProgram();
const users = program.commands.find((command) => command.name() === "users")!;
const names = users.commands.map((command) => command.name());
expect(names).toEqual(expect.arrayContaining(["create", "list"]));
});
test("users list exposes common filters and pagination options", () => {
const program = createProgram();
const users = program.commands.find((command) => command.name() === "users")!;
const list = users.commands.find((command) => command.name() === "list")!;
const optionNames = list.options.map((option) => option.long);
expect(optionNames).toEqual(
expect.arrayContaining([
"--json",
"--limit",
"--offset",
"--query",
"--email-address",
"--phone-number",
"--username",
"--user-id",
"--external-id",
"--order-by",
"--secret-key",
"--app",
"--instance",
]),
);
});
describe("parseIntegerOption (via users list --limit / --offset)", () => {
function parseUsersList(args: readonly string[]) {
return createProgram().parseAsync(["users", "list", ...args], { from: "user" });
}
test.each([
{
label: "--limit 0",
args: ["--limit", "0"],
expected: /Must be 1-250/,
},
{
label: "--limit 251",
args: ["--limit", "251"],
expected: /Must be 1-250/,
},
{
label: "--limit -5 (post-fix surfaces range message)",
args: ["--limit", "-5"],
expected: /Must be 1-250/,
},
{
label: "--limit abc",
args: ["--limit", "abc"],
expected: /Must be an integer/,
},
{
label: "--limit 1.5",
args: ["--limit", "1.5"],
expected: /Must be an integer/,
},
{
label: "--offset -1",
args: ["--offset", "-1"],
expected: /Must be >= 0/,
},
])("rejects $label", async ({ args, expected }) => {
await expect(parseUsersList(args)).rejects.toThrow(expected);
});
});
test("users create exposes --json output, curated flags, and -d/--data for inline request bodies", () => {
const program = createProgram();
const users = program.commands.find((command) => command.name() === "users")!;
const create = users.commands.find((command) => command.name() === "create")!;
const optionNames = create.options.map((option) => option.long);
expect(optionNames).toEqual(
expect.arrayContaining([
"--json",
"--email",
"--phone",
"--username",
"--password",
"--first-name",
"--last-name",
"--external-id",
"--data",
"--file",
"--dry-run",
"--yes",
]),
);
});
test("users parent command exposes targeting flags inherited by subcommands", () => {
const program = createProgram();
const users = program.commands.find((command) => command.name() === "users")!;
const optionNames = users.options.map((option) => option.long);
expect(optionNames).toEqual(expect.arrayContaining(["--secret-key", "--app", "--instance"]));
});
test("users create documents -d and --file for raw BAPI request bodies", () => {
const program = createProgram();
const users = program.commands.find((command) => command.name() === "users")!;
const create = users.commands.find((command) => command.name() === "create")!;
const help = create.helpInformation();
expect(help).toContain("-d, --data");
expect(help).toContain("--file");
});
describe("formatApiBody", () => {
// --- Single error with meta ---
test("surfaces unsupported_features from meta", () => {
const body = JSON.stringify({
errors: [
{
code: "unsupported_subscription_plan_features",
message: "Your plan does not support these features",
meta: { unsupported_features: ["saml", "custom_roles"] },
},
],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toContain("Your plan does not support these features");
expect(result).toContain("Unsupported features: saml, custom_roles");
});
test("surfaces suggestions from unknown_config_key meta", () => {
const body = JSON.stringify({
errors: [
{
code: "unknown_config_key",
message: "Unknown config key: sesion",
meta: { param_name: "sesion", suggestions: ["session"] },
},
],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toContain("Unknown config key: sesion");
expect(result).toContain("Did you mean: session");
expect(result).toContain("Parameter: sesion");
});
test("surfaces feature name from feature_not_enabled meta", () => {
const body = JSON.stringify({
errors: [
{
code: "feature_not_enabled",
message: "This feature is not enabled on this instance",
meta: { param_name: "organizations" },
},
],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toContain("This feature is not enabled on this instance");
expect(result).toContain("Feature: organizations");
});
test("surfaces param_name for config_validation_error", () => {
const body = JSON.stringify({
errors: [
{
code: "config_validation_error",
message: "Invalid value for session.lifetime",
meta: { param_name: "session.lifetime", config_key: "session" },
},
],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toContain("Invalid value for session.lifetime");
expect(result).toContain("Parameter: session.lifetime");
});
test("surfaces param_name for destructive_operation_not_allowed", () => {
const body = JSON.stringify({
errors: [
{
code: "destructive_operation_not_allowed",
message: "Cannot clear this key without destructive=true",
meta: { param_name: "sign_up.mode" },
},
],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toContain("Cannot clear this key");
expect(result).toContain("Parameter: sign_up.mode");
});
test("surfaces param_name for form_param_value_invalid", () => {
const body = JSON.stringify({
errors: [
{
code: "form_param_value_invalid",
message: "Value is not in the allowed set",
meta: { param_name: "branding.logo_url" },
},
],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toContain("Value is not in the allowed set");
expect(result).toContain("Parameter: branding.logo_url");
});
// --- Multiple errors ---
// The structured path reads from the first parsed error only.
test("formats multiple errors: surfaces first error with its meta", () => {
const body = JSON.stringify({
errors: [
{
code: "config_validation_error",
message: "Invalid session lifetime",
meta: { param_name: "session.lifetime" },
},
{
code: "unknown_config_key",
message: "Unknown key: bogus",
meta: { param_name: "bogus", suggestions: ["session"] },
},
],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toContain("Invalid session lifetime");
expect(result).toContain("Parameter: session.lifetime");
});
// --- Error without meta ---
test("handles error without meta gracefully", () => {
const body = JSON.stringify({
errors: [{ code: "resource_not_found", message: "Instance not found" }],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toBe("Instance not found");
});
// --- Bodies without a Clerk errors array ---
// parseApiBody falls back to truncateBody(body) as the message when there
// is no errors[0], so formatStructuredError returns the truncated body string.
test("returns truncated body when no errors array (error field only)", () => {
const body = JSON.stringify({ error: "Something went wrong" });
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toBe(body);
});
test("returns truncated body when no errors array (message field only)", () => {
const body = JSON.stringify({ message: "Bad request" });
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toBe(body);
});
test("truncates non-JSON body over 200 chars", () => {
const body = "x".repeat(300);
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toBe("x".repeat(200) + "...");
});
test("returns short non-JSON body as-is", () => {
const result = formatApiBody(new ApiError(400, "Bad Request"), false);
expect(result).toBe("Bad Request");
});
// --- Verbose mode ---
test("verbose mode returns full pretty-printed JSON", () => {
const obj = { errors: [{ code: "test", message: "test msg" }] };
const body = JSON.stringify(obj);
const result = formatApiBody(new ApiError(400, body), true);
expect(result).toBe("\n" + JSON.stringify(obj, null, 2));
});
test("verbose mode returns raw body for non-JSON", () => {
const result = formatApiBody(new ApiError(400, "not json"), true);
expect(result).toBe("\nnot json");
});
// --- Edge cases ---
test("handles empty errors array by returning truncated body", () => {
const body = JSON.stringify({ errors: [], message: "fallback" });
const result = formatApiBody(new ApiError(400, body), false);
// No errors[0] so parseApiBody falls back to truncateBody(body)
expect(result).toBe(body);
});
test("handles error with empty meta", () => {
const body = JSON.stringify({
errors: [{ code: "config_validation_error", message: "Bad value", meta: {} }],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toBe("Bad value");
});
test("handles unsupported_subscription_plan_features with empty unsupported_features", () => {
const body = JSON.stringify({
errors: [
{
code: "unsupported_subscription_plan_features",
message: "Plan limitation",
meta: { unsupported_features: [] },
},
],
});
const result = formatApiBody(new ApiError(400, body), false);
expect(result).toBe("Plan limitation");
});
});
describe("help: clerk skill install tip", () => {
const TIP_SUBSTR = "Give AI agents better Clerk context";
// Capture help output including `addHelpText("after", ...)`. The custom
// formatter in lib/help.ts rebuilds help from scratch, so the "after"
// listener only fires during outputHelp (which writes via stdout).
function renderHelp(): string {
const program = createProgram();
let captured = "";
const origWrite = process.stdout.write.bind(process.stdout);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(process.stdout as unknown as { write: (chunk: any) => boolean }).write = (chunk) => {
captured += typeof chunk === "string" ? chunk : chunk.toString();
return true;
};
try {
program.outputHelp();
} finally {
(process.stdout as unknown as { write: typeof origWrite }).write = origWrite;
}
return captured;
}
let tmpHome: string;
let tmpCwd: string;
let originalHome: string | undefined;
let originalCwd: string;
beforeEach(() => {
originalHome = process.env.HOME;
originalCwd = process.cwd();
tmpHome = mkdtempSync(join(tmpdir(), "clerk-help-home-"));
tmpCwd = mkdtempSync(join(tmpdir(), "clerk-help-cwd-"));
process.env.HOME = tmpHome;
process.chdir(tmpCwd);
});
afterEach(() => {
process.chdir(originalCwd);
if (originalHome === undefined) delete process.env.HOME;
else process.env.HOME = originalHome;
rmSync(tmpHome, { recursive: true, force: true });
rmSync(tmpCwd, { recursive: true, force: true });
});
test("shows the tip when no skill is installed anywhere", () => {
const help = renderHelp();
expect(help).toContain(TIP_SUBSTR);
expect(help).toContain("clerk skill install");
});
for (const dir of STANDARD_AGENT_DIRS) {
test(`hides the tip when ${dir}/skills/clerk-cli/SKILL.md exists under HOME`, () => {
const target = join(tmpHome, dir, "skills/clerk-cli");
mkdirSync(target, { recursive: true });
writeFileSync(join(target, "SKILL.md"), "ok");
expect(renderHelp()).not.toContain(TIP_SUBSTR);
});
test(`hides the tip when ${dir}/skills/clerk-cli/SKILL.md exists under cwd`, () => {
const target = join(tmpCwd, dir, "skills/clerk-cli");
mkdirSync(target, { recursive: true });
writeFileSync(join(target, "SKILL.md"), "ok");
expect(renderHelp()).not.toContain(TIP_SUBSTR);
});
}
for (const rel of EXTRA_REL_PATHS) {
test(`hides the tip when ${rel} exists under cwd`, () => {
const full = join(tmpCwd, rel);
mkdirSync(dirname(full), { recursive: true });
writeFileSync(full, "ok");
expect(renderHelp()).not.toContain(TIP_SUBSTR);
});
}
});