@ptkl/toolkit 1.4.0 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -121,7 +121,7 @@ Default scope is a least-privilege toolkit preset (`src/lib/oauth/ScopePreset.ts
121
121
 
122
122
  Access tokens (15 min) refresh transparently when a command starts, serialized across processes by a per-profile lock in `~/.ptkl` (the rotated refresh token is saved); long-running commands such as watch modes refresh only at start. If the session expired or was revoked you are asked to log in again. `profile inspect` masks tokens.
123
123
 
124
- Not available with OAuth profiles (routes OAuth does not admit; the CLI says so on a 403): workflow, sandbox, kortex, integration(s), satellite, billing, logs, forge, project administration, and user and role changes unless you `--add-scope "edit base_users"`. Use a `--legacy` profile for these.
124
+ Not available with OAuth profiles (routes OAuth does not admit; the CLI says so on a 403): workflow, sandbox, kortex, integration(s), satellite, logs, forge, project administration, and user and role changes unless you `--add-scope "edit base_users"`. Use a `--legacy` profile for these.
125
125
 
126
126
  ## Using the --profile Flag
127
127
 
@@ -0,0 +1,52 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ const calls = {};
3
+ const client = {
4
+ get: vi.fn(), post: vi.fn(), put: vi.fn(),
5
+ };
6
+ const appApi = {
7
+ client,
8
+ download: vi.fn(async (ref, version) => { calls.download = [ref, version]; return {}; }),
9
+ updateSettings: vi.fn(async (v, ref) => ({ v, ref })),
10
+ };
11
+ vi.mock('@ptkl/sdk', () => ({ Platform: class {
12
+ app() { return appApi; }
13
+ } }));
14
+ vi.mock('../../lib/util.js', () => ({
15
+ default: {
16
+ getCurrentProfile: () => ({ token: 't', host: 'h', name: 'p' }),
17
+ getClientForProfile: () => ({ app: () => appApi }),
18
+ },
19
+ }));
20
+ vi.mock('vite', () => ({ build: vi.fn(), createServer: vi.fn() }));
21
+ vi.mock('../../playground.js', () => ({ default: class {
22
+ } }));
23
+ import apps from '../apps.js';
24
+ describe('apps', () => {
25
+ beforeEach(() => { vi.clearAllMocks(); });
26
+ it('download passes (ref, version) in SDK order', async () => {
27
+ await apps.download({ apptype: 'app', version: '1.2.3', ref: 'my-app', output: '' });
28
+ expect(appApi.download).toHaveBeenCalledWith('my-app', '1.2.3');
29
+ });
30
+ it('remove-version GETs settings then PUTs the filtered list', async () => {
31
+ client.get.mockResolvedValue({ data: { public_version: '2', settings: [{ version: '1' }, { version: '2' }, { version: '3' }] } });
32
+ await apps.removeVersion({ version: '3', ref: 'r' });
33
+ expect(client.get).toHaveBeenCalledWith('/v3/system/gateway/app-service/app/r/settings');
34
+ expect(appApi.updateSettings).toHaveBeenCalledWith({ settings: [{ version: '1' }, { version: '2' }] }, 'r');
35
+ });
36
+ it('remove-version refuses the public version', async () => {
37
+ client.get.mockResolvedValue({ data: { public_version: '2', settings: [] } });
38
+ await expect(apps.removeVersion({ version: '2', ref: 'r' })).rejects.toThrow(/public version/);
39
+ expect(appApi.updateSettings).not.toHaveBeenCalled();
40
+ });
41
+ it('bundle upload posts to the platform app upload route', async () => {
42
+ const { default: Cmd } = await import('../apps.js');
43
+ client.post.mockResolvedValue({});
44
+ await Cmd.constructor.postArchive(appApi, 'app', Buffer.from('x'));
45
+ expect(client.post.mock.calls[0][0]).toBe('/v3/system/gateway/app-service/app/upload');
46
+ });
47
+ it('public-app is refused under an OAuth profile', () => {
48
+ const cls = apps.constructor;
49
+ expect(() => cls.assertAllowed('public-app', { auth: 'oauth', client_id: 'x', refresh_token: 'r' })).toThrow(/OAuth/);
50
+ expect(() => cls.assertAllowed('app', { auth: 'oauth' })).not.toThrow();
51
+ });
52
+ });
@@ -7,7 +7,8 @@ import { Writable } from "stream";
7
7
  import { writeFileSync } from "fs";
8
8
  import Util from "../lib/util.js";
9
9
  import Playground from "../playground.js";
10
- import { join } from 'path';
10
+ import { join, resolve } from 'path';
11
+ import OAuthSession from "../lib/oauth/OAuthSession.js";
11
12
  /**
12
13
  * Deprecation notice: Apps as such will be deprecated in favor for Protokol Forge and this will be removed in the future.
13
14
  */
@@ -71,11 +72,36 @@ class AppsCommand {
71
72
  const { apptype, version, ref, output } = options;
72
73
  const profile = util.getCurrentProfile();
73
74
  const client = new Api({ token: profile.token, host: profile.host }).app(apptype);
74
- return await client.download(version, ref, output);
75
+ AppsCommand.assertAllowed(apptype, profile);
76
+ const res = await client.download(ref, version);
77
+ if (output && res?.data) {
78
+ const file = resolve(output, `${ref}-${version}.tar.gz`);
79
+ writeFileSync(file, Buffer.from(res.data));
80
+ console.log(`Downloaded to ${file}`);
81
+ }
82
+ return res;
83
+ }
84
+ /** `public-app` routes are deprecated and denied to OAuth tokens. */
85
+ static assertAllowed(apptype, profile) {
86
+ if (apptype === "public-app" && OAuthSession.isOAuth(profile)) {
87
+ throw new Error("public-app routes are deprecated and not available to OAuth profiles. Use an API-user profile (`ptkl profile new --legacy`).");
88
+ }
89
+ }
90
+ /** POST a tar.gz to the app-service upload route (shared by `upload` and `bundle -u`). */
91
+ static async postArchive(api, apptype, buffer, build) {
92
+ const formData = new FormData();
93
+ formData.append('app', new Blob([buffer], { type: "application/gzip" }), "app.tar.gz");
94
+ if (build)
95
+ formData.append('build', 'true');
96
+ return await api.client.post(`/v3/system/gateway/app-service/${apptype}/upload`, formData, {
97
+ timeout: 60000,
98
+ headers: { 'Content-Type': 'multipart/form-data' }
99
+ });
75
100
  }
76
101
  async upload(options) {
77
102
  const { apptype, directory, build } = options;
78
103
  const profile = util.getCurrentProfile();
104
+ AppsCommand.assertAllowed(apptype, profile);
79
105
  const api = new Api({ token: profile.token, host: profile.host }).app(apptype);
80
106
  try {
81
107
  let buffer = Buffer.alloc(0);
@@ -93,19 +119,7 @@ class AppsCommand {
93
119
  .on('error', reject);
94
120
  });
95
121
  console.log('Archive created successfully');
96
- // Create FormData with buffer
97
- const formData = new FormData();
98
- const blob = new Blob([buffer], { type: 'application/gzip' });
99
- formData.append('app', blob, 'app.tar.gz');
100
- if (build) {
101
- formData.append('build', 'true');
102
- }
103
- return await api.client.post(`/v3/system/gateway/app-service/${apptype}/upload`, formData, {
104
- timeout: 60000,
105
- headers: {
106
- 'Content-Type': 'multipart/form-data'
107
- }
108
- });
122
+ return await AppsCommand.postArchive(api, apptype, buffer, build);
109
123
  }
110
124
  catch (error) {
111
125
  throw error;
@@ -200,17 +214,20 @@ class AppsCommand {
200
214
  callback();
201
215
  },
202
216
  });
203
- c({ gzip: true, cwd: distPath }, ['.']).pipe(bufferStream).on('finish', () => {
204
- const buffer = Buffer.concat(chunks);
205
- client.app().bundleUpload(buffer).then(() => {
206
- console.log('Bundle uploaded successfully');
217
+ await new Promise((done) => {
218
+ c({ gzip: true, cwd: distPath }, ['.']).pipe(bufferStream).on('finish', () => {
219
+ AppsCommand.postArchive(client.app("app"), "app", Buffer.concat(chunks)).then(() => {
220
+ console.log('Bundle uploaded successfully');
221
+ })
222
+ .catch((error) => {
223
+ console.error('Bundle error:', error.response?.data?.message ?? error.message);
224
+ })
225
+ .finally(done);
207
226
  })
208
- .catch((error) => {
209
- console.error('Bundle error:', error.response.data.message);
227
+ .on('error', (error) => {
228
+ console.error('Error creating the archive:', error.message);
229
+ done();
210
230
  });
211
- })
212
- .on('error', (error) => {
213
- console.error('Error creating the archive:', error.message);
214
231
  });
215
232
  }
216
233
  else {
@@ -233,16 +250,15 @@ class AppsCommand {
233
250
  }
234
251
  async removeVersion(options) {
235
252
  const { version, ref } = options;
236
- const profile = util.getClientForProfile();
237
- const client = profile.app();
238
- const { data } = await client.getApp(ref);
253
+ const api = util.getClientForProfile().app("app");
254
+ const url = `/v3/system/gateway/app-service/app/${ref}/settings`;
255
+ const res = await api.client.get(url);
256
+ const data = res.data?.data ?? res.data;
239
257
  if (data.public_version === version) {
240
258
  throw new Error("Cannot remove public version");
241
259
  }
242
- const settings = data.settings.filter((s) => s.version !== version);
243
- return await client.updateSettings({
244
- 'settings': settings
245
- }, ref);
260
+ const settings = (data.settings ?? []).filter((s) => s.version !== version);
261
+ return await api.updateSettings({ settings }, ref);
246
262
  }
247
263
  }
248
264
  export default new AppsCommand();
@@ -279,7 +279,7 @@ class ForgeCommand {
279
279
  // `services`/`variables`/`run` are wrapped named methods on the v0.10 `Forge` client;
280
280
  // `domains` has no named methods yet, so it goes through the client's underlying
281
281
  // authenticated AxiosInstance (`.client`, a public property on every SDK client) — the same
282
- // stopgap pattern used by `ptkl functions create` / `ptkl project billing-modes`.
282
+ // stopgap pattern used by `ptkl functions create`.
283
283
  .addCommand(registerCommand(new Command("services")
284
284
  .description("List services declared by a Forge app")
285
285
  .argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref) => {
@@ -9,8 +9,7 @@ import { registerCommand, withProfile } from "../lib/scaffold.js";
9
9
  * supports POST for creation, but the v0.10 `Functions` client does not yet wrap that in a named
10
10
  * method — `create` goes through the same authenticated client instance's underlying `.client`
11
11
  * (a public AxiosInstance, see @ptkl/sdk/beta BaseClient) rather than a named method, the same
12
- * stopgap pattern used by `ptkl project billing-modes`/`auto-topup`, pending a follow-up SDK WP
13
- * to give `Functions` a `create()` method.
12
+ * stopgap pattern, pending a follow-up SDK WP to give `Functions` a `create()` method.
14
13
  *
15
14
  * Return-shape contract: every subcommand here resolves to the *payload*, never a raw
16
15
  * AxiosResponse. `Functions.run()` already unwraps `.data` in the SDK; `list`/`get`/`update`/
@@ -20,7 +20,6 @@ import config from "./config.js";
20
20
  import ratchet from "./ratchet.js";
21
21
  import thunder from "./thunder.js";
22
22
  import sandbox from "./sandbox.js";
23
- import billing from "./billing.js";
24
23
  import integration from "./integration.js";
25
24
  import satellite from "./satellite.js";
26
25
  export const commands = [
@@ -42,7 +41,6 @@ export const commands = [
42
41
  ratchet.register(),
43
42
  thunder.register(),
44
43
  sandbox.register(),
45
- billing.register(),
46
44
  integration.register(),
47
45
  satellite.register(),
48
46
  kortex.register(),
@@ -74,7 +74,7 @@ class KortexCommand {
74
74
  .requiredOption('--amount <amount>', 'Amount of credits to add')
75
75
  .option('-r, --reason <reason>', 'Reason for the top-up')).action(withProfile(async (profile, opts) => {
76
76
  // No dedicated `topUp` method exists on the SDK `Kortex` client yet — reuse its
77
- // authenticated axios instance (same pattern as project.ts's billing-modes/auto-topup)
77
+ // authenticated axios instance
78
78
  // instead of hand-rolling a raw axios call.
79
79
  const client = kortexClient(profile);
80
80
  const res = await client.client.post(`/luma/kortex/v1/user-access/${opts.uuid}/top-up`, {
@@ -2,12 +2,7 @@ import { Command } from "commander";
2
2
  import * as sdk from "../lib/sdk.js";
3
3
  import { registerCommand, withProfile } from "../lib/scaffold.js";
4
4
  /** `ptkl project` — project/workspace/invite/user control-plane (RFC §6, "Project control-plane").
5
- * Maps 1:1 onto the SDK `Project` client (@ptkl/sdk/beta) except `billing-modes` and `auto-topup`,
6
- * which the platform exposes (platform-api/internal/project/controllers/{billing_modes,edit_auto_topup_settings}.go)
7
- * but the v0.10 `Project` client does not yet wrap in typed methods. Those two subcommands go
8
- * through the same authenticated client instance's underlying `.client` (a public AxiosInstance,
9
- * see @ptkl/sdk/beta BaseClient) rather than a named method — a stopgap for a follow-up SDK WP to
10
- * give `Project` `getBillingModes()/updateBillingModes()/updateAutoTopupSettings()` methods. */
5
+ * Maps 1:1 onto the SDK `Project` client (@ptkl/sdk/beta). */
11
6
  function parseJSON(label, raw) {
12
7
  try {
13
8
  return JSON.parse(raw);
@@ -67,32 +62,6 @@ class ProjectCommand {
67
62
  return res.data;
68
63
  })));
69
64
  cmd.addCommand(this.registerUsers());
70
- cmd.addCommand(registerCommand(new Command("billing-modes")
71
- .description("Get or update the project's per-service usage billing mode overrides")
72
- .option("-s, --set <json>", "Usage billing modes to set, as a JSON object string (e.g. '{\"kortex\":\"credits\"}'); omit to read the current modes")).action(withProfile(async (profile, opts) => {
73
- const client = sdk.project(profile);
74
- if (opts.set) {
75
- const usage_billing_modes = parseJSON("--set", opts.set);
76
- const res = await client.client.put("/v1/project/billing-modes", { usage_billing_modes });
77
- return res.data;
78
- }
79
- const res = await client.client.get("/v1/project/billing-modes");
80
- return res.data;
81
- })));
82
- cmd.addCommand(registerCommand(new Command("auto-topup")
83
- .description("Configure automatic balance top-up for the current project")
84
- .requiredOption("--enabled <enabled>", "Enable or disable auto top-up: true | false")
85
- .option("--threshold <threshold>", "Balance threshold (in cents) that triggers a top-up", "0")
86
- .option("--amount <amount>", "Amount (in cents) to top up when triggered", "0")).action(withProfile(async (profile, opts) => {
87
- const client = sdk.project(profile);
88
- const body = {
89
- auto_topup_enabled: opts.enabled === "true",
90
- auto_topup_threshold: Number(opts.threshold),
91
- auto_topup_amount: Number(opts.amount),
92
- };
93
- const res = await client.client.put("/v1/project/auto-topup-settings", body);
94
- return res.data;
95
- })));
96
65
  return cmd;
97
66
  }
98
67
  registerWorkspace() {
@@ -13,8 +13,7 @@ import { registerCommand, withProfile } from "../lib/scaffold.js";
13
13
  * (also `account`/`app`/`integration`) redeemed via `POST /v1/project/codes/{code}/redeem` and
14
14
  * listed via `GET /v1/project/codes/redeemed` (internal/project/controllers/code_redeem.go,
15
15
  * internal/project/domain/code/service.go). The v0.10 `Project` client has no typed method for
16
- * either route yet, so — same stopgap already used in `project.ts` for `billing-modes`/
17
- * `auto-topup` — these two subcommands go through the authenticated client instance's public
16
+ * either route yet, so these two subcommands go through the authenticated client instance's public
18
17
  * `.client` (an AxiosInstance, see @ptkl/sdk/beta BaseClient) rather than a named method, pending
19
18
  * a follow-up SDK WP to give `Project` `redeemCode()`/`listRedeemedCodes()`. */
20
19
  function parseJSON(label, raw) {
@@ -90,7 +90,10 @@ export default class OAuthSession {
90
90
  return undefined;
91
91
  const challenge = String(res.headers?.["www-authenticate"] ?? "");
92
92
  if (res.status === 403 && (/insufficient_scope/.test(challenge) || OAuthSession.isOAuth(profile))) {
93
- return "This command isn't available to OAuth tokens (insufficient scope). Use a profile created with `ptkl profile new`.";
93
+ const named = /scope="([^"]+)"/.exec(challenge)?.[1] ?? res.data?.required_scope ?? res.data?.scope;
94
+ const missing = typeof named === "string" && named.trim() ? named.trim() : undefined;
95
+ return `This profile's token lacks ${missing ? `the permission "${missing}"` : "a permission this command needs"}. `
96
+ + `Log in again with \`ptkl profile new --add-scope "${missing ?? "<permission>"}"\`, or use an API-user profile (\`--legacy\`) for CI.`;
94
97
  }
95
98
  if (res.status === 401 && OAuthSession.isOAuth(profile)) {
96
99
  return `The OAuth token was rejected. Run \`ptkl profile oauth\` again to log in${profile ? ` (profile '${profile.name}')` : ""}.`;
@@ -9,6 +9,26 @@ export const SCOPE_PRESET = [
9
9
  { permission: "manage base_components", commands: "component, generate-types, ratchet test connection" },
10
10
  { permission: "manage base_templates", commands: "template" },
11
11
  { permission: "manage base_thunder", commands: "thunder" },
12
+ { permission: "list forge", commands: "forge list" },
13
+ { permission: "read thunder", commands: "thunder (data read)" },
14
+ { permission: "write thunder", commands: "thunder (data write)" },
15
+ { permission: "manage base_workflows", commands: "workflow" },
16
+ { permission: "create base_users", commands: "project invite, invites" },
17
+ { permission: "manage integrations", commands: "integration list/install" },
18
+ { permission: "view_transactions protokol-payments", commands: "integration payments (transactions)" },
19
+ { permission: "refund_transaction protokol-payments", commands: "integration payments refund" },
20
+ { permission: "void_transaction protokol-payments", commands: "integration payments void/deactivate" },
21
+ { permission: "read protokol-mail", commands: "integration mail (list/get/attachments)" },
22
+ { permission: "send protokol-mail", commands: "integration mail (send/resend)" },
23
+ { permission: "manage timber", commands: "integration timber query/usage, logs" },
24
+ { permission: "write timber", commands: "integration timber write" },
25
+ { permission: "use protokol-media", commands: "integration dms (dirs, backup, policies, reminders, download)" },
26
+ { permission: "utilities protokol-media", commands: "integration dms (libraries, convert, ocr)" },
27
+ { permission: "upload protokol-media", commands: "integration dms upload" },
28
+ { permission: "read_documents protokol-media", commands: "integration dms document (read/list/revisions/generate)" },
29
+ { permission: "create_document protokol-media", commands: "integration dms document create" },
30
+ { permission: "edit_document protokol-media", commands: "integration dms document (update/comment)" },
31
+ { permission: "delete_document protokol-media", commands: "integration dms document (delete/restore)" },
12
32
  { permission: "read base_ratchet", commands: "ratchet (list/get)" },
13
33
  { permission: "inspect base_ratchet", commands: "ratchet (query inspect)" },
14
34
  { permission: "read base_users", commands: "users (list)" },
@@ -48,6 +48,19 @@ describe("ScopePreset", () => {
48
48
  expect(ScopePreset.resolve({ scope: "x", addScope: "y,x" })).toEqual(["x", "y"]);
49
49
  expect(ScopePreset.resolve({ addScope: "edit base_users" })).toContain("edit base_users");
50
50
  });
51
+ it("covers thunder data, workflows, invites, forge list and integrations", () => {
52
+ expect(ScopePreset.permissions).toEqual(expect.arrayContaining([
53
+ "read thunder", "write thunder", "manage base_workflows", "create base_users", "list forge", "manage integrations",
54
+ "view_transactions protokol-payments", "refund_transaction protokol-payments", "void_transaction protokol-payments",
55
+ "read protokol-mail", "send protokol-mail", "manage timber", "write timber",
56
+ "use protokol-media", "utilities protokol-media", "upload protokol-media",
57
+ "read_documents protokol-media", "create_document protokol-media", "edit_document protokol-media", "delete_document protokol-media"
58
+ ]));
59
+ for (const bad of ["admin", "manage forge"])
60
+ expect(ScopePreset.permissions).not.toContain(bad);
61
+ const wire = ScopePreset.toWire(ScopePreset.permissions);
62
+ expect(wire).toContain(`perm64:${Buffer.from("write thunder").toString("base64url")}`);
63
+ });
51
64
  it("asks for API-user management and secrets by default", () => {
52
65
  expect(ScopePreset.permissions).toEqual(expect.arrayContaining(["edit base_users", "manage_secrets base_users", "dev env_access"]));
53
66
  });
@@ -189,7 +202,11 @@ describe("OAuthSession", () => {
189
202
  });
190
203
  it("maps 403 insufficient_scope to an unavailable-to-OAuth message", () => {
191
204
  const err = { response: { status: 403, headers: { "www-authenticate": 'Bearer error="insufficient_scope"' } } };
192
- expect(OAuthSession.describeApiError(err)).toMatch(/isn't available to OAuth tokens/);
205
+ expect(OAuthSession.describeApiError(err)).toMatch(/lacks a permission this command needs/);
206
+ expect(OAuthSession.describeApiError(err)).toMatch(/--add-scope "<permission>"/);
207
+ expect(OAuthSession.describeApiError(err)).toMatch(/--legacy/);
208
+ const named = { response: { status: 403, headers: { "www-authenticate": 'Bearer error="insufficient_scope", scope="read thunder"' } } };
209
+ expect(OAuthSession.describeApiError(named)).toMatch(/lacks the permission "read thunder"[\s\S]*--add-scope "read thunder"/);
193
210
  expect(OAuthSession.describeApiError({ response: { status: 403, headers: {} } })).toBeUndefined();
194
211
  });
195
212
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptkl/toolkit",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "A command-line toolkit for managing Protokol platform applications, profiles, functions, and components",
5
5
  "keywords": [
6
6
  "protokol",
@@ -1,111 +0,0 @@
1
- import { resolve } from "path";
2
- import { writeFileSync } from "fs";
3
- import { Command } from "commander";
4
- import * as sdk from "../lib/sdk.js";
5
- import { registerCommand, withEnvOption, withProfile } from "../lib/scaffold.js";
6
- /** `ptkl billing` — subscriptions, invoices, credits/balance, usage pricing and per-project
7
- * billing-mode overrides (RFC §6 "Billing": `subscriptions invoices invoice-pdf balance topup
8
- * credits prices billing-modes`). Maps onto the SDK `Transactions` client (@ptkl/sdk/beta),
9
- * reached via `platform.billing()` (an alias of `platform.transactions()`) — the
10
- * `transactions/…` gateway prefix. This is the **billing** service, not distributed/database
11
- * transactions (see RFC §5(c)). */
12
- function parseJSON(label, raw) {
13
- try {
14
- return JSON.parse(raw);
15
- }
16
- catch {
17
- console.error(`${label} must be valid JSON`);
18
- process.exit(1);
19
- }
20
- }
21
- class BillingCommand {
22
- register() {
23
- const cmd = new Command("billing").description("Manage billing: subscriptions, invoices, balance/credits and pricing");
24
- cmd.addCommand(registerCommand(new Command("subscriptions").description("List all subscriptions (including expired) for the current project")).action(withProfile(async (profile) => {
25
- const res = await sdk.platform(profile).billing().getSubscriptions();
26
- return res.data;
27
- })));
28
- cmd.addCommand(registerCommand(new Command("invoices")
29
- .description("List invoices for the current project, or get a single invoice by uuid")
30
- .argument("[uuid]", "Invoice uuid — omit to list all invoices")).action(withProfile(async (profile, uuid) => {
31
- const client = sdk.platform(profile).billing();
32
- const res = uuid ? await client.getInvoice(uuid) : await client.getInvoices();
33
- return res.data;
34
- })));
35
- cmd.addCommand(this.registerInvoicePdf());
36
- cmd.addCommand(registerCommand(new Command("balance").description("Get the current project's credit balance")).action(withProfile(async (profile) => {
37
- const res = await sdk.platform(profile).billing().getBalance();
38
- return res.data;
39
- })));
40
- cmd.addCommand(registerCommand(new Command("topup")
41
- .description("Generate a checkout link to top up the project's credit balance")
42
- .requiredOption("-a, --amount-cents <cents>", "Purchase amount in USD cents (e.g. 1000 = $10.00)")
43
- .option("-c, --currency <currency>", "ISO 4217 currency code (defaults to USD server-side)")).action(withProfile(async (profile, opts) => {
44
- const res = await sdk.platform(profile).billing().topUp({
45
- amount_cents: Number(opts.amountCents),
46
- ...(opts.currency ? { currency: opts.currency } : {}),
47
- });
48
- return res.data;
49
- })));
50
- cmd.addCommand(registerCommand(new Command("credits")
51
- .description("Get the project's credit activity (deductions/top-ups) history")
52
- .option("-l, --limit <n>", "Max rows to return (server default 50, capped at 200)")
53
- .option("--offset <n>", "Row offset for pagination")
54
- .option("-t, --type <type>", "Filter by entry type (e.g. deduction | topup)")
55
- .option("-y, --year <year>", "Filter by year")
56
- .option("-m, --month <month>", "Filter by month")).action(withProfile(async (profile, opts) => {
57
- const query = {
58
- ...(opts.limit !== undefined ? { limit: Number(opts.limit) } : {}),
59
- ...(opts.offset !== undefined ? { offset: Number(opts.offset) } : {}),
60
- ...(opts.type ? { type: opts.type } : {}),
61
- ...(opts.year !== undefined ? { year: Number(opts.year) } : {}),
62
- ...(opts.month !== undefined ? { month: Number(opts.month) } : {}),
63
- };
64
- const res = await sdk.platform(profile).billing().getCreditsHistory(query);
65
- return res.data;
66
- })));
67
- cmd.addCommand(registerCommand(new Command("prices")
68
- .description("Get the usage-based pricing table for a given currency")
69
- .requiredOption("-c, --currency <currency>", "ISO 4217 currency code, e.g. USD or RSD")).action(withProfile(async (profile, opts) => {
70
- const res = await sdk.platform(profile).billing().getPrices(opts.currency);
71
- return res.data;
72
- })));
73
- cmd.addCommand(registerCommand(new Command("billing-modes")
74
- .description("Get the project's usage-billing-mode overrides, or set one with --option-code/--mode/--data")
75
- .option("--option-code <code>", "Usage option code to update (requires --mode, or use --data)")
76
- .option("--mode <mode>", "Billing mode to set: credits | hybrid | invoice (requires --option-code)")
77
- .option("-d, --data <json>", "Update payload as a JSON string ({ option_code, mode }) — alternative to --option-code/--mode")).action(withProfile(async (profile, opts) => {
78
- const client = sdk.platform(profile).billing();
79
- if (opts.data) {
80
- const payload = parseJSON("--data", opts.data);
81
- const res = await client.updateBillingModes(payload);
82
- return res.data;
83
- }
84
- if (opts.optionCode || opts.mode) {
85
- if (!opts.optionCode || !opts.mode) {
86
- console.error("--option-code and --mode must be provided together");
87
- process.exit(1);
88
- }
89
- const res = await client.updateBillingModes({ option_code: opts.optionCode, mode: opts.mode });
90
- return res.data;
91
- }
92
- const res = await client.getBillingModes();
93
- return res.data;
94
- })));
95
- return cmd;
96
- }
97
- registerInvoicePdf() {
98
- const pdfCmd = withEnvOption(new Command("invoice-pdf")
99
- .description("Download an invoice as a PDF")
100
- .argument("<uuid>", "Invoice uuid")
101
- .requiredOption("-o, --out <file>", "File path to write the PDF to"));
102
- pdfCmd.action(withProfile(async (profile, uuid, opts) => {
103
- const res = await sdk.platform(profile).billing().getInvoicePdf(uuid);
104
- const outPath = resolve(opts.out);
105
- writeFileSync(outPath, Buffer.from(res.data));
106
- console.log(`Invoice PDF written to ${outPath}`);
107
- }));
108
- return pdfCmd;
109
- }
110
- }
111
- export default new BillingCommand();