@01.software/cli 0.3.0 → 0.4.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/dist/index.js CHANGED
@@ -9,8 +9,7 @@ import {
9
9
  CollectionClient,
10
10
  OrderApi,
11
11
  CartApi,
12
- ProductApi,
13
- parseApiKey
12
+ ProductApi
14
13
  } from "@01.software/sdk";
15
14
  import pc from "picocolors";
16
15
 
@@ -108,7 +107,7 @@ function loadCredentialsFrom(filePath) {
108
107
  try {
109
108
  const raw = readFileSync(filePath, "utf-8");
110
109
  const data = JSON.parse(raw);
111
- if (!data.clientKey || !data.secretKey) return null;
110
+ if (!data.publishableKey || !data.secretKey) return null;
112
111
  return data;
113
112
  } catch {
114
113
  return null;
@@ -130,56 +129,65 @@ ${entry}
130
129
  }
131
130
 
132
131
  // src/lib/client.ts
132
+ function isValidBearerToken(secret) {
133
+ return secret.startsWith("sk01_") || secret.startsWith("pat01_");
134
+ }
135
+ var tenantHeaderInterceptorInstalled = false;
136
+ function installTenantHeaderInterceptor(tenantId) {
137
+ if (tenantHeaderInterceptorInstalled) return;
138
+ tenantHeaderInterceptorInstalled = true;
139
+ const originalFetch = globalThis.fetch.bind(globalThis);
140
+ globalThis.fetch = async (input, init) => {
141
+ const headers = new Headers(init?.headers);
142
+ if (!headers.has("X-Tenant-Id")) headers.set("X-Tenant-Id", tenantId);
143
+ return originalFetch(input, { ...init, headers });
144
+ };
145
+ }
133
146
  function resolveClient(apiKeyFlag) {
134
- let clientKey;
135
- let secretKey;
136
- if (apiKeyFlag) {
137
- try {
138
- const parsed = parseApiKey(apiKeyFlag);
139
- clientKey = parsed.clientKey;
140
- secretKey = parsed.secretKey;
141
- } catch {
142
- console.error(
143
- pc.red(
144
- 'Invalid --api-key value. Expected Base64-encoded "clientKey:secretKey".'
145
- )
146
- );
147
- process.exit(2);
148
- }
149
- } else {
150
- clientKey = process.env.SOFTWARE_CLIENT_KEY;
151
- secretKey = process.env.SOFTWARE_SECRET_KEY;
152
- }
153
- if (!clientKey || !secretKey) {
147
+ let publishableKey = process.env.SOFTWARE_PUBLISHABLE_KEY;
148
+ let secretKey = apiKeyFlag ?? process.env.SOFTWARE_SECRET_KEY;
149
+ let tenantId;
150
+ if (!publishableKey || !secretKey) {
154
151
  const local = loadLocalCredentials();
155
152
  if (local) {
156
- clientKey = local.clientKey;
157
- secretKey = local.secretKey;
153
+ publishableKey = publishableKey ?? local.publishableKey;
154
+ secretKey = secretKey ?? local.secretKey;
155
+ tenantId = local.tenantId;
158
156
  }
159
157
  }
160
- if (!clientKey || !secretKey) {
158
+ if (!publishableKey || !secretKey) {
161
159
  const stored = loadCredentials();
162
160
  if (stored) {
163
- clientKey = stored.clientKey;
164
- secretKey = stored.secretKey;
161
+ publishableKey = publishableKey ?? stored.publishableKey;
162
+ secretKey = secretKey ?? stored.secretKey;
163
+ tenantId = tenantId ?? stored.tenantId;
165
164
  }
166
165
  }
167
- if (!clientKey || !secretKey) {
166
+ if (!publishableKey || !secretKey) {
168
167
  console.error(pc.red("Authentication required."));
169
168
  console.error(
170
169
  pc.dim(
171
- 'Run "01 login" to authenticate via browser,\nor set SOFTWARE_CLIENT_KEY and SOFTWARE_SECRET_KEY environment variables,\nor use the --api-key <base64> flag.'
170
+ 'Run "01 login" to authenticate via browser,\nor pass --api-key <token>,\nor set SOFTWARE_PUBLISHABLE_KEY and SOFTWARE_SECRET_KEY environment variables.'
172
171
  )
173
172
  );
174
173
  process.exit(2);
175
174
  }
176
- const apiOpts = { clientKey, secretKey };
175
+ if (!isValidBearerToken(secretKey)) {
176
+ console.error(
177
+ pc.red(
178
+ "Invalid API key format. Expected sk01_ or pat01_ token.\nLegacy hex credentials are no longer accepted \u2014 run `01 login` to re-authenticate."
179
+ )
180
+ );
181
+ process.exit(2);
182
+ }
183
+ if (tenantId) installTenantHeaderInterceptor(tenantId);
184
+ const apiOpts = { publishableKey, secretKey };
177
185
  return {
178
- collections: new CollectionClient(clientKey, secretKey),
186
+ collections: new CollectionClient(publishableKey, secretKey),
179
187
  api: new OrderApi(apiOpts),
180
188
  cart: new CartApi(apiOpts),
181
189
  product: new ProductApi(apiOpts),
182
- clientKey,
190
+ publishableKey,
183
191
  secretKey
184
192
  };
185
193
  }
@@ -896,64 +904,104 @@ var ERROR_HTML = (msg) => `<!DOCTYPE html>
896
904
  </head><body><div class="card"><div class="icon err">!</div><h1>Authentication failed</h1><p>${escapeHtml(msg)}</p></div></body></html>`;
897
905
  function startAuthServer(options) {
898
906
  return new Promise((resolve2, reject) => {
907
+ const corsHeaders = {
908
+ "Access-Control-Allow-Origin": WEB_URL,
909
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
910
+ "Access-Control-Allow-Headers": "Content-Type",
911
+ "Access-Control-Max-Age": "600",
912
+ Vary: "Origin"
913
+ };
914
+ const finalize = (creds) => {
915
+ options.saveFn({
916
+ publishableKey: creds.publishableKey,
917
+ secretKey: creds.secretKey,
918
+ ...creds.tenantId ? { tenantId: creds.tenantId } : {},
919
+ tenantName: creds.tenant
920
+ });
921
+ if (Array.isArray(creds.tenants)) {
922
+ const valid = creds.tenants.filter(
923
+ (t) => typeof t?.id === "string" && typeof t?.name === "string"
924
+ );
925
+ if (valid.length > 0) saveTenantList(valid);
926
+ }
927
+ console.log(pc4.green(`
928
+ Logged in successfully!`));
929
+ console.log(pc4.dim(`Tenant: ${creds.tenant}`));
930
+ };
899
931
  const server = createServer((req, res) => {
900
932
  if (!req.url) {
901
- res.writeHead(400).end();
933
+ res.writeHead(400, corsHeaders).end();
902
934
  return;
903
935
  }
904
936
  const url = new URL(req.url, `http://localhost`);
905
937
  if (url.pathname !== "/callback") {
906
- res.writeHead(404).end();
938
+ res.writeHead(404, corsHeaders).end();
907
939
  return;
908
940
  }
909
- const receivedState = url.searchParams.get("state");
910
- const clientKey = url.searchParams.get("clientKey");
911
- const secretKey = url.searchParams.get("secretKey");
912
- const tenant = url.searchParams.get("tenant");
913
- const tenantIdParam = url.searchParams.get("tenantId");
914
- const tenantsParam = url.searchParams.get("tenants");
915
- const error = url.searchParams.get("error");
916
- if (error) {
917
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(ERROR_HTML(error));
918
- console.error(pc4.red(`Login failed: ${error}`));
919
- cleanup(2);
941
+ if (req.method === "OPTIONS") {
942
+ res.writeHead(200, corsHeaders).end();
920
943
  return;
921
944
  }
922
- if (receivedState !== options.state) {
923
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(ERROR_HTML("State mismatch \u2014 possible CSRF attack."));
924
- console.error(pc4.red("Login failed: state mismatch."));
925
- cleanup(2);
945
+ if (req.method === "POST") {
946
+ const origin = req.headers.origin;
947
+ if (!origin || origin !== WEB_URL) {
948
+ res.writeHead(403, { ...corsHeaders, "Content-Type": "application/json" }).end(JSON.stringify({ error: "Forbidden: invalid origin" }));
949
+ return;
950
+ }
951
+ let body = "";
952
+ req.on("data", (chunk) => {
953
+ body += chunk;
954
+ if (body.length > 64 * 1024) {
955
+ res.writeHead(413, { ...corsHeaders, "Content-Type": "application/json" }).end(JSON.stringify({ error: "Payload too large" }));
956
+ req.destroy();
957
+ }
958
+ });
959
+ req.on("end", () => {
960
+ let parsed;
961
+ try {
962
+ parsed = JSON.parse(body);
963
+ } catch {
964
+ res.writeHead(400, { ...corsHeaders, "Content-Type": "application/json" }).end(JSON.stringify({ error: "Invalid JSON" }));
965
+ return;
966
+ }
967
+ const publishableKey = parsed.publishableKey;
968
+ const secretKey = parsed.secretKey;
969
+ const tenant = parsed.tenant;
970
+ const tenantIdParam = parsed.tenantId;
971
+ const tenantsParam = parsed.tenants;
972
+ const receivedState = parsed.state;
973
+ if (receivedState !== options.state) {
974
+ res.writeHead(403, { ...corsHeaders, "Content-Type": "application/json" }).end(JSON.stringify({ error: "State mismatch" }));
975
+ console.error(pc4.red("Login failed: state mismatch."));
976
+ cleanup(2);
977
+ return;
978
+ }
979
+ if (typeof publishableKey !== "string" || typeof secretKey !== "string" || typeof tenant !== "string") {
980
+ res.writeHead(400, { ...corsHeaders, "Content-Type": "application/json" }).end(JSON.stringify({ error: "Missing credentials" }));
981
+ console.error(pc4.red("Login failed: missing credentials."));
982
+ cleanup(2);
983
+ return;
984
+ }
985
+ finalize({
986
+ publishableKey,
987
+ secretKey,
988
+ tenant,
989
+ tenantId: typeof tenantIdParam === "string" ? tenantIdParam : void 0,
990
+ tenants: tenantsParam
991
+ });
992
+ res.writeHead(200, { ...corsHeaders, "Content-Type": "application/json" }).end(JSON.stringify({ success: true }));
993
+ cleanup(0);
994
+ });
926
995
  return;
927
996
  }
928
- if (!clientKey || !secretKey || !tenant) {
929
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(ERROR_HTML("Missing credentials in callback."));
930
- console.error(pc4.red("Login failed: missing credentials."));
997
+ const error = url.searchParams.get("error");
998
+ if (error) {
999
+ res.writeHead(200, { ...corsHeaders, "Content-Type": "text/html; charset=utf-8" }).end(ERROR_HTML(error));
1000
+ console.error(pc4.red(`Login failed: ${error}`));
931
1001
  cleanup(2);
932
1002
  return;
933
1003
  }
934
- options.saveFn({
935
- clientKey,
936
- secretKey,
937
- ...tenantIdParam ? { tenantId: tenantIdParam } : {},
938
- tenantName: tenant
939
- });
940
- if (tenantsParam) {
941
- try {
942
- const parsed = JSON.parse(tenantsParam);
943
- if (Array.isArray(parsed)) {
944
- const valid = parsed.filter(
945
- (t) => typeof t?.id === "string" && typeof t?.name === "string"
946
- );
947
- if (valid.length > 0) saveTenantList(valid);
948
- }
949
- } catch {
950
- }
951
- }
952
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(SUCCESS_HTML);
953
- console.log(pc4.green(`
954
- Logged in successfully!`));
955
- console.log(pc4.dim(`Tenant: ${tenant}`));
956
- cleanup(0);
1004
+ res.writeHead(200, { ...corsHeaders, "Content-Type": "text/html; charset=utf-8" }).end(SUCCESS_HTML);
957
1005
  });
958
1006
  let timeout;
959
1007
  let completed = false;
@@ -1025,10 +1073,10 @@ ${loginUrl}`));
1025
1073
  console.log(pc4.dim('Not logged in. Run "01 login" to authenticate.'));
1026
1074
  return;
1027
1075
  }
1028
- const masked = creds.clientKey.length > 8 ? creds.clientKey.slice(0, 4) + "..." + creds.clientKey.slice(-4) : "****";
1076
+ const masked = creds.publishableKey.length > 8 ? creds.publishableKey.slice(0, 4) + "..." + creds.publishableKey.slice(-4) : "****";
1029
1077
  const scope = isLocal ? pc4.cyan(" (local)") : "";
1030
1078
  console.log(`Tenant: ${pc4.bold(creds.tenantName)}${scope}`);
1031
- console.log(`Client Key: ${pc4.dim(masked)}`);
1079
+ console.log(`Publishable Key: ${pc4.dim(masked)}`);
1032
1080
  console.log(`Stored at: ${pc4.dim(creds.storedAt)}`);
1033
1081
  console.log(
1034
1082
  `File: ${pc4.dim(isLocal ? getLocalCredentialsPath() : getCredentialsPath())}`
@@ -1135,17 +1183,12 @@ function registerSchemaCommands(program2, getClient2, getFormat2) {
1135
1183
  throw new Error(`Unknown collection "${collection}". ${hint}`);
1136
1184
  }
1137
1185
  const client = getClient2();
1138
- const { createServerToken } = await import("@01.software/sdk/auth");
1139
- const token = await createServerToken(
1140
- client.clientKey,
1141
- client.secretKey
1142
- );
1143
1186
  const baseUrl = getApiUrl();
1144
1187
  const url = `${baseUrl}/api/tenants/schema/${encodeURIComponent(collection)}`;
1145
1188
  const response = await fetch(url, {
1146
1189
  headers: {
1147
- "X-Client-Key": client.clientKey,
1148
- Authorization: `Bearer ${token}`
1190
+ "X-Publishable-Key": client.publishableKey,
1191
+ Authorization: `Bearer ${client.secretKey}`
1149
1192
  }
1150
1193
  });
1151
1194
  if (!response.ok) {
@@ -1191,7 +1234,7 @@ function registerMcpCommands(program2) {
1191
1234
  const child = spawn(process.execPath, [stdioEntry], {
1192
1235
  env: {
1193
1236
  ...process.env,
1194
- SOFTWARE_CLIENT_KEY: client.clientKey,
1237
+ SOFTWARE_PUBLISHABLE_KEY: client.publishableKey,
1195
1238
  SOFTWARE_SECRET_KEY: client.secretKey
1196
1239
  },
1197
1240
  stdio: ["inherit", "inherit", "inherit"]
@@ -1212,7 +1255,7 @@ process.on("unhandledRejection", (err) => {
1212
1255
  exitWithError(err);
1213
1256
  });
1214
1257
  var program = new Command();
1215
- program.name("01").description("CLI for the 01.software platform").version(version).option("--api-key <base64>", "Base64-encoded API key (clientKey:secretKey)").option("--format <format>", "Output format: json, table, or ndjson");
1258
+ program.name("01").description("CLI for the 01.software platform").version(version).option("--api-key <key>", "API key (sk01_... or pat01_... token)").option("--format <format>", "Output format: json, table, or ndjson");
1216
1259
  var getFormat = () => program.opts().format ?? process.env.OUTPUT_FORMAT ?? "json";
1217
1260
  var getClient = () => resolveClient(program.opts().apiKey);
1218
1261
  registerCrudCommands(program, getClient, getFormat);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/lib/client.ts","../src/lib/credentials.ts","../src/lib/output.ts","../src/commands/crud.ts","../src/lib/parse.ts","../src/commands/order.ts","../src/commands/return.ts","../src/commands/cart.ts","../src/commands/stock.ts","../src/commands/transaction.ts","../src/commands/auth.ts","../src/commands/schema.ts","../src/commands/mcp.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { resolveClient } from './lib/client.js'\nimport { exitWithError } from './lib/output.js'\nimport { registerCrudCommands } from './commands/crud.js'\nimport { registerOrderCommands } from './commands/order.js'\nimport { registerReturnCommands } from './commands/return.js'\nimport { registerCartCommands } from './commands/cart.js'\nimport { registerStockCommands } from './commands/stock.js'\nimport { registerTransactionCommands } from './commands/transaction.js'\nimport { registerAuthCommands } from './commands/auth.js'\nimport { registerSchemaCommands } from './commands/schema.js'\nimport { registerMcpCommands } from './commands/mcp.js'\n\nconst require = createRequire(import.meta.url)\nconst { version } = require('../package.json') as { version: string }\n\nprocess.on('unhandledRejection', (err) => {\n exitWithError(err)\n})\n\nconst program = new Command()\n\nprogram\n .name('01')\n .description('CLI for the 01.software platform')\n .version(version)\n .option('--api-key <base64>', 'Base64-encoded API key (clientKey:secretKey)')\n .option('--format <format>', 'Output format: json, table, or ndjson')\n\nconst getFormat = () =>\n (program.opts().format ?? process.env.OUTPUT_FORMAT ?? 'json') as string\nconst getClient = () =>\n resolveClient(program.opts().apiKey as string | undefined)\n\nregisterCrudCommands(program, getClient, getFormat)\nregisterOrderCommands(program, getClient, getFormat)\nregisterReturnCommands(program, getClient, getFormat)\nregisterCartCommands(program, getClient, getFormat)\nregisterStockCommands(program, getClient, getFormat)\nregisterTransactionCommands(program, getClient, getFormat)\nregisterSchemaCommands(program, getClient, getFormat)\nregisterMcpCommands(program)\nregisterAuthCommands(program)\n\nprogram.parse()\n","import {\n CollectionClient,\n OrderApi,\n CartApi,\n ProductApi,\n parseApiKey,\n} from '@01.software/sdk'\nimport pc from 'picocolors'\nimport { loadCredentials, loadLocalCredentials } from './credentials.js'\n\nexport interface ResolvedClient {\n collections: CollectionClient\n api: OrderApi\n cart: CartApi\n product: ProductApi\n clientKey: string\n secretKey: string\n}\n\nexport function resolveClient(apiKeyFlag?: string): ResolvedClient {\n let clientKey: string | undefined\n let secretKey: string | undefined\n\n if (apiKeyFlag) {\n try {\n const parsed = parseApiKey(apiKeyFlag)\n clientKey = parsed.clientKey\n secretKey = parsed.secretKey\n } catch {\n console.error(\n pc.red(\n 'Invalid --api-key value. Expected Base64-encoded \"clientKey:secretKey\".',\n ),\n )\n process.exit(2)\n }\n } else {\n clientKey = process.env.SOFTWARE_CLIENT_KEY\n secretKey = process.env.SOFTWARE_SECRET_KEY\n }\n\n // Fallback: local credentials (./01software/credentials.json)\n if (!clientKey || !secretKey) {\n const local = loadLocalCredentials()\n if (local) {\n clientKey = local.clientKey\n secretKey = local.secretKey\n }\n }\n\n // Fallback: global credentials (~/.01software/credentials.json)\n if (!clientKey || !secretKey) {\n const stored = loadCredentials()\n if (stored) {\n clientKey = stored.clientKey\n secretKey = stored.secretKey\n }\n }\n\n if (!clientKey || !secretKey) {\n console.error(pc.red('Authentication required.'))\n console.error(\n pc.dim(\n 'Run \"01 login\" to authenticate via browser,\\n' +\n 'or set SOFTWARE_CLIENT_KEY and SOFTWARE_SECRET_KEY environment variables,\\n' +\n 'or use the --api-key <base64> flag.',\n ),\n )\n process.exit(2)\n }\n\n const apiOpts = { clientKey, secretKey }\n\n return {\n collections: new CollectionClient(clientKey, secretKey),\n api: new OrderApi(apiOpts),\n cart: new CartApi(apiOpts),\n product: new ProductApi(apiOpts),\n clientKey,\n secretKey,\n }\n}\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n unlinkSync,\n appendFileSync,\n} from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nexport interface StoredCredentials {\n clientKey: string\n secretKey: string\n tenantId?: string\n tenantName: string\n storedAt: string\n}\n\nexport interface TenantInfo {\n id: string\n name: string\n}\n\nconst DIR_NAME = '.01software'\nconst FILE_NAME = 'credentials.json'\nconst TENANTS_FILE = 'tenants.json'\n\n// ---------------------------------------------------------------------------\n// Global credentials (~/.01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getCredentialsPath(): string {\n return join(homedir(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getCredentialsPath())\n}\n\nexport function saveCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function deleteCredentials(): boolean {\n const filePath = getCredentialsPath()\n if (!existsSync(filePath)) return false\n\n unlinkSync(filePath)\n return true\n}\n\n// ---------------------------------------------------------------------------\n// Local credentials (./01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getLocalCredentialsPath(): string {\n return join(process.cwd(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadLocalCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getLocalCredentialsPath())\n}\n\nexport function saveLocalCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(process.cwd(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getLocalCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n\n // Ensure .01software/ is in .gitignore\n ensureGitignore()\n}\n\n// ---------------------------------------------------------------------------\n// Tenant list cache (~/.01software/tenants.json)\n// ---------------------------------------------------------------------------\n\nexport function saveTenantList(tenants: TenantInfo[]): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n writeFileSync(filePath, JSON.stringify(tenants, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function loadTenantList(): TenantInfo[] | null {\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw)\n if (!Array.isArray(data)) return null\n const valid = data.filter(\n (t): t is TenantInfo =>\n typeof t?.id === 'string' && typeof t?.name === 'string',\n )\n return valid.length > 0 ? valid : null\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction loadCredentialsFrom(filePath: string): StoredCredentials | null {\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw) as StoredCredentials\n if (!data.clientKey || !data.secretKey) return null\n return data\n } catch {\n return null\n }\n}\n\nfunction ensureGitignore(): void {\n const gitignorePath = join(process.cwd(), '.gitignore')\n const entry = '.01software/'\n\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8')\n if (content.includes(entry)) return\n appendFileSync(gitignorePath, `\\n${entry}\\n`, 'utf-8')\n } else {\n writeFileSync(gitignorePath, `${entry}\\n`, 'utf-8')\n }\n}\n","import pc from 'picocolors'\n\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2))\n}\n\nexport function printTable(data: unknown): void {\n if (Array.isArray(data)) {\n if (data.length === 0) {\n console.log(pc.dim('(empty)'))\n return\n }\n const keys = Object.keys(data[0] as Record<string, unknown>)\n const widths = keys.map((k) =>\n Math.max(\n k.length,\n ...data.map(\n (row) => String((row as Record<string, unknown>)[k] ?? '').length,\n ),\n ),\n )\n\n // Header\n console.log(keys.map((k, i) => k.padEnd(widths[i]!)).join(' '))\n console.log(keys.map((_, i) => '-'.repeat(widths[i]!)).join(' '))\n\n // Rows\n for (const row of data) {\n console.log(\n keys\n .map((k, i) =>\n String((row as Record<string, unknown>)[k] ?? '').padEnd(\n widths[i]!,\n ),\n )\n .join(' '),\n )\n }\n } else if (data && typeof data === 'object') {\n const entries = Object.entries(data as Record<string, unknown>)\n const maxKey = Math.max(...entries.map(([k]) => k.length))\n for (const [key, value] of entries) {\n const display =\n typeof value === 'object' ? JSON.stringify(value) : String(value)\n console.log(`${pc.bold(key.padEnd(maxKey))} ${display}`)\n }\n } else {\n console.log(String(data))\n }\n}\n\nfunction printNdjson(data: unknown): void {\n if (Array.isArray(data)) {\n data.forEach((item) => console.log(JSON.stringify(item)))\n } else if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const { docs, ...meta } = data as {\n docs: unknown[]\n [key: string]: unknown\n }\n ;(docs as unknown[]).forEach((doc) => console.log(JSON.stringify(doc)))\n if (Object.keys(meta).length > 0)\n console.log(JSON.stringify({ _meta: meta }))\n } else {\n console.log(JSON.stringify(data))\n }\n}\n\nexport function printResult(data: unknown, format: string): void {\n if (format === 'ndjson') {\n printNdjson(data)\n } else if (format === 'table') {\n // For find responses with docs array, print the docs as table\n if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const resp = data as {\n docs: unknown[]\n totalDocs: number\n page: number\n totalPages: number\n }\n printTable(resp.docs)\n console.log(\n pc.dim(\n `\\n${resp.totalDocs} total | page ${resp.page}/${resp.totalPages}`,\n ),\n )\n return\n }\n printTable(data)\n } else {\n printJson(data)\n }\n}\n\nexport function getExitCode(error: unknown): number {\n if (!error || typeof error !== 'object') return 1\n const err = error as Record<string, unknown>\n\n // SDK error name\n if (err.name === 'ConfigError') return 2\n if (err.name === 'ValidationError') return 3\n if (err.name === 'NetworkError' || err.name === 'TimeoutError') return 4\n if (err.name === 'GoneError') return 5\n if (err.name === 'UsageLimitError') return 6\n\n // HTTP status fallback\n const s = err.status as number | undefined\n if (s === 401) return 2\n if (s === 400 || s === 422) return 3\n if (s === 408 || s === 503) return 4\n if (s === 404) return 5\n if (s === 429) return 6\n\n return 1\n}\n\nexport function exitWithError(error: unknown): never {\n printError(error)\n process.exit(getExitCode(error))\n}\n\nexport function printError(error: unknown): void {\n if (error && typeof error === 'object' && 'message' in error) {\n const err = error as {\n message: string\n code?: string\n status?: number\n suggestion?: string\n }\n console.error(pc.red(`Error: ${err.message}`))\n if (err.code) console.error(pc.dim(`Code: ${err.code}`))\n if (err.status) console.error(pc.dim(`Status: ${err.status}`))\n if (err.suggestion) console.error(pc.yellow(err.suggestion))\n } else {\n console.error(pc.red(String(error)))\n }\n}\n","import { readFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { Command } from 'commander'\nimport { COLLECTIONS } from '@01.software/sdk'\nimport type { ApiQueryOptions } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson } from '../lib/parse.js'\n\nfunction readFileAsBlob(filePath: string): { blob: Blob; filename: string } {\n const buffer = readFileSync(filePath)\n return { blob: new Blob([buffer]), filename: basename(filePath) }\n}\n\nfunction validateCollection(name: string): string {\n if (!(COLLECTIONS as readonly string[]).includes(name)) {\n const normalized = name.replace(/-/g, '').toLowerCase()\n const suggestions = COLLECTIONS.filter((c) => {\n const cn = c.replace(/-/g, '').toLowerCase()\n return (\n cn.startsWith(normalized) ||\n normalized.startsWith(cn) ||\n (normalized.length >= 3 && cn.includes(normalized))\n )\n }).slice(0, 5)\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 --help\" for available collections.'\n throw new Error(`Unknown collection \"${name}\". ${hint}`)\n }\n return name\n}\n\nfunction parseSelect(input: string): Record<string, boolean> {\n return Object.fromEntries(input.split(',').map((f) => [f.trim(), true]))\n}\n\nexport function registerCrudCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n program\n .command('query <collection>')\n .description('Query documents from a collection')\n .option('--where <json>', 'Filter conditions (JSON)')\n .option('--limit <n>', 'Max results', (v: string) => parseInt(v, 10))\n .option('--page <n>', 'Page number', (v: string) => parseInt(v, 10))\n .option('--sort <field>', 'Sort field (prefix with - for descending)')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.where) options.where = parseJson(opts.where, 'where')\n if (opts.limit) options.limit = opts.limit\n if (opts.page) options.page = opts.page\n if (opts.sort) options.sort = opts.sort\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .find(options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('get <collection> <id>')\n .description('Get a document by ID')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .findById(id, options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('create <collection>')\n .description('Create a new document')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'create',\n collection: col,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .create(data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update <collection> <id>')\n .description('Update a document by ID')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update',\n collection: col,\n id,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .update(id, data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete <collection> <id>')\n .description('Delete a document by ID')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete',\n collection: col,\n id,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .remove(id)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update-many <collection>')\n .description('Update multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .requiredOption('--data <json>', 'Update data (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update-many',\n collection: col,\n where,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .updateMany(where, data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete-many <collection>')\n .description('Delete multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete-many',\n collection: col,\n where,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .removeMany(where)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import pc from 'picocolors'\n\nexport function parseJson(\n value: string,\n label: string,\n): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value)\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed)\n ) {\n console.error(pc.red(`--${label} must be a JSON object.`))\n process.exit(3)\n }\n return parsed as Record<string, unknown>\n } catch {\n console.error(pc.red(`Invalid JSON for --${label}: ${value}`))\n process.exit(3)\n }\n}\n\nexport function parseJsonArray(value: string, label: string): unknown[] {\n try {\n const parsed = JSON.parse(value)\n if (!Array.isArray(parsed)) {\n console.error(pc.red(`--${label} must be a JSON array.`))\n process.exit(3)\n }\n return parsed\n } catch {\n console.error(pc.red(`Invalid JSON for --${label}: ${value}`))\n process.exit(3)\n }\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson, parseJsonArray } from '../lib/parse.js'\n\nexport function registerOrderCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const order = program.command('order').description('Order management')\n\n order\n .command('create')\n .description('Create a new order')\n .option('--payment-id <id>', 'Payment ID')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--email <email>', 'Customer email')\n .option('--customer <id>', 'Customer ID')\n .option('--name <name>', 'Customer name')\n .option('--phone <phone>', 'Customer phone')\n .requiredOption('--shipping-address <json>', 'Shipping address (JSON)')\n .requiredOption('--products <json>', 'Order products array (JSON)')\n .requiredOption('--total-amount <n>', 'Total amount', parseFloat)\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const shippingAddress = parseJson(\n opts.shippingAddress,\n 'shipping-address',\n )\n const orderProducts = parseJsonArray(opts.products, 'products')\n const data = {\n paymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot: {\n email: opts.email,\n name: opts.name,\n phone: opts.phone,\n },\n customer: opts.customer,\n shippingAddress,\n orderProducts,\n totalAmount: opts.totalAmount,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.createOrder({\n ...data,\n orderProducts: orderProducts as Parameters<\n typeof client.api.createOrder\n >[0]['orderProducts'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('get <orderNumber>')\n .description('Get an order by order number')\n .action(async (orderNumber: string) => {\n try {\n const client = getClient()\n const result = await client.api.getOrder({ orderNumber })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('update <orderNumber>')\n .description('Update order status')\n .requiredOption('--status <status>', 'New status')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = { orderNumber, status: opts.status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.updateOrder(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('checkout')\n .description('Convert a cart to an order')\n .requiredOption('--cart-id <id>', 'Cart ID')\n .option('--payment-id <id>', 'Payment ID (optional for free orders)')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--customer <json>', 'Customer snapshot (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const customerSnapshot = parseJson(opts.customer, 'customer')\n const data = {\n cartId: opts.cartId,\n paymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order checkout', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.checkout({\n ...data,\n customerSnapshot: customerSnapshot as Parameters<\n typeof client.api.checkout\n >[0]['customerSnapshot'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('fulfill <orderNumber>')\n .description('Create a fulfillment for an order')\n .requiredOption('--items <json>', 'Fulfillment items array (JSON)')\n .option('--carrier <name>', 'Shipping carrier')\n .option('--tracking-number <num>', 'Tracking number')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const items = parseJsonArray(opts.items, 'items')\n const data = {\n orderNumber,\n items,\n carrier: opts.carrier,\n trackingNumber: opts.trackingNumber,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order fulfill', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.createFulfillment({\n ...data,\n items: items as Parameters<\n typeof client.api.createFulfillment\n >[0]['items'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerReturnCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const ret = program.command('return').description('Return management')\n\n ret\n .command('create <orderNumber>')\n .description('Create a return request')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .option(\n '--reason <reason>',\n 'Return reason (change_of_mind, defective, wrong_delivery, damaged, other)',\n )\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const returnProducts = parseJsonArray(opts.products, 'products')\n const data = {\n orderNumber,\n returnProducts,\n refundAmount: opts.refundAmount,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.createReturn({\n ...data,\n returnProducts: returnProducts as Parameters<\n typeof client.api.createReturn\n >[0]['returnProducts'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('update <returnId>')\n .description('Update return status')\n .requiredOption(\n '--status <status>',\n 'New status (processing, approved, rejected, completed)',\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (returnId: string, opts) => {\n try {\n const data = { returnId, status: opts.status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.updateReturn(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('refund <orderNumber>')\n .description('Return with refund')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .requiredOption('--payment-id <id>', 'Payment ID')\n .option('--reason <reason>', 'Return reason')\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--refund-receipt-url <url>', 'Refund receipt URL')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const returnProducts = parseJsonArray(opts.products, 'products')\n const data = {\n orderNumber,\n returnProducts,\n refundAmount: opts.refundAmount,\n paymentId: opts.paymentId,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n refundReceiptUrl: opts.refundReceiptUrl,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return refund', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.returnWithRefund({\n ...data,\n returnProducts: returnProducts as Parameters<\n typeof client.api.returnWithRefund\n >[0]['returnProducts'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerCartCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const cart = program.command('cart').description('Cart management')\n\n cart\n .command('add <cartId>')\n .description('Add an item to cart')\n .requiredOption('--product <id>', 'Product ID')\n .requiredOption('--variant <id>', 'Variant ID')\n .requiredOption('--option <id>', 'Option ID')\n .requiredOption('--quantity <n>', 'Quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartId: string, opts) => {\n try {\n const data = {\n cartId,\n product: opts.product,\n variant: opts.variant,\n option: opts.option,\n quantity: opts.quantity,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart add', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.cart.addItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('update <cartItemId>')\n .description('Update cart item quantity')\n .requiredOption('--quantity <n>', 'New quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n const data = { cartItemId, quantity: opts.quantity }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.cart.updateItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('remove <cartItemId>')\n .description('Remove an item from cart')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'cart remove',\n data: { cartItemId },\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.cart.removeItem({ cartItemId })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerStockCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const stock = program.command('stock').description('Stock management')\n\n stock\n .command('check')\n .description('Check stock availability')\n .requiredOption(\n '--items <json>',\n 'Items to check (JSON array of { optionId, quantity })',\n )\n .action(async (opts) => {\n try {\n const client = getClient()\n const items = parseJsonArray(opts.items, 'items') as Parameters<\n typeof client.product.stockCheck\n >[0]['items']\n const result = await client.product.stockCheck({ items })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerTransactionCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const tx = program\n .command('transaction')\n .description('Transaction management')\n\n tx.command('update')\n .description('Update transaction status')\n .requiredOption('--payment-id <id>', 'Payment ID')\n .requiredOption(\n '--status <status>',\n 'New status (pending, paid, failed, canceled)',\n )\n .requiredOption('--payment-method <method>', 'Payment method')\n .requiredOption('--receipt-url <url>', 'Receipt URL')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = {\n paymentId: opts.paymentId,\n status: opts.status,\n paymentMethod: opts.paymentMethod,\n receiptUrl: opts.receiptUrl,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'transaction update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.updateTransaction(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer } from 'node:http'\nimport { execFile, exec } from 'node:child_process'\nimport { platform } from 'node:os'\nimport { URL } from 'node:url'\nimport type { Command } from 'commander'\nimport pc from 'picocolors'\nimport {\n loadCredentials,\n saveCredentials,\n deleteCredentials,\n getCredentialsPath,\n loadLocalCredentials,\n saveLocalCredentials,\n getLocalCredentialsPath,\n loadTenantList,\n saveTenantList,\n type TenantInfo,\n} from '../lib/credentials.js'\n\nconst WEB_URL = process.env.SOFTWARE_WEB_URL || 'https://01.software'\nconst TIMEOUT_MS = 3 * 60 * 1000 // 3 minutes\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\nfunction openBrowser(url: string): void {\n const os = platform()\n\n const onError = () => {\n console.log(\n pc.yellow(\n `Could not open browser automatically. Open this URL manually:\\n${url}`,\n ),\n )\n }\n\n if (os === 'win32') {\n exec(`start \"\" \"${url}\"`, (err) => {\n if (err) onError()\n })\n } else {\n const cmd = os === 'darwin' ? 'open' : 'xdg-open'\n execFile(cmd, [url], (err) => {\n if (err) onError()\n })\n }\n}\n\nconst PAGE_STYLE = `*{margin:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;background:#fff;color:#252525}\n@media(prefers-color-scheme:dark){body{background:#252525;color:#f5f5f5}}\n.card{text-align:center;padding:2rem 2.5rem;border-radius:10px;max-width:380px;width:100%}\n.icon{width:40px;height:40px;margin:0 auto 1rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.25rem}\n.icon.ok{background:rgba(0,0,0,.05);color:#252525}\n.icon.err{background:rgba(220,38,38,.08);color:#dc2626}\n@media(prefers-color-scheme:dark){.icon.ok{background:rgba(255,255,255,.08);color:#f5f5f5}}\nh1{font-size:.875rem;font-weight:600;margin-bottom:.375rem}\np{font-size:.75rem;color:#737373;line-height:1.5}`\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon ok\">\\u2713</div><h1>Authenticated</h1><p>You can close this tab and return to the terminal.</p></div></body></html>`\n\nconst ERROR_HTML = (msg: string) => `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login Error</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon err\">!</div><h1>Authentication failed</h1><p>${escapeHtml(msg)}</p></div></body></html>`\n\n/**\n * Start a local HTTP server that receives the OAuth-like callback from the browser.\n * Returns a promise that resolves with the received credentials, or rejects on error/timeout.\n */\nfunction startAuthServer(options: {\n state: string\n saveFn: (creds: {\n clientKey: string\n secretKey: string\n tenantId?: string\n tenantName: string\n }) => void\n}): Promise<{ port: number; cleanup: (exitCode?: number) => void }> {\n return new Promise((resolve, reject) => {\n const server = createServer((req, res) => {\n if (!req.url) {\n res.writeHead(400).end()\n return\n }\n\n const url = new URL(req.url, `http://localhost`)\n\n if (url.pathname !== '/callback') {\n res.writeHead(404).end()\n return\n }\n\n const receivedState = url.searchParams.get('state')\n const clientKey = url.searchParams.get('clientKey')\n const secretKey = url.searchParams.get('secretKey')\n const tenant = url.searchParams.get('tenant')\n const tenantIdParam = url.searchParams.get('tenantId')\n const tenantsParam = url.searchParams.get('tenants')\n const error = url.searchParams.get('error')\n\n if (error) {\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })\n .end(ERROR_HTML(error))\n console.error(pc.red(`Login failed: ${error}`))\n cleanup(2)\n return\n }\n\n if (receivedState !== options.state) {\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })\n .end(ERROR_HTML('State mismatch — possible CSRF attack.'))\n console.error(pc.red('Login failed: state mismatch.'))\n cleanup(2)\n return\n }\n\n if (!clientKey || !secretKey || !tenant) {\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })\n .end(ERROR_HTML('Missing credentials in callback.'))\n console.error(pc.red('Login failed: missing credentials.'))\n cleanup(2)\n return\n }\n\n // Save credentials using the provided save function\n options.saveFn({\n clientKey,\n secretKey,\n ...(tenantIdParam ? { tenantId: tenantIdParam } : {}),\n tenantName: tenant,\n })\n\n // Cache tenant list if provided\n if (tenantsParam) {\n try {\n const parsed = JSON.parse(tenantsParam)\n if (Array.isArray(parsed)) {\n const valid = parsed.filter(\n (t): t is TenantInfo =>\n typeof t?.id === 'string' && typeof t?.name === 'string',\n )\n if (valid.length > 0) saveTenantList(valid)\n }\n } catch {\n // Ignore malformed tenants param\n }\n }\n\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })\n .end(SUCCESS_HTML)\n\n console.log(pc.green(`\\nLogged in successfully!`))\n console.log(pc.dim(`Tenant: ${tenant}`))\n cleanup(0)\n })\n\n let timeout: ReturnType<typeof setTimeout>\n let completed = false\n\n function cleanup(exitCode = 0) {\n if (completed) return\n completed = true\n clearTimeout(timeout)\n server.close(() => process.exit(exitCode))\n }\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address()\n if (!addr || typeof addr === 'string') {\n reject(new Error('Failed to start local server.'))\n return\n }\n\n timeout = setTimeout(() => {\n console.error(\n pc.red('\\nLogin timed out (3 minutes). Please try again.'),\n )\n cleanup(4)\n }, TIMEOUT_MS)\n\n resolve({ port: addr.port, cleanup })\n })\n\n server.on('error', (err) => {\n reject(err)\n })\n })\n}\n\nexport function registerAuthCommands(program: Command): void {\n program\n .command('login')\n .description('Login via browser and store credentials')\n .action(async () => {\n const state = randomBytes(32).toString('hex')\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n saveCredentials(creds)\n console.log(pc.dim(`Credentials saved to ${getCredentialsPath()}`))\n },\n })\n\n const params = new URLSearchParams({ port: String(port), state })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim('Opening browser for login...'))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n\n program\n .command('logout')\n .description('Remove stored credentials')\n .action(() => {\n const deleted = deleteCredentials()\n if (deleted) {\n console.log(pc.green('Logged out. Credentials removed.'))\n } else {\n console.log(pc.dim('No stored credentials found.'))\n }\n })\n\n program\n .command('whoami')\n .description('Show current authentication status')\n .action(() => {\n // Check local credentials first\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const creds = localCreds || globalCreds\n const isLocal = !!localCreds\n\n if (!creds) {\n console.log(pc.dim('Not logged in. Run \"01 login\" to authenticate.'))\n return\n }\n\n const masked =\n creds.clientKey.length > 8\n ? creds.clientKey.slice(0, 4) + '...' + creds.clientKey.slice(-4)\n : '****'\n\n const scope = isLocal ? pc.cyan(' (local)') : ''\n console.log(`Tenant: ${pc.bold(creds.tenantName)}${scope}`)\n console.log(`Client Key: ${pc.dim(masked)}`)\n console.log(`Stored at: ${pc.dim(creds.storedAt)}`)\n console.log(\n `File: ${pc.dim(isLocal ? getLocalCredentialsPath() : getCredentialsPath())}`,\n )\n })\n\n // -------------------------------------------------------------------------\n // tenant subcommands\n // -------------------------------------------------------------------------\n const tenant = program\n .command('tenant')\n .description('Manage tenant switching')\n\n tenant\n .command('list')\n .description('Show cached tenant list')\n .action(() => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.log(pc.dim('No cached tenants. Run \"01 login\" first.'))\n return\n }\n\n // Determine active tenant\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const activeCreds = localCreds || globalCreds\n const activeId = activeCreds?.tenantId\n const activeName = activeCreds?.tenantName\n\n console.log(pc.bold('Cached tenants:\\n'))\n for (const t of tenants) {\n const active = (activeId ? t.id === activeId : t.name === activeName)\n ? pc.green(' *')\n : ''\n console.log(` ${t.name}${active}`)\n }\n console.log()\n if (activeName) {\n const scope = localCreds ? '(local)' : '(global)'\n console.log(pc.dim(`* active ${scope}`))\n }\n })\n\n tenant\n .command('use <name>')\n .description('Switch to a different tenant via browser')\n .option('--local', 'Save credentials locally in the current project')\n .action(async (name: string, opts: { local?: boolean }) => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.error(pc.red('No cached tenants. Run \"01 login\" first.'))\n process.exit(2)\n }\n\n const match = tenants.find(\n (t) => t.name.toLowerCase() === name.toLowerCase(),\n )\n if (!match) {\n console.error(pc.red(`Tenant \"${name}\" not found in cache.`))\n console.error(\n pc.dim(`Available: ${tenants.map((t) => t.name).join(', ')}`),\n )\n process.exit(3)\n }\n\n const state = randomBytes(32).toString('hex')\n const isLocal = !!opts.local\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n if (isLocal) {\n saveLocalCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getLocalCredentialsPath()}`),\n )\n } else {\n saveCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getCredentialsPath()}`),\n )\n }\n },\n })\n\n const params = new URLSearchParams({\n port: String(port),\n state,\n tenantId: match.id,\n })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim(`Switching to tenant \"${match.name}\"...`))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n}\n","import { Command } from 'commander'\nimport { COLLECTIONS } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\ndeclare const __DEFAULT_API_URL__: string\n\nfunction getApiUrl(): string {\n return (\n process.env.SOFTWARE_API_URL ||\n process.env.NEXT_PUBLIC_SOFTWARE_API_URL ||\n __DEFAULT_API_URL__\n ).replace(/\\/$/, '')\n}\n\nexport function registerSchemaCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const schema = program\n .command('schema')\n .description('Collection schema introspection')\n\n schema\n .command('list')\n .description('List available collections')\n .action(() => {\n printResult(COLLECTIONS, getFormat())\n })\n\n schema\n .command('show <collection>')\n .description('Show collection field schema')\n .action(async (collection: string) => {\n try {\n if (!(COLLECTIONS as readonly string[]).includes(collection)) {\n const normalized = collection.replace(/-/g, '').toLowerCase()\n const suggestions = (COLLECTIONS as readonly string[])\n .filter((c) => {\n const cn = c.replace(/-/g, '').toLowerCase()\n return (\n cn.startsWith(normalized) ||\n normalized.startsWith(cn) ||\n (normalized.length >= 3 && cn.includes(normalized))\n )\n })\n .slice(0, 5)\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 schema list\" for available collections.'\n throw new Error(`Unknown collection \"${collection}\". ${hint}`)\n }\n const client = getClient()\n const { createServerToken } = await import('@01.software/sdk/auth')\n const token = await createServerToken(\n client.clientKey,\n client.secretKey,\n )\n const baseUrl = getApiUrl()\n\n const url = `${baseUrl}/api/tenants/schema/${encodeURIComponent(collection)}`\n const response = await fetch(url, {\n headers: {\n 'X-Client-Key': client.clientKey,\n Authorization: `Bearer ${token}`,\n },\n })\n\n if (!response.ok) {\n const body = await response\n .json()\n .catch(() => ({ error: response.statusText }))\n const err = new Error(\n (body as { error?: string }).error || `HTTP ${response.status}`,\n )\n Object.assign(err, { status: response.status })\n throw err\n }\n\n const result = await response.json()\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { resolve, dirname } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { spawn } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport type { Command } from 'commander'\nimport { resolveClient } from '../lib/client.js'\nimport { exitWithError } from '../lib/output.js'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * Locate the MCP stdio entry point.\n * Resolve order:\n * 1. Monorepo sibling: packages/cli/src/commands → apps/mcp/.xmcp/stdio.js\n * 2. Monorepo sibling (from dist): packages/cli/dist/commands → apps/mcp/.xmcp/stdio.js\n */\nfunction findStdioEntry(): string | null {\n // src/commands or dist/commands → packages/cli → packages → root → apps/mcp\n for (const depth of ['../../../..', '../../..']) {\n const candidate = resolve(__dirname, depth, 'apps/mcp/.xmcp/stdio.js')\n if (existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport function registerMcpCommands(program: Command) {\n program\n .command('mcp')\n .description('Start MCP server over stdio')\n .action(() => {\n // 1. Validate credentials before spawning (exits with code 2 if missing)\n const client = resolveClient(program.opts().apiKey as string | undefined)\n\n // 2. Find stdio.js entry point\n const stdioEntry = findStdioEntry()\n if (!stdioEntry) {\n exitWithError(\n new Error(\n 'MCP server not found. Ensure apps/mcp is built (pnpm --filter mcp build).',\n ),\n )\n }\n\n // 3. Spawn stdio process (inherits env with SOFTWARE_CLIENT_KEY + SOFTWARE_SECRET_KEY)\n const child = spawn(process.execPath, [stdioEntry], {\n env: {\n ...process.env,\n SOFTWARE_CLIENT_KEY: client.clientKey,\n SOFTWARE_SECRET_KEY: client.secretKey,\n },\n stdio: ['inherit', 'inherit', 'inherit'],\n })\n\n child.on('error', (err) => {\n exitWithError(new Error(`Failed to start MCP server: ${err.message}`))\n })\n\n child.on('exit', (code) => {\n process.exit(code ?? 0)\n })\n })\n}\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACDxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,QAAQ;;;ACPf;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY;AACrB,SAAS,eAAe;AAexB,IAAM,WAAW;AACjB,IAAM,YAAY;AAClB,IAAM,eAAe;AAMd,SAAS,qBAA6B;AAC3C,SAAO,KAAK,QAAQ,GAAG,UAAU,SAAS;AAC5C;AAEO,SAAS,kBAA4C;AAC1D,SAAO,oBAAoB,mBAAmB,CAAC;AACjD;AAEO,SAAS,gBACd,OACM;AACN,QAAM,MAAM,KAAK,QAAQ,GAAG,QAAQ;AACpC,MAAI,CAAC,WAAW,GAAG,GAAG;AACpB,cAAU,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,EACjD;AAEA,QAAM,WAAW,mBAAmB;AACpC,QAAM,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["pc","readFileSync","pc","readFileSync","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","pc","pc","resolve","program","COLLECTIONS","program","getClient","getFormat","COLLECTIONS","existsSync","existsSync","program","require"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/lib/client.ts","../src/lib/credentials.ts","../src/lib/output.ts","../src/commands/crud.ts","../src/lib/parse.ts","../src/commands/order.ts","../src/commands/return.ts","../src/commands/cart.ts","../src/commands/stock.ts","../src/commands/transaction.ts","../src/commands/auth.ts","../src/commands/schema.ts","../src/commands/mcp.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { resolveClient } from './lib/client.js'\nimport { exitWithError } from './lib/output.js'\nimport { registerCrudCommands } from './commands/crud.js'\nimport { registerOrderCommands } from './commands/order.js'\nimport { registerReturnCommands } from './commands/return.js'\nimport { registerCartCommands } from './commands/cart.js'\nimport { registerStockCommands } from './commands/stock.js'\nimport { registerTransactionCommands } from './commands/transaction.js'\nimport { registerAuthCommands } from './commands/auth.js'\nimport { registerSchemaCommands } from './commands/schema.js'\nimport { registerMcpCommands } from './commands/mcp.js'\n\nconst require = createRequire(import.meta.url)\nconst { version } = require('../package.json') as { version: string }\n\nprocess.on('unhandledRejection', (err) => {\n exitWithError(err)\n})\n\nconst program = new Command()\n\nprogram\n .name('01')\n .description('CLI for the 01.software platform')\n .version(version)\n .option('--api-key <key>', 'API key (sk01_... or pat01_... token)')\n .option('--format <format>', 'Output format: json, table, or ndjson')\n\nconst getFormat = () =>\n (program.opts().format ?? process.env.OUTPUT_FORMAT ?? 'json') as string\nconst getClient = () =>\n resolveClient(program.opts().apiKey as string | undefined)\n\nregisterCrudCommands(program, getClient, getFormat)\nregisterOrderCommands(program, getClient, getFormat)\nregisterReturnCommands(program, getClient, getFormat)\nregisterCartCommands(program, getClient, getFormat)\nregisterStockCommands(program, getClient, getFormat)\nregisterTransactionCommands(program, getClient, getFormat)\nregisterSchemaCommands(program, getClient, getFormat)\nregisterMcpCommands(program)\nregisterAuthCommands(program)\n\nprogram.parse()\n","import {\n CollectionClient,\n OrderApi,\n CartApi,\n ProductApi,\n} from '@01.software/sdk'\nimport pc from 'picocolors'\nimport { loadCredentials, loadLocalCredentials } from './credentials.js'\n\nexport interface ResolvedClient {\n collections: CollectionClient\n api: OrderApi\n cart: CartApi\n product: ProductApi\n publishableKey: string\n secretKey: string\n}\n\n/**\n * Accepted opaque bearer token prefixes.\n * - `sk01_` = tenant-level API key (created in Console > Settings > API Keys)\n * - `pat01_` = user-level Personal Access Token\n * Legacy hex HMAC secrets from the pre-2026-04 auth system are rejected.\n */\nfunction isValidBearerToken(secret: string): boolean {\n return secret.startsWith('sk01_') || secret.startsWith('pat01_')\n}\n\nlet tenantHeaderInterceptorInstalled = false\n\n/**\n * Install a global fetch interceptor that injects `X-Tenant-Id` for every\n * outgoing request. PAT tokens can belong to users with multiple tenants, so\n * the server needs this header to disambiguate. sk01_ API keys are already\n * tenant-scoped server-side and do not need the header, but it is harmless.\n */\nfunction installTenantHeaderInterceptor(tenantId: string): void {\n if (tenantHeaderInterceptorInstalled) return\n tenantHeaderInterceptorInstalled = true\n\n const originalFetch = globalThis.fetch.bind(globalThis)\n\n globalThis.fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const headers = new Headers(init?.headers)\n if (!headers.has('X-Tenant-Id')) headers.set('X-Tenant-Id', tenantId)\n return originalFetch(input, { ...init, headers })\n }\n}\n\n/**\n * Resolve credentials in priority order:\n * 1. `--api-key <token>` flag (overrides secretKey only; publishableKey still\n * comes from env/credentials)\n * 2. `SOFTWARE_PUBLISHABLE_KEY` + `SOFTWARE_SECRET_KEY` env vars\n * 3. Local project credentials (`./01software/credentials.json`)\n * 4. Global user credentials (`~/.01software/credentials.json`)\n */\nexport function resolveClient(apiKeyFlag?: string): ResolvedClient {\n let publishableKey: string | undefined = process.env.SOFTWARE_PUBLISHABLE_KEY\n let secretKey: string | undefined =\n apiKeyFlag ?? process.env.SOFTWARE_SECRET_KEY\n let tenantId: string | undefined\n\n if (!publishableKey || !secretKey) {\n const local = loadLocalCredentials()\n if (local) {\n publishableKey = publishableKey ?? local.publishableKey\n secretKey = secretKey ?? local.secretKey\n tenantId = local.tenantId\n }\n }\n\n if (!publishableKey || !secretKey) {\n const stored = loadCredentials()\n if (stored) {\n publishableKey = publishableKey ?? stored.publishableKey\n secretKey = secretKey ?? stored.secretKey\n tenantId = tenantId ?? stored.tenantId\n }\n }\n\n if (!publishableKey || !secretKey) {\n console.error(pc.red('Authentication required.'))\n console.error(\n pc.dim(\n 'Run \"01 login\" to authenticate via browser,\\n' +\n 'or pass --api-key <token>,\\n' +\n 'or set SOFTWARE_PUBLISHABLE_KEY and SOFTWARE_SECRET_KEY environment variables.',\n ),\n )\n process.exit(2)\n }\n\n if (!isValidBearerToken(secretKey)) {\n console.error(\n pc.red(\n 'Invalid API key format. Expected sk01_ or pat01_ token.\\n' +\n 'Legacy hex credentials are no longer accepted — run `01 login` to re-authenticate.',\n ),\n )\n process.exit(2)\n }\n\n if (tenantId) installTenantHeaderInterceptor(tenantId)\n\n const apiOpts = { publishableKey, secretKey }\n\n return {\n collections: new CollectionClient(publishableKey, secretKey),\n api: new OrderApi(apiOpts),\n cart: new CartApi(apiOpts),\n product: new ProductApi(apiOpts),\n publishableKey,\n secretKey,\n }\n}\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n unlinkSync,\n appendFileSync,\n} from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nexport interface StoredCredentials {\n publishableKey: string\n /** Bearer token — either secretKey (hex) or PAT (pat01_...) */\n secretKey: string\n tenantId?: string\n tenantName: string\n storedAt: string\n}\n\nexport interface TenantInfo {\n id: string\n name: string\n}\n\nconst DIR_NAME = '.01software'\nconst FILE_NAME = 'credentials.json'\nconst TENANTS_FILE = 'tenants.json'\n\n// ---------------------------------------------------------------------------\n// Global credentials (~/.01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getCredentialsPath(): string {\n return join(homedir(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getCredentialsPath())\n}\n\nexport function saveCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function deleteCredentials(): boolean {\n const filePath = getCredentialsPath()\n if (!existsSync(filePath)) return false\n\n unlinkSync(filePath)\n return true\n}\n\n// ---------------------------------------------------------------------------\n// Local credentials (./01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getLocalCredentialsPath(): string {\n return join(process.cwd(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadLocalCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getLocalCredentialsPath())\n}\n\nexport function saveLocalCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(process.cwd(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getLocalCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n\n // Ensure .01software/ is in .gitignore\n ensureGitignore()\n}\n\n// ---------------------------------------------------------------------------\n// Tenant list cache (~/.01software/tenants.json)\n// ---------------------------------------------------------------------------\n\nexport function saveTenantList(tenants: TenantInfo[]): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n writeFileSync(filePath, JSON.stringify(tenants, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function loadTenantList(): TenantInfo[] | null {\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw)\n if (!Array.isArray(data)) return null\n const valid = data.filter(\n (t): t is TenantInfo =>\n typeof t?.id === 'string' && typeof t?.name === 'string',\n )\n return valid.length > 0 ? valid : null\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction loadCredentialsFrom(filePath: string): StoredCredentials | null {\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw) as StoredCredentials\n if (!data.publishableKey || !data.secretKey) return null\n return data\n } catch {\n return null\n }\n}\n\nfunction ensureGitignore(): void {\n const gitignorePath = join(process.cwd(), '.gitignore')\n const entry = '.01software/'\n\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8')\n if (content.includes(entry)) return\n appendFileSync(gitignorePath, `\\n${entry}\\n`, 'utf-8')\n } else {\n writeFileSync(gitignorePath, `${entry}\\n`, 'utf-8')\n }\n}\n","import pc from 'picocolors'\n\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2))\n}\n\nexport function printTable(data: unknown): void {\n if (Array.isArray(data)) {\n if (data.length === 0) {\n console.log(pc.dim('(empty)'))\n return\n }\n const keys = Object.keys(data[0] as Record<string, unknown>)\n const widths = keys.map((k) =>\n Math.max(\n k.length,\n ...data.map(\n (row) => String((row as Record<string, unknown>)[k] ?? '').length,\n ),\n ),\n )\n\n // Header\n console.log(keys.map((k, i) => k.padEnd(widths[i]!)).join(' '))\n console.log(keys.map((_, i) => '-'.repeat(widths[i]!)).join(' '))\n\n // Rows\n for (const row of data) {\n console.log(\n keys\n .map((k, i) =>\n String((row as Record<string, unknown>)[k] ?? '').padEnd(\n widths[i]!,\n ),\n )\n .join(' '),\n )\n }\n } else if (data && typeof data === 'object') {\n const entries = Object.entries(data as Record<string, unknown>)\n const maxKey = Math.max(...entries.map(([k]) => k.length))\n for (const [key, value] of entries) {\n const display =\n typeof value === 'object' ? JSON.stringify(value) : String(value)\n console.log(`${pc.bold(key.padEnd(maxKey))} ${display}`)\n }\n } else {\n console.log(String(data))\n }\n}\n\nfunction printNdjson(data: unknown): void {\n if (Array.isArray(data)) {\n data.forEach((item) => console.log(JSON.stringify(item)))\n } else if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const { docs, ...meta } = data as {\n docs: unknown[]\n [key: string]: unknown\n }\n ;(docs as unknown[]).forEach((doc) => console.log(JSON.stringify(doc)))\n if (Object.keys(meta).length > 0)\n console.log(JSON.stringify({ _meta: meta }))\n } else {\n console.log(JSON.stringify(data))\n }\n}\n\nexport function printResult(data: unknown, format: string): void {\n if (format === 'ndjson') {\n printNdjson(data)\n } else if (format === 'table') {\n // For find responses with docs array, print the docs as table\n if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const resp = data as {\n docs: unknown[]\n totalDocs: number\n page: number\n totalPages: number\n }\n printTable(resp.docs)\n console.log(\n pc.dim(\n `\\n${resp.totalDocs} total | page ${resp.page}/${resp.totalPages}`,\n ),\n )\n return\n }\n printTable(data)\n } else {\n printJson(data)\n }\n}\n\nexport function getExitCode(error: unknown): number {\n if (!error || typeof error !== 'object') return 1\n const err = error as Record<string, unknown>\n\n // SDK error name\n if (err.name === 'ConfigError') return 2\n if (err.name === 'ValidationError') return 3\n if (err.name === 'NetworkError' || err.name === 'TimeoutError') return 4\n if (err.name === 'GoneError') return 5\n if (err.name === 'UsageLimitError') return 6\n\n // HTTP status fallback\n const s = err.status as number | undefined\n if (s === 401) return 2\n if (s === 400 || s === 422) return 3\n if (s === 408 || s === 503) return 4\n if (s === 404) return 5\n if (s === 429) return 6\n\n return 1\n}\n\nexport function exitWithError(error: unknown): never {\n printError(error)\n process.exit(getExitCode(error))\n}\n\nexport function printError(error: unknown): void {\n if (error && typeof error === 'object' && 'message' in error) {\n const err = error as {\n message: string\n code?: string\n status?: number\n suggestion?: string\n }\n console.error(pc.red(`Error: ${err.message}`))\n if (err.code) console.error(pc.dim(`Code: ${err.code}`))\n if (err.status) console.error(pc.dim(`Status: ${err.status}`))\n if (err.suggestion) console.error(pc.yellow(err.suggestion))\n } else {\n console.error(pc.red(String(error)))\n }\n}\n","import { readFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { Command } from 'commander'\nimport { COLLECTIONS } from '@01.software/sdk'\nimport type { ApiQueryOptions } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson } from '../lib/parse.js'\n\nfunction readFileAsBlob(filePath: string): { blob: Blob; filename: string } {\n const buffer = readFileSync(filePath)\n return { blob: new Blob([buffer]), filename: basename(filePath) }\n}\n\nfunction validateCollection(name: string): string {\n if (!(COLLECTIONS as readonly string[]).includes(name)) {\n const normalized = name.replace(/-/g, '').toLowerCase()\n const suggestions = COLLECTIONS.filter((c) => {\n const cn = c.replace(/-/g, '').toLowerCase()\n return (\n cn.startsWith(normalized) ||\n normalized.startsWith(cn) ||\n (normalized.length >= 3 && cn.includes(normalized))\n )\n }).slice(0, 5)\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 --help\" for available collections.'\n throw new Error(`Unknown collection \"${name}\". ${hint}`)\n }\n return name\n}\n\nfunction parseSelect(input: string): Record<string, boolean> {\n return Object.fromEntries(input.split(',').map((f) => [f.trim(), true]))\n}\n\nexport function registerCrudCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n program\n .command('query <collection>')\n .description('Query documents from a collection')\n .option('--where <json>', 'Filter conditions (JSON)')\n .option('--limit <n>', 'Max results', (v: string) => parseInt(v, 10))\n .option('--page <n>', 'Page number', (v: string) => parseInt(v, 10))\n .option('--sort <field>', 'Sort field (prefix with - for descending)')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.where) options.where = parseJson(opts.where, 'where')\n if (opts.limit) options.limit = opts.limit\n if (opts.page) options.page = opts.page\n if (opts.sort) options.sort = opts.sort\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .find(options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('get <collection> <id>')\n .description('Get a document by ID')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .findById(id, options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('create <collection>')\n .description('Create a new document')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'create',\n collection: col,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .create(data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update <collection> <id>')\n .description('Update a document by ID')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update',\n collection: col,\n id,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .update(id, data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete <collection> <id>')\n .description('Delete a document by ID')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete',\n collection: col,\n id,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .remove(id)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update-many <collection>')\n .description('Update multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .requiredOption('--data <json>', 'Update data (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update-many',\n collection: col,\n where,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .updateMany(where, data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete-many <collection>')\n .description('Delete multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete-many',\n collection: col,\n where,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col as (typeof COLLECTIONS)[number])\n .removeMany(where)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import pc from 'picocolors'\n\nexport function parseJson(\n value: string,\n label: string,\n): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value)\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed)\n ) {\n console.error(pc.red(`--${label} must be a JSON object.`))\n process.exit(3)\n }\n return parsed as Record<string, unknown>\n } catch {\n console.error(pc.red(`Invalid JSON for --${label}: ${value}`))\n process.exit(3)\n }\n}\n\nexport function parseJsonArray(value: string, label: string): unknown[] {\n try {\n const parsed = JSON.parse(value)\n if (!Array.isArray(parsed)) {\n console.error(pc.red(`--${label} must be a JSON array.`))\n process.exit(3)\n }\n return parsed\n } catch {\n console.error(pc.red(`Invalid JSON for --${label}: ${value}`))\n process.exit(3)\n }\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson, parseJsonArray } from '../lib/parse.js'\n\nexport function registerOrderCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const order = program.command('order').description('Order management')\n\n order\n .command('create')\n .description('Create a new order')\n .option('--payment-id <id>', 'Payment ID')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--email <email>', 'Customer email')\n .option('--customer <id>', 'Customer ID')\n .option('--name <name>', 'Customer name')\n .option('--phone <phone>', 'Customer phone')\n .requiredOption('--shipping-address <json>', 'Shipping address (JSON)')\n .requiredOption('--products <json>', 'Order products array (JSON)')\n .requiredOption('--total-amount <n>', 'Total amount', parseFloat)\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const shippingAddress = parseJson(\n opts.shippingAddress,\n 'shipping-address',\n )\n const orderProducts = parseJsonArray(opts.products, 'products')\n const data = {\n paymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot: {\n email: opts.email,\n name: opts.name,\n phone: opts.phone,\n },\n customer: opts.customer,\n shippingAddress,\n orderProducts,\n totalAmount: opts.totalAmount,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.createOrder({\n ...data,\n orderProducts: orderProducts as Parameters<\n typeof client.api.createOrder\n >[0]['orderProducts'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('get <orderNumber>')\n .description('Get an order by order number')\n .action(async (orderNumber: string) => {\n try {\n const client = getClient()\n const result = await client.api.getOrder({ orderNumber })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('update <orderNumber>')\n .description('Update order status')\n .requiredOption('--status <status>', 'New status')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = { orderNumber, status: opts.status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.updateOrder(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('checkout')\n .description('Convert a cart to an order')\n .requiredOption('--cart-id <id>', 'Cart ID')\n .option('--payment-id <id>', 'Payment ID (optional for free orders)')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--customer <json>', 'Customer snapshot (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const customerSnapshot = parseJson(opts.customer, 'customer')\n const data = {\n cartId: opts.cartId,\n paymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order checkout', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.checkout({\n ...data,\n customerSnapshot: customerSnapshot as Parameters<\n typeof client.api.checkout\n >[0]['customerSnapshot'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('fulfill <orderNumber>')\n .description('Create a fulfillment for an order')\n .requiredOption('--items <json>', 'Fulfillment items array (JSON)')\n .option('--carrier <name>', 'Shipping carrier')\n .option('--tracking-number <num>', 'Tracking number')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const items = parseJsonArray(opts.items, 'items')\n const data = {\n orderNumber,\n items,\n carrier: opts.carrier,\n trackingNumber: opts.trackingNumber,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order fulfill', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.createFulfillment({\n ...data,\n items: items as Parameters<\n typeof client.api.createFulfillment\n >[0]['items'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerReturnCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const ret = program.command('return').description('Return management')\n\n ret\n .command('create <orderNumber>')\n .description('Create a return request')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .option(\n '--reason <reason>',\n 'Return reason (change_of_mind, defective, wrong_delivery, damaged, other)',\n )\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const returnProducts = parseJsonArray(opts.products, 'products')\n const data = {\n orderNumber,\n returnProducts,\n refundAmount: opts.refundAmount,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.createReturn({\n ...data,\n returnProducts: returnProducts as Parameters<\n typeof client.api.createReturn\n >[0]['returnProducts'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('update <returnId>')\n .description('Update return status')\n .requiredOption(\n '--status <status>',\n 'New status (processing, approved, rejected, completed)',\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (returnId: string, opts) => {\n try {\n const data = { returnId, status: opts.status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.updateReturn(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('refund <orderNumber>')\n .description('Return with refund')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .requiredOption('--payment-id <id>', 'Payment ID')\n .option('--reason <reason>', 'Return reason')\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--refund-receipt-url <url>', 'Refund receipt URL')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const returnProducts = parseJsonArray(opts.products, 'products')\n const data = {\n orderNumber,\n returnProducts,\n refundAmount: opts.refundAmount,\n paymentId: opts.paymentId,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n refundReceiptUrl: opts.refundReceiptUrl,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return refund', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.returnWithRefund({\n ...data,\n returnProducts: returnProducts as Parameters<\n typeof client.api.returnWithRefund\n >[0]['returnProducts'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerCartCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const cart = program.command('cart').description('Cart management')\n\n cart\n .command('add <cartId>')\n .description('Add an item to cart')\n .requiredOption('--product <id>', 'Product ID')\n .requiredOption('--variant <id>', 'Variant ID')\n .requiredOption('--option <id>', 'Option ID')\n .requiredOption('--quantity <n>', 'Quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartId: string, opts) => {\n try {\n const data = {\n cartId,\n product: opts.product,\n variant: opts.variant,\n option: opts.option,\n quantity: opts.quantity,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart add', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.cart.addItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('update <cartItemId>')\n .description('Update cart item quantity')\n .requiredOption('--quantity <n>', 'New quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n const data = { cartItemId, quantity: opts.quantity }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.cart.updateItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('remove <cartItemId>')\n .description('Remove an item from cart')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'cart remove',\n data: { cartItemId },\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.cart.removeItem({ cartItemId })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerStockCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const stock = program.command('stock').description('Stock management')\n\n stock\n .command('check')\n .description('Check stock availability')\n .requiredOption(\n '--items <json>',\n 'Items to check (JSON array of { optionId, quantity })',\n )\n .action(async (opts) => {\n try {\n const client = getClient()\n const items = parseJsonArray(opts.items, 'items') as Parameters<\n typeof client.product.stockCheck\n >[0]['items']\n const result = await client.product.stockCheck({ items })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerTransactionCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const tx = program\n .command('transaction')\n .description('Transaction management')\n\n tx.command('update')\n .description('Update transaction status')\n .requiredOption('--payment-id <id>', 'Payment ID')\n .requiredOption(\n '--status <status>',\n 'New status (pending, paid, failed, canceled)',\n )\n .requiredOption('--payment-method <method>', 'Payment method')\n .requiredOption('--receipt-url <url>', 'Receipt URL')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = {\n paymentId: opts.paymentId,\n status: opts.status,\n paymentMethod: opts.paymentMethod,\n receiptUrl: opts.receiptUrl,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'transaction update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.api.updateTransaction(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer } from 'node:http'\nimport { execFile, exec } from 'node:child_process'\nimport { platform } from 'node:os'\nimport { URL } from 'node:url'\nimport type { Command } from 'commander'\nimport pc from 'picocolors'\nimport {\n loadCredentials,\n saveCredentials,\n deleteCredentials,\n getCredentialsPath,\n loadLocalCredentials,\n saveLocalCredentials,\n getLocalCredentialsPath,\n loadTenantList,\n saveTenantList,\n type TenantInfo,\n} from '../lib/credentials.js'\n\nconst WEB_URL = process.env.SOFTWARE_WEB_URL || 'https://01.software'\nconst TIMEOUT_MS = 3 * 60 * 1000 // 3 minutes\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\nfunction openBrowser(url: string): void {\n const os = platform()\n\n const onError = () => {\n console.log(\n pc.yellow(\n `Could not open browser automatically. Open this URL manually:\\n${url}`,\n ),\n )\n }\n\n if (os === 'win32') {\n exec(`start \"\" \"${url}\"`, (err) => {\n if (err) onError()\n })\n } else {\n const cmd = os === 'darwin' ? 'open' : 'xdg-open'\n execFile(cmd, [url], (err) => {\n if (err) onError()\n })\n }\n}\n\nconst PAGE_STYLE = `*{margin:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;background:#fff;color:#252525}\n@media(prefers-color-scheme:dark){body{background:#252525;color:#f5f5f5}}\n.card{text-align:center;padding:2rem 2.5rem;border-radius:10px;max-width:380px;width:100%}\n.icon{width:40px;height:40px;margin:0 auto 1rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.25rem}\n.icon.ok{background:rgba(0,0,0,.05);color:#252525}\n.icon.err{background:rgba(220,38,38,.08);color:#dc2626}\n@media(prefers-color-scheme:dark){.icon.ok{background:rgba(255,255,255,.08);color:#f5f5f5}}\nh1{font-size:.875rem;font-weight:600;margin-bottom:.375rem}\np{font-size:.75rem;color:#737373;line-height:1.5}`\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon ok\">\\u2713</div><h1>Authenticated</h1><p>You can close this tab and return to the terminal.</p></div></body></html>`\n\nconst ERROR_HTML = (msg: string) => `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login Error</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon err\">!</div><h1>Authentication failed</h1><p>${escapeHtml(msg)}</p></div></body></html>`\n\n/**\n * Start a local HTTP server that receives the OAuth-like callback from the browser.\n * Returns a promise that resolves with the received credentials, or rejects on error/timeout.\n */\nfunction startAuthServer(options: {\n state: string\n saveFn: (creds: {\n publishableKey: string\n secretKey: string\n tenantId?: string\n tenantName: string\n }) => void\n}): Promise<{ port: number; cleanup: (exitCode?: number) => void }> {\n return new Promise((resolve, reject) => {\n const corsHeaders: Record<string, string> = {\n 'Access-Control-Allow-Origin': WEB_URL,\n 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Max-Age': '600',\n Vary: 'Origin',\n }\n\n const finalize = (creds: {\n publishableKey: string\n secretKey: string\n tenant: string\n tenantId?: string\n tenants?: unknown\n }) => {\n options.saveFn({\n publishableKey: creds.publishableKey,\n secretKey: creds.secretKey,\n ...(creds.tenantId ? { tenantId: creds.tenantId } : {}),\n tenantName: creds.tenant,\n })\n\n if (Array.isArray(creds.tenants)) {\n const valid = creds.tenants.filter(\n (t): t is TenantInfo =>\n typeof (t as TenantInfo)?.id === 'string' &&\n typeof (t as TenantInfo)?.name === 'string',\n )\n if (valid.length > 0) saveTenantList(valid)\n }\n\n console.log(pc.green(`\\nLogged in successfully!`))\n console.log(pc.dim(`Tenant: ${creds.tenant}`))\n }\n\n const server = createServer((req, res) => {\n if (!req.url) {\n res.writeHead(400, corsHeaders).end()\n return\n }\n\n const url = new URL(req.url, `http://localhost`)\n\n if (url.pathname !== '/callback') {\n res.writeHead(404, corsHeaders).end()\n return\n }\n\n // CORS preflight\n if (req.method === 'OPTIONS') {\n res.writeHead(200, corsHeaders).end()\n return\n }\n\n // POST /callback — JSON body (new path)\n if (req.method === 'POST') {\n // Validate Origin to prevent cross-origin credential delivery\n const origin = req.headers.origin\n if (!origin || origin !== WEB_URL) {\n res\n .writeHead(403, { ...corsHeaders, 'Content-Type': 'application/json' })\n .end(JSON.stringify({ error: 'Forbidden: invalid origin' }))\n return\n }\n let body = ''\n req.on('data', (chunk) => {\n body += chunk\n if (body.length > 64 * 1024) {\n res\n .writeHead(413, { ...corsHeaders, 'Content-Type': 'application/json' })\n .end(JSON.stringify({ error: 'Payload too large' }))\n req.destroy()\n }\n })\n req.on('end', () => {\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(body)\n } catch {\n res\n .writeHead(400, { ...corsHeaders, 'Content-Type': 'application/json' })\n .end(JSON.stringify({ error: 'Invalid JSON' }))\n return\n }\n\n const publishableKey = parsed.publishableKey\n const secretKey = parsed.secretKey\n const tenant = parsed.tenant\n const tenantIdParam = parsed.tenantId\n const tenantsParam = parsed.tenants\n const receivedState = parsed.state\n\n if (receivedState !== options.state) {\n res\n .writeHead(403, { ...corsHeaders, 'Content-Type': 'application/json' })\n .end(JSON.stringify({ error: 'State mismatch' }))\n console.error(pc.red('Login failed: state mismatch.'))\n cleanup(2)\n return\n }\n\n if (\n typeof publishableKey !== 'string' ||\n typeof secretKey !== 'string' ||\n typeof tenant !== 'string'\n ) {\n res\n .writeHead(400, { ...corsHeaders, 'Content-Type': 'application/json' })\n .end(JSON.stringify({ error: 'Missing credentials' }))\n console.error(pc.red('Login failed: missing credentials.'))\n cleanup(2)\n return\n }\n\n finalize({\n publishableKey,\n secretKey,\n tenant,\n tenantId: typeof tenantIdParam === 'string' ? tenantIdParam : undefined,\n tenants: tenantsParam,\n })\n\n res\n .writeHead(200, { ...corsHeaders, 'Content-Type': 'application/json' })\n .end(JSON.stringify({ success: true }))\n\n cleanup(0)\n })\n return\n }\n\n // GET /callback — error display only\n const error = url.searchParams.get('error')\n if (error) {\n res\n .writeHead(200, { ...corsHeaders, 'Content-Type': 'text/html; charset=utf-8' })\n .end(ERROR_HTML(error))\n console.error(pc.red(`Login failed: ${error}`))\n cleanup(2)\n return\n }\n\n res\n .writeHead(200, { ...corsHeaders, 'Content-Type': 'text/html; charset=utf-8' })\n .end(SUCCESS_HTML)\n })\n\n let timeout: ReturnType<typeof setTimeout>\n let completed = false\n\n function cleanup(exitCode = 0) {\n if (completed) return\n completed = true\n clearTimeout(timeout)\n server.close(() => process.exit(exitCode))\n }\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address()\n if (!addr || typeof addr === 'string') {\n reject(new Error('Failed to start local server.'))\n return\n }\n\n timeout = setTimeout(() => {\n console.error(\n pc.red('\\nLogin timed out (3 minutes). Please try again.'),\n )\n cleanup(4)\n }, TIMEOUT_MS)\n\n resolve({ port: addr.port, cleanup })\n })\n\n server.on('error', (err) => {\n reject(err)\n })\n })\n}\n\nexport function registerAuthCommands(program: Command): void {\n program\n .command('login')\n .description('Login via browser and store credentials')\n .action(async () => {\n const state = randomBytes(32).toString('hex')\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n saveCredentials(creds)\n console.log(pc.dim(`Credentials saved to ${getCredentialsPath()}`))\n },\n })\n\n const params = new URLSearchParams({ port: String(port), state })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim('Opening browser for login...'))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n\n program\n .command('logout')\n .description('Remove stored credentials')\n .action(() => {\n const deleted = deleteCredentials()\n if (deleted) {\n console.log(pc.green('Logged out. Credentials removed.'))\n } else {\n console.log(pc.dim('No stored credentials found.'))\n }\n })\n\n program\n .command('whoami')\n .description('Show current authentication status')\n .action(() => {\n // Check local credentials first\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const creds = localCreds || globalCreds\n const isLocal = !!localCreds\n\n if (!creds) {\n console.log(pc.dim('Not logged in. Run \"01 login\" to authenticate.'))\n return\n }\n\n const masked =\n creds.publishableKey.length > 8\n ? creds.publishableKey.slice(0, 4) + '...' + creds.publishableKey.slice(-4)\n : '****'\n\n const scope = isLocal ? pc.cyan(' (local)') : ''\n console.log(`Tenant: ${pc.bold(creds.tenantName)}${scope}`)\n console.log(`Publishable Key: ${pc.dim(masked)}`)\n console.log(`Stored at: ${pc.dim(creds.storedAt)}`)\n console.log(\n `File: ${pc.dim(isLocal ? getLocalCredentialsPath() : getCredentialsPath())}`,\n )\n })\n\n // -------------------------------------------------------------------------\n // tenant subcommands\n // -------------------------------------------------------------------------\n const tenant = program\n .command('tenant')\n .description('Manage tenant switching')\n\n tenant\n .command('list')\n .description('Show cached tenant list')\n .action(() => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.log(pc.dim('No cached tenants. Run \"01 login\" first.'))\n return\n }\n\n // Determine active tenant\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const activeCreds = localCreds || globalCreds\n const activeId = activeCreds?.tenantId\n const activeName = activeCreds?.tenantName\n\n console.log(pc.bold('Cached tenants:\\n'))\n for (const t of tenants) {\n const active = (activeId ? t.id === activeId : t.name === activeName)\n ? pc.green(' *')\n : ''\n console.log(` ${t.name}${active}`)\n }\n console.log()\n if (activeName) {\n const scope = localCreds ? '(local)' : '(global)'\n console.log(pc.dim(`* active ${scope}`))\n }\n })\n\n tenant\n .command('use <name>')\n .description('Switch to a different tenant via browser')\n .option('--local', 'Save credentials locally in the current project')\n .action(async (name: string, opts: { local?: boolean }) => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.error(pc.red('No cached tenants. Run \"01 login\" first.'))\n process.exit(2)\n }\n\n const match = tenants.find(\n (t) => t.name.toLowerCase() === name.toLowerCase(),\n )\n if (!match) {\n console.error(pc.red(`Tenant \"${name}\" not found in cache.`))\n console.error(\n pc.dim(`Available: ${tenants.map((t) => t.name).join(', ')}`),\n )\n process.exit(3)\n }\n\n const state = randomBytes(32).toString('hex')\n const isLocal = !!opts.local\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n if (isLocal) {\n saveLocalCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getLocalCredentialsPath()}`),\n )\n } else {\n saveCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getCredentialsPath()}`),\n )\n }\n },\n })\n\n const params = new URLSearchParams({\n port: String(port),\n state,\n tenantId: match.id,\n })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim(`Switching to tenant \"${match.name}\"...`))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n}\n","import { Command } from 'commander'\nimport { COLLECTIONS } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\ndeclare const __DEFAULT_API_URL__: string\n\nfunction getApiUrl(): string {\n return (\n process.env.SOFTWARE_API_URL ||\n process.env.NEXT_PUBLIC_SOFTWARE_API_URL ||\n __DEFAULT_API_URL__\n ).replace(/\\/$/, '')\n}\n\nexport function registerSchemaCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const schema = program\n .command('schema')\n .description('Collection schema introspection')\n\n schema\n .command('list')\n .description('List available collections')\n .action(() => {\n printResult(COLLECTIONS, getFormat())\n })\n\n schema\n .command('show <collection>')\n .description('Show collection field schema')\n .action(async (collection: string) => {\n try {\n if (!(COLLECTIONS as readonly string[]).includes(collection)) {\n const normalized = collection.replace(/-/g, '').toLowerCase()\n const suggestions = (COLLECTIONS as readonly string[])\n .filter((c) => {\n const cn = c.replace(/-/g, '').toLowerCase()\n return (\n cn.startsWith(normalized) ||\n normalized.startsWith(cn) ||\n (normalized.length >= 3 && cn.includes(normalized))\n )\n })\n .slice(0, 5)\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 schema list\" for available collections.'\n throw new Error(`Unknown collection \"${collection}\". ${hint}`)\n }\n const client = getClient()\n const baseUrl = getApiUrl()\n\n const url = `${baseUrl}/api/tenants/schema/${encodeURIComponent(collection)}`\n const response = await fetch(url, {\n headers: {\n 'X-Publishable-Key': client.publishableKey,\n Authorization: `Bearer ${client.secretKey}`,\n },\n })\n\n if (!response.ok) {\n const body = await response\n .json()\n .catch(() => ({ error: response.statusText }))\n const err = new Error(\n (body as { error?: string }).error || `HTTP ${response.status}`,\n )\n Object.assign(err, { status: response.status })\n throw err\n }\n\n const result = await response.json()\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { resolve, dirname } from 'node:path'\nimport { existsSync } from 'node:fs'\nimport { spawn } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport type { Command } from 'commander'\nimport { resolveClient } from '../lib/client.js'\nimport { exitWithError } from '../lib/output.js'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * Locate the MCP stdio entry point.\n * Resolve order:\n * 1. Monorepo sibling: packages/cli/src/commands → apps/mcp/.xmcp/stdio.js\n * 2. Monorepo sibling (from dist): packages/cli/dist/commands → apps/mcp/.xmcp/stdio.js\n */\nfunction findStdioEntry(): string | null {\n // src/commands or dist/commands → packages/cli → packages → root → apps/mcp\n for (const depth of ['../../../..', '../../..']) {\n const candidate = resolve(__dirname, depth, 'apps/mcp/.xmcp/stdio.js')\n if (existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport function registerMcpCommands(program: Command) {\n program\n .command('mcp')\n .description('Start MCP server over stdio')\n .action(() => {\n // 1. Validate credentials before spawning (exits with code 2 if missing)\n const client = resolveClient(program.opts().apiKey as string | undefined)\n\n // 2. Find stdio.js entry point\n const stdioEntry = findStdioEntry()\n if (!stdioEntry) {\n exitWithError(\n new Error(\n 'MCP server not found. Ensure apps/mcp is built (pnpm --filter mcp build).',\n ),\n )\n }\n\n // 3. Spawn stdio process (inherits env with SOFTWARE_PUBLISHABLE_KEY + SOFTWARE_SECRET_KEY)\n const child = spawn(process.execPath, [stdioEntry], {\n env: {\n ...process.env,\n SOFTWARE_PUBLISHABLE_KEY: client.publishableKey,\n SOFTWARE_SECRET_KEY: client.secretKey,\n },\n stdio: ['inherit', 'inherit', 'inherit'],\n })\n\n child.on('error', (err) => {\n exitWithError(new Error(`Failed to start MCP server: ${err.message}`))\n })\n\n child.on('exit', (code) => {\n process.exit(code ?? 0)\n })\n })\n}\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACDxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,QAAQ;;;ACNf;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY;AACrB,SAAS,eAAe;AAgBxB,IAAM,WAAW;AACjB,IAAM,YAAY;AAClB,IAAM,eAAe;AAMd,SAAS,qBAA6B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,IAAMC,WAAU,cAAc,YAAY,GAAG;AAC7C,IAAM,EAAE,QAAQ,IAAIA,SAAQ,iBAAiB;AAE7C,QAAQ,GAAG,sBAAsB,CAAC,QAAQ;AACxC,gBAAc,GAAG;AACnB,CAAC;AAED,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,IAAI,EACT,YAAY,kCAAkC,EAC9C,QAAQ,OAAO,EACf,OAAO,mBAAmB,uCAAuC,EACjE,OAAO,qBAAqB,uCAAuC;AAEtE,IAAM,YAAY,MACf,QAAQ,KAAK,EAAE,UAAU,QAAQ,IAAI,iBAAiB;AACzD,IAAM,YAAY,MAChB,cAAc,QAAQ,KAAK,EAAE,MAA4B;AAE3D,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,uBAAuB,SAAS,WAAW,SAAS;AACpD,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,4BAA4B,SAAS,WAAW,SAAS;AACzD,uBAAuB,SAAS,WAAW,SAAS;AACpD,oBAAoB,OAAO;AAC3B,qBAAqB,OAAO;AAE5B,QAAQ,MAAM;","names":["pc","readFileSync","pc","readFileSync","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","pc","pc","resolve","program","COLLECTIONS","program","getClient","getFormat","COLLECTIONS","existsSync","existsSync","program","require"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@01.software/cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "CLI tool for 01.software platform",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,9 +15,10 @@
15
15
  "dependencies": {
16
16
  "commander": "^14.0.3",
17
17
  "picocolors": "^1.1.1",
18
- "@01.software/sdk": "0.4.0"
18
+ "@01.software/sdk": "0.9.0"
19
19
  },
20
20
  "devDependencies": {
21
+ "@types/node": "^22.0.0",
21
22
  "tsup": "^8.5.0",
22
23
  "typescript": "^5.9.3",
23
24
  "vitest": "3.2.3"
@@ -29,13 +30,7 @@
29
30
  "build": "tsup",
30
31
  "dev": "tsup --watch",
31
32
  "check-types": "tsc --noEmit",
32
- "version:dev": "node ../../scripts/update-version.js",
33
- "publish:dev": "pnpm run version:dev && pnpm publish --no-git-checks --access public --tag dev",
34
- "publish:local": "pnpm run version:dev && DEFAULT_API_URL=http://localhost:3000 pnpm publish --no-git-checks --access public --tag local",
35
- "version:patch": "pnpm version patch --no-git-tag-version",
36
- "version:minor": "pnpm version minor --no-git-tag-version",
37
- "version:major": "pnpm version major --no-git-tag-version",
38
- "publish:prod": "pnpm publish --access public",
33
+ "release": "node ../../scripts/publish.js",
39
34
  "test": "vitest run"
40
35
  }
41
36
  }