@ptkl/toolkit 1.4.4 → 1.5.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 +14 -1
- package/dist/commands/__tests__/capabilities.test.js +83 -0
- package/dist/commands/__tests__/componentRunAs.test.js +65 -0
- package/dist/commands/__tests__/forge-bundle-layout.test.js +46 -0
- package/dist/commands/__tests__/forge-bundle-path.test.js +29 -0
- package/dist/commands/__tests__/forge-variables.test.js +16 -0
- package/dist/commands/__tests__/role.test.js +83 -0
- package/dist/commands/__tests__/runAs.test.js +63 -0
- package/dist/commands/__tests__/thunder.test.js +46 -0
- package/dist/commands/component.js +9 -3
- package/dist/commands/forge.js +106 -135
- package/dist/commands/functions.js +11 -5
- package/dist/commands/integrations/payments.js +11 -7
- package/dist/commands/role.js +45 -54
- package/dist/commands/satellite.js +0 -5
- package/dist/commands/thunder.js +19 -12
- package/dist/commands/workflow.js +10 -4
- package/dist/lib/__tests__/apiError.test.js +14 -0
- package/dist/lib/__tests__/apiErrorCapabilities.test.js +23 -0
- package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +34 -0
- package/dist/lib/__tests__/forgeDevServiceExec.test.js +61 -0
- package/dist/lib/__tests__/forgeDevServiceServer.test.js +113 -0
- package/dist/lib/__tests__/forgeDevToken.test.js +85 -0
- package/dist/lib/__tests__/runIdentity.test.js +101 -0
- package/dist/lib/__tests__/thunder.test.js +101 -0
- package/dist/lib/apiError.js +83 -1
- package/dist/lib/forgeDevKernelPlugin.js +90 -4
- package/dist/lib/forgeDevServiceExec.js +49 -0
- package/dist/lib/forgeDevServiceServer.js +163 -0
- package/dist/lib/forgeDevToken.js +126 -0
- package/dist/lib/oauth/ScopePreset.js +4 -3
- package/dist/lib/oauth/__tests__/oauth.test.js +6 -3
- package/dist/lib/runIdentity.js +51 -0
- package/dist/lib/thunder.js +98 -0
- package/package.json +2 -2
package/dist/commands/forge.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
|
+
import { forbiddenDetails } from "../lib/apiError.js";
|
|
2
3
|
import { build, createServer } from 'vite';
|
|
3
4
|
import { c } from 'tar';
|
|
4
5
|
import { Writable } from "stream";
|
|
@@ -8,6 +9,9 @@ import axios from 'axios';
|
|
|
8
9
|
import Util from "../lib/util.js";
|
|
9
10
|
import { dirname, extname, isAbsolute, join } from 'path';
|
|
10
11
|
import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
|
|
12
|
+
import { ForgeDevToken } from '../lib/forgeDevToken.js';
|
|
13
|
+
import { ForgeDevServiceExec } from '../lib/forgeDevServiceExec.js';
|
|
14
|
+
import { ForgeDevServiceServer } from '../lib/forgeDevServiceServer.js';
|
|
11
15
|
import { kortexDevPlugin } from '../lib/kortexDevPlugin.js';
|
|
12
16
|
import * as sdk from "../lib/sdk.js";
|
|
13
17
|
import { registerCommand, withProfile } from "../lib/scaffold.js";
|
|
@@ -41,6 +45,56 @@ function assertPermissionBytesWithinBudget(runtimePermissions = [], entitlements
|
|
|
41
45
|
throw new Error(`Declared permissions total ${bytes} bytes across ${all.length} entries, exceeding the ${MAX_PERMISSION_BYTES} byte limit`);
|
|
42
46
|
}
|
|
43
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Validates the default variables an app declares: dev and live objects of plain values and
|
|
50
|
+
* secretgen:: generators. A secret:: value would be published with the revision, so it is refused
|
|
51
|
+
* here as it is at ship (appservice is the authority).
|
|
52
|
+
*/
|
|
53
|
+
export function assertVariablesAreDefaults(variables) {
|
|
54
|
+
if (variables === undefined || variables === null)
|
|
55
|
+
return;
|
|
56
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
57
|
+
if (!isObject(variables))
|
|
58
|
+
throw new Error("variables must be an object with dev and live");
|
|
59
|
+
const walk = (node, path) => {
|
|
60
|
+
for (const [key, value] of Object.entries(node)) {
|
|
61
|
+
const at = `${path}.${key}`;
|
|
62
|
+
if (isObject(value)) {
|
|
63
|
+
walk(value, at);
|
|
64
|
+
}
|
|
65
|
+
else if (typeof value === "string" && /^(secret|secretref|enc)::/.test(value)) {
|
|
66
|
+
throw new Error(`${at}: an app declares defaults only (plain values or secretgen::); a secret:: value would be published with the app`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
for (const [env, tree] of Object.entries(variables)) {
|
|
71
|
+
if (env !== "dev" && env !== "live")
|
|
72
|
+
throw new Error(`variables.${env}: unknown environment`);
|
|
73
|
+
if (!isObject(tree))
|
|
74
|
+
throw new Error(`variables.${env} must be an object`);
|
|
75
|
+
walk(tree, `variables.${env}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Where a built bundle keeps one of its files. Layout 2 (what `forge bundle` writes) splits the
|
|
80
|
+
* bundle into browser/ and server/; layout 1 was one flat folder and is still what an older build
|
|
81
|
+
* on disk looks like. The platform reads the layout off the manifest and prefixes the path the same
|
|
82
|
+
* way (appservice BundleLayoutService), so anything reading a bundle locally has to read it too —
|
|
83
|
+
* reading a path the bundler no longer writes is how `forge install` stopped finding its script.
|
|
84
|
+
*
|
|
85
|
+
* An unreadable manifest means nothing is built: it resolves flat and the caller reports the miss
|
|
86
|
+
* against the file it actually wanted, which is the more useful error than one about the manifest.
|
|
87
|
+
*/
|
|
88
|
+
export function bundleFilePath(distDir, kind, file) {
|
|
89
|
+
let layout;
|
|
90
|
+
try {
|
|
91
|
+
layout = JSON.parse(readFileSync(join(distDir, "manifest.json"), "utf-8"))?.layout;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
layout = undefined;
|
|
95
|
+
}
|
|
96
|
+
return layout === 2 ? join(distDir, kind, file) : join(distDir, file);
|
|
97
|
+
}
|
|
44
98
|
/**
|
|
45
99
|
* Validates requires.integrations. Codes are not checked against the live option
|
|
46
100
|
* set — it can change after an app ships, and an unknown code is reported at
|
|
@@ -385,17 +439,21 @@ class ForgeCommand {
|
|
|
385
439
|
// Change to the app directory
|
|
386
440
|
process.chdir(path);
|
|
387
441
|
const module = await import(`${path}/ptkl.config.js`);
|
|
388
|
-
const { views, name, version, distPath: distPath = join(path, 'dist'), icon, type, label, permissions, install_permissions, runtime_permissions, entitlements, requires, scripts, services, ssrRenderer, } = module.default ?? {};
|
|
442
|
+
const { views, name, version, distPath: distPath = join(path, 'dist'), icon, type, label, permissions, install_permissions, runtime_permissions, entitlements, requires, variables, scripts, services, ssrRenderer, } = module.default ?? {};
|
|
389
443
|
const iconBase64 = encodeIcon(icon, path);
|
|
390
444
|
// Clean dist folder before building to remove stale files
|
|
391
445
|
if (existsSync(distPath)) {
|
|
392
446
|
rmSync(distPath, { recursive: true, force: true });
|
|
393
447
|
}
|
|
448
|
+
// Layout 2: browser-served files and server-side files never share a folder.
|
|
449
|
+
const browserDir = join(distPath, 'browser');
|
|
450
|
+
const serverDir = join(distPath, 'server');
|
|
394
451
|
// Validate the declared permission budget. Mirrors assertPermissionBytesWithinBudget in
|
|
395
452
|
// appservice and assertPermissionSetWithinBudget in platform-api — same 64 KB, so a build
|
|
396
453
|
// that passes here is not rejected at publish or at a user's app launch.
|
|
397
454
|
assertPermissionBytesWithinBudget(runtime_permissions ?? [], entitlements ?? []);
|
|
398
455
|
assertRequiresIsValid(requires);
|
|
456
|
+
assertVariablesAreDefaults(variables);
|
|
399
457
|
// Normalize views: support both string entries and object entries with access/permissions
|
|
400
458
|
const normalizedViews = {};
|
|
401
459
|
if (views) {
|
|
@@ -410,6 +468,7 @@ class ForgeCommand {
|
|
|
410
468
|
}
|
|
411
469
|
// build manifest file
|
|
412
470
|
const manifest = {
|
|
471
|
+
layout: 2,
|
|
413
472
|
name,
|
|
414
473
|
version,
|
|
415
474
|
...(type !== 'service' && { views: {} }),
|
|
@@ -420,6 +479,7 @@ class ForgeCommand {
|
|
|
420
479
|
runtime_permissions: runtime_permissions ?? [],
|
|
421
480
|
entitlements: entitlements ?? [],
|
|
422
481
|
requires: requires ?? null,
|
|
482
|
+
...(variables && { variables }),
|
|
423
483
|
scripts: {},
|
|
424
484
|
type: type || 'platform',
|
|
425
485
|
ssrRenderer,
|
|
@@ -444,7 +504,7 @@ class ForgeCommand {
|
|
|
444
504
|
root: path,
|
|
445
505
|
mode: mode ?? 'production',
|
|
446
506
|
build: {
|
|
447
|
-
outDir:
|
|
507
|
+
outDir: browserDir,
|
|
448
508
|
emptyOutDir: true,
|
|
449
509
|
}
|
|
450
510
|
});
|
|
@@ -463,7 +523,7 @@ class ForgeCommand {
|
|
|
463
523
|
root: path,
|
|
464
524
|
mode: mode ?? 'production',
|
|
465
525
|
build: {
|
|
466
|
-
outDir:
|
|
526
|
+
outDir: serverDir,
|
|
467
527
|
emptyOutDir: false,
|
|
468
528
|
target: 'esnext',
|
|
469
529
|
ssr: ssrRenderer, // Mark this as an SSR build with the entry point
|
|
@@ -496,7 +556,6 @@ class ForgeCommand {
|
|
|
496
556
|
}
|
|
497
557
|
else {
|
|
498
558
|
// Platform/service apps: custom bundle format with views, scripts, and services
|
|
499
|
-
const bundleBasePath = `/luma/appservice/v1/forge/static/bundle/${name}/${version}/`;
|
|
500
559
|
const buildViews = Object.keys(normalizedViews).map(async (view) => {
|
|
501
560
|
const viewDef = normalizedViews[view];
|
|
502
561
|
// Store view with access info in manifest
|
|
@@ -515,7 +574,7 @@ class ForgeCommand {
|
|
|
515
574
|
const result = await build({
|
|
516
575
|
root: path,
|
|
517
576
|
mode: bundleMode,
|
|
518
|
-
base:
|
|
577
|
+
base: '/',
|
|
519
578
|
// Keep the JSX transform and React runtime on the same side even if
|
|
520
579
|
// the invoking shell exports NODE_ENV=development (Vite derives
|
|
521
580
|
// isProduction from NODE_ENV, not from mode). A split ships jsxDEV()
|
|
@@ -532,7 +591,7 @@ class ForgeCommand {
|
|
|
532
591
|
dedupe: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'],
|
|
533
592
|
},
|
|
534
593
|
build: {
|
|
535
|
-
outDir:
|
|
594
|
+
outDir: browserDir,
|
|
536
595
|
emptyOutDir: false,
|
|
537
596
|
rollupOptions: {
|
|
538
597
|
input: viewDef.entry,
|
|
@@ -541,7 +600,7 @@ class ForgeCommand {
|
|
|
541
600
|
// Name outputs by the view KEY, not the entry file's basename —
|
|
542
601
|
// the manifest and AppView resolve `${view}.bundle.js` / `${view}.css`,
|
|
543
602
|
// so an entry named index.tsx must still emit `${view}.*`.
|
|
544
|
-
// Other assets keep a hashed name: all views share
|
|
603
|
+
// Other assets keep a hashed name: all views share browserDir, so
|
|
545
604
|
// entry-derived names (e.g. index.css from two views) collide.
|
|
546
605
|
entryFileNames: `${view}.bundle.js`,
|
|
547
606
|
assetFileNames: (assetInfo) => assetInfo.name?.endsWith('.css') ? `${view}.css` : `[name]-[hash].[ext]`,
|
|
@@ -558,7 +617,8 @@ class ForgeCommand {
|
|
|
558
617
|
for (const fileName in bundle) {
|
|
559
618
|
const chunk = bundle[fileName];
|
|
560
619
|
if (chunk.type === 'chunk' && chunk.code) {
|
|
561
|
-
|
|
620
|
+
// The shell sets $forge.filesBase (same-origin /_app/...) before loading the bundle.
|
|
621
|
+
const runtimeBaseResolver = `const __ptklForgeBundleBase=()=>{const b=typeof window!=='undefined'&&window.$forge&&window.$forge.filesBase;if(!b)throw new Error('Forge shell did not provide filesBase');return b;};\n`;
|
|
562
622
|
chunk.code = runtimeBaseResolver + chunk.code;
|
|
563
623
|
// Transform dynamic imports in the final bundled code
|
|
564
624
|
chunk.code = chunk.code.replace(/import\(['`"]\.\/([^'`"]+)['`"]\)/g, `dynamicImport(__ptklForgeBundleBase() + '$1')`);
|
|
@@ -582,9 +642,9 @@ class ForgeCommand {
|
|
|
582
642
|
const result = await build({
|
|
583
643
|
root: path,
|
|
584
644
|
mode: mode ?? 'production',
|
|
585
|
-
base:
|
|
645
|
+
base: '/',
|
|
586
646
|
build: {
|
|
587
|
-
outDir:
|
|
647
|
+
outDir: serverDir,
|
|
588
648
|
emptyOutDir: false,
|
|
589
649
|
target: 'esnext',
|
|
590
650
|
rollupOptions: {
|
|
@@ -592,7 +652,11 @@ class ForgeCommand {
|
|
|
592
652
|
external: ['axios'],
|
|
593
653
|
output: {
|
|
594
654
|
format: 'esm',
|
|
595
|
-
|
|
655
|
+
// Named for the manifest KEY, not the entry file: the manifest records
|
|
656
|
+
// `${script}.script.js`, so `install: 'src/setup.ts'` emitted setup.script.js
|
|
657
|
+
// under a manifest that declared install.script.js — a file nothing could find,
|
|
658
|
+
// locally or at publish.
|
|
659
|
+
entryFileNames: `${script}.script.js`,
|
|
596
660
|
assetFileNames: (assetInfo) => {
|
|
597
661
|
return '[name].[ext]';
|
|
598
662
|
},
|
|
@@ -666,7 +730,7 @@ class ForgeCommand {
|
|
|
666
730
|
}
|
|
667
731
|
// Build service scripts
|
|
668
732
|
if (services && services.length > 0) {
|
|
669
|
-
const servicesDir = join(
|
|
733
|
+
const servicesDir = join(serverDir, 'services');
|
|
670
734
|
if (!existsSync(servicesDir)) {
|
|
671
735
|
mkdirSync(servicesDir, { recursive: true });
|
|
672
736
|
}
|
|
@@ -675,7 +739,7 @@ class ForgeCommand {
|
|
|
675
739
|
const result = await build({
|
|
676
740
|
root: path,
|
|
677
741
|
mode: mode ?? 'production',
|
|
678
|
-
base:
|
|
742
|
+
base: '/',
|
|
679
743
|
build: {
|
|
680
744
|
outDir: servicesDir,
|
|
681
745
|
emptyOutDir: false,
|
|
@@ -752,7 +816,7 @@ class ForgeCommand {
|
|
|
752
816
|
client.forge().bundleUpload(buffer).then(() => {
|
|
753
817
|
console.log('Bundle uploaded successfully');
|
|
754
818
|
}).catch((error) => {
|
|
755
|
-
console.error('\x1b[31m%s\x1b[0m', `Bundle upload failed: ${error.response?.data?.message || error.message}`);
|
|
819
|
+
console.error('\x1b[31m%s\x1b[0m', `Bundle upload failed: ${forbiddenDetails(error.response?.data) ?? (error.response?.data?.message || error.message)}`);
|
|
756
820
|
});
|
|
757
821
|
});
|
|
758
822
|
}
|
|
@@ -829,6 +893,17 @@ class ForgeCommand {
|
|
|
829
893
|
srv.on('error', reject);
|
|
830
894
|
});
|
|
831
895
|
}
|
|
896
|
+
// Two independent mints. The page is a view session and refreshes its own token in the
|
|
897
|
+
// browser, which a source-minted actor cannot do, so it is NOT source-minted. The service
|
|
898
|
+
// server runs submitted source and re-mints on 401/403 instead of refreshing.
|
|
899
|
+
const devEnv = env === 'live' ? 'live' : 'dev';
|
|
900
|
+
const pageToken = new ForgeDevToken(host, appName ?? '', devEnv, Util.getCurrentProfile().token, false);
|
|
901
|
+
const serviceToken = new ForgeDevToken(host, appName ?? '', devEnv, Util.getCurrentProfile().token, true);
|
|
902
|
+
// The page and services run as the app or not at all. The developer's token only mints.
|
|
903
|
+
if (!(await pageToken.current())) {
|
|
904
|
+
console.error(`❌ ${pageToken.failureMessage()}`);
|
|
905
|
+
process.exit(1);
|
|
906
|
+
}
|
|
832
907
|
// Start Vite dev server
|
|
833
908
|
const server = await createServer({
|
|
834
909
|
root: path,
|
|
@@ -850,7 +925,7 @@ class ForgeCommand {
|
|
|
850
925
|
DEV_HUB_PORT
|
|
851
926
|
},
|
|
852
927
|
plugins: [
|
|
853
|
-
forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT),
|
|
928
|
+
forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT, env ?? 'dev', host, pageToken),
|
|
854
929
|
kortexDevPlugin({
|
|
855
930
|
host,
|
|
856
931
|
token: Util.getCurrentProfile().token,
|
|
@@ -1014,10 +1089,8 @@ class ForgeCommand {
|
|
|
1014
1089
|
// --- Local service dev server ---
|
|
1015
1090
|
if (appName && services && services.length > 0) {
|
|
1016
1091
|
const os = await import('os');
|
|
1017
|
-
const http = await import('http');
|
|
1018
1092
|
const { join } = await import('path');
|
|
1019
1093
|
const { readFileSync, existsSync, mkdirSync } = await import('fs');
|
|
1020
|
-
const { randomUUID } = await import('crypto');
|
|
1021
1094
|
const profile = Util.getCurrentProfile();
|
|
1022
1095
|
const serviceDir = join(os.default.tmpdir(), `ptkl-dev-${appName}`, '_services');
|
|
1023
1096
|
mkdirSync(serviceDir, { recursive: true });
|
|
@@ -1090,124 +1163,17 @@ class ForgeCommand {
|
|
|
1090
1163
|
}
|
|
1091
1164
|
});
|
|
1092
1165
|
}
|
|
1093
|
-
// Build a lookup of service config by name
|
|
1094
|
-
const serviceConfig = {};
|
|
1095
|
-
for (const svc of services) {
|
|
1096
|
-
serviceConfig[svc.name] = svc;
|
|
1097
|
-
}
|
|
1098
1166
|
const SERVICE_PORT = servicePort;
|
|
1099
|
-
const
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
const url = new URL(req.url || '/', `http://localhost:${SERVICE_PORT}`);
|
|
1110
|
-
const serviceName = url.pathname.replace(/^\//, '').replace(/\/$/, '');
|
|
1111
|
-
if (!serviceName || serviceName === '') {
|
|
1112
|
-
// List available services
|
|
1113
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1114
|
-
res.end(JSON.stringify({
|
|
1115
|
-
app: appName,
|
|
1116
|
-
type: appType,
|
|
1117
|
-
services: services.map((s) => ({
|
|
1118
|
-
name: s.name,
|
|
1119
|
-
access: s.access || 'public',
|
|
1120
|
-
url: `http://localhost:${SERVICE_PORT}/${s.name}`,
|
|
1121
|
-
})),
|
|
1122
|
-
}, null, 2));
|
|
1123
|
-
return;
|
|
1124
|
-
}
|
|
1125
|
-
const code = serviceBundles[serviceName];
|
|
1126
|
-
if (!code) {
|
|
1127
|
-
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
1128
|
-
res.end(JSON.stringify({ error: `Service "${serviceName}" not found` }));
|
|
1129
|
-
return;
|
|
1130
|
-
}
|
|
1131
|
-
// Read request body
|
|
1132
|
-
const chunks = [];
|
|
1133
|
-
for await (const chunk of req)
|
|
1134
|
-
chunks.push(chunk);
|
|
1135
|
-
const rawBody = Buffer.concat(chunks).toString();
|
|
1136
|
-
let parsedBody = {};
|
|
1137
|
-
try {
|
|
1138
|
-
parsedBody = rawBody ? JSON.parse(rawBody) : {};
|
|
1139
|
-
}
|
|
1140
|
-
catch {
|
|
1141
|
-
parsedBody = rawBody;
|
|
1142
|
-
}
|
|
1143
|
-
// Parse query params
|
|
1144
|
-
const query = {};
|
|
1145
|
-
url.searchParams.forEach((v, k) => { query[k] = v; });
|
|
1146
|
-
// Build request headers object
|
|
1147
|
-
const reqHeaders = {};
|
|
1148
|
-
for (const [k, v] of Object.entries(req.headers)) {
|
|
1149
|
-
if (typeof v === 'string')
|
|
1150
|
-
reqHeaders[k] = v;
|
|
1151
|
-
}
|
|
1152
|
-
const svcConf = serviceConfig[serviceName];
|
|
1153
|
-
const executionId = randomUUID();
|
|
1154
|
-
console.log(`→ ${req.method} /${serviceName} (${executionId.slice(0, 8)})`);
|
|
1155
|
-
try {
|
|
1156
|
-
const evalResponse = await axios.post(`${profile.host}/luma/forge-runtime/api/services/exec`, {
|
|
1157
|
-
expression: code,
|
|
1158
|
-
project_uuid: 'dev',
|
|
1159
|
-
env: env ?? 'dev',
|
|
1160
|
-
actor: profile.token,
|
|
1161
|
-
context: {
|
|
1162
|
-
appUuid: `dev-${appName}`,
|
|
1163
|
-
appName,
|
|
1164
|
-
serviceName,
|
|
1165
|
-
executionId,
|
|
1166
|
-
access: svcConf?.access || 'public',
|
|
1167
|
-
},
|
|
1168
|
-
input: parsedBody,
|
|
1169
|
-
body: parsedBody,
|
|
1170
|
-
query,
|
|
1171
|
-
headers: reqHeaders,
|
|
1172
|
-
}, {
|
|
1173
|
-
headers: {
|
|
1174
|
-
'Content-Type': 'application/json',
|
|
1175
|
-
'Authorization': `Bearer ${profile.token}`,
|
|
1176
|
-
},
|
|
1177
|
-
timeout: 310000,
|
|
1178
|
-
validateStatus: () => true,
|
|
1179
|
-
});
|
|
1180
|
-
const data = evalResponse.data;
|
|
1181
|
-
if (data.logs?.length) {
|
|
1182
|
-
data.logs.forEach((log) => console.log(` 📋 [${serviceName}] ${log}`));
|
|
1183
|
-
}
|
|
1184
|
-
if (data.error) {
|
|
1185
|
-
res.writeHead(evalResponse.status || 500, { 'Content-Type': 'application/json' });
|
|
1186
|
-
res.end(JSON.stringify({ error: data.error, logs: data.logs }));
|
|
1187
|
-
console.log(` ❌ [${serviceName}] ${data.error}`);
|
|
1188
|
-
}
|
|
1189
|
-
else if (data.response) {
|
|
1190
|
-
const resp = data.response;
|
|
1191
|
-
const status = resp.statusCode || 200;
|
|
1192
|
-
const contentType = resp.contentType || 'application/json';
|
|
1193
|
-
res.writeHead(status, { 'Content-Type': contentType });
|
|
1194
|
-
res.end(typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body));
|
|
1195
|
-
console.log(` ✅ [${serviceName}] ${status} ${contentType}`);
|
|
1196
|
-
}
|
|
1197
|
-
else {
|
|
1198
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1199
|
-
res.end(JSON.stringify(data));
|
|
1200
|
-
console.log(` ✅ [${serviceName}] 200`);
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
catch (err) {
|
|
1204
|
-
const msg = err.response?.data?.message || err.message;
|
|
1205
|
-
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
1206
|
-
res.end(JSON.stringify({ error: `Eval server error: ${msg}` }));
|
|
1207
|
-
console.error(` ❌ [${serviceName}] ${msg}`);
|
|
1208
|
-
}
|
|
1209
|
-
});
|
|
1210
|
-
server.listen(SERVICE_PORT, () => {
|
|
1167
|
+
const serviceExec = new ForgeDevServiceExec(`${profile.host}/luma/forge-runtime/api/services/exec`, serviceToken, (url, body, config) => axios.post(url, body, config));
|
|
1168
|
+
new ForgeDevServiceServer({
|
|
1169
|
+
port: SERVICE_PORT,
|
|
1170
|
+
appName,
|
|
1171
|
+
appType,
|
|
1172
|
+
env: env ?? 'dev',
|
|
1173
|
+
services: services,
|
|
1174
|
+
bundles: serviceBundles,
|
|
1175
|
+
exec: serviceExec,
|
|
1176
|
+
}).listen(() => {
|
|
1211
1177
|
console.log(`\n⚡ Service dev server running at http://localhost:${SERVICE_PORT}`);
|
|
1212
1178
|
for (const svc of services) {
|
|
1213
1179
|
console.log(` POST http://localhost:${SERVICE_PORT}/${svc.name}`);
|
|
@@ -1381,7 +1347,12 @@ class ForgeCommand {
|
|
|
1381
1347
|
console.log(`No '${scriptType}' script defined in ptkl.config.js`);
|
|
1382
1348
|
return;
|
|
1383
1349
|
}
|
|
1384
|
-
|
|
1350
|
+
// distPath may be relative in ptkl.config.js; bundle() resolves it by chdir'ing into the app
|
|
1351
|
+
// dir first, and this runs from wherever the developer invoked ptkl.
|
|
1352
|
+
const dist = distPath
|
|
1353
|
+
? (isAbsolute(distPath) ? distPath : join(appPath, distPath))
|
|
1354
|
+
: join(appPath, 'dist');
|
|
1355
|
+
const scriptFile = bundleFilePath(dist, 'server', `${scriptType}.script.js`);
|
|
1385
1356
|
let scriptCode;
|
|
1386
1357
|
try {
|
|
1387
1358
|
scriptCode = readFileSync(scriptFile, 'utf-8');
|
|
@@ -2,6 +2,7 @@ import { Command } from "commander";
|
|
|
2
2
|
import { readFileSync } from "fs";
|
|
3
3
|
import { resolve } from "path";
|
|
4
4
|
import * as sdk from "../lib/sdk.js";
|
|
5
|
+
import RunIdentityService from "../lib/runIdentity.js";
|
|
5
6
|
import { registerCommand, withProfile } from "../lib/scaffold.js";
|
|
6
7
|
/** `ptkl functions` — platform function CRUD + invocation (RFC §6, "Functions").
|
|
7
8
|
* Maps onto the SDK `Functions` client (@ptkl/sdk/beta) for `list`/`get`/`update`/`run`/
|
|
@@ -44,7 +45,7 @@ class FunctionsCommand {
|
|
|
44
45
|
})));
|
|
45
46
|
cmd.addCommand(registerCommand(new Command("get")
|
|
46
47
|
.description("Get function")
|
|
47
|
-
.argument("<reference>", "Reference to the function which can be name, tag or uuid")).action(withProfile(async (profile, reference) => {
|
|
48
|
+
.argument("<reference>", "Reference to the function which can be name, tag or uuid")).action(withProfile(async (profile, reference, opts) => {
|
|
48
49
|
const res = await sdk.platform(profile).function().get(reference);
|
|
49
50
|
return res.data;
|
|
50
51
|
})));
|
|
@@ -61,21 +62,26 @@ class FunctionsCommand {
|
|
|
61
62
|
cmd.addCommand(registerCommand(new Command("create")
|
|
62
63
|
.description("Create a new function")
|
|
63
64
|
.option("-d, --data <data>", "Full create payload as JSON string (overrides --file)")
|
|
64
|
-
.option("-i, --file <file>", "Path to a JSON file containing the full create payload")
|
|
65
|
+
.option("-i, --file <file>", "Path to a JSON file containing the full create payload")
|
|
66
|
+
.option("--run-as <prn>", "Identity the function runs as (prompted for when interactive)")).action(withProfile(async (profile, opts) => {
|
|
65
67
|
const { data: dataStr, file } = opts;
|
|
66
68
|
const payload = readPayload("--data", dataStr, file);
|
|
67
69
|
const client = sdk.platform(profile).function();
|
|
68
|
-
const
|
|
70
|
+
const identity = new RunIdentityService(client.client);
|
|
71
|
+
const runAs = await identity.forCreate(opts.runAs);
|
|
72
|
+
const res = await client.client.post("/v1/system/function", identity.withRunAs(payload, runAs));
|
|
69
73
|
return res.data;
|
|
70
74
|
})));
|
|
71
75
|
cmd.addCommand(registerCommand(new Command("update")
|
|
72
76
|
.description("Update an existing function")
|
|
73
77
|
.argument("<uuid>", "UUID of the function to update")
|
|
74
78
|
.option("-d, --data <data>", "Fields to update, as a JSON object string (overrides --file)")
|
|
75
|
-
.option("-i, --file <file>", "Path to a JSON file containing the fields to update")
|
|
79
|
+
.option("-i, --file <file>", "Path to a JSON file containing the fields to update")
|
|
80
|
+
.option("--run-as <prn>", "Change the identity the function runs as")).action(withProfile(async (profile, uuid, opts) => {
|
|
76
81
|
const { data: dataStr, file } = opts;
|
|
77
82
|
const payload = readPayload("--data", dataStr, file);
|
|
78
|
-
const
|
|
83
|
+
const identity = new RunIdentityService();
|
|
84
|
+
const res = await sdk.platform(profile).function().update(uuid, identity.withRunAs(payload, opts.runAs));
|
|
79
85
|
return res.data;
|
|
80
86
|
})));
|
|
81
87
|
cmd.addCommand(registerCommand(new Command("signature")
|
|
@@ -71,7 +71,7 @@ class PaymentsCommand {
|
|
|
71
71
|
registerList() {
|
|
72
72
|
return registerCommand(new Command("list")
|
|
73
73
|
.description("List payment transactions for a user")
|
|
74
|
-
.
|
|
74
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
75
75
|
.option("-s, --status <status>", "Filter by transaction status")
|
|
76
76
|
.option("--sort-by <field>", "Field to sort by")
|
|
77
77
|
.option("--sort-direction <direction>", "Sort direction: asc | desc")
|
|
@@ -88,7 +88,7 @@ class PaymentsCommand {
|
|
|
88
88
|
page: opts.page !== undefined ? Number(opts.page) : undefined,
|
|
89
89
|
}
|
|
90
90
|
: undefined;
|
|
91
|
-
const res = await sdk.payments(profile).getTransactions(
|
|
91
|
+
const res = await sdk.payments(profile).getTransactions(params);
|
|
92
92
|
return res?.data ?? res;
|
|
93
93
|
}));
|
|
94
94
|
}
|
|
@@ -99,7 +99,7 @@ class PaymentsCommand {
|
|
|
99
99
|
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
100
100
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
101
101
|
await isActive(profile, "protokol-payments");
|
|
102
|
-
const res = await sdk.payments(profile).getTransaction(opts.
|
|
102
|
+
const res = await sdk.payments(profile).getTransaction(opts.tx);
|
|
103
103
|
return res?.data ?? res;
|
|
104
104
|
}));
|
|
105
105
|
}
|
|
@@ -109,6 +109,7 @@ class PaymentsCommand {
|
|
|
109
109
|
.addOption(providerOption())
|
|
110
110
|
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
111
111
|
.requiredOption("-d, --description <description>", "Payment description")
|
|
112
|
+
.requiredOption("--currency <code>", "3-letter currency code (e.g. EUR)")
|
|
112
113
|
.option("--token <token>", "Pre-existing tokenized card to charge, if any")
|
|
113
114
|
.option("--is-token-request", "Request tokenization of the card during payment")
|
|
114
115
|
.option("--redirect-url <url>", "URL to redirect to after payment")
|
|
@@ -117,6 +118,7 @@ class PaymentsCommand {
|
|
|
117
118
|
const res = await sdk.payments(profile).getPaymentLink(opts.provider, {
|
|
118
119
|
...parseAmount(opts),
|
|
119
120
|
description: opts.description,
|
|
121
|
+
currency: opts.currency,
|
|
120
122
|
...(opts.token ? { token: opts.token } : {}),
|
|
121
123
|
...(opts.isTokenRequest ? { isTokenRequest: true } : {}),
|
|
122
124
|
...(opts.redirectUrl ? { redirectUrl: opts.redirectUrl } : {}),
|
|
@@ -148,12 +150,14 @@ class PaymentsCommand {
|
|
|
148
150
|
.addOption(providerOption())
|
|
149
151
|
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
150
152
|
.requiredOption("--token <token>", "Tokenized card to charge")
|
|
151
|
-
.requiredOption("-d, --description <description>", "Payment description")
|
|
153
|
+
.requiredOption("-d, --description <description>", "Payment description")
|
|
154
|
+
.option("--currency <code>", "3-letter currency code (e.g. EUR)"))).action(withProfile(async (profile, opts) => {
|
|
152
155
|
await isActive(profile, "protokol-payments");
|
|
153
156
|
const res = await sdk.payments(profile).directPayUsingToken(opts.provider, {
|
|
154
157
|
...parseAmount(opts),
|
|
155
158
|
token: opts.token,
|
|
156
159
|
description: opts.description,
|
|
160
|
+
...(opts.currency ? { currency: opts.currency } : {}),
|
|
157
161
|
});
|
|
158
162
|
return res?.data ?? res;
|
|
159
163
|
}));
|
|
@@ -165,7 +169,7 @@ class PaymentsCommand {
|
|
|
165
169
|
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
166
170
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
167
171
|
await isActive(profile, "protokol-payments");
|
|
168
|
-
const res = await sdk.payments(profile).refund(opts.
|
|
172
|
+
const res = await sdk.payments(profile).refund(opts.tx);
|
|
169
173
|
return res?.data ?? res;
|
|
170
174
|
}));
|
|
171
175
|
}
|
|
@@ -176,7 +180,7 @@ class PaymentsCommand {
|
|
|
176
180
|
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
177
181
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
178
182
|
await isActive(profile, "protokol-payments");
|
|
179
|
-
const res = await sdk.payments(profile).voidTransaction(opts.
|
|
183
|
+
const res = await sdk.payments(profile).voidTransaction(opts.tx);
|
|
180
184
|
return res?.data ?? res;
|
|
181
185
|
}));
|
|
182
186
|
}
|
|
@@ -187,7 +191,7 @@ class PaymentsCommand {
|
|
|
187
191
|
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
188
192
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
189
193
|
await isActive(profile, "protokol-payments");
|
|
190
|
-
const res = await sdk.payments(profile).deactivatePaymentLink(opts.
|
|
194
|
+
const res = await sdk.payments(profile).deactivatePaymentLink(opts.tx);
|
|
191
195
|
return res?.data ?? res;
|
|
192
196
|
}));
|
|
193
197
|
}
|