@ptkl/toolkit 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -2
- package/dist/commands/forge.js +93 -4
- package/dist/commands/integrations/payments.js +22 -17
- package/dist/lib/kortexDevPlugin.js +523 -0
- package/package.json +1 -1
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
|
|
package/dist/commands/forge.js
CHANGED
|
@@ -8,6 +8,7 @@ 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 { kortexDevPlugin } from '../lib/kortexDevPlugin.js';
|
|
11
12
|
import * as sdk from "../lib/sdk.js";
|
|
12
13
|
import { registerCommand, withProfile } from "../lib/scaffold.js";
|
|
13
14
|
function parseJSON(label, raw) {
|
|
@@ -19,6 +20,76 @@ function parseJSON(label, raw) {
|
|
|
19
20
|
process.exit(1);
|
|
20
21
|
}
|
|
21
22
|
}
|
|
23
|
+
/** Values are JSON when they parse as JSON, otherwise the raw string —
|
|
24
|
+
* same convention as `ptkl forge variables add`. */
|
|
25
|
+
function parseVarValue(raw) {
|
|
26
|
+
try {
|
|
27
|
+
return JSON.parse(raw);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return raw;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** `KEY=value` → `{ KEY: <parsed value> }`. Splits on the FIRST `=` so values may contain `=`. */
|
|
34
|
+
function parseVarPair(pair, flag) {
|
|
35
|
+
const trimmed = pair.trim();
|
|
36
|
+
const eq = trimmed.indexOf('=');
|
|
37
|
+
if (eq < 1) {
|
|
38
|
+
console.error(`${flag} must be in KEY=value form (got '${pair}')`);
|
|
39
|
+
process.exit(1);
|
|
40
|
+
}
|
|
41
|
+
return [trimmed.slice(0, eq).trim(), parseVarValue(trimmed.slice(eq + 1))];
|
|
42
|
+
}
|
|
43
|
+
/** `--vars` payload: `KEY=value;KEY2=value2` (also accepts newline-separated). */
|
|
44
|
+
function parseVarList(list) {
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const pair of list.split(/[;\n]/)) {
|
|
47
|
+
if (!pair.trim())
|
|
48
|
+
continue;
|
|
49
|
+
const [key, value] = parseVarPair(pair, '--vars');
|
|
50
|
+
out[key] = value;
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Build the `$variables` map the local script run should see, mirroring what the
|
|
56
|
+
* platform injects from the app's stored variables (`app.variables[env]`).
|
|
57
|
+
*
|
|
58
|
+
* Sources, lowest precedence first:
|
|
59
|
+
* 1. `--vars-file <path>` — JSON, either a flat map or env-keyed (`{ dev: {...}, live: {...} }`)
|
|
60
|
+
* 2. `--vars KEY=v;KEY2=v2`
|
|
61
|
+
* 3. `--var KEY=v` (repeatable)
|
|
62
|
+
*/
|
|
63
|
+
function collectVariables(options, env) {
|
|
64
|
+
let fromFile = {};
|
|
65
|
+
if (options.varsFile) {
|
|
66
|
+
const filePath = isAbsolute(options.varsFile) ? options.varsFile : join(process.cwd(), options.varsFile);
|
|
67
|
+
if (!existsSync(filePath)) {
|
|
68
|
+
console.error(`--vars-file not found: ${filePath}`);
|
|
69
|
+
process.exit(1);
|
|
70
|
+
}
|
|
71
|
+
const parsed = parseJSON('--vars-file', readFileSync(filePath, 'utf-8'));
|
|
72
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
73
|
+
console.error(`--vars-file must contain a JSON object`);
|
|
74
|
+
process.exit(1);
|
|
75
|
+
}
|
|
76
|
+
// Env-keyed shape ({ dev: {...}, live: {...} }) mirrors how variables are stored
|
|
77
|
+
// on the app; anything else is treated as a flat map applied to every env.
|
|
78
|
+
const keys = Object.keys(parsed);
|
|
79
|
+
const envKeyed = keys.length > 0 && keys.every(k => (k === 'dev' || k === 'live') && parsed[k] && typeof parsed[k] === 'object' && !Array.isArray(parsed[k]));
|
|
80
|
+
fromFile = envKeyed ? (parsed[env] ?? {}) : parsed;
|
|
81
|
+
}
|
|
82
|
+
const fromList = (options.vars ?? []).reduce((acc, list) => ({ ...acc, ...parseVarList(list) }), {});
|
|
83
|
+
const fromPairs = (options.var ?? []).reduce((acc, pair) => {
|
|
84
|
+
const [key, value] = parseVarPair(pair, '--var');
|
|
85
|
+
return { ...acc, [key]: value };
|
|
86
|
+
}, {});
|
|
87
|
+
return { ...fromFile, ...fromList, ...fromPairs };
|
|
88
|
+
}
|
|
89
|
+
/** commander collector for repeatable options. */
|
|
90
|
+
function collect(value, previous = []) {
|
|
91
|
+
return previous.concat([value]);
|
|
92
|
+
}
|
|
22
93
|
function formatBuildError(reason) {
|
|
23
94
|
const lines = [];
|
|
24
95
|
if (reason.id || reason.loc) {
|
|
@@ -111,12 +182,18 @@ class ForgeCommand {
|
|
|
111
182
|
.requiredOption("-p, --path <path>", "Path to the app directory (where ptkl.config.js is located)")
|
|
112
183
|
.option("--env <env>", "Run for a specific env only (dev or live). Omit to run for both.")
|
|
113
184
|
.option("-b, --bundle", "Build the bundle before running the install script")
|
|
185
|
+
.option("--var <key=value>", "Set an app variable for the run ($variables). Repeatable.", collect)
|
|
186
|
+
.option("--vars <list>", "Set several app variables at once: 'KEY=value;KEY2=value2'. Repeatable.", collect)
|
|
187
|
+
.option("--vars-file <path>", "JSON file of app variables — flat map, or env-keyed { dev: {...}, live: {...} }")
|
|
114
188
|
.action((options) => this.install(options)))
|
|
115
189
|
.addCommand(new Command("uninstall")
|
|
116
190
|
.description("Dry-run the app uninstall script locally against the active profile (no actual uninstallation). Runs for both dev and live by default.")
|
|
117
191
|
.requiredOption("-p, --path <path>", "Path to the app directory (where ptkl.config.js is located)")
|
|
118
192
|
.option("--env <env>", "Run for a specific env only (dev or live). Omit to run for both.")
|
|
119
193
|
.option("-b, --bundle", "Build the bundle before running the uninstall script")
|
|
194
|
+
.option("--var <key=value>", "Set an app variable for the run ($variables). Repeatable.", collect)
|
|
195
|
+
.option("--vars <list>", "Set several app variables at once: 'KEY=value;KEY2=value2'. Repeatable.", collect)
|
|
196
|
+
.option("--vars-file <path>", "JSON file of app variables — flat map, or env-keyed { dev: {...}, live: {...} }")
|
|
120
197
|
.action((options) => this.uninstall(options)))
|
|
121
198
|
// --- Deployed-app management (appservice) -------------------------------------------
|
|
122
199
|
// These subcommands use the shared scaffold (src/lib/sdk.ts + src/lib/scaffold.ts) and
|
|
@@ -698,6 +775,7 @@ class ForgeCommand {
|
|
|
698
775
|
},
|
|
699
776
|
plugins: [
|
|
700
777
|
forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT),
|
|
778
|
+
kortexDevPlugin(),
|
|
701
779
|
{
|
|
702
780
|
// Console bridge (dev only): when the app runs EMBEDDED (e.g. the
|
|
703
781
|
// Studio's Preview iframe), forward console output + uncaught errors
|
|
@@ -1200,7 +1278,7 @@ class ForgeCommand {
|
|
|
1200
1278
|
await this.bundle({ path, upload: false });
|
|
1201
1279
|
const envs = env ? [env] : ['dev', 'live'];
|
|
1202
1280
|
for (const e of envs) {
|
|
1203
|
-
await ForgeCommand._runScript(path, 'install', e);
|
|
1281
|
+
await ForgeCommand._runScript(path, 'install', e, collectVariables(options, e));
|
|
1204
1282
|
}
|
|
1205
1283
|
}
|
|
1206
1284
|
async uninstall(options) {
|
|
@@ -1210,10 +1288,10 @@ class ForgeCommand {
|
|
|
1210
1288
|
await this.bundle({ path, upload: false });
|
|
1211
1289
|
const envs = env ? [env] : ['dev', 'live'];
|
|
1212
1290
|
for (const e of envs) {
|
|
1213
|
-
await ForgeCommand._runScript(path, 'uninstall', e);
|
|
1291
|
+
await ForgeCommand._runScript(path, 'uninstall', e, collectVariables(options, e));
|
|
1214
1292
|
}
|
|
1215
1293
|
}
|
|
1216
|
-
static async _runScript(appPath, scriptType, env = 'dev') {
|
|
1294
|
+
static async _runScript(appPath, scriptType, env = 'dev', variables = {}) {
|
|
1217
1295
|
appPath = isAbsolute(appPath) ? appPath : join(process.cwd(), appPath);
|
|
1218
1296
|
const module = await import(`${appPath}/ptkl.config.js`);
|
|
1219
1297
|
const { name, distPath, scripts } = module.default ?? {};
|
|
@@ -1241,7 +1319,16 @@ class ForgeCommand {
|
|
|
1241
1319
|
}
|
|
1242
1320
|
};
|
|
1243
1321
|
global.axiosAdapter = axios;
|
|
1244
|
-
|
|
1322
|
+
// In the platform runtime the sandbox is seeded with the app's stored variables for
|
|
1323
|
+
// the env being installed (`app.variables[env]` → `$variables`). Locally there is no
|
|
1324
|
+
// app record yet, so the variables come from --var/--vars/--vars-file.
|
|
1325
|
+
global.$variables = variables;
|
|
1326
|
+
global.$currentEnv = env;
|
|
1327
|
+
const varKeys = Object.keys(variables);
|
|
1328
|
+
console.log(`Running ${scriptType} script for '${name}' (profile: ${profile.name}, env: ${env})...`);
|
|
1329
|
+
console.log(varKeys.length
|
|
1330
|
+
? `$variables: ${varKeys.join(', ')}\n`
|
|
1331
|
+
: `$variables: none — pass --var KEY=value to inject them\n`);
|
|
1245
1332
|
// The bundle is: `return async()=>{try{ ...code... }catch(err){return {_error_:true,...}}}`
|
|
1246
1333
|
// new Function(scriptCode) creates a function whose body is that code.
|
|
1247
1334
|
// Calling it returns the async function, which we then await.
|
|
@@ -1250,6 +1337,8 @@ class ForgeCommand {
|
|
|
1250
1337
|
// Cleanup globals
|
|
1251
1338
|
delete global.window;
|
|
1252
1339
|
delete global.axiosAdapter;
|
|
1340
|
+
delete global.$variables;
|
|
1341
|
+
delete global.$currentEnv;
|
|
1253
1342
|
if (result && result._error_) {
|
|
1254
1343
|
const displayMessage = result?.response?.data?.message || result.message ||
|
|
1255
1344
|
(result.errors && result.errors.length > 0
|
|
@@ -3,11 +3,16 @@ import * as sdk from "../../lib/sdk.js";
|
|
|
3
3
|
import { registerCommand, withProfile } from "../../lib/scaffold.js";
|
|
4
4
|
import { integrationSub, isActive } from "../integration.js";
|
|
5
5
|
/** `ptkl integration payments` — typed interface onto the `protokol-payments` integration (RFC
|
|
6
|
-
* §4.3 / §6.1, layer 2). `ptkl integration payments refund --provider monri --
|
|
7
|
-
* is literally `new Integrations({profile}).getPayments().refund('monri',
|
|
8
|
-
* `/karadjordje/v1/payment/monri/
|
|
6
|
+
* §4.3 / §6.1, layer 2). `ptkl integration payments refund --provider monri --tx <T>`
|
|
7
|
+
* is literally `new Integrations({profile}).getPayments().refund('monri', T)` ->
|
|
8
|
+
* `/karadjordje/v1/payment/monri/refund/{T}` — reached here via `sdk.payments(profile)`
|
|
9
9
|
* (src/lib/sdk.ts), which builds the same `Payments` client against the integrations gateway.
|
|
10
10
|
*
|
|
11
|
+
* `--user`/`-u` is deprecated and ignored: the backend never accepted a userId in the URL
|
|
12
|
+
* (it resolves the caller from the request's project identity), so the SDK dropped the
|
|
13
|
+
* parameter. The flag is kept optional here purely so existing scripts passing `-u` don't
|
|
14
|
+
* break with an "unknown option" error; the value is accepted and discarded.
|
|
15
|
+
*
|
|
11
16
|
* Every subcommand pre-checks `isActive('protokol-payments')` (see ../integration.ts) so an
|
|
12
17
|
* installed-but-inactive integration fails with a friendly hint instead of a raw 403. */
|
|
13
18
|
// The SDK's `PaymentProvider` type (@ptkl/sdk/beta, types/integrations/payments.ts) currently only
|
|
@@ -91,10 +96,10 @@ class PaymentsCommand {
|
|
|
91
96
|
return registerCommand(new Command("get")
|
|
92
97
|
.description("Get a single payment transaction")
|
|
93
98
|
.addOption(providerOption())
|
|
94
|
-
.
|
|
99
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
95
100
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
96
101
|
await isActive(profile, "protokol-payments");
|
|
97
|
-
const res = await sdk.payments(profile).getTransaction(opts.provider, opts.
|
|
102
|
+
const res = await sdk.payments(profile).getTransaction(opts.provider, opts.tx);
|
|
98
103
|
return res?.data ?? res;
|
|
99
104
|
}));
|
|
100
105
|
}
|
|
@@ -102,14 +107,14 @@ class PaymentsCommand {
|
|
|
102
107
|
return registerCommand(amountOptions(new Command("link")
|
|
103
108
|
.description("Create a payment link")
|
|
104
109
|
.addOption(providerOption())
|
|
105
|
-
.
|
|
110
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
106
111
|
.requiredOption("-d, --description <description>", "Payment description")
|
|
107
112
|
.option("--token <token>", "Pre-existing tokenized card to charge, if any")
|
|
108
113
|
.option("--is-token-request", "Request tokenization of the card during payment")
|
|
109
114
|
.option("--redirect-url <url>", "URL to redirect to after payment")
|
|
110
115
|
.option("--lang <lang>", "Payment page language: en | es | ba | hr"))).action(withProfile(async (profile, opts) => {
|
|
111
116
|
await isActive(profile, "protokol-payments");
|
|
112
|
-
const res = await sdk.payments(profile).getPaymentLink(opts.provider,
|
|
117
|
+
const res = await sdk.payments(profile).getPaymentLink(opts.provider, {
|
|
113
118
|
...parseAmount(opts),
|
|
114
119
|
description: opts.description,
|
|
115
120
|
...(opts.token ? { token: opts.token } : {}),
|
|
@@ -124,12 +129,12 @@ class PaymentsCommand {
|
|
|
124
129
|
return registerCommand(new Command("token-request")
|
|
125
130
|
.description("Create a token-request link (tokenize a card without charging it)")
|
|
126
131
|
.addOption(providerOption())
|
|
127
|
-
.
|
|
132
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
128
133
|
.requiredOption("-d, --description <description>", "Description shown on the payment page")
|
|
129
134
|
.option("--redirect-url <url>", "URL to redirect to after tokenization")
|
|
130
135
|
.option("--lang <lang>", "Payment page language: en | es | ba | hr")).action(withProfile(async (profile, opts) => {
|
|
131
136
|
await isActive(profile, "protokol-payments");
|
|
132
|
-
const res = await sdk.payments(profile).getTokenRequestLink(opts.provider,
|
|
137
|
+
const res = await sdk.payments(profile).getTokenRequestLink(opts.provider, {
|
|
133
138
|
description: opts.description,
|
|
134
139
|
...(opts.redirectUrl ? { redirectUrl: opts.redirectUrl } : {}),
|
|
135
140
|
...(opts.lang ? { lang: opts.lang } : {}),
|
|
@@ -141,11 +146,11 @@ class PaymentsCommand {
|
|
|
141
146
|
return registerCommand(amountOptions(new Command("direct-pay")
|
|
142
147
|
.description("Charge a previously tokenized card directly (no redirect)")
|
|
143
148
|
.addOption(providerOption())
|
|
144
|
-
.
|
|
149
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
145
150
|
.requiredOption("--token <token>", "Tokenized card to charge")
|
|
146
151
|
.requiredOption("-d, --description <description>", "Payment description"))).action(withProfile(async (profile, opts) => {
|
|
147
152
|
await isActive(profile, "protokol-payments");
|
|
148
|
-
const res = await sdk.payments(profile).directPayUsingToken(opts.provider,
|
|
153
|
+
const res = await sdk.payments(profile).directPayUsingToken(opts.provider, {
|
|
149
154
|
...parseAmount(opts),
|
|
150
155
|
token: opts.token,
|
|
151
156
|
description: opts.description,
|
|
@@ -157,10 +162,10 @@ class PaymentsCommand {
|
|
|
157
162
|
return registerCommand(new Command("refund")
|
|
158
163
|
.description("Refund a payment transaction")
|
|
159
164
|
.addOption(providerOption())
|
|
160
|
-
.
|
|
165
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
161
166
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
162
167
|
await isActive(profile, "protokol-payments");
|
|
163
|
-
const res = await sdk.payments(profile).refund(opts.provider, opts.
|
|
168
|
+
const res = await sdk.payments(profile).refund(opts.provider, opts.tx);
|
|
164
169
|
return res?.data ?? res;
|
|
165
170
|
}));
|
|
166
171
|
}
|
|
@@ -168,10 +173,10 @@ class PaymentsCommand {
|
|
|
168
173
|
return registerCommand(new Command("void")
|
|
169
174
|
.description("Void a payment transaction")
|
|
170
175
|
.addOption(providerOption())
|
|
171
|
-
.
|
|
176
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
172
177
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
173
178
|
await isActive(profile, "protokol-payments");
|
|
174
|
-
const res = await sdk.payments(profile).voidTransaction(opts.provider, opts.
|
|
179
|
+
const res = await sdk.payments(profile).voidTransaction(opts.provider, opts.tx);
|
|
175
180
|
return res?.data ?? res;
|
|
176
181
|
}));
|
|
177
182
|
}
|
|
@@ -179,10 +184,10 @@ class PaymentsCommand {
|
|
|
179
184
|
return registerCommand(new Command("cancel")
|
|
180
185
|
.description("Cancel (deactivate) a payment link")
|
|
181
186
|
.addOption(providerOption())
|
|
182
|
-
.
|
|
187
|
+
.option("-u, --user <userId>", "Deprecated, no longer used")
|
|
183
188
|
.requiredOption("-t, --tx <transactionId>", "Transaction id")).action(withProfile(async (profile, opts) => {
|
|
184
189
|
await isActive(profile, "protokol-payments");
|
|
185
|
-
const res = await sdk.payments(profile).deactivatePaymentLink(opts.provider, opts.
|
|
190
|
+
const res = await sdk.payments(profile).deactivatePaymentLink(opts.provider, opts.tx);
|
|
186
191
|
return res?.data ?? res;
|
|
187
192
|
}));
|
|
188
193
|
}
|
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vite plugin that polyfills `window.kortex` during `ptkl forge dev` and
|
|
3
|
+
* injects a developer tools panel for inspecting registered Kortex tools.
|
|
4
|
+
*
|
|
5
|
+
* In production the platform-forge runtime provides the real `window.kortex`,
|
|
6
|
+
* but during local development it's absent — so all `registerTool()` /
|
|
7
|
+
* `useKortexTool()` calls silently no-op. This plugin closes that gap:
|
|
8
|
+
*
|
|
9
|
+
* 1. Polyfills `window.kortex` with a fully functional KortexAPI that stores
|
|
10
|
+
* every registered tool, just like production.
|
|
11
|
+
* 2. Injects a floating DevTools overlay so developers can see every
|
|
12
|
+
* registered tool, its schema, policy, and page context in real time.
|
|
13
|
+
* 3. Includes a tool tester — invoke any tool with custom JSON arguments
|
|
14
|
+
* and inspect the return value or error.
|
|
15
|
+
*/
|
|
16
|
+
export function kortexDevPlugin() {
|
|
17
|
+
// ── Polyfill script (runs BEFORE the app) ──────────────────────────
|
|
18
|
+
const polyfillScript = `(function(){
|
|
19
|
+
if (window.kortex) return; // already provided (e.g. by the real platform runtime)
|
|
20
|
+
|
|
21
|
+
var _tools = [];
|
|
22
|
+
var _context = null;
|
|
23
|
+
var _helperActive = false;
|
|
24
|
+
var _listeners = [];
|
|
25
|
+
|
|
26
|
+
function notify() {
|
|
27
|
+
for (var i = 0; i < _listeners.length; i++) _listeners[i]();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
window.kortex = {
|
|
31
|
+
get tools() { return _tools; },
|
|
32
|
+
|
|
33
|
+
_context: null,
|
|
34
|
+
_helperActive: false,
|
|
35
|
+
|
|
36
|
+
registerTool: function (schema, executeFn, policy) {
|
|
37
|
+
// Remove any existing tool with the same name
|
|
38
|
+
var name = schema && schema.function && schema.function.name;
|
|
39
|
+
if (name) {
|
|
40
|
+
for (var i = _tools.length - 1; i >= 0; i--) {
|
|
41
|
+
if (_tools[i].schema.function.name === name) _tools.splice(i, 1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
_tools.push({
|
|
45
|
+
schema: schema,
|
|
46
|
+
execute: executeFn,
|
|
47
|
+
policy: policy || {}
|
|
48
|
+
});
|
|
49
|
+
_context = window.kortex._context;
|
|
50
|
+
_helperActive = window.kortex._helperActive;
|
|
51
|
+
notify();
|
|
52
|
+
console.log('[kortex dev] tool registered:', (name || '(unnamed)'),
|
|
53
|
+
'(total:', _tools.length + ')');
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
unregisterTool: function (name) {
|
|
57
|
+
for (var i = _tools.length - 1; i >= 0; i--) {
|
|
58
|
+
if (_tools[i].schema.function.name === name) {
|
|
59
|
+
_tools.splice(i, 1);
|
|
60
|
+
notify();
|
|
61
|
+
console.log('[kortex dev] tool unregistered:', name,
|
|
62
|
+
'(total:', _tools.length + ')');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
registerContext: function (label, description, icon) {
|
|
69
|
+
window.kortex._context = { label: label, description: description || '', icon: icon || null };
|
|
70
|
+
_context = window.kortex._context;
|
|
71
|
+
notify();
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
unregisterContext: function () {
|
|
75
|
+
window.kortex._context = null;
|
|
76
|
+
_context = null;
|
|
77
|
+
notify();
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
showHelper: function () {
|
|
81
|
+
window.kortex._helperActive = true;
|
|
82
|
+
_helperActive = true;
|
|
83
|
+
notify();
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
hideHelper: function () {
|
|
87
|
+
window.kortex._helperActive = false;
|
|
88
|
+
_helperActive = false;
|
|
89
|
+
notify();
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
// Internal: subscribe to changes (used by the devtools panel)
|
|
93
|
+
_subscribe: function (fn) {
|
|
94
|
+
_listeners.push(fn);
|
|
95
|
+
return function () {
|
|
96
|
+
var idx = _listeners.indexOf(fn);
|
|
97
|
+
if (idx >= 0) _listeners.splice(idx, 1);
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// Keep _context and _helperActive getters in sync
|
|
103
|
+
Object.defineProperty(window.kortex, '_context', {
|
|
104
|
+
get: function () { return _context; },
|
|
105
|
+
set: function (v) { _context = v; },
|
|
106
|
+
enumerable: true, configurable: true
|
|
107
|
+
});
|
|
108
|
+
Object.defineProperty(window.kortex, '_helperActive', {
|
|
109
|
+
get: function () { return _helperActive; },
|
|
110
|
+
set: function (v) { _helperActive = v; },
|
|
111
|
+
enumerable: true, configurable: true
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
console.log('[ptkl forge dev] kortex polyfill ready');
|
|
115
|
+
})();`;
|
|
116
|
+
// ── DevTools panel script (runs AFTER the polyfill) ────────────────
|
|
117
|
+
const devtoolsScript = `(function(){
|
|
118
|
+
if (window.__KORTEX_DEVTOOLS_LOADED) return;
|
|
119
|
+
window.__KORTEX_DEVTOOLS_LOADED = true;
|
|
120
|
+
|
|
121
|
+
// Wait for kortex polyfill
|
|
122
|
+
function waitForKortex(cb) {
|
|
123
|
+
if (window.kortex) { cb(); return; }
|
|
124
|
+
var tries = 0;
|
|
125
|
+
var iv = setInterval(function () {
|
|
126
|
+
if (window.kortex || ++tries > 50) { clearInterval(iv); if (window.kortex) cb(); }
|
|
127
|
+
}, 100);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
waitForKortex(function () {
|
|
131
|
+
|
|
132
|
+
// ── Styles ──────────────────────────────────────────────
|
|
133
|
+
var style = document.createElement('style');
|
|
134
|
+
style.textContent = [
|
|
135
|
+
'@keyframes ktx-slide-up { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }',
|
|
136
|
+
'@keyframes ktx-fade-in { from { opacity: 0; } to { opacity: 1; } }',
|
|
137
|
+
'@keyframes ktx-pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.12); } }',
|
|
138
|
+
'.ktx-btn {',
|
|
139
|
+
' position: fixed; bottom: 16px; right: 16px; z-index: 99990;',
|
|
140
|
+
' display: flex; align-items: center; gap: 6px;',
|
|
141
|
+
' padding: 8px 14px; border-radius: 20px; border: 1px solid rgba(255,255,255,0.12);',
|
|
142
|
+
' background: #1e1e2e; color: #cdd6f4; cursor: pointer;',
|
|
143
|
+
' font-family: system-ui, -apple-system, sans-serif; font-size: 13px; font-weight: 500;',
|
|
144
|
+
' box-shadow: 0 4px 24px rgba(0,0,0,0.4); transition: box-shadow 0.2s, background 0.2s;',
|
|
145
|
+
' user-select: none;',
|
|
146
|
+
'}',
|
|
147
|
+
'.ktx-btn:hover { background: #313244; box-shadow: 0 6px 32px rgba(0,0,0,0.5); }',
|
|
148
|
+
'.ktx-badge {',
|
|
149
|
+
' display: inline-flex; align-items: center; justify-content: center;',
|
|
150
|
+
' min-width: 20px; height: 20px; border-radius: 10px;',
|
|
151
|
+
' background: #cba6f7; color: #1e1e2e; font-size: 11px; font-weight: 700;',
|
|
152
|
+
' padding: 0 6px;',
|
|
153
|
+
'}',
|
|
154
|
+
'.ktx-badge:empty { display: none; }',
|
|
155
|
+
'.ktx-panel {',
|
|
156
|
+
' position: fixed; bottom: 60px; right: 16px; z-index: 99989;',
|
|
157
|
+
' width: 520px; max-height: 480px;',
|
|
158
|
+
' border-radius: 12px; border: 1px solid rgba(255,255,255,0.1);',
|
|
159
|
+
' background: #1e1e2e; color: #cdd6f4;',
|
|
160
|
+
' box-shadow: 0 8px 40px rgba(0,0,0,0.5);',
|
|
161
|
+
' font-family: system-ui, -apple-system, sans-serif; font-size: 13px;',
|
|
162
|
+
' display: none; flex-direction: column; overflow: hidden;',
|
|
163
|
+
' animation: ktx-slide-up 0.2s ease-out;',
|
|
164
|
+
'}',
|
|
165
|
+
'.ktx-panel.open { display: flex; }',
|
|
166
|
+
'.ktx-panel-header {',
|
|
167
|
+
' display: flex; align-items: center; justify-content: space-between;',
|
|
168
|
+
' padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,0.08);',
|
|
169
|
+
' background: #181825; flex-shrink: 0;',
|
|
170
|
+
'}',
|
|
171
|
+
'.ktx-panel-title { font-weight: 600; font-size: 14px; display: flex; align-items: center; gap: 8px; }',
|
|
172
|
+
'.ktx-tabs { display: flex; gap: 2px; }',
|
|
173
|
+
'.ktx-tab {',
|
|
174
|
+
' padding: 5px 12px; border-radius: 6px; border: none; cursor: pointer;',
|
|
175
|
+
' background: transparent; color: #a6adc8; font-size: 12px; font-family: inherit;',
|
|
176
|
+
' transition: background 0.15s, color 0.15s;',
|
|
177
|
+
'}',
|
|
178
|
+
'.ktx-tab:hover { background: #313244; color: #cdd6f4; }',
|
|
179
|
+
'.ktx-tab.active { background: #45475a; color: #cdd6f4; }',
|
|
180
|
+
'.ktx-panel-body {',
|
|
181
|
+
' flex: 1; overflow-y: auto; padding: 8px 14px;',
|
|
182
|
+
' scrollbar-width: thin; scrollbar-color: #45475a transparent;',
|
|
183
|
+
'}',
|
|
184
|
+
'.ktx-panel-body::-webkit-scrollbar { width: 6px; }',
|
|
185
|
+
'.ktx-panel-body::-webkit-scrollbar-thumb { background: #45475a; border-radius: 3px; }',
|
|
186
|
+
'.ktx-empty {',
|
|
187
|
+
' text-align: center; padding: 32px 16px; color: #585b70;',
|
|
188
|
+
'}',
|
|
189
|
+
'.ktx-tool-card {',
|
|
190
|
+
' border: 1px solid rgba(255,255,255,0.06); border-radius: 8px;',
|
|
191
|
+
' margin-bottom: 8px; background: #181825; overflow: hidden;',
|
|
192
|
+
'}',
|
|
193
|
+
'.ktx-tool-card-header {',
|
|
194
|
+
' display: flex; align-items: center; justify-content: space-between;',
|
|
195
|
+
' padding: 8px 12px; cursor: pointer; user-select: none;',
|
|
196
|
+
' transition: background 0.15s;',
|
|
197
|
+
'}',
|
|
198
|
+
'.ktx-tool-card-header:hover { background: #313244; }',
|
|
199
|
+
'.ktx-tool-name { font-weight: 600; font-size: 13px; color: #cba6f7; }',
|
|
200
|
+
'.ktx-tool-desc { font-size: 12px; color: #a6adc8; margin-top: 2px; }',
|
|
201
|
+
'.ktx-tool-meta { display: flex; gap: 6px; align-items: center; flex-shrink: 0; }',
|
|
202
|
+
'.ktx-tag {',
|
|
203
|
+
' display: inline-block; padding: 2px 7px; border-radius: 4px;',
|
|
204
|
+
' font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;',
|
|
205
|
+
'}',
|
|
206
|
+
'.ktx-tag-risk-low { background: rgba(166,227,161,0.15); color: #a6e3a1; }',
|
|
207
|
+
'.ktx-tag-risk-medium { background: rgba(249,226,175,0.15); color: #f9e2af; }',
|
|
208
|
+
'.ktx-tag-risk-high { background: rgba(243,139,168,0.15); color: #f38ba8; }',
|
|
209
|
+
'.ktx-tag-confirm { background: rgba(203,166,247,0.15); color: #cba6f7; }',
|
|
210
|
+
'.ktx-tool-card-body {',
|
|
211
|
+
' display: none; padding: 10px 12px; border-top: 1px solid rgba(255,255,255,0.06);',
|
|
212
|
+
' background: #11111b;',
|
|
213
|
+
'}',
|
|
214
|
+
'.ktx-tool-card.expanded .ktx-tool-card-body { display: block; }',
|
|
215
|
+
'.ktx-params {',
|
|
216
|
+
' font-family: "SF Mono", "Cascadia Code", "Fira Code", monospace;',
|
|
217
|
+
' font-size: 11px; background: #181825; padding: 10px; border-radius: 6px;',
|
|
218
|
+
' overflow-x: auto; white-space: pre; color: #a6adc8;',
|
|
219
|
+
' max-height: 160px; overflow-y: auto;',
|
|
220
|
+
'}',
|
|
221
|
+
'.ktx-section-label {',
|
|
222
|
+
' font-size: 11px; font-weight: 600; color: #585b70;',
|
|
223
|
+
' text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px; margin-top: 10px;',
|
|
224
|
+
'}',
|
|
225
|
+
'.ktx-section-label:first-child { margin-top: 0; }',
|
|
226
|
+
'.ktx-test-btn {',
|
|
227
|
+
' display: inline-flex; align-items: center; gap: 4px;',
|
|
228
|
+
' padding: 4px 10px; border-radius: 5px; border: 1px solid rgba(255,255,255,0.1);',
|
|
229
|
+
' background: #313244; color: #cdd6f4; cursor: pointer;',
|
|
230
|
+
' font-size: 11px; font-family: inherit; margin-top: 8px; transition: background 0.15s;',
|
|
231
|
+
'}',
|
|
232
|
+
'.ktx-test-btn:hover { background: #45475a; }',
|
|
233
|
+
'.ktx-test-area {',
|
|
234
|
+
' margin-top: 8px; border-top: 1px solid rgba(255,255,255,0.06); padding-top: 8px;',
|
|
235
|
+
'}',
|
|
236
|
+
'.ktx-test-input {',
|
|
237
|
+
' width: 100%; box-sizing: border-box; min-height: 60px;',
|
|
238
|
+
' background: #181825; border: 1px solid rgba(255,255,255,0.1); border-radius: 6px;',
|
|
239
|
+
' color: #cdd6f4; padding: 8px; font-size: 12px; font-family: monospace;',
|
|
240
|
+
' resize: vertical;',
|
|
241
|
+
'}',
|
|
242
|
+
'.ktx-test-input:focus { outline: none; border-color: #cba6f7; }',
|
|
243
|
+
'.ktx-test-result {',
|
|
244
|
+
' margin-top: 6px; padding: 8px; border-radius: 6px;',
|
|
245
|
+
' font-size: 11px; font-family: monospace; max-height: 120px; overflow-y: auto;',
|
|
246
|
+
' white-space: pre-wrap; word-break: break-all;',
|
|
247
|
+
'}',
|
|
248
|
+
'.ktx-test-result.success { background: rgba(166,227,161,0.08); color: #a6e3a1; border: 1px solid rgba(166,227,161,0.15); }',
|
|
249
|
+
'.ktx-test-result.error { background: rgba(243,139,168,0.08); color: #f38ba8; border: 1px solid rgba(243,139,168,0.15); }',
|
|
250
|
+
'.ktx-close-btn {',
|
|
251
|
+
' border: none; background: none; color: #585b70; cursor: pointer;',
|
|
252
|
+
' font-size: 18px; line-height: 1; padding: 0 4px; transition: color 0.15s;',
|
|
253
|
+
'}',
|
|
254
|
+
'.ktx-close-btn:hover { color: #cdd6f4; }',
|
|
255
|
+
'.ktx-chevron { font-size: 12px; color: #585b70; transition: transform 0.2s; }',
|
|
256
|
+
'.ktx-tool-card.expanded .ktx-chevron { transform: rotate(180deg); }',
|
|
257
|
+
'.ktx-context-card {',
|
|
258
|
+
' border: 1px solid rgba(255,255,255,0.06); border-radius: 8px;',
|
|
259
|
+
' padding: 12px; background: #181825;',
|
|
260
|
+
'}',
|
|
261
|
+
'.ktx-context-label { font-weight: 600; color: #cba6f7; }',
|
|
262
|
+
'.ktx-context-desc { color: #a6adc8; font-size: 12px; margin-top: 4px; }',
|
|
263
|
+
].join('\\n');
|
|
264
|
+
document.head.appendChild(style);
|
|
265
|
+
|
|
266
|
+
// ── DOM ──────────────────────────────────────────────────
|
|
267
|
+
var open = false;
|
|
268
|
+
var activeTab = 'tools';
|
|
269
|
+
|
|
270
|
+
// Toggle button
|
|
271
|
+
var btn = document.createElement('button');
|
|
272
|
+
btn.className = 'ktx-btn';
|
|
273
|
+
btn.innerHTML = '\\uD83D\\uDEE0 Kortex <span class="ktx-badge" id="ktx-badge"></span>';
|
|
274
|
+
btn.onclick = function () {
|
|
275
|
+
open = !open;
|
|
276
|
+
panel.className = 'ktx-panel' + (open ? ' open' : '');
|
|
277
|
+
render();
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
// Panel
|
|
281
|
+
var panel = document.createElement('div');
|
|
282
|
+
panel.className = 'ktx-panel';
|
|
283
|
+
panel.innerHTML = [
|
|
284
|
+
'<div class="ktx-panel-header">',
|
|
285
|
+
' <div class="ktx-panel-title">\\uD83D\\uDEE0 Kortex DevTools</div>',
|
|
286
|
+
' <div class="ktx-tabs">',
|
|
287
|
+
' <button class="ktx-tab active" data-tab="tools">Tools (<span id="ktx-tool-count">0</span>)</button>',
|
|
288
|
+
' <button class="ktx-tab" data-tab="context">Context</button>',
|
|
289
|
+
' </div>',
|
|
290
|
+
' <button class="ktx-close-btn" id="ktx-close">×</button>',
|
|
291
|
+
'</div>',
|
|
292
|
+
'<div class="ktx-panel-body" id="ktx-body"></div>',
|
|
293
|
+
].join('');
|
|
294
|
+
|
|
295
|
+
// Close button
|
|
296
|
+
panel.querySelector('#ktx-close').onclick = function (e) {
|
|
297
|
+
e.stopPropagation();
|
|
298
|
+
open = false;
|
|
299
|
+
panel.className = 'ktx-panel';
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
// Tab switching
|
|
303
|
+
panel.querySelectorAll('.ktx-tab').forEach(function (tab) {
|
|
304
|
+
tab.onclick = function (e) {
|
|
305
|
+
e.stopPropagation();
|
|
306
|
+
activeTab = tab.dataset.tab;
|
|
307
|
+
render();
|
|
308
|
+
};
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
document.body.appendChild(btn);
|
|
312
|
+
document.body.appendChild(panel);
|
|
313
|
+
|
|
314
|
+
// ── Render ───────────────────────────────────────────────
|
|
315
|
+
function getTools() {
|
|
316
|
+
return (window.kortex && window.kortex.tools) ? window.kortex.tools : [];
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function getContext() {
|
|
320
|
+
return (window.kortex && window.kortex._context) ? window.kortex._context : null;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function render() {
|
|
324
|
+
var tools = getTools();
|
|
325
|
+
var ctx = getContext();
|
|
326
|
+
|
|
327
|
+
// Badge
|
|
328
|
+
var badge = document.getElementById('ktx-badge');
|
|
329
|
+
if (badge) badge.textContent = tools.length || '';
|
|
330
|
+
|
|
331
|
+
// Tab counts
|
|
332
|
+
var toolCountEl = document.getElementById('ktx-tool-count');
|
|
333
|
+
if (toolCountEl) toolCountEl.textContent = tools.length;
|
|
334
|
+
|
|
335
|
+
// Tabs
|
|
336
|
+
panel.querySelectorAll('.ktx-tab').forEach(function (t) {
|
|
337
|
+
t.className = 'ktx-tab' + (t.dataset.tab === activeTab ? ' active' : '');
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
// Body
|
|
341
|
+
var body = document.getElementById('ktx-body');
|
|
342
|
+
if (!body) return;
|
|
343
|
+
|
|
344
|
+
if (activeTab === 'tools') {
|
|
345
|
+
renderTools(body, tools);
|
|
346
|
+
} else {
|
|
347
|
+
renderContext(body, ctx);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function renderTools(body, tools) {
|
|
352
|
+
if (tools.length === 0) {
|
|
353
|
+
body.innerHTML = '<div class="ktx-empty">No tools registered yet.<br><span style="font-size:11px">Call <code>registerTool()</code> or <code>useKortexTool()</code> from your app.</span></div>';
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
var html = '';
|
|
358
|
+
for (var i = 0; i < tools.length; i++) {
|
|
359
|
+
var t = tools[i];
|
|
360
|
+
var name = t.schema && t.schema.function ? t.schema.function.name : '(unnamed)';
|
|
361
|
+
var desc = (t.schema && t.schema.function && t.schema.function.description) || '';
|
|
362
|
+
var params = (t.schema && t.schema.function && t.schema.function.parameters) || null;
|
|
363
|
+
var policy = t.policy || {};
|
|
364
|
+
var risk = policy.risk || '';
|
|
365
|
+
var needsConfirm = policy.requiresConfirmation;
|
|
366
|
+
var category = policy.category || '';
|
|
367
|
+
|
|
368
|
+
var tags = '';
|
|
369
|
+
if (risk) {
|
|
370
|
+
var riskClass = 'ktx-tag-risk-' + risk;
|
|
371
|
+
tags += '<span class="ktx-tag ' + riskClass + '">' + risk + '</span>';
|
|
372
|
+
}
|
|
373
|
+
if (needsConfirm) {
|
|
374
|
+
tags += '<span class="ktx-tag ktx-tag-confirm">confirm</span>';
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
html += '<div class="ktx-tool-card" data-idx="' + i + '">';
|
|
378
|
+
html += '<div class="ktx-tool-card-header" onclick="(function(el){ var card=el.closest(\\'.ktx-tool-card\\'); card.classList.toggle(\\'expanded\\'); })(this)">';
|
|
379
|
+
html += '<div><div class="ktx-tool-name">' + esc(name) + '</div>';
|
|
380
|
+
if (desc) html += '<div class="ktx-tool-desc">' + esc(desc.slice(0, 80)) + (desc.length > 80 ? '...' : '') + '</div>';
|
|
381
|
+
html += '</div>';
|
|
382
|
+
html += '<div class="ktx-tool-meta">' + tags + '<span class="ktx-chevron">\\u25BC</span></div>';
|
|
383
|
+
html += '</div>';
|
|
384
|
+
|
|
385
|
+
// Expanded body
|
|
386
|
+
html += '<div class="ktx-tool-card-body">';
|
|
387
|
+
if (desc) html += '<div class="ktx-section-label">Description</div><div style="font-size:12px;color:#a6adc8">' + esc(desc) + '</div>';
|
|
388
|
+
if (category) html += '<div class="ktx-section-label">Category</div><div style="font-size:12px;color:#a6adc8">' + esc(category) + '</div>';
|
|
389
|
+
if (params) {
|
|
390
|
+
html += '<div class="ktx-section-label">Parameters Schema</div>';
|
|
391
|
+
html += '<div class="ktx-params">' + esc(JSON.stringify(params, null, 2)) + '</div>';
|
|
392
|
+
}
|
|
393
|
+
html += '<button class="ktx-test-btn" onclick="(function(el){ var card=el.closest(\\'.ktx-tool-card\\'); var idx=parseInt(card.dataset.idx); window.__ktx_testTool(idx, card); })(this)">\\u25B6 Test</button>';
|
|
394
|
+
html += '<div class="ktx-test-area" style="display:none">';
|
|
395
|
+
html += '<textarea class="ktx-test-input" placeholder=\\'{\"key\": \"value\"}\\' rows="3"></textarea>';
|
|
396
|
+
html += '<div style="display:flex;gap:6px;margin-top:6px">';
|
|
397
|
+
html += '<button class="ktx-test-btn" onclick="(function(el){ var card=el.closest(\\'.ktx-tool-card\\'); var idx=parseInt(card.dataset.idx); window.__ktx_runTest(idx, card); })(this)">Run</button>';
|
|
398
|
+
html += '<button class="ktx-test-btn" style="background:transparent" onclick="(function(el){ var area=el.closest(\\'.ktx-test-area\\'); area.style.display=\\'none\\'; var res=area.querySelector(\\'.ktx-test-result\\'); if(res)res.remove(); })(this)">Cancel</button>';
|
|
399
|
+
html += '</div>';
|
|
400
|
+
html += '</div>';
|
|
401
|
+
html += '</div>'; // ktx-tool-card-body
|
|
402
|
+
|
|
403
|
+
html += '</div>'; // ktx-tool-card
|
|
404
|
+
}
|
|
405
|
+
body.innerHTML = html;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function renderContext(body, ctx) {
|
|
409
|
+
if (!ctx) {
|
|
410
|
+
body.innerHTML = '<div class="ktx-empty">No page context registered.<br><span style="font-size:11px">Call <code>registerContext()</code> or <code>useKortexContext()</code> from your app.</span></div>';
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
var html = '<div class="ktx-context-card">';
|
|
414
|
+
html += '<div class="ktx-context-label">' + esc(ctx.label) + '</div>';
|
|
415
|
+
if (ctx.description) html += '<div class="ktx-context-desc">' + esc(ctx.description) + '</div>';
|
|
416
|
+
if (ctx.icon) html += '<div style="margin-top:8px;font-size:11px;color:#585b70">Icon: ' + esc(ctx.icon) + '</div>';
|
|
417
|
+
html += '</div>';
|
|
418
|
+
body.innerHTML = html;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function esc(s) {
|
|
422
|
+
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// ── Tool testing ─────────────────────────────────────────
|
|
426
|
+
window.__ktx_testTool = function (idx, card) {
|
|
427
|
+
var area = card.querySelector('.ktx-test-area');
|
|
428
|
+
if (!area) return;
|
|
429
|
+
var showing = area.style.display !== 'none';
|
|
430
|
+
area.style.display = showing ? 'none' : 'block';
|
|
431
|
+
// Clear previous result
|
|
432
|
+
var prevResult = area.querySelector('.ktx-test-result');
|
|
433
|
+
if (prevResult) prevResult.remove();
|
|
434
|
+
// Focus the input
|
|
435
|
+
if (!showing) {
|
|
436
|
+
var input = area.querySelector('.ktx-test-input');
|
|
437
|
+
if (input) setTimeout(function () { input.focus(); }, 50);
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
window.__ktx_runTest = function (idx, card) {
|
|
442
|
+
var tools = getTools();
|
|
443
|
+
var tool = tools[idx];
|
|
444
|
+
if (!tool) return;
|
|
445
|
+
|
|
446
|
+
var area = card.querySelector('.ktx-test-area');
|
|
447
|
+
var input = area.querySelector('.ktx-test-input');
|
|
448
|
+
var prevResult = area.querySelector('.ktx-test-result');
|
|
449
|
+
if (prevResult) prevResult.remove();
|
|
450
|
+
|
|
451
|
+
var args;
|
|
452
|
+
try {
|
|
453
|
+
args = input.value.trim() ? JSON.parse(input.value) : {};
|
|
454
|
+
} catch (e) {
|
|
455
|
+
showResult(area, 'Invalid JSON: ' + e.message, false);
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
try {
|
|
460
|
+
var result = tool.execute(args);
|
|
461
|
+
if (result && typeof result.then === 'function') {
|
|
462
|
+
result.then(
|
|
463
|
+
function (v) { showResult(area, JSON.stringify(v, null, 2), true); },
|
|
464
|
+
function (e) { showResult(area, 'Error: ' + (e && e.message ? e.message : String(e)), false); }
|
|
465
|
+
);
|
|
466
|
+
} else {
|
|
467
|
+
showResult(area, JSON.stringify(result, null, 2), true);
|
|
468
|
+
}
|
|
469
|
+
} catch (e) {
|
|
470
|
+
showResult(area, 'Error: ' + (e && e.message ? e.message : String(e)), false);
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
function showResult(area, text, success) {
|
|
475
|
+
var div = document.createElement('div');
|
|
476
|
+
div.className = 'ktx-test-result ' + (success ? 'success' : 'error');
|
|
477
|
+
div.textContent = text;
|
|
478
|
+
area.appendChild(div);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// ── Subscribe to changes ─────────────────────────────────
|
|
482
|
+
if (window.kortex._subscribe) {
|
|
483
|
+
window.kortex._subscribe(function () {
|
|
484
|
+
if (open) render();
|
|
485
|
+
// Always update the badge
|
|
486
|
+
var badge = document.getElementById('ktx-badge');
|
|
487
|
+
if (badge) {
|
|
488
|
+
var tools = getTools();
|
|
489
|
+
badge.textContent = tools.length || '';
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// Initial render for badge
|
|
495
|
+
var badge = document.getElementById('ktx-badge');
|
|
496
|
+
if (badge) {
|
|
497
|
+
var tools = getTools();
|
|
498
|
+
badge.textContent = tools.length || '';
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
console.log('[ptkl forge dev] Kortex DevTools ready \\u2014 click the \\uD83D\\uDEE0 button to inspect registered tools');
|
|
502
|
+
});
|
|
503
|
+
})();`;
|
|
504
|
+
return {
|
|
505
|
+
name: 'ptkl-kortex-dev',
|
|
506
|
+
transformIndexHtml() {
|
|
507
|
+
return [
|
|
508
|
+
{
|
|
509
|
+
tag: 'script',
|
|
510
|
+
attrs: { type: 'text/javascript' },
|
|
511
|
+
children: polyfillScript,
|
|
512
|
+
injectTo: 'head-prepend',
|
|
513
|
+
},
|
|
514
|
+
{
|
|
515
|
+
tag: 'script',
|
|
516
|
+
attrs: { type: 'text/javascript' },
|
|
517
|
+
children: devtoolsScript,
|
|
518
|
+
injectTo: 'body',
|
|
519
|
+
},
|
|
520
|
+
];
|
|
521
|
+
},
|
|
522
|
+
};
|
|
523
|
+
}
|