@ptkl/toolkit 0.14.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -207,8 +207,8 @@ ptkl forge list
207
207
  Dry-run install or uninstall scripts locally against the active profile.
208
208
 
209
209
  ```bash
210
- ptkl forge install -p <path> [--env dev|live] [-b]
211
- ptkl forge uninstall -p <path> [--env dev|live] [-b]
210
+ ptkl forge install -p <path> [--env dev|live] [-b] [--var KEY=value]
211
+ ptkl forge uninstall -p <path> [--env dev|live] [-b] [--var KEY=value]
212
212
  ```
213
213
 
214
214
  | Flag | Description |
@@ -216,6 +216,23 @@ ptkl forge uninstall -p <path> [--env dev|live] [-b]
216
216
  | `-p, --path <path>` | **(required)** Path to the app directory |
217
217
  | `--env <env>` | Run for a specific env only (omit to run both) |
218
218
  | `-b, --bundle` | Build the bundle before running the script |
219
+ | `--var <key=value>` | Set one app variable (`$variables`) for the run. Repeatable. |
220
+ | `--vars <list>` | Set several at once: `'KEY=value;KEY2=value2'`. Repeatable. |
221
+ | `--vars-file <path>` | JSON file of variables — flat, or env-keyed `{ "dev": {...}, "live": {...} }` |
222
+
223
+ On the platform, the install script reads the app's stored variables for the environment
224
+ through the `$variables` global. Locally there is no app record, so pass them in:
225
+
226
+ ```bash
227
+ ptkl forge install -p ./my-app --env dev \
228
+ --var WEBHOOK_URL=https://staging.example.com/hook \
229
+ --var MAX_RETRIES=3
230
+ ```
231
+
232
+ Values are parsed as JSON when valid (`3` → number, `true` → boolean, `{"a":1}` → object)
233
+ and kept as strings otherwise. Sources merge in order `--vars-file` → `--vars` → `--var`,
234
+ so a base file can be overridden per run. These flags affect the local dry run only —
235
+ they never write to the deployed app's variables.
219
236
 
220
237
  ### `ptkl forge remove-version`
221
238
 
@@ -0,0 +1,111 @@
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();
@@ -0,0 +1,33 @@
1
+ import { Command } from "commander";
2
+ import * as sdk from "../lib/sdk.js";
3
+ import { registerCommand, withProfile } from "../lib/scaffold.js";
4
+ /** `ptkl config` — per-user configuration (RFC §4.1 "Config": `GET/PUT config/user`).
5
+ * Maps 1:1 onto the SDK `Config` client (@ptkl/sdk/beta). */
6
+ function parseJSON(label, raw) {
7
+ try {
8
+ return JSON.parse(raw);
9
+ }
10
+ catch {
11
+ console.error(`${label} must be valid JSON`);
12
+ process.exit(1);
13
+ }
14
+ }
15
+ class ConfigCommand {
16
+ register() {
17
+ const cmd = new Command("config").description("Get or set the current user's configuration");
18
+ cmd.addCommand(registerCommand(new Command("get").description("Get the current user's configuration")).action(withProfile(async (profile) => {
19
+ const res = await sdk.config(profile).getUserConfig();
20
+ return res.data;
21
+ })));
22
+ cmd.addCommand(registerCommand(new Command("set")
23
+ .description("Update the current user's configuration")
24
+ .requiredOption("-p, --path <path>", "Config path to write")
25
+ .requiredOption("-d, --data <json>", "Config data as a JSON string")).action(withProfile(async (profile, opts) => {
26
+ const data = parseJSON("--data", opts.data);
27
+ const res = await sdk.config(profile).updateUserConfig({ path: opts.path, data });
28
+ return res.data;
29
+ })));
30
+ return cmd;
31
+ }
32
+ }
33
+ export default new ConfigCommand();
@@ -8,6 +8,87 @@ import axios from 'axios';
8
8
  import Util from "../lib/util.js";
9
9
  import { dirname, extname, isAbsolute, join } from 'path';
10
10
  import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
11
+ import * as sdk from "../lib/sdk.js";
12
+ import { registerCommand, withProfile } from "../lib/scaffold.js";
13
+ function parseJSON(label, raw) {
14
+ try {
15
+ return JSON.parse(raw);
16
+ }
17
+ catch {
18
+ console.error(`${label} must be valid JSON`);
19
+ process.exit(1);
20
+ }
21
+ }
22
+ /** Values are JSON when they parse as JSON, otherwise the raw string —
23
+ * same convention as `ptkl forge variables add`. */
24
+ function parseVarValue(raw) {
25
+ try {
26
+ return JSON.parse(raw);
27
+ }
28
+ catch {
29
+ return raw;
30
+ }
31
+ }
32
+ /** `KEY=value` → `{ KEY: <parsed value> }`. Splits on the FIRST `=` so values may contain `=`. */
33
+ function parseVarPair(pair, flag) {
34
+ const trimmed = pair.trim();
35
+ const eq = trimmed.indexOf('=');
36
+ if (eq < 1) {
37
+ console.error(`${flag} must be in KEY=value form (got '${pair}')`);
38
+ process.exit(1);
39
+ }
40
+ return [trimmed.slice(0, eq).trim(), parseVarValue(trimmed.slice(eq + 1))];
41
+ }
42
+ /** `--vars` payload: `KEY=value;KEY2=value2` (also accepts newline-separated). */
43
+ function parseVarList(list) {
44
+ const out = {};
45
+ for (const pair of list.split(/[;\n]/)) {
46
+ if (!pair.trim())
47
+ continue;
48
+ const [key, value] = parseVarPair(pair, '--vars');
49
+ out[key] = value;
50
+ }
51
+ return out;
52
+ }
53
+ /**
54
+ * Build the `$variables` map the local script run should see, mirroring what the
55
+ * platform injects from the app's stored variables (`app.variables[env]`).
56
+ *
57
+ * Sources, lowest precedence first:
58
+ * 1. `--vars-file <path>` — JSON, either a flat map or env-keyed (`{ dev: {...}, live: {...} }`)
59
+ * 2. `--vars KEY=v;KEY2=v2`
60
+ * 3. `--var KEY=v` (repeatable)
61
+ */
62
+ function collectVariables(options, env) {
63
+ let fromFile = {};
64
+ if (options.varsFile) {
65
+ const filePath = isAbsolute(options.varsFile) ? options.varsFile : join(process.cwd(), options.varsFile);
66
+ if (!existsSync(filePath)) {
67
+ console.error(`--vars-file not found: ${filePath}`);
68
+ process.exit(1);
69
+ }
70
+ const parsed = parseJSON('--vars-file', readFileSync(filePath, 'utf-8'));
71
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
72
+ console.error(`--vars-file must contain a JSON object`);
73
+ process.exit(1);
74
+ }
75
+ // Env-keyed shape ({ dev: {...}, live: {...} }) mirrors how variables are stored
76
+ // on the app; anything else is treated as a flat map applied to every env.
77
+ const keys = Object.keys(parsed);
78
+ const envKeyed = keys.length > 0 && keys.every(k => (k === 'dev' || k === 'live') && parsed[k] && typeof parsed[k] === 'object' && !Array.isArray(parsed[k]));
79
+ fromFile = envKeyed ? (parsed[env] ?? {}) : parsed;
80
+ }
81
+ const fromList = (options.vars ?? []).reduce((acc, list) => ({ ...acc, ...parseVarList(list) }), {});
82
+ const fromPairs = (options.var ?? []).reduce((acc, pair) => {
83
+ const [key, value] = parseVarPair(pair, '--var');
84
+ return { ...acc, [key]: value };
85
+ }, {});
86
+ return { ...fromFile, ...fromList, ...fromPairs };
87
+ }
88
+ /** commander collector for repeatable options. */
89
+ function collect(value, previous = []) {
90
+ return previous.concat([value]);
91
+ }
11
92
  function formatBuildError(reason) {
12
93
  const lines = [];
13
94
  if (reason.id || reason.loc) {
@@ -100,13 +181,122 @@ class ForgeCommand {
100
181
  .requiredOption("-p, --path <path>", "Path to the app directory (where ptkl.config.js is located)")
101
182
  .option("--env <env>", "Run for a specific env only (dev or live). Omit to run for both.")
102
183
  .option("-b, --bundle", "Build the bundle before running the install script")
184
+ .option("--var <key=value>", "Set an app variable for the run ($variables). Repeatable.", collect)
185
+ .option("--vars <list>", "Set several app variables at once: 'KEY=value;KEY2=value2'. Repeatable.", collect)
186
+ .option("--vars-file <path>", "JSON file of app variables — flat map, or env-keyed { dev: {...}, live: {...} }")
103
187
  .action((options) => this.install(options)))
104
188
  .addCommand(new Command("uninstall")
105
189
  .description("Dry-run the app uninstall script locally against the active profile (no actual uninstallation). Runs for both dev and live by default.")
106
190
  .requiredOption("-p, --path <path>", "Path to the app directory (where ptkl.config.js is located)")
107
191
  .option("--env <env>", "Run for a specific env only (dev or live). Omit to run for both.")
108
192
  .option("-b, --bundle", "Build the bundle before running the uninstall script")
109
- .action((options) => this.uninstall(options)));
193
+ .option("--var <key=value>", "Set an app variable for the run ($variables). Repeatable.", collect)
194
+ .option("--vars <list>", "Set several app variables at once: 'KEY=value;KEY2=value2'. Repeatable.", collect)
195
+ .option("--vars-file <path>", "JSON file of app variables — flat map, or env-keyed { dev: {...}, live: {...} }")
196
+ .action((options) => this.uninstall(options)))
197
+ // --- Deployed-app management (appservice) -------------------------------------------
198
+ // These subcommands use the shared scaffold (src/lib/sdk.ts + src/lib/scaffold.ts) and
199
+ // the SDK `Forge` client (@ptkl/sdk/beta), unlike bundle/dev/setup/list/install/uninstall
200
+ // above, which predate that scaffold and talk to a v0.9 client via Util.getClientForProfile().
201
+ // `services`/`variables`/`run` are wrapped named methods on the v0.10 `Forge` client;
202
+ // `domains` has no named methods yet, so it goes through the client's underlying
203
+ // authenticated AxiosInstance (`.client`, a public property on every SDK client) — the same
204
+ // stopgap pattern used by `ptkl functions create` / `ptkl project billing-modes`.
205
+ .addCommand(registerCommand(new Command("services")
206
+ .description("List services declared by a Forge app")
207
+ .argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref) => {
208
+ const res = await sdk.platform(profile).forge().listServices(ref);
209
+ return res.data;
210
+ })))
211
+ .addCommand(this.registerVariables())
212
+ .addCommand(this.registerDomains())
213
+ .addCommand(registerCommand(new Command("run")
214
+ .description("Invoke a deployed Forge service app. A bare name runs the CURRENT app's service; " +
215
+ "a PRN (prn:forge:{ref}:service/{name}) runs another app's service, where ref is an app name or uuid.")
216
+ .argument("<service>", "Service name (current app) or PRN: prn:forge:{ref}:service/{name}")
217
+ .option("-b, --body <json>", "Request body as a JSON string, sent as the POST payload")
218
+ .option("-q, --query <json>", "Query params as a JSON object string")
219
+ .option("-H, --headers <json>", "Extra request headers as a JSON object string")).action(withProfile(async (profile, service, opts) => {
220
+ const body = opts.body ? parseJSON("--body", opts.body) : undefined;
221
+ const query = opts.query ? parseJSON("--query", opts.query) : undefined;
222
+ const headers = opts.headers ? parseJSON("--headers", opts.headers) : undefined;
223
+ const res = await sdk.platform(profile).forge().runService(service, body, { query, headers });
224
+ return res.data;
225
+ })));
226
+ }
227
+ /** `forge variables get|set|add <ref>` — get/replace/merge a Forge app's variables
228
+ * (getVariables/updateVariables/addVariable on the SDK `Forge` client). */
229
+ registerVariables() {
230
+ const variables = new Command("variables").description("Manage a Forge app's variables");
231
+ variables.addCommand(registerCommand(new Command("get")
232
+ .description("Get all variables for a Forge app")
233
+ .argument("<ref>", "App reference (uuid or name)")).action(withProfile(async (profile, ref) => {
234
+ const res = await sdk.platform(profile).forge().getVariables(ref);
235
+ return res.data;
236
+ })));
237
+ variables.addCommand(registerCommand(new Command("set")
238
+ .description("Replace ALL variables for a Forge app (full overwrite, not a merge)")
239
+ .argument("<ref>", "App reference (uuid or name)")
240
+ .requiredOption("-d, --data <json>", "Full variables object as a JSON string (replaces all existing variables)")).action(withProfile(async (profile, ref, opts) => {
241
+ const payload = parseJSON("--data", opts.data);
242
+ const res = await sdk.platform(profile).forge().updateVariables(ref, payload);
243
+ return res.data;
244
+ })));
245
+ variables.addCommand(registerCommand(new Command("add")
246
+ .description("Add or update a single variable on a Forge app (merges into existing variables)")
247
+ .argument("<ref>", "App reference (uuid or name)")
248
+ .argument("<key>", "Variable key")
249
+ .argument("<value>", "Variable value (parsed as JSON if it's valid JSON, otherwise kept as a string)")).action(withProfile(async (profile, ref, key, value) => {
250
+ let parsedValue = value;
251
+ try {
252
+ parsedValue = JSON.parse(value);
253
+ }
254
+ catch { /* not JSON — keep the raw string */ }
255
+ const res = await sdk.platform(profile).forge().addVariable(ref, key, parsedValue);
256
+ return res.data;
257
+ })));
258
+ return variables;
259
+ }
260
+ /** `forge domains add|verify|refresh|remove <ref> <domain>` — custom-domain lifecycle for
261
+ * public Forge apps (appservice `POST/DELETE /luma/appservice/v1/forge/:ref/domain[/verify|/refresh]`,
262
+ * see platform-docs/docs/forge/custom-domains.md). No named SDK method exists yet, so this calls
263
+ * the SDK `Forge` client's underlying authenticated AxiosInstance directly (`.client`, see the
264
+ * stopgap-pattern note above `services`). */
265
+ registerDomains() {
266
+ const domains = new Command("domains").description("Manage custom domains for a public Forge app");
267
+ domains.addCommand(registerCommand(new Command("add")
268
+ .description("Register a custom domain (returns a DNS TXT validationKey to prove ownership)")
269
+ .argument("<ref>", "App reference (uuid or name)")
270
+ .argument("<domain>", "Custom domain, e.g. app.example.com")).action(withProfile(async (profile, ref, domain) => {
271
+ const client = sdk.platform(profile).forge();
272
+ const res = await client.client.post(`/luma/appservice/v1/forge/${ref}/domain`, { domain });
273
+ return res.data;
274
+ })));
275
+ domains.addCommand(registerCommand(new Command("verify")
276
+ .description("Verify a custom domain's DNS TXT record against its validation key")
277
+ .argument("<ref>", "App reference (uuid or name)")
278
+ .argument("<domain>", "Custom domain to verify")).action(withProfile(async (profile, ref, domain) => {
279
+ const client = sdk.platform(profile).forge();
280
+ const res = await client.client.post(`/luma/appservice/v1/forge/${ref}/domain/verify`, { domain });
281
+ return res.data;
282
+ })));
283
+ domains.addCommand(registerCommand(new Command("refresh")
284
+ .description("Refresh an expired validation key for an unvalidated custom domain")
285
+ .argument("<ref>", "App reference (uuid or name)")
286
+ .argument("<domain>", "Custom domain")).action(withProfile(async (profile, ref, domain) => {
287
+ const client = sdk.platform(profile).forge();
288
+ const res = await client.client.post(`/luma/appservice/v1/forge/${ref}/domain/refresh`, { domain });
289
+ return res.data;
290
+ })));
291
+ domains.addCommand(registerCommand(new Command("remove")
292
+ .description("Remove a custom domain")
293
+ .argument("<ref>", "App reference (uuid or name)")
294
+ .argument("<domain>", "Custom domain to remove")).action(withProfile(async (profile, ref, domain) => {
295
+ const client = sdk.platform(profile).forge();
296
+ const res = await client.client.delete(`/luma/appservice/v1/forge/${ref}/domain`, { data: { domain } });
297
+ return res.data;
298
+ })));
299
+ return domains;
110
300
  }
111
301
  async bundle(options) {
112
302
  const { path: rawPath, upload, mode } = options;
@@ -244,10 +434,26 @@ class ForgeCommand {
244
434
  manifest.views[view] = `${view}.bundle.js`;
245
435
  }
246
436
  try {
437
+ const bundleMode = mode ?? 'production';
247
438
  const result = await build({
248
439
  root: path,
249
- mode: mode ?? 'production',
440
+ mode: bundleMode,
250
441
  base: bundleBasePath,
442
+ // Keep the JSX transform and React runtime on the same side even if
443
+ // the invoking shell exports NODE_ENV=development (Vite derives
444
+ // isProduction from NODE_ENV, not from mode). A split ships jsxDEV()
445
+ // calls against production React → "jsxDEV is not a function".
446
+ esbuild: {
447
+ jsxDev: bundleMode !== 'production',
448
+ },
449
+ define: {
450
+ 'process.env.NODE_ENV': JSON.stringify(bundleMode),
451
+ },
452
+ resolve: {
453
+ // One React copy even when @ptkl/components is npm-linked (the
454
+ // linked repo carries its own node_modules/react).
455
+ dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],
456
+ },
251
457
  build: {
252
458
  outDir: distPath,
253
459
  emptyOutDir: false,
@@ -255,10 +461,13 @@ class ForgeCommand {
255
461
  input: viewDef.entry,
256
462
  output: {
257
463
  format: 'esm',
464
+ // Name outputs by the view KEY, not the entry file's basename —
465
+ // the manifest and AppView resolve `${view}.bundle.js` / `${view}.css`,
466
+ // so an entry named index.tsx must still emit `${view}.*`.
467
+ // Other assets keep a hashed name: all views share distPath, so
468
+ // entry-derived names (e.g. index.css from two views) collide.
258
469
  entryFileNames: `${view}.bundle.js`,
259
- assetFileNames: (assetInfo) => {
260
- return '[name].[ext]'; // Example: Customize the output file name format
261
- },
470
+ assetFileNames: (assetInfo) => assetInfo.name?.endsWith('.css') ? `${view}.css` : `[name]-[hash].[ext]`,
262
471
  manualChunks: undefined,
263
472
  inlineDynamicImports: true,
264
473
  }
@@ -564,7 +773,7 @@ class ForgeCommand {
564
773
  DEV_HUB_PORT
565
774
  },
566
775
  plugins: [
567
- forgeDevKernelPlugin(appName, platformUrl),
776
+ forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT),
568
777
  {
569
778
  // Console bridge (dev only): when the app runs EMBEDDED (e.g. the
570
779
  // Studio's Preview iframe), forward console output + uncaught errors
@@ -659,9 +868,17 @@ class ForgeCommand {
659
868
  mode: 'production',
660
869
  logLevel: 'silent',
661
870
  plugins: [],
662
- // Explicitly define NODE_ENV for this build so esbuild strips dev-only
663
- // code paths (e.g. React dev warnings) in the view bundle, regardless
664
- // of what process.env.NODE_ENV is set to in the surrounding process.
871
+ // The dev hub serves PRODUCTION builds of views. The dev server created
872
+ // above set process.env.NODE_ENV=development for this whole process, and
873
+ // Vite derives isProduction from NODE_ENV (not from mode) — so both the
874
+ // JSX transform and React's runtime must be forced to production TOGETHER:
875
+ // - jsxDev:false → esbuild emits jsx() from react/jsx-runtime
876
+ // - define → React resolves its production runtime
877
+ // Forcing only the define ships dev jsxDEV() calls against production
878
+ // React, where jsxDEV is undefined → "_a.jsxDEV is not a function".
879
+ esbuild: {
880
+ jsxDev: false,
881
+ },
665
882
  define: {
666
883
  'process.env.NODE_ENV': '"production"',
667
884
  },
@@ -1059,7 +1276,7 @@ class ForgeCommand {
1059
1276
  await this.bundle({ path, upload: false });
1060
1277
  const envs = env ? [env] : ['dev', 'live'];
1061
1278
  for (const e of envs) {
1062
- await ForgeCommand._runScript(path, 'install', e);
1279
+ await ForgeCommand._runScript(path, 'install', e, collectVariables(options, e));
1063
1280
  }
1064
1281
  }
1065
1282
  async uninstall(options) {
@@ -1069,10 +1286,10 @@ class ForgeCommand {
1069
1286
  await this.bundle({ path, upload: false });
1070
1287
  const envs = env ? [env] : ['dev', 'live'];
1071
1288
  for (const e of envs) {
1072
- await ForgeCommand._runScript(path, 'uninstall', e);
1289
+ await ForgeCommand._runScript(path, 'uninstall', e, collectVariables(options, e));
1073
1290
  }
1074
1291
  }
1075
- static async _runScript(appPath, scriptType, env = 'dev') {
1292
+ static async _runScript(appPath, scriptType, env = 'dev', variables = {}) {
1076
1293
  appPath = isAbsolute(appPath) ? appPath : join(process.cwd(), appPath);
1077
1294
  const module = await import(`${appPath}/ptkl.config.js`);
1078
1295
  const { name, distPath, scripts } = module.default ?? {};
@@ -1100,7 +1317,16 @@ class ForgeCommand {
1100
1317
  }
1101
1318
  };
1102
1319
  global.axiosAdapter = axios;
1103
- console.log(`Running ${scriptType} script for '${name}' (profile: ${profile.name}, env: ${env})...\n`);
1320
+ // In the platform runtime the sandbox is seeded with the app's stored variables for
1321
+ // the env being installed (`app.variables[env]` → `$variables`). Locally there is no
1322
+ // app record yet, so the variables come from --var/--vars/--vars-file.
1323
+ global.$variables = variables;
1324
+ global.$currentEnv = env;
1325
+ const varKeys = Object.keys(variables);
1326
+ console.log(`Running ${scriptType} script for '${name}' (profile: ${profile.name}, env: ${env})...`);
1327
+ console.log(varKeys.length
1328
+ ? `$variables: ${varKeys.join(', ')}\n`
1329
+ : `$variables: none — pass --var KEY=value to inject them\n`);
1104
1330
  // The bundle is: `return async()=>{try{ ...code... }catch(err){return {_error_:true,...}}}`
1105
1331
  // new Function(scriptCode) creates a function whose body is that code.
1106
1332
  // Calling it returns the async function, which we then await.
@@ -1109,6 +1335,8 @@ class ForgeCommand {
1109
1335
  // Cleanup globals
1110
1336
  delete global.window;
1111
1337
  delete global.axiosAdapter;
1338
+ delete global.$variables;
1339
+ delete global.$currentEnv;
1112
1340
  if (result && result._error_) {
1113
1341
  const displayMessage = result?.response?.data?.message || result.message ||
1114
1342
  (result.errors && result.errors.length > 0
@@ -1,27 +1,92 @@
1
1
  import { Command } from "commander";
2
- import util from "../lib/util.js";
3
- import { Platform as Api } from "@ptkl/sdk";
4
- import OutputFormatCommand from "./outputCommand.js";
5
- class FunctionsCommand {
6
- register() {
7
- return new Command('functions')
8
- .description('Manage functions')
9
- .version('0.1.0')
10
- .addCommand(new OutputFormatCommand(new Command('list')
11
- .description('List functions')).action(this.list))
12
- .addCommand(new OutputFormatCommand(new Command('get')
13
- .description('Get function')
14
- .argument("<reference>", "Reference to the function which can be name, tag or uuid")).action(this.get));
2
+ import { readFileSync } from "fs";
3
+ import { resolve } from "path";
4
+ import * as sdk from "../lib/sdk.js";
5
+ import { registerCommand, withProfile } from "../lib/scaffold.js";
6
+ /** `ptkl functions` — platform function CRUD + invocation (RFC §6, "Functions").
7
+ * Maps onto the SDK `Functions` client (@ptkl/sdk/beta) for `list`/`get`/`update`/`run`/
8
+ * `signature` (`generateSignature`). The platform's `system/function` collection endpoint also
9
+ * supports POST for creation, but the v0.10 `Functions` client does not yet wrap that in a named
10
+ * method — `create` goes through the same authenticated client instance's underlying `.client`
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.
14
+ *
15
+ * Return-shape contract: every subcommand here resolves to the *payload*, never a raw
16
+ * AxiosResponse. `Functions.run()` already unwraps `.data` in the SDK; `list`/`get`/`update`/
17
+ * `generateSignature` do not (they resolve to the AxiosResponse), so this command layer unwraps
18
+ * `.data` itself for those — matching `create`, which reads `.data` off the raw axios call. This
19
+ * keeps `-f json`/`-f jsonpath`/`-f template` consistent across all six subcommands. */
20
+ function parseJSON(label, raw) {
21
+ try {
22
+ return JSON.parse(raw);
23
+ }
24
+ catch {
25
+ console.error(`${label} must be valid JSON`);
26
+ process.exit(1);
27
+ }
28
+ }
29
+ function readPayload(label, dataStr, file) {
30
+ if (file) {
31
+ return JSON.parse(readFileSync(resolve(file), "utf-8"));
15
32
  }
16
- async list() {
17
- const profile = util.getCurrentProfile();
18
- const client = new Api({ token: profile.token, host: profile.host }).function();
19
- return await client.list();
33
+ if (dataStr) {
34
+ return parseJSON(label, dataStr);
20
35
  }
21
- async get(reference) {
22
- const profile = util.getCurrentProfile();
23
- const client = new Api({ token: profile.token, host: profile.host }).function();
24
- return await client.get(reference);
36
+ console.error("Error: either --data or --file must be provided");
37
+ process.exit(1);
38
+ }
39
+ class FunctionsCommand {
40
+ register() {
41
+ const cmd = new Command("functions").description("Manage functions").version("0.1.0");
42
+ cmd.addCommand(registerCommand(new Command("list").description("List functions")).action(withProfile(async (profile) => {
43
+ const res = await sdk.platform(profile).function().list();
44
+ return res.data;
45
+ })));
46
+ cmd.addCommand(registerCommand(new Command("get")
47
+ .description("Get function")
48
+ .argument("<reference>", "Reference to the function which can be name, tag or uuid")).action(withProfile(async (profile, reference) => {
49
+ const res = await sdk.platform(profile).function().get(reference);
50
+ return res.data;
51
+ })));
52
+ cmd.addCommand(registerCommand(new Command("run")
53
+ .description("Run a platform function")
54
+ .argument("<reference>", "Reference to the function which can be name, tag or uuid")
55
+ .option("-i, --input <json>", "Input payload as a JSON string")
56
+ .option("-q, --query <json>", "Query params as a JSON object string")).action(withProfile(async (profile, reference, opts) => {
57
+ const { input: inputStr, query: queryStr } = opts;
58
+ const input = inputStr ? parseJSON("--input", inputStr) : undefined;
59
+ const query = queryStr ? parseJSON("--query", queryStr) : undefined;
60
+ return await sdk.platform(profile).function().run(reference, { input, query });
61
+ })));
62
+ cmd.addCommand(registerCommand(new Command("create")
63
+ .description("Create a new function")
64
+ .option("-d, --data <data>", "Full create payload as JSON string (overrides --file)")
65
+ .option("-i, --file <file>", "Path to a JSON file containing the full create payload")).action(withProfile(async (profile, opts) => {
66
+ const { data: dataStr, file } = opts;
67
+ const payload = readPayload("--data", dataStr, file);
68
+ const client = sdk.platform(profile).function();
69
+ const res = await client.client.post("/v1/system/function", payload);
70
+ return res.data;
71
+ })));
72
+ cmd.addCommand(registerCommand(new Command("update")
73
+ .description("Update an existing function")
74
+ .argument("<uuid>", "UUID of the function to update")
75
+ .option("-d, --data <data>", "Fields to update, as a JSON object string (overrides --file)")
76
+ .option("-i, --file <file>", "Path to a JSON file containing the fields to update")).action(withProfile(async (profile, uuid, opts) => {
77
+ const { data: dataStr, file } = opts;
78
+ const payload = readPayload("--data", dataStr, file);
79
+ const res = await sdk.platform(profile).function().update(uuid, payload);
80
+ return res.data;
81
+ })));
82
+ cmd.addCommand(registerCommand(new Command("signature")
83
+ .description("Generate the IDL signature for a function in a given environment")
84
+ .argument("<env>", "Environment to resolve the signature against, e.g. dev | live")
85
+ .argument("<reference>", "Reference to the function which can be name, tag or uuid")).action(withProfile(async (profile, env, reference) => {
86
+ const res = await sdk.platform(profile).function().generateSignature(reference, env);
87
+ return res.data;
88
+ })));
89
+ return cmd;
25
90
  }
26
91
  }
27
- export default new FunctionsCommand;
92
+ export default new FunctionsCommand();