pcific 0.0.0-stage → 0.2.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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/SKILL.md +127 -0
  4. package/dist/api/catalog.js +637 -0
  5. package/dist/api/run.js +960 -0
  6. package/dist/api/search.js +171 -0
  7. package/dist/api/shortcuts.js +799 -0
  8. package/dist/bin.js +648 -0
  9. package/dist/commands/auth.js +513 -0
  10. package/dist/commands/doctor.js +410 -0
  11. package/dist/commands/init.js +306 -0
  12. package/dist/commands/sync.js +214 -0
  13. package/dist/detect.js +214 -0
  14. package/dist/env.js +339 -0
  15. package/dist/goLive.js +629 -0
  16. package/dist/keyLink.js +305 -0
  17. package/dist/mcp/server.js +206 -0
  18. package/dist/mcp/tools.js +689 -0
  19. package/dist/python/template.js +793 -0
  20. package/dist/schema/discover.js +324 -0
  21. package/dist/schema/helpers.js +396 -0
  22. package/dist/schema/prismaToJsonSchema.js +197 -0
  23. package/dist/schema/push.js +570 -0
  24. package/dist/schema/tsToJsonSchema.js +405 -0
  25. package/dist/schema/zodToJsonSchema.js +442 -0
  26. package/dist/templates/openapi.json +1 -0
  27. package/dist/templates/sdk/auth.ts +139 -0
  28. package/dist/templates/sdk/client.ts +1059 -0
  29. package/dist/templates/sdk/errors.ts +76 -0
  30. package/dist/templates/sdk/generated-types.ts +5746 -0
  31. package/dist/templates/sdk/http.ts +359 -0
  32. package/dist/templates/sdk/index.ts +84 -0
  33. package/dist/templates/sdk/json.ts +24 -0
  34. package/dist/templates/sdk/kit.ts +516 -0
  35. package/dist/templates/sdk/multipart.ts +99 -0
  36. package/dist/templates/sdk/sse.ts +131 -0
  37. package/dist/templates/sdk/verify.ts +766 -0
  38. package/dist/templates/sdk-js/auth.d.ts +20 -0
  39. package/dist/templates/sdk-js/auth.js +85 -0
  40. package/dist/templates/sdk-js/client.d.ts +324 -0
  41. package/dist/templates/sdk-js/client.js +607 -0
  42. package/dist/templates/sdk-js/errors.d.ts +51 -0
  43. package/dist/templates/sdk-js/errors.js +48 -0
  44. package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
  45. package/dist/templates/sdk-js/generated-types.js +5 -0
  46. package/dist/templates/sdk-js/http.d.ts +50 -0
  47. package/dist/templates/sdk-js/http.js +263 -0
  48. package/dist/templates/sdk-js/index.d.ts +9 -0
  49. package/dist/templates/sdk-js/index.js +7 -0
  50. package/dist/templates/sdk-js/json.d.ts +11 -0
  51. package/dist/templates/sdk-js/json.js +16 -0
  52. package/dist/templates/sdk-js/kit.d.ts +220 -0
  53. package/dist/templates/sdk-js/kit.js +208 -0
  54. package/dist/templates/sdk-js/multipart.d.ts +23 -0
  55. package/dist/templates/sdk-js/multipart.js +61 -0
  56. package/dist/templates/sdk-js/sse.d.ts +12 -0
  57. package/dist/templates/sdk-js/sse.js +99 -0
  58. package/dist/templates/sdk-js/verify.d.ts +114 -0
  59. package/dist/templates/sdk-js/verify.js +506 -0
  60. package/dist/templates.js +925 -0
  61. package/dist/ui.js +399 -0
  62. package/dist/webhooks/events.js +171 -0
  63. package/dist/webhooks/listen.js +772 -0
  64. package/package.json +32 -4
@@ -0,0 +1,960 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { findOperation, isJsonObject, isJsonString, loadOpenApiCatalog, } from "./catalog.js";
5
+ export const CLI_USER_AGENT = "pcific-cli/0.1.0";
6
+ export const DEFAULT_BASE_URL = "https://business.pcific.ai";
7
+ export class BaseUrlError extends Error {
8
+ code = "INVALID_BASE_URL";
9
+ tryThis;
10
+ constructor(message, tryThis) {
11
+ super(message);
12
+ this.name = "BaseUrlError";
13
+ this.tryThis = tryThis;
14
+ }
15
+ }
16
+ export function isStreamTty(stream) {
17
+ return Boolean(stream.isTTY);
18
+ }
19
+ export function redactSecrets(text) {
20
+ return text
21
+ .replace(/\bpcific_(test|live)_(?!safeguard\b|orbit\b|ask\b|message_check\b)[A-Za-z0-9_-]{6,}/g, "pcific_$1_***")
22
+ .replace(/whsec_[A-Za-z0-9_-]+/g, "whsec_***");
23
+ }
24
+ export function normalizeBaseUrl(raw) {
25
+ const value = (raw ?? DEFAULT_BASE_URL).trim();
26
+ if (!value) {
27
+ return DEFAULT_BASE_URL;
28
+ }
29
+ let parsed;
30
+ try {
31
+ parsed = new URL(value);
32
+ }
33
+ catch {
34
+ throw new BaseUrlError(`Invalid base URL "${value}".`, `Pass a full http:// or https:// URL such as "${DEFAULT_BASE_URL}" with --base-url or PCIFIC_BASE_URL.`);
35
+ }
36
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
37
+ throw new BaseUrlError(`Unsupported base URL protocol "${parsed.protocol}". Only http:// and https:// are allowed.`, `Use an https:// or http:// URL such as "${DEFAULT_BASE_URL}" with --base-url or PCIFIC_BASE_URL.`);
38
+ }
39
+ return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, "");
40
+ }
41
+ function parseEnvValue(rawValue) {
42
+ const trimmed = rawValue.trim();
43
+ if (trimmed.length === 0) {
44
+ return "";
45
+ }
46
+ const quote = trimmed[0];
47
+ if (quote === '"' || quote === "'") {
48
+ let out = "";
49
+ for (let i = 1; i < trimmed.length; i += 1) {
50
+ const ch = trimmed[i];
51
+ if (quote === '"' && ch === "\\" && i + 1 < trimmed.length) {
52
+ const next = trimmed[i + 1];
53
+ if (next === "n")
54
+ out += "\n";
55
+ else if (next === "r")
56
+ out += "\r";
57
+ else if (next === "t")
58
+ out += "\t";
59
+ else
60
+ out += next;
61
+ i += 1;
62
+ continue;
63
+ }
64
+ if (ch === quote) {
65
+ return out;
66
+ }
67
+ out += ch;
68
+ }
69
+ return out;
70
+ }
71
+ const commentIdx = trimmed.indexOf("#");
72
+ return commentIdx === -1 ? trimmed : trimmed.slice(0, commentIdx).trim();
73
+ }
74
+ export function parseDotEnv(raw) {
75
+ const result = new Map();
76
+ for (const rawLine of raw.split(/\r?\n/)) {
77
+ const trimmed = rawLine.trim();
78
+ if (!trimmed || trimmed.startsWith("#")) {
79
+ continue;
80
+ }
81
+ const line = trimmed.startsWith("export ") ? trimmed.slice("export ".length).trim() : trimmed;
82
+ const eqIndex = line.indexOf("=");
83
+ if (eqIndex <= 0) {
84
+ continue;
85
+ }
86
+ const key = line.slice(0, eqIndex).trim();
87
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
88
+ continue;
89
+ }
90
+ const value = parseEnvValue(line.slice(eqIndex + 1));
91
+ result.set(key, value);
92
+ }
93
+ return result;
94
+ }
95
+ export function readMergedEnv(cwd, envOverride) {
96
+ const merged = new Map();
97
+ for (const filename of [".env", ".env.local"]) {
98
+ const envFilePath = path.join(cwd, filename);
99
+ if (existsSync(envFilePath)) {
100
+ for (const [key, value] of parseDotEnv(readFileSync(envFilePath, "utf8"))) {
101
+ merged.set(key, value);
102
+ }
103
+ }
104
+ }
105
+ const baseEnv = envOverride ?? process.env;
106
+ for (const [key, value] of Object.entries(baseEnv)) {
107
+ if (value !== undefined) {
108
+ merged.set(key, value);
109
+ }
110
+ }
111
+ return merged;
112
+ }
113
+ export function resolveTestKey(cwd, envOverride) {
114
+ const merged = readMergedEnv(cwd, envOverride);
115
+ const testKey = merged.get("PCIFIC_TEST_KEY")?.trim();
116
+ const apiKey = merged.get("PCIFIC_API_KEY")?.trim();
117
+ const liveKey = merged.get("PCIFIC_LIVE_KEY")?.trim();
118
+ const marketplaceId = merged.get("PCIFIC_MARKETPLACE_ID")?.trim() || undefined;
119
+ const baseUrl = merged.get("PCIFIC_BASE_URL")?.trim() || undefined;
120
+ if (testKey) {
121
+ if (testKey.startsWith("pcific_live_")) {
122
+ return {
123
+ ok: false,
124
+ code: "LIVE_KEY_REFUSED",
125
+ error: "Refusing to run with a live API key (pcific_live_***). The PCIFIC CLI only uses test keys.",
126
+ tryThis: "Put a test key (pcific_test_...) in PCIFIC_TEST_KEY or run `npx pcific init` to link one. Keep live keys only in your hosting provider's production secrets.",
127
+ };
128
+ }
129
+ if (!testKey.startsWith("pcific_test_")) {
130
+ return {
131
+ ok: false,
132
+ code: "INVALID_TEST_KEY_FORMAT",
133
+ error: "PCIFIC_TEST_KEY does not start with pcific_test_.",
134
+ tryThis: "Set PCIFIC_TEST_KEY to a valid test key starting with pcific_test_, or run `npx pcific init` to link a new test key.",
135
+ };
136
+ }
137
+ return { ok: true, apiKey: testKey, marketplaceId, baseUrl };
138
+ }
139
+ if (apiKey) {
140
+ if (apiKey.startsWith("pcific_live_")) {
141
+ return {
142
+ ok: false,
143
+ code: "LIVE_KEY_REFUSED",
144
+ error: "Refusing to run with a live API key in PCIFIC_API_KEY (pcific_live_***). The PCIFIC CLI only uses test keys.",
145
+ tryThis: "Store your test key in PCIFIC_TEST_KEY (starting with pcific_test_) and keep live keys only in your production host's secret manager.",
146
+ };
147
+ }
148
+ if (apiKey.startsWith("pcific_test_")) {
149
+ return { ok: true, apiKey, marketplaceId, baseUrl };
150
+ }
151
+ }
152
+ if (liveKey) {
153
+ return {
154
+ ok: false,
155
+ code: "LIVE_KEY_REFUSED",
156
+ error: "Only PCIFIC_LIVE_KEY is set, and the PCIFIC CLI refuses to use live keys to prevent accidental production charges or changes.",
157
+ tryThis: "Run `npx pcific init` to link a test key into .env as PCIFIC_TEST_KEY, then re-run this command.",
158
+ };
159
+ }
160
+ return {
161
+ ok: false,
162
+ code: "MISSING_TEST_KEY",
163
+ error: "No PCIFIC_TEST_KEY was found in your environment or .env file.",
164
+ tryThis: "Run `npx pcific init` to link a test key into .env, or export PCIFIC_TEST_KEY=pcific_test_... and try again.",
165
+ };
166
+ }
167
+ export function formatApiError(status, body, requestIdHeader) {
168
+ if (isJsonObject(body)) {
169
+ const code = isJsonString(body.code) ? body.code : `HTTP_${status}`;
170
+ const error = isJsonString(body.error)
171
+ ? redactSecrets(body.error)
172
+ : `PCIFIC API returned HTTP ${status}.`;
173
+ const tryThis = isJsonString(body.tryThis)
174
+ ? redactSecrets(body.tryThis)
175
+ : "Check your parameters, permissions, and base URL, then try again.";
176
+ const requestId = isJsonString(body.requestId) ? body.requestId : requestIdHeader;
177
+ const problems = [];
178
+ if (Array.isArray(body.problems)) {
179
+ for (const entry of body.problems) {
180
+ if (!isJsonObject(entry)) {
181
+ continue;
182
+ }
183
+ const item = {};
184
+ if (isJsonString(entry.path)) {
185
+ item.path = entry.path;
186
+ }
187
+ if (isJsonString(entry.problem)) {
188
+ item.problem = redactSecrets(entry.problem);
189
+ }
190
+ if (isJsonString(entry.tryThis)) {
191
+ item.tryThis = redactSecrets(entry.tryThis);
192
+ }
193
+ problems.push(item);
194
+ }
195
+ }
196
+ const structured = {
197
+ status,
198
+ code,
199
+ error,
200
+ tryThis,
201
+ };
202
+ if (problems.length > 0) {
203
+ structured.problems = problems;
204
+ }
205
+ if (requestId) {
206
+ structured.requestId = requestId;
207
+ }
208
+ return structured;
209
+ }
210
+ const fallback = {
211
+ status,
212
+ code: `HTTP_${status}`,
213
+ error: isJsonString(body) && body.trim()
214
+ ? redactSecrets(body.trim())
215
+ : `PCIFIC API returned HTTP ${status}.`,
216
+ tryThis: "Inspect the status code and retry once the underlying issue is fixed.",
217
+ };
218
+ if (requestIdHeader) {
219
+ fallback.requestId = requestIdHeader;
220
+ }
221
+ return fallback;
222
+ }
223
+ export function buildQueryString(entries) {
224
+ if (entries.length === 0) {
225
+ return "";
226
+ }
227
+ const params = new URLSearchParams();
228
+ for (const [key, value] of entries) {
229
+ params.set(key, value);
230
+ }
231
+ return `?${params.toString()}`;
232
+ }
233
+ export async function callPcificTestApi(params) {
234
+ if (params.apiKey.startsWith("pcific_live_")) {
235
+ throw new Error("Refusing to call PCIFIC API with a live key.");
236
+ }
237
+ const fetchImpl = params.fetchFn ?? globalThis.fetch;
238
+ const method = params.method.toUpperCase();
239
+ const queryString = buildQueryString(params.query ?? []);
240
+ const url = `${normalizeBaseUrl(params.baseUrl)}${params.path}${queryString}`;
241
+ const headers = {
242
+ Authorization: `Bearer ${params.apiKey}`,
243
+ Accept: "application/json",
244
+ "User-Agent": CLI_USER_AGENT,
245
+ };
246
+ if (method !== "GET") {
247
+ headers["Idempotency-Key"] = params.idempotencyKey ?? randomUUID();
248
+ }
249
+ const fetchHeaders = new Headers();
250
+ for (const [headerKey, headerValue] of Object.entries(headers)) {
251
+ if (headerValue !== undefined) {
252
+ fetchHeaders.set(headerKey, headerValue);
253
+ }
254
+ }
255
+ const requestInit = {
256
+ method,
257
+ headers: fetchHeaders,
258
+ };
259
+ if (params.body !== undefined) {
260
+ headers["Content-Type"] = "application/json";
261
+ fetchHeaders.set("Content-Type", "application/json");
262
+ requestInit.body = JSON.stringify(params.body);
263
+ }
264
+ else if (method !== "GET" && method !== "DELETE") {
265
+ headers["Content-Type"] = "application/json";
266
+ fetchHeaders.set("Content-Type", "application/json");
267
+ }
268
+ const response = await fetchImpl(url, requestInit);
269
+ const rawText = await response.text();
270
+ let parsedBody = null;
271
+ if (rawText.trim()) {
272
+ try {
273
+ // SAFETY: JSON.parse returns JSON values matching ApiJsonValue.
274
+ parsedBody = JSON.parse(rawText);
275
+ }
276
+ catch {
277
+ parsedBody = rawText;
278
+ }
279
+ }
280
+ const requestId = response.headers.get("x-request-id") ?? undefined;
281
+ const safeHeaders = {
282
+ ...headers,
283
+ Authorization: "Bearer pcific_test_***",
284
+ };
285
+ if (!response.ok) {
286
+ return {
287
+ ok: false,
288
+ status: response.status,
289
+ url,
290
+ method,
291
+ headers: safeHeaders,
292
+ requestId,
293
+ body: parsedBody,
294
+ rawText,
295
+ error: formatApiError(response.status, parsedBody, requestId),
296
+ };
297
+ }
298
+ return {
299
+ ok: true,
300
+ status: response.status,
301
+ url,
302
+ method,
303
+ headers: safeHeaders,
304
+ requestId,
305
+ body: parsedBody,
306
+ rawText,
307
+ };
308
+ }
309
+ function writeOut(stream, text) {
310
+ stream.write(`${redactSecrets(text)}\n`);
311
+ }
312
+ function writeErrorOut(stderr, useJson, payload) {
313
+ if (useJson) {
314
+ writeOut(stderr, JSON.stringify({ ok: false, ...payload }));
315
+ return;
316
+ }
317
+ const statusPart = payload.status ? ` (HTTP ${payload.status})` : "";
318
+ writeOut(stderr, `Error [${payload.code}]${statusPart}: ${payload.error}`);
319
+ if (payload.problems && payload.problems.length > 0) {
320
+ for (const problem of payload.problems) {
321
+ const location = problem.path ? `${problem.path}: ` : "";
322
+ const next = problem.tryThis ? ` (${problem.tryThis})` : "";
323
+ writeOut(stderr, ` - ${location}${problem.problem ?? "Invalid value"}${next}`);
324
+ }
325
+ }
326
+ writeOut(stderr, `Try this: ${payload.tryThis}`);
327
+ if (payload.requestId) {
328
+ writeOut(stderr, `Request ID: ${payload.requestId}`);
329
+ }
330
+ }
331
+ function formatSchemaType(schema) {
332
+ if (!schema) {
333
+ return "any";
334
+ }
335
+ if (schema.$circularRef) {
336
+ return `ref(${schema.$circularRef})`;
337
+ }
338
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
339
+ return `enum(${schema.enum.map((v) => JSON.stringify(v)).join(" | ")})`;
340
+ }
341
+ if (Array.isArray(schema.type)) {
342
+ return schema.type.join(" | ");
343
+ }
344
+ if (schema.type === "array") {
345
+ return `${formatSchemaType(schema.items)}[]`;
346
+ }
347
+ if (isJsonString(schema.type)) {
348
+ return schema.type;
349
+ }
350
+ if (schema.properties) {
351
+ return "object";
352
+ }
353
+ if (Array.isArray(schema.oneOf)) {
354
+ return schema.oneOf.map((branch) => formatSchemaType(branch)).join(" | ");
355
+ }
356
+ if (Array.isArray(schema.anyOf)) {
357
+ return schema.anyOf.map((branch) => formatSchemaType(branch)).join(" | ");
358
+ }
359
+ return "any";
360
+ }
361
+ function flattenSchemaFields(schema, prefix = "", depth = 0) {
362
+ if (!schema || depth > 3 || schema.$circularRef) {
363
+ return [];
364
+ }
365
+ const fields = [];
366
+ const props = schema.properties ?? {};
367
+ const requiredSet = new Set(schema.required ?? []);
368
+ for (const [name, propSchema] of Object.entries(props)) {
369
+ const fullName = prefix ? `${prefix}.${name}` : name;
370
+ const field = {
371
+ name: fullName,
372
+ type: formatSchemaType(propSchema),
373
+ required: requiredSet.has(name),
374
+ description: propSchema.description ?? "",
375
+ };
376
+ if (Array.isArray(propSchema.enum)) {
377
+ field.enum = propSchema.enum;
378
+ }
379
+ fields.push(field);
380
+ if (propSchema.properties && depth < 2) {
381
+ fields.push(...flattenSchemaFields(propSchema, fullName, depth + 1));
382
+ }
383
+ }
384
+ return fields;
385
+ }
386
+ function buildExampleCommand(op) {
387
+ const parts = ["pcific", "api", op.operationId];
388
+ for (const param of op.parameters) {
389
+ if (param.in === "path") {
390
+ parts.push("--param", `${param.name}=<${param.name}>`);
391
+ }
392
+ }
393
+ if (op.exampleBody !== undefined && op.method !== "GET") {
394
+ parts.push("--data", `'${JSON.stringify(op.exampleBody)}'`);
395
+ }
396
+ if (op.method !== "GET") {
397
+ parts.push("--dry-run");
398
+ }
399
+ return parts.join(" ");
400
+ }
401
+ function parseKeyValueArg(raw, flagName) {
402
+ const eqIndex = raw.indexOf("=");
403
+ if (eqIndex <= 0) {
404
+ return {
405
+ ok: false,
406
+ error: `Invalid ${flagName} value "${raw}". Expected key=value.`,
407
+ tryThis: `Pass ${flagName} as key=value, for example ${flagName} id=abc123.`,
408
+ };
409
+ }
410
+ return {
411
+ ok: true,
412
+ key: raw.slice(0, eqIndex),
413
+ value: raw.slice(eqIndex + 1),
414
+ };
415
+ }
416
+ function chunkToBuffer(chunk) {
417
+ if (Buffer.isBuffer(chunk)) {
418
+ return chunk;
419
+ }
420
+ if (chunk instanceof Uint8Array) {
421
+ return Buffer.from(chunk);
422
+ }
423
+ return Buffer.from(chunk, "utf8");
424
+ }
425
+ async function readStreamText(stream) {
426
+ const chunks = [];
427
+ for await (const chunk of stream) {
428
+ // SAFETY: NodeJS.ReadableStream yields string | Buffer chunks in UTF-8/binary mode.
429
+ chunks.push(chunkToBuffer(chunk));
430
+ }
431
+ return Buffer.concat(chunks).toString("utf8");
432
+ }
433
+ function extractPathPlaceholders(routePath) {
434
+ const names = [];
435
+ const regex = /\{([^}]+)\}/g;
436
+ let match = regex.exec(routePath);
437
+ while (match !== null) {
438
+ names.push(match[1]);
439
+ match = regex.exec(routePath);
440
+ }
441
+ return names;
442
+ }
443
+ const API_HELP = [
444
+ "Usage:",
445
+ " pcific api list [--tag <tag>] [--json] [--plain]",
446
+ " pcific api describe <operationId> [--json] [--plain]",
447
+ " pcific api [call] <operationId> [--param k=v] [--query k=v] [--data '<json>'|@file.json|-] [--dry-run] [--json] [--plain]",
448
+ "",
449
+ "Safety:",
450
+ " - Uses PCIFIC_TEST_KEY only. Live keys (pcific_live_...) are always refused.",
451
+ " - --dry-run is a local CLI preview only and never sends requests or ?dryRun=1.",
452
+ " - Non-GET calls automatically attach an Idempotency-Key header.",
453
+ ].join("\n");
454
+ export async function runApiCommand(args, options = {}) {
455
+ const cwd = options.cwd ?? process.cwd();
456
+ const stdout = options.stdout ?? process.stdout;
457
+ const stderr = options.stderr ?? process.stderr;
458
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
459
+ writeOut(stdout, API_HELP);
460
+ return 0;
461
+ }
462
+ let jsonFlag = Boolean(options.json);
463
+ let plainFlag = Boolean(options.plain);
464
+ let dryRun = false;
465
+ let tagFilter;
466
+ let baseUrlFlag;
467
+ let marketplaceIdFlag;
468
+ let idempotencyKeyFlag;
469
+ let dataArg;
470
+ const pathParams = new Map();
471
+ const queryParams = new Map();
472
+ const positionals = [];
473
+ const getUseJson = () => jsonFlag || (!plainFlag && !isStreamTty(stdout));
474
+ for (let i = 0; i < args.length; i += 1) {
475
+ const arg = args[i];
476
+ if (arg === "--help" || arg === "-h") {
477
+ writeOut(stdout, API_HELP);
478
+ return 0;
479
+ }
480
+ if (arg === "--json") {
481
+ jsonFlag = true;
482
+ continue;
483
+ }
484
+ if (arg === "--plain") {
485
+ plainFlag = true;
486
+ continue;
487
+ }
488
+ if (arg === "--dry-run") {
489
+ dryRun = true;
490
+ continue;
491
+ }
492
+ if (arg === "--tag" || arg.startsWith("--tag=")) {
493
+ const value = arg.startsWith("--tag=") ? arg.slice("--tag=".length) : args[i + 1];
494
+ if (!value || (!arg.startsWith("--tag=") && value.startsWith("-"))) {
495
+ writeErrorOut(stderr, getUseJson(), {
496
+ code: "MISSING_FLAG_VALUE",
497
+ error: "Missing value for --tag.",
498
+ tryThis: "Pass a tag name, for example: pcific api list --tag Safeguard",
499
+ });
500
+ return 1;
501
+ }
502
+ if (!arg.startsWith("--tag=")) {
503
+ i += 1;
504
+ }
505
+ tagFilter = value;
506
+ continue;
507
+ }
508
+ if (arg === "--base-url" || arg.startsWith("--base-url=")) {
509
+ const value = arg.startsWith("--base-url=") ? arg.slice("--base-url=".length) : args[i + 1];
510
+ if (!value || (!arg.startsWith("--base-url=") && value.startsWith("-"))) {
511
+ writeErrorOut(stderr, getUseJson(), {
512
+ code: "MISSING_FLAG_VALUE",
513
+ error: "Missing value for --base-url.",
514
+ tryThis: "Pass a URL, for example --base-url https://business.pcific.ai",
515
+ });
516
+ return 1;
517
+ }
518
+ if (!arg.startsWith("--base-url=")) {
519
+ i += 1;
520
+ }
521
+ baseUrlFlag = value;
522
+ continue;
523
+ }
524
+ if (arg === "--marketplace-id" || arg.startsWith("--marketplace-id=")) {
525
+ const value = arg.startsWith("--marketplace-id=")
526
+ ? arg.slice("--marketplace-id=".length)
527
+ : args[i + 1];
528
+ if (!value || (!arg.startsWith("--marketplace-id=") && value.startsWith("-"))) {
529
+ writeErrorOut(stderr, getUseJson(), {
530
+ code: "MISSING_FLAG_VALUE",
531
+ error: "Missing value for --marketplace-id.",
532
+ tryThis: "Pass a shop id from GET /api/v1/marketplaces.",
533
+ });
534
+ return 1;
535
+ }
536
+ if (!arg.startsWith("--marketplace-id=")) {
537
+ i += 1;
538
+ }
539
+ marketplaceIdFlag = value;
540
+ continue;
541
+ }
542
+ if (arg === "--idempotency-key" || arg.startsWith("--idempotency-key=")) {
543
+ const value = arg.startsWith("--idempotency-key=")
544
+ ? arg.slice("--idempotency-key=".length)
545
+ : args[i + 1];
546
+ if (!value || (!arg.startsWith("--idempotency-key=") && value.startsWith("-"))) {
547
+ writeErrorOut(stderr, getUseJson(), {
548
+ code: "MISSING_FLAG_VALUE",
549
+ error: "Missing value for --idempotency-key.",
550
+ tryThis: "Pass a unique key between 1 and 255 ASCII characters.",
551
+ });
552
+ return 1;
553
+ }
554
+ if (!arg.startsWith("--idempotency-key=")) {
555
+ i += 1;
556
+ }
557
+ idempotencyKeyFlag = value;
558
+ continue;
559
+ }
560
+ if (arg === "--param" || arg === "-p" || arg.startsWith("--param=")) {
561
+ const value = arg.startsWith("--param=") ? arg.slice("--param=".length) : args[i + 1];
562
+ if (!value || (!arg.startsWith("--param=") && value.startsWith("-"))) {
563
+ writeErrorOut(stderr, getUseJson(), {
564
+ code: "MISSING_FLAG_VALUE",
565
+ error: "Missing value for --param.",
566
+ tryThis: "Pass a path parameter as key=value, for example --param id=abc123.",
567
+ });
568
+ return 1;
569
+ }
570
+ if (!arg.startsWith("--param=")) {
571
+ i += 1;
572
+ }
573
+ const parsed = parseKeyValueArg(value, "--param");
574
+ if (!parsed.ok) {
575
+ writeErrorOut(stderr, getUseJson(), {
576
+ code: "INVALID_PARAM",
577
+ error: parsed.error,
578
+ tryThis: parsed.tryThis,
579
+ });
580
+ return 1;
581
+ }
582
+ pathParams.set(parsed.key, parsed.value);
583
+ continue;
584
+ }
585
+ if (arg === "--query" || arg === "-q" || arg.startsWith("--query=")) {
586
+ const value = arg.startsWith("--query=") ? arg.slice("--query=".length) : args[i + 1];
587
+ if (!value || (!arg.startsWith("--query=") && value.startsWith("-"))) {
588
+ writeErrorOut(stderr, getUseJson(), {
589
+ code: "MISSING_FLAG_VALUE",
590
+ error: "Missing value for --query.",
591
+ tryThis: "Pass a query parameter as key=value, for example --query limit=10.",
592
+ });
593
+ return 1;
594
+ }
595
+ if (!arg.startsWith("--query=")) {
596
+ i += 1;
597
+ }
598
+ const parsed = parseKeyValueArg(value, "--query");
599
+ if (!parsed.ok) {
600
+ writeErrorOut(stderr, getUseJson(), {
601
+ code: "INVALID_QUERY",
602
+ error: parsed.error,
603
+ tryThis: parsed.tryThis,
604
+ });
605
+ return 1;
606
+ }
607
+ if (queryParams.has(parsed.key)) {
608
+ writeErrorOut(stderr, getUseJson(), {
609
+ code: "QUERY_PARAMETER_REPEATED",
610
+ error: `Query parameter "${parsed.key}" was passed more than once.`,
611
+ tryThis: `Send --query ${parsed.key}=<value> only once; PCIFIC refuses repeated query parameters.`,
612
+ });
613
+ return 1;
614
+ }
615
+ queryParams.set(parsed.key, parsed.value);
616
+ continue;
617
+ }
618
+ if (arg === "--data" || arg === "-d" || arg.startsWith("--data=")) {
619
+ const value = arg.startsWith("--data=") ? arg.slice("--data=".length) : args[i + 1];
620
+ if (value === undefined ||
621
+ (!arg.startsWith("--data=") && value !== "-" && value.startsWith("-"))) {
622
+ writeErrorOut(stderr, getUseJson(), {
623
+ code: "MISSING_FLAG_VALUE",
624
+ error: "Missing value for --data.",
625
+ tryThis: "Pass inline JSON ('{\"key\":\"value\"}'), @file.json, or - for stdin.",
626
+ });
627
+ return 1;
628
+ }
629
+ if (!arg.startsWith("--data=")) {
630
+ i += 1;
631
+ }
632
+ dataArg = value;
633
+ continue;
634
+ }
635
+ if (arg.startsWith("-")) {
636
+ writeErrorOut(stderr, getUseJson(), {
637
+ code: "UNKNOWN_FLAG",
638
+ error: `Unknown flag "${arg}" for pcific api.`,
639
+ tryThis: "Run pcific api --help to see supported flags.",
640
+ });
641
+ return 1;
642
+ }
643
+ positionals.push(arg);
644
+ }
645
+ const useJson = getUseJson();
646
+ const subcommand = positionals[0];
647
+ if (!subcommand) {
648
+ writeOut(stdout, API_HELP);
649
+ return 0;
650
+ }
651
+ const catalog = loadOpenApiCatalog({ openapiPath: options.openapiPath });
652
+ if (subcommand === "list") {
653
+ const ops = tagFilter
654
+ ? catalog.operations.filter((op) => op.tags.some((tag) => tag.toLowerCase() === tagFilter.toLowerCase()))
655
+ : catalog.operations;
656
+ if (useJson) {
657
+ const listPayload = {
658
+ total: ops.length,
659
+ tags: catalog.tags,
660
+ operations: ops.map((op) => ({
661
+ operationId: op.operationId,
662
+ method: op.method,
663
+ path: op.path,
664
+ tags: op.tags,
665
+ summary: op.summary,
666
+ })),
667
+ };
668
+ if (tagFilter) {
669
+ listPayload.tag = tagFilter;
670
+ }
671
+ writeOut(stdout, JSON.stringify(listPayload));
672
+ return 0;
673
+ }
674
+ writeOut(stdout, `PCIFIC API operations (${ops.length}${tagFilter ? ` tagged "${tagFilter}"` : ""}):`);
675
+ writeOut(stdout, "");
676
+ for (const op of ops) {
677
+ writeOut(stdout, `${op.operationId} ${op.method} ${op.path}`);
678
+ if (op.summary) {
679
+ writeOut(stdout, ` ${op.summary}`);
680
+ }
681
+ }
682
+ return 0;
683
+ }
684
+ if (subcommand === "describe") {
685
+ const targetId = positionals.slice(1).join(" ").trim();
686
+ if (!targetId) {
687
+ writeErrorOut(stderr, useJson, {
688
+ code: "MISSING_OPERATION_ID",
689
+ error: "Missing operationId for `pcific api describe`.",
690
+ tryThis: "Pass an operationId, for example: pcific api describe put-safeguard-settings",
691
+ });
692
+ return 1;
693
+ }
694
+ const op = findOperation(catalog, targetId);
695
+ if (!op) {
696
+ writeErrorOut(stderr, useJson, {
697
+ code: "OPERATION_NOT_FOUND",
698
+ error: `Unknown PCIFIC API operation "${targetId}".`,
699
+ tryThis: `Run \`pcific search "${targetId}"\` or \`pcific api list\` to find the exact operationId.`,
700
+ });
701
+ return 1;
702
+ }
703
+ const pathParamDocs = op.parameters.filter((p) => p.in === "path");
704
+ const queryParamDocs = op.parameters.filter((p) => p.in === "query");
705
+ const bodyFields = flattenSchemaFields(op.requestBodySchema);
706
+ const exampleCommand = buildExampleCommand(op);
707
+ if (useJson) {
708
+ writeOut(stdout, JSON.stringify({
709
+ operationId: op.operationId,
710
+ method: op.method,
711
+ path: op.path,
712
+ tags: op.tags,
713
+ summary: op.summary,
714
+ description: op.description,
715
+ idempotent: op.idempotent,
716
+ pathParameters: pathParamDocs,
717
+ queryParameters: queryParamDocs,
718
+ requestBodyRequired: op.requestBodyRequired,
719
+ requestBodyContentTypes: op.requestBodyContentTypes,
720
+ requestBodyFields: bodyFields,
721
+ requestBodySchema: op.requestBodySchema,
722
+ exampleBody: op.exampleBody,
723
+ exampleCommand,
724
+ }));
725
+ return 0;
726
+ }
727
+ writeOut(stdout, `${op.operationId} (${op.method} ${op.path})`);
728
+ if (op.tags.length > 0) {
729
+ writeOut(stdout, `Tags: ${op.tags.join(", ")}`);
730
+ }
731
+ if (op.summary) {
732
+ writeOut(stdout, `Summary: ${op.summary}`);
733
+ }
734
+ if (op.description) {
735
+ writeOut(stdout, `Permissions/Notes: ${op.description}`);
736
+ }
737
+ if (pathParamDocs.length > 0) {
738
+ writeOut(stdout, "");
739
+ writeOut(stdout, "Path parameters:");
740
+ for (const param of pathParamDocs) {
741
+ writeOut(stdout, ` - ${param.name} (${formatSchemaType(param.schema)}, required)${param.description ? `: ${param.description}` : ""}`);
742
+ }
743
+ }
744
+ if (queryParamDocs.length > 0) {
745
+ writeOut(stdout, "");
746
+ writeOut(stdout, "Query parameters:");
747
+ for (const param of queryParamDocs) {
748
+ writeOut(stdout, ` - ${param.name} (${formatSchemaType(param.schema)}, ${param.required ? "required" : "optional"})${param.description ? `: ${param.description}` : ""}`);
749
+ }
750
+ }
751
+ if (bodyFields.length > 0) {
752
+ writeOut(stdout, "");
753
+ writeOut(stdout, "JSON body fields:");
754
+ for (const field of bodyFields) {
755
+ const reqLabel = field.required ? "required" : "optional";
756
+ writeOut(stdout, ` - ${field.name} (${field.type}, ${reqLabel})${field.description ? `: ${field.description}` : ""}`);
757
+ }
758
+ }
759
+ else if (op.requestBodyContentTypes.length > 0) {
760
+ writeOut(stdout, "");
761
+ writeOut(stdout, `Request body content types: ${op.requestBodyContentTypes.join(", ")}`);
762
+ }
763
+ writeOut(stdout, "");
764
+ writeOut(stdout, `Example: ${exampleCommand}`);
765
+ return 0;
766
+ }
767
+ const targetId = subcommand === "call"
768
+ ? positionals.slice(1).join(" ").trim()
769
+ : positionals.join(" ").trim();
770
+ if (!targetId) {
771
+ writeErrorOut(stderr, useJson, {
772
+ code: "MISSING_OPERATION_ID",
773
+ error: "Missing operationId for `pcific api`.",
774
+ tryThis: 'Run `pcific search "safeguard settings"` or `pcific api list` to pick an operation.',
775
+ });
776
+ return 1;
777
+ }
778
+ const op = findOperation(catalog, targetId);
779
+ if (!op) {
780
+ writeErrorOut(stderr, useJson, {
781
+ code: "OPERATION_NOT_FOUND",
782
+ error: `Unknown PCIFIC API operation "${targetId}".`,
783
+ tryThis: `Run \`pcific search "${targetId}"\` or \`pcific api list\` to find the exact operationId.`,
784
+ });
785
+ return 1;
786
+ }
787
+ const requiredPathNames = new Set([
788
+ ...extractPathPlaceholders(op.path),
789
+ ...op.parameters.filter((p) => p.in === "path").map((p) => p.name),
790
+ ]);
791
+ const missingPathParams = [...requiredPathNames].filter((name) => !pathParams.has(name));
792
+ if (missingPathParams.length > 0) {
793
+ writeErrorOut(stderr, useJson, {
794
+ code: "MISSING_PATH_PARAMETER",
795
+ error: `Missing required path parameter${missingPathParams.length > 1 ? "s" : ""}: ${missingPathParams.join(", ")}.`,
796
+ tryThis: `Supply ${missingPathParams.map((n) => `--param ${n}=<value>`).join(" ")} and retry.`,
797
+ });
798
+ return 1;
799
+ }
800
+ const resolvedPath = op.path.replace(/\{([^}]+)\}/g, (_match, paramName) => encodeURIComponent(pathParams.get(paramName) ?? ""));
801
+ let parsedBody;
802
+ if (dataArg !== undefined) {
803
+ let rawJsonText = dataArg;
804
+ if (dataArg === "-") {
805
+ rawJsonText = await readStreamText(options.stdin ?? process.stdin);
806
+ }
807
+ else if (dataArg.startsWith("@")) {
808
+ const fileRef = dataArg.slice(1);
809
+ const resolvedFile = path.isAbsolute(fileRef) ? fileRef : path.resolve(cwd, fileRef);
810
+ if (!existsSync(resolvedFile)) {
811
+ writeErrorOut(stderr, useJson, {
812
+ code: "DATA_FILE_NOT_FOUND",
813
+ error: `JSON data file not found at "${fileRef}".`,
814
+ tryThis: "Check the path passed to --data @file.json and try again.",
815
+ });
816
+ return 1;
817
+ }
818
+ rawJsonText = readFileSync(resolvedFile, "utf8");
819
+ }
820
+ try {
821
+ // SAFETY: JSON.parse returns JSON values matching ApiJsonValue.
822
+ parsedBody = JSON.parse(rawJsonText);
823
+ }
824
+ catch (err) {
825
+ writeErrorOut(stderr, useJson, {
826
+ code: "INVALID_JSON",
827
+ error: `Could not parse --data as JSON: ${err instanceof Error ? err.message : String(err)}`,
828
+ tryThis: 'Pass valid JSON to --data, for example --data \'{"minimumScore":7}\'.',
829
+ });
830
+ return 1;
831
+ }
832
+ }
833
+ const keyResult = resolveTestKey(cwd, options.env);
834
+ if (!keyResult.ok) {
835
+ if (!(dryRun && keyResult.code === "MISSING_TEST_KEY")) {
836
+ writeErrorOut(stderr, useJson, {
837
+ code: keyResult.code,
838
+ error: keyResult.error,
839
+ tryThis: keyResult.tryThis,
840
+ });
841
+ return 1;
842
+ }
843
+ }
844
+ const mergedEnv = readMergedEnv(cwd, options.env);
845
+ const marketplaceId = marketplaceIdFlag ??
846
+ (keyResult.ok
847
+ ? keyResult.marketplaceId
848
+ : mergedEnv.get("PCIFIC_MARKETPLACE_ID")?.trim() || undefined);
849
+ let baseUrl;
850
+ try {
851
+ baseUrl = normalizeBaseUrl(baseUrlFlag ??
852
+ options.baseUrl ??
853
+ (keyResult.ok ? keyResult.baseUrl : mergedEnv.get("PCIFIC_BASE_URL")?.trim()) ??
854
+ catalog.serverUrl);
855
+ }
856
+ catch (err) {
857
+ if (err instanceof BaseUrlError) {
858
+ writeErrorOut(stderr, useJson, {
859
+ code: err.code,
860
+ error: err.message,
861
+ tryThis: err.tryThis,
862
+ });
863
+ return 1;
864
+ }
865
+ throw err;
866
+ }
867
+ const queryEntries = [...queryParams.entries()];
868
+ const acceptsMarketplaceIdQuery = op.parameters.some((p) => p.in === "query" && p.name === "marketplaceId");
869
+ if (marketplaceId && !queryParams.has("marketplaceId") && acceptsMarketplaceIdQuery) {
870
+ queryEntries.push(["marketplaceId", marketplaceId]);
871
+ }
872
+ const fullUrl = `${baseUrl}${resolvedPath}${buildQueryString(queryEntries)}`;
873
+ if (dryRun) {
874
+ const previewHeaders = {
875
+ Authorization: "Bearer pcific_test_***",
876
+ Accept: "application/json",
877
+ "User-Agent": CLI_USER_AGENT,
878
+ };
879
+ if (op.method !== "GET") {
880
+ previewHeaders["Idempotency-Key"] = idempotencyKeyFlag ?? "<generated-uuid-on-send>";
881
+ }
882
+ if (parsedBody !== undefined || (op.method !== "GET" && op.method !== "DELETE")) {
883
+ previewHeaders["Content-Type"] = "application/json";
884
+ }
885
+ const previewHeaderObj = {
886
+ Authorization: previewHeaders.Authorization,
887
+ Accept: previewHeaders.Accept,
888
+ "User-Agent": previewHeaders["User-Agent"],
889
+ };
890
+ if (previewHeaders["Idempotency-Key"]) {
891
+ previewHeaderObj["Idempotency-Key"] = previewHeaders["Idempotency-Key"];
892
+ }
893
+ if (previewHeaders["Content-Type"]) {
894
+ previewHeaderObj["Content-Type"] = previewHeaders["Content-Type"];
895
+ }
896
+ const preview = {
897
+ dryRun: true,
898
+ networkCallMade: false,
899
+ operationId: op.operationId,
900
+ method: op.method,
901
+ url: fullUrl,
902
+ headers: previewHeaderObj,
903
+ };
904
+ if (parsedBody !== undefined) {
905
+ preview.body = parsedBody;
906
+ }
907
+ if (useJson) {
908
+ writeOut(stdout, JSON.stringify(preview));
909
+ }
910
+ else {
911
+ writeOut(stdout, "Dry run (local preview only, no network call made):");
912
+ writeOut(stdout, `${op.method} ${fullUrl}`);
913
+ writeOut(stdout, "Headers:");
914
+ for (const [k, v] of Object.entries(previewHeaders)) {
915
+ writeOut(stdout, ` ${k}: ${v}`);
916
+ }
917
+ if (parsedBody !== undefined) {
918
+ writeOut(stdout, "Body:");
919
+ writeOut(stdout, JSON.stringify(parsedBody, null, 2));
920
+ }
921
+ }
922
+ return 0;
923
+ }
924
+ const apiKey = keyResult.ok ? keyResult.apiKey : "";
925
+ try {
926
+ const response = await callPcificTestApi({
927
+ method: op.method,
928
+ path: resolvedPath,
929
+ baseUrl,
930
+ apiKey,
931
+ query: queryEntries,
932
+ body: parsedBody,
933
+ idempotencyKey: idempotencyKeyFlag,
934
+ fetchFn: options.fetch,
935
+ });
936
+ if (!response.ok) {
937
+ const apiError = response.error ?? formatApiError(response.status, response.body, response.requestId);
938
+ writeErrorOut(stderr, useJson, apiError);
939
+ return 1;
940
+ }
941
+ if (useJson) {
942
+ writeOut(stdout, JSON.stringify(response.body));
943
+ }
944
+ else if (isJsonString(response.body)) {
945
+ writeOut(stdout, response.body);
946
+ }
947
+ else {
948
+ writeOut(stdout, JSON.stringify(response.body, null, 2));
949
+ }
950
+ return 0;
951
+ }
952
+ catch (err) {
953
+ writeErrorOut(stderr, useJson, {
954
+ code: "NETWORK_ERROR",
955
+ error: `Request failed: ${err instanceof Error ? err.message : String(err)}`,
956
+ tryThis: `Check your network connection and base URL (${baseUrl}), then retry.`,
957
+ });
958
+ return 1;
959
+ }
960
+ }