@revenexx/integrations-node-devkit 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -28,15 +28,194 @@ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${_
28
28
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
29
 
30
30
  // src/cli.ts
31
- var import_node_fs5 = require("fs");
31
+ var import_node_fs8 = require("fs");
32
32
  var import_node_http2 = require("http");
33
33
  var import_node_module = require("module");
34
- var import_node_path4 = require("path");
35
- var import_node_url2 = require("url");
34
+ var import_node_path7 = require("path");
35
+ var import_node_url3 = require("url");
36
36
 
37
- // src/env.ts
37
+ // src/cli-args.ts
38
38
  var import_node_fs = require("fs");
39
39
  var import_node_path = require("path");
40
+
41
+ // src/errors.ts
42
+ var DevApiError = class extends Error {
43
+ constructor(status, message, errors) {
44
+ super(message);
45
+ this.status = status;
46
+ this.errors = errors;
47
+ this.name = "DevApiError";
48
+ }
49
+ status;
50
+ errors;
51
+ };
52
+ var CliError = class extends Error {
53
+ constructor(message) {
54
+ super(message);
55
+ this.name = "CliError";
56
+ }
57
+ };
58
+
59
+ // src/ports.ts
60
+ var import_node_net = require("net");
61
+ var DEFAULT_LIMIT = 20;
62
+ async function listenWithFallback(server, options) {
63
+ const limit = options.strict ? 1 : options.limit ?? DEFAULT_LIMIT;
64
+ const first = options.port;
65
+ for (let port = first; port < first + limit; port += 1) {
66
+ const bound = await bind(server, port);
67
+ if (bound !== null) {
68
+ return bound;
69
+ }
70
+ }
71
+ throw options.strict ? new CliError(`Port ${first} is already in use. Stop whatever is holding it, or pass a different --port.`) : new CliError(`No free port between ${first} and ${first + limit - 1}. Pass --port <n> to choose one explicitly.`);
72
+ }
73
+ function bind(server, port) {
74
+ return new Promise((resolvePort, reject) => {
75
+ const onError = (err) => {
76
+ server.removeListener("listening", onListening);
77
+ if (err.code === "EADDRINUSE") {
78
+ resolvePort(null);
79
+ return;
80
+ }
81
+ reject(err);
82
+ };
83
+ const onListening = () => {
84
+ server.removeListener("error", onError);
85
+ const address = server.address();
86
+ resolvePort(typeof address === "object" && address !== null ? address.port : port);
87
+ };
88
+ server.once("error", onError);
89
+ server.once("listening", onListening);
90
+ server.listen(port);
91
+ });
92
+ }
93
+ async function findFreePort(base, limit = DEFAULT_LIMIT) {
94
+ for (let port = base; port < base + limit; port += 1) {
95
+ if (await isFree(port)) {
96
+ return port;
97
+ }
98
+ }
99
+ throw new CliError(`No free port between ${base} and ${base + limit - 1} for the preview UI.`);
100
+ }
101
+ function isFree(port) {
102
+ return new Promise((resolveFree) => {
103
+ const probe = (0, import_node_net.createServer)();
104
+ probe.once("error", () => resolveFree(false));
105
+ probe.once("listening", () => probe.close(() => resolveFree(true)));
106
+ probe.listen(port);
107
+ });
108
+ }
109
+ function parsePort(value, flag) {
110
+ if (value === void 0 || value.startsWith("-")) {
111
+ throw new CliError(`${flag} needs a port number, e.g. \`${flag} 4000\`.`);
112
+ }
113
+ const port = Number(value);
114
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
115
+ throw new CliError(`${flag} expects an integer between 1 and 65535, got \`${value}\`.`);
116
+ }
117
+ return port;
118
+ }
119
+
120
+ // src/cli-args.ts
121
+ var DEFAULT_PORT = 3555;
122
+ function parseArgs(argv, env = process.env) {
123
+ const cwd = process.cwd();
124
+ const opts = {
125
+ entry: "",
126
+ seedDir: (0, import_node_path.resolve)(cwd, "dev/seeds"),
127
+ stateFile: (0, import_node_path.resolve)(cwd, ".revenexx-dev/state.json"),
128
+ persist: true,
129
+ port: env.PORT === void 0 ? DEFAULT_PORT : parsePort(env.PORT, "$PORT"),
130
+ portExplicit: env.PORT !== void 0,
131
+ uiDir: null,
132
+ serveUi: true,
133
+ open: false,
134
+ previewDir: null,
135
+ force: false,
136
+ parallel: false
137
+ };
138
+ let command = null;
139
+ for (let i = 0; i < argv.length; i++) {
140
+ const arg = argv[i];
141
+ switch (arg) {
142
+ case "reset":
143
+ command = "reset";
144
+ break;
145
+ case "init-preview":
146
+ command = "init-preview";
147
+ break;
148
+ case "preview":
149
+ command = "preview";
150
+ break;
151
+ case "--dir":
152
+ opts.previewDir = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
153
+ break;
154
+ case "--force":
155
+ opts.force = true;
156
+ break;
157
+ case "--parallel":
158
+ opts.parallel = true;
159
+ break;
160
+ case "--entry":
161
+ opts.entry = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
162
+ break;
163
+ case "--seed":
164
+ opts.seedDir = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
165
+ break;
166
+ case "--state":
167
+ opts.stateFile = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
168
+ break;
169
+ case "--no-persist":
170
+ opts.persist = false;
171
+ break;
172
+ case "--port":
173
+ opts.port = parsePort(argv[++i], "--port");
174
+ opts.portExplicit = true;
175
+ break;
176
+ case "--ui":
177
+ opts.uiDir = (0, import_node_path.resolve)(cwd, argv[++i] ?? "");
178
+ break;
179
+ case "--no-ui":
180
+ opts.serveUi = false;
181
+ break;
182
+ case "--open":
183
+ opts.open = true;
184
+ break;
185
+ // Both are consumed by loadEnvFile() before parsing; listed here so they
186
+ // do not fall through to the unknown-option branch. A repeated `--env`
187
+ // resolves to the last one, so each occurrence skips its own value.
188
+ case "--env":
189
+ i++;
190
+ break;
191
+ case "--no-env":
192
+ break;
193
+ case "--version":
194
+ case "-v":
195
+ command = "version";
196
+ break;
197
+ default:
198
+ if (arg?.startsWith("--env-file")) {
199
+ if (!arg.includes("=")) {
200
+ i++;
201
+ }
202
+ break;
203
+ }
204
+ if (arg?.startsWith("-")) {
205
+ throw new CliError(`Unknown option: ${arg}`);
206
+ }
207
+ }
208
+ }
209
+ if (!opts.entry) {
210
+ const src = (0, import_node_path.resolve)(cwd, "src/index.ts");
211
+ opts.entry = (0, import_node_fs.existsSync)(src) ? src : (0, import_node_path.resolve)(cwd, "dist/index.js");
212
+ }
213
+ return { command, options: opts };
214
+ }
215
+
216
+ // src/env.ts
217
+ var import_node_fs2 = require("fs");
218
+ var import_node_path2 = require("path");
40
219
  var ENV_FILE_MIN_NODE = "20.12";
41
220
  var NODE_OWNED_FLAGS = ["--env-file", "--env-file-if-exists"];
42
221
  function nodeOwnedEnvFlag(argv) {
@@ -55,13 +234,13 @@ function resolveEnvFile(argv, cwd = process.cwd()) {
55
234
  if (!value || value.startsWith("-")) {
56
235
  throw new Error("--env requires a path.");
57
236
  }
58
- named = { path: (0, import_node_path.resolve)(cwd, value), explicit: true, raw: value };
237
+ named = { path: (0, import_node_path2.resolve)(cwd, value), explicit: true, raw: value };
59
238
  }
60
- return named ?? { path: (0, import_node_path.resolve)(cwd, ".env"), explicit: false };
239
+ return named ?? { path: (0, import_node_path2.resolve)(cwd, ".env"), explicit: false };
61
240
  }
62
241
  function missingFileMessage(choice, cwd) {
63
242
  const raw = choice.raw;
64
- if (raw && raw === (0, import_node_path.basename)(raw) && (0, import_node_fs.existsSync)((0, import_node_path.resolve)(cwd, `.env.${raw}`))) {
243
+ if (raw && raw === (0, import_node_path2.basename)(raw) && (0, import_node_fs2.existsSync)((0, import_node_path2.resolve)(cwd, `.env.${raw}`))) {
65
244
  return `--env: ${choice.path} does not exist. Did you mean --env .env.${raw}? The flag takes a path, not an environment name.`;
66
245
  }
67
246
  return `--env: ${choice.path} does not exist.`;
@@ -76,7 +255,7 @@ function loadEnvFile(argv, options = {}) {
76
255
  if (!choice.path) {
77
256
  return null;
78
257
  }
79
- if (!(0, import_node_fs.existsSync)(choice.path)) {
258
+ if (!(0, import_node_fs2.existsSync)(choice.path)) {
80
259
  if (choice.explicit) {
81
260
  throw new Error(missingFileMessage(choice, cwd));
82
261
  }
@@ -91,24 +270,34 @@ function loadEnvFile(argv, options = {}) {
91
270
  }
92
271
 
93
272
  // src/index.ts
94
- var import_node_fs3 = require("fs");
95
-
96
- // src/errors.ts
97
- var DevApiError = class extends Error {
98
- constructor(status, message, errors) {
99
- super(message);
100
- this.status = status;
101
- this.errors = errors;
102
- this.name = "DevApiError";
103
- }
104
- status;
105
- errors;
106
- };
273
+ var import_node_fs5 = require("fs");
107
274
 
108
275
  // src/loader.ts
276
+ var import_node_fs3 = require("fs");
277
+ var import_node_path3 = require("path");
109
278
  var import_node_url = require("url");
110
279
  var import_integrations_node_sdk = require("@revenexx/integrations-node-sdk");
111
- function resolveExports(mod) {
280
+ var UNKNOWN_PACKAGE = { name: "unknown", version: "0.0.0", label: "Local package" };
281
+ function readPackageInfo(entryPath) {
282
+ let dir = (0, import_node_path3.dirname)(entryPath);
283
+ for (let up = 0; up < 6; up += 1) {
284
+ const candidate = (0, import_node_path3.join)(dir, "package.json");
285
+ if ((0, import_node_fs3.existsSync)(candidate)) {
286
+ try {
287
+ const pkg = JSON.parse((0, import_node_fs3.readFileSync)(candidate, "utf-8"));
288
+ if (pkg.name) {
289
+ return { name: pkg.name, version: pkg.version ?? "0.0.0", label: pkg.name.split("/").pop() ?? pkg.name };
290
+ }
291
+ } catch {
292
+ }
293
+ }
294
+ const parent = (0, import_node_path3.dirname)(dir);
295
+ if (parent === dir) break;
296
+ dir = parent;
297
+ }
298
+ return UNKNOWN_PACKAGE;
299
+ }
300
+ function resolveExports(mod, packageInfo = UNKNOWN_PACKAGE) {
112
301
  if (!Array.isArray(mod.NODES)) {
113
302
  throw new Error("Package entry does not export a `NODES` array. Export `NODES: INode[]`.");
114
303
  }
@@ -125,7 +314,9 @@ function resolveExports(mod) {
125
314
  nodes,
126
315
  credentials,
127
316
  templates,
128
- manifest: (0, import_integrations_node_sdk.buildManifest)(nodes, credentials, templates)
317
+ manifest: (0, import_integrations_node_sdk.buildManifest)(nodes, credentials, templates),
318
+ packageInfo,
319
+ loadedAt: (/* @__PURE__ */ new Date()).toISOString()
129
320
  };
130
321
  }
131
322
  var tsxRegistered = false;
@@ -137,6 +328,10 @@ async function ensureTsxRegistered() {
137
328
  register();
138
329
  tsxRegistered = true;
139
330
  }
331
+ var RELOADABLE_SOURCE = /\.(?:[cm]?[jt]sx?|json)$/;
332
+ function isReloadableSource(file) {
333
+ return RELOADABLE_SOURCE.test(file);
334
+ }
140
335
  async function importFresh(entryPath) {
141
336
  if (/\.[cm]?tsx?$/.test(entryPath)) {
142
337
  await ensureTsxRegistered();
@@ -145,17 +340,19 @@ async function importFresh(entryPath) {
145
340
  return await import(href);
146
341
  }
147
342
  async function loadPackageFromEntry(entryPath) {
148
- return resolveExports(await importFresh(entryPath));
343
+ return resolveExports(await importFresh(entryPath), readPackageInfo(entryPath));
149
344
  }
150
345
 
151
346
  // src/persistence.ts
152
- var import_node_fs2 = require("fs");
153
- var import_node_path2 = require("path");
347
+ var import_node_fs4 = require("fs");
348
+ var import_node_path4 = require("path");
154
349
 
155
350
  // src/store.ts
156
351
  var import_node_crypto = require("crypto");
157
352
  var DEV_TENANT_ID = "dev-tenant";
158
- var STORE_SCHEMA_VERSION = 1;
353
+ var BLOB_DEFINITION_VERSION = "v0-draft";
354
+ var EXECUTION_MODES = ["async_only", "sync_only", "caller_decides"];
355
+ var STORE_SCHEMA_VERSION = 2;
159
356
  function now() {
160
357
  return (/* @__PURE__ */ new Date()).toISOString();
161
358
  }
@@ -198,6 +395,9 @@ var DevStore = class {
198
395
  status: input.status ?? "active",
199
396
  config: input.config,
200
397
  durableCreds: input.durableCreds ?? null,
398
+ lastTestAt: null,
399
+ lastTestOk: null,
400
+ lastTestMessage: null,
201
401
  createdAt: ts,
202
402
  updatedAt: ts
203
403
  };
@@ -226,6 +426,21 @@ var DevStore = class {
226
426
  this.touch();
227
427
  return record;
228
428
  }
429
+ /**
430
+ * Records the outcome of a credential test. The service persists this on the
431
+ * record and reports it back from `POST /credentials/{id}/test`.
432
+ */
433
+ recordCredentialTest(id, result) {
434
+ const record = this.credentials.get(id);
435
+ if (!record) {
436
+ return void 0;
437
+ }
438
+ record.lastTestAt = now();
439
+ record.lastTestOk = result.ok;
440
+ record.lastTestMessage = result.message ?? null;
441
+ this.touch();
442
+ return record;
443
+ }
229
444
  deleteCredential(id) {
230
445
  const deleted = this.credentials.delete(id);
231
446
  if (deleted) {
@@ -272,7 +487,12 @@ var DevStore = class {
272
487
  const record = {
273
488
  id: this.nextWorkflowId++,
274
489
  name: input.name,
275
- definition: input.definition,
490
+ description: input.description ?? null,
491
+ blob: input.blob,
492
+ blobDefinitionVersion: input.blobDefinitionVersion ?? BLOB_DEFINITION_VERSION,
493
+ active: input.active ?? true,
494
+ executionMode: input.executionMode ?? EXECUTION_MODES[0],
495
+ revision: 1,
276
496
  buildStatus: "ready",
277
497
  createdAt: ts,
278
498
  updatedAt: ts
@@ -286,7 +506,8 @@ var DevStore = class {
286
506
  if (!record) {
287
507
  return void 0;
288
508
  }
289
- Object.assign(record, patch, { updatedAt: now() });
509
+ const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== void 0));
510
+ Object.assign(record, defined, { revision: record.revision + 1, updatedAt: now() });
290
511
  this.touch();
291
512
  return record;
292
513
  }
@@ -427,16 +648,23 @@ function applySeeds(store, seeds, env = process.env) {
427
648
  });
428
649
  }
429
650
  for (const workflow of seeds.workflows ?? []) {
430
- store.createWorkflow(interpolateEnv(workflow, env));
651
+ const resolved = interpolateEnv(workflow, env);
652
+ store.createWorkflow({
653
+ name: resolved.name,
654
+ blob: resolved.blob ?? resolved.definition ?? {},
655
+ description: resolved.description,
656
+ active: resolved.active,
657
+ executionMode: resolved.executionMode
658
+ });
431
659
  }
432
660
  }
433
661
  function loadState(file, log = console.warn) {
434
- if (!(0, import_node_fs2.existsSync)(file)) {
662
+ if (!(0, import_node_fs4.existsSync)(file)) {
435
663
  return null;
436
664
  }
437
665
  let parsed;
438
666
  try {
439
- parsed = JSON.parse((0, import_node_fs2.readFileSync)(file, "utf-8"));
667
+ parsed = JSON.parse((0, import_node_fs4.readFileSync)(file, "utf-8"));
440
668
  } catch {
441
669
  log(`Ignoring ${file}: not valid JSON.`);
442
670
  return null;
@@ -448,14 +676,14 @@ function loadState(file, log = console.warn) {
448
676
  return parsed;
449
677
  }
450
678
  function saveState(file, snapshot) {
451
- (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(file), { recursive: true });
452
- (0, import_node_fs2.writeFileSync)(file, JSON.stringify(snapshot, null, 2), "utf-8");
679
+ (0, import_node_fs4.mkdirSync)((0, import_node_path4.dirname)(file), { recursive: true });
680
+ (0, import_node_fs4.writeFileSync)(file, JSON.stringify(snapshot, null, 2), "utf-8");
453
681
  }
454
682
  var SEED_ENTRY_CANDIDATES = ["index.ts", "index.mjs", "index.js", "seeds.ts", "seeds.js"];
455
683
  async function loadSeedsFromDir(dir) {
456
684
  for (const candidate of SEED_ENTRY_CANDIDATES) {
457
- const path = (0, import_node_path2.resolve)(dir, candidate);
458
- if ((0, import_node_fs2.existsSync)(path)) {
685
+ const path = (0, import_node_path4.resolve)(dir, candidate);
686
+ if ((0, import_node_fs4.existsSync)(path)) {
459
687
  const mod = await importFresh(path);
460
688
  return mod.default ?? mod.seeds ?? {};
461
689
  }
@@ -721,6 +949,56 @@ async function validateNodeConfig(loaded, store, input) {
721
949
  }
722
950
  return { valid: Object.keys(errors).length === 0, errors };
723
951
  }
952
+ var MIN_TIMEOUT_MS = 1e3;
953
+ var DEFAULT_TIMEOUT_MS = 3e4;
954
+ var ExecuteTimeout = class extends Error {
955
+ };
956
+ async function executeNodeTest(loaded, store, input) {
957
+ const node = findNode(loaded, input.slug, input.version);
958
+ const logs = [];
959
+ const record = (level) => (message, meta) => {
960
+ logs.push(meta === void 0 ? { level, message } : { level, message, meta });
961
+ };
962
+ const timeoutMs = Math.max(MIN_TIMEOUT_MS, input.timeoutMs ?? DEFAULT_TIMEOUT_MS);
963
+ const controller = new AbortController();
964
+ let timer;
965
+ const expired = new Promise((_resolve, reject) => {
966
+ timer = setTimeout(() => {
967
+ controller.abort();
968
+ reject(new ExecuteTimeout());
969
+ }, timeoutMs);
970
+ });
971
+ const ctx = {
972
+ signal: controller.signal,
973
+ logger: { info: record("info"), warn: record("warn"), error: record("error") },
974
+ secrets: {
975
+ async get(key) {
976
+ const secret = store.getSecret(key);
977
+ if (!secret) {
978
+ throw new DevApiError(404, `Secret '${key}' not found.`);
979
+ }
980
+ return secret.value;
981
+ }
982
+ },
983
+ credentials: {
984
+ async get(id) {
985
+ return (await resolveCredentialInstance(loaded, store, id)).credentials;
986
+ }
987
+ }
988
+ };
989
+ try {
990
+ const result = await Promise.race([node.execute(ctx, { ...input.config, ...input.inputs }), expired]);
991
+ return { outputs: result.outputs ?? {}, branch: result.branch ?? null, logs };
992
+ } catch (err) {
993
+ if (err instanceof DevApiError) {
994
+ throw err;
995
+ }
996
+ const reason = err instanceof ExecuteTimeout || controller.signal.aborted ? `timed out after ${timeoutMs} ms` : err.message;
997
+ throw new DevApiError(502, `Node execution failed: ${reason}`, { logs: logs.map((l) => `${l.level}: ${l.message}`) });
998
+ } finally {
999
+ clearTimeout(timer);
1000
+ }
1001
+ }
724
1002
  async function testCredentialConfig(loaded, store, typeSlug, config) {
725
1003
  const cred = findCredential(loaded, typeSlug);
726
1004
  return cred.test(credentialContext(store), config);
@@ -762,16 +1040,22 @@ async function exchangeOAuthCode(loaded, store, credentialId, params) {
762
1040
  var import_node_http = __toESM(require("http"), 1);
763
1041
 
764
1042
  // src/http.ts
1043
+ var API_VERSION = "1.0.0";
1044
+ var BASE_HEADERS = {
1045
+ "X-Api-Version": API_VERSION,
1046
+ "Access-Control-Allow-Origin": "*",
1047
+ "Access-Control-Allow-Headers": "*",
1048
+ "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS"
1049
+ };
765
1050
  function sendJson(res, status, body) {
766
1051
  const payload = JSON.stringify(body);
767
- res.writeHead(status, {
768
- "Content-Type": "application/json",
769
- "Access-Control-Allow-Origin": "*",
770
- "Access-Control-Allow-Headers": "*",
771
- "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS"
772
- });
1052
+ res.writeHead(status, { "Content-Type": "application/json", ...BASE_HEADERS });
773
1053
  res.end(payload);
774
1054
  }
1055
+ function sendNoContent(res) {
1056
+ res.writeHead(204, BASE_HEADERS);
1057
+ res.end();
1058
+ }
775
1059
  function sendError(res, err) {
776
1060
  if (err instanceof DevApiError) {
777
1061
  sendJson(res, err.status, err.errors ? { message: err.message, errors: err.errors } : { message: err.message });
@@ -809,20 +1093,24 @@ function hasDynamicSchema(desc) {
809
1093
  function hasDynamicOutputs(desc) {
810
1094
  return (desc.outputs ?? []).some((o) => o.resolveOutputs === true);
811
1095
  }
812
- function nodeToApi(desc) {
1096
+ function nodeToApi(desc, ctx) {
813
1097
  const [namespace] = desc.slug.split(":");
814
1098
  return {
815
1099
  name: desc.name,
816
1100
  namespace: namespace ?? null,
817
1101
  slug: desc.slug,
818
1102
  version: desc.version,
1103
+ // The contract declares `package` and both timestamps as present. Nodes here
1104
+ // come from the developer's working tree, so the package identity is read from
1105
+ // their package.json and the timestamps are when the mock loaded the entry.
1106
+ package: ctx?.packageInfo ?? null,
819
1107
  manifest_version: import_integrations_node_sdk3.MANIFEST_VERSION,
820
1108
  manifest: desc,
821
1109
  has_dynamic_options: hasDynamicOptions(desc),
822
1110
  has_dynamic_schema: hasDynamicSchema(desc),
823
1111
  has_dynamic_outputs: hasDynamicOutputs(desc),
824
- created_at: null,
825
- updated_at: null
1112
+ created_at: ctx?.loadedAt ?? null,
1113
+ updated_at: ctx?.loadedAt ?? null
826
1114
  };
827
1115
  }
828
1116
  function credentialTypeToApi(desc) {
@@ -832,6 +1120,7 @@ function credentialTypeToApi(desc) {
832
1120
  name: desc.name,
833
1121
  description: desc.description ?? null,
834
1122
  icon: desc.icon ?? null,
1123
+ images: desc.images ?? [],
835
1124
  auth_kind: desc.authKind,
836
1125
  fields: desc.fields
837
1126
  };
@@ -867,7 +1156,16 @@ function workflowToApi(record) {
867
1156
  return {
868
1157
  id: record.id,
869
1158
  name: record.name,
870
- definition: record.definition,
1159
+ description: record.description,
1160
+ blob_definition_version: record.blobDefinitionVersion,
1161
+ blob: record.blob,
1162
+ active: record.active,
1163
+ execution_mode: record.executionMode,
1164
+ revision: record.revision,
1165
+ // The service reports blob-validation warnings here. The mock's validation is
1166
+ // schema-light (see the fidelity caveats), so it never has any — but the field
1167
+ // is part of the contract and clients may read it.
1168
+ warnings: [],
871
1169
  build_status: record.buildStatus,
872
1170
  created_at: record.createdAt,
873
1171
  updated_at: record.updatedAt
@@ -896,6 +1194,7 @@ function templateSummaryToApi(t) {
896
1194
  shortDescription: t.shortDescription ?? null,
897
1195
  description: t.description ?? null,
898
1196
  icon: t.icon ?? null,
1197
+ images: t.images ?? [],
899
1198
  industries: t.industries ?? [],
900
1199
  vendors: t.vendors ?? [],
901
1200
  triggerTypes: (t.triggers ?? []).map((tr) => tr.type)
@@ -904,9 +1203,13 @@ function templateSummaryToApi(t) {
904
1203
  function templateFullToApi(t) {
905
1204
  return {
906
1205
  ...templateSummaryToApi(t),
907
- blobVersion: t.blobVersion,
1206
+ // snake_case per the contract, even though the surrounding template fields are
1207
+ // camelCase and the SDK's own field is `blobVersion`.
1208
+ blob_version: t.blobVersion,
908
1209
  definition: t.definition,
909
- triggers: t.triggers ?? []
1210
+ // `config` is optional in the SDK (a manual trigger has none) but declared in
1211
+ // the contract, so normalise it to an object rather than omitting it.
1212
+ triggers: (t.triggers ?? []).map((tr) => ({ ...tr, config: tr.config ?? {} }))
910
1213
  };
911
1214
  }
912
1215
 
@@ -934,13 +1237,15 @@ async function handle(req, res, deps) {
934
1237
  switch (seg[0]) {
935
1238
  case void 0:
936
1239
  case "health":
1240
+ // The service's health route is `/up` (Laravel's default); `/health` is kept
1241
+ // because the devkit has always answered there.
1242
+ case "up":
937
1243
  return void sendJson(res, 200, { status: "ok" });
938
1244
  case "me":
939
1245
  return void sendJson(res, 200, {
940
- id: "dev-user",
941
- name: "Dev User",
942
- email: "dev@revenexx.test",
943
- tenant_id: DEV_TENANT_ID
1246
+ user: { id: 1, zitadel_id: "dev-user", email: "dev@revenexx.test", name: "Dev User" },
1247
+ context: { tenant_id: DEV_TENANT_ID, active_plane: "public", roles: ["admin", "user"] },
1248
+ claims: { iss: "https://id.revenexx.test", sub: "dev-user", aud: ["devkit"] }
944
1249
  });
945
1250
  case "schemas":
946
1251
  return handleSchemas(res, deps, seg);
@@ -967,15 +1272,22 @@ function handleSchemas(res, deps, seg) {
967
1272
  throw new DevApiError(404, "Schema domain required.");
968
1273
  }
969
1274
  const schemas = deps.schemas ?? {};
970
- const schema = version && schemas[`${domain}/${version}`] || schemas[domain];
1275
+ if (!version) {
1276
+ const versions = Object.keys(schemas).filter((key) => key.startsWith(`${domain}/`)).map((key) => key.slice(domain.length + 1)).sort();
1277
+ if (versions.length === 0 && !schemas[domain]) {
1278
+ throw new DevApiError(404, `Unknown schema domain '${domain}'. Vendor it into assets/schemas.`);
1279
+ }
1280
+ return void sendJson(res, 200, { domain, versions });
1281
+ }
1282
+ const schema = schemas[`${domain}/${version}`];
971
1283
  if (!schema) {
972
- throw new DevApiError(404, `No schema for '${domain}${version ? `/${version}` : ""}'. Vendor it into assets/schemas.`);
1284
+ throw new DevApiError(404, `Unknown schema version '${domain}/${version}'. Vendor it into assets/schemas.`);
973
1285
  }
974
- sendJson(res, 200, schema);
1286
+ sendJson(res, 200, { domain, version, schema });
975
1287
  }
976
1288
  async function handleNodes(req, res, method, loaded, store, seg) {
977
1289
  if (seg.length === 1 && method === "GET") {
978
- return void sendJson(res, 200, { data: loaded.manifest.nodes.map(nodeToApi) });
1290
+ return void sendJson(res, 200, { data: loaded.manifest.nodes.map((n) => nodeToApi(n, nodeApiContext(loaded))) });
979
1291
  }
980
1292
  const slug = seg[1];
981
1293
  if (!slug) {
@@ -1016,15 +1328,36 @@ async function handleNodes(req, res, method, loaded, store, seg) {
1016
1328
  });
1017
1329
  return void sendJson(res, 200, result);
1018
1330
  }
1331
+ if (seg[3] === "execute:test" && method === "POST") {
1332
+ const body = await readJson(req);
1333
+ const result = await executeNodeTest(loaded, store, {
1334
+ slug,
1335
+ version,
1336
+ config: body.config ?? {},
1337
+ inputs: body.inputs ?? {},
1338
+ timeoutMs: body.timeout_ms
1339
+ });
1340
+ return void sendJson(res, 200, result);
1341
+ }
1019
1342
  if (seg.length === 3 && method === "GET") {
1020
- const node = loaded.manifest.nodes.find((n) => n.slug === slug && (version === "latest" || n.version === version));
1021
- if (!node) {
1022
- throw new DevApiError(404, `Node '${slug}@${version}' not found.`);
1023
- }
1024
- return void sendJson(res, 200, nodeToApi(node));
1343
+ return void sendJson(res, 200, nodeToApi(findManifestNode(loaded, slug, version), nodeApiContext(loaded)));
1344
+ }
1345
+ if (seg.length === 3 && method === "DELETE") {
1346
+ findManifestNode(loaded, slug, version);
1347
+ return void sendNoContent(res);
1025
1348
  }
1026
1349
  throw new DevApiError(404, `No route for nodes/${seg.slice(1).join("/")}`);
1027
1350
  }
1351
+ function nodeApiContext(loaded) {
1352
+ return { packageInfo: loaded.packageInfo, loadedAt: loaded.loadedAt };
1353
+ }
1354
+ function findManifestNode(loaded, slug, version) {
1355
+ const node = loaded.manifest.nodes.find((n) => n.slug === slug && (version === "latest" || n.version === version));
1356
+ if (!node) {
1357
+ throw new DevApiError(404, `Node '${slug}@${version}' not found.`);
1358
+ }
1359
+ return node;
1360
+ }
1028
1361
  function handleCredentialTypes(res, loaded, seg) {
1029
1362
  if (seg.length === 1) {
1030
1363
  return void sendJson(res, 200, {
@@ -1088,7 +1421,13 @@ async function handleCredentials(req, res, method, loaded, store, seg, url) {
1088
1421
  }
1089
1422
  if (seg[2] === "test" && method === "POST") {
1090
1423
  const result = await testCredentialInstance(loaded, store, id);
1091
- return void sendJson(res, 200, result);
1424
+ const record = store.recordCredentialTest(id, { ok: result.ok, message: result.message ?? null });
1425
+ return void sendJson(res, 200, {
1426
+ ok: result.ok,
1427
+ message: result.message ?? null,
1428
+ last_test_at: record?.lastTestAt ?? null,
1429
+ last_test_ok: record?.lastTestOk ?? result.ok
1430
+ });
1092
1431
  }
1093
1432
  if (seg[2] === "oauth" && seg[3] === "authorize-url" && method === "POST") {
1094
1433
  const redirectUri = "http://localhost/api/v1/credentials/oauth/callback";
@@ -1113,7 +1452,7 @@ async function handleCredentials(req, res, method, loaded, store, seg, url) {
1113
1452
  }
1114
1453
  if (method === "DELETE") {
1115
1454
  store.deleteCredential(id);
1116
- return void sendJson(res, 200, { deleted: true });
1455
+ return void sendNoContent(res);
1117
1456
  }
1118
1457
  }
1119
1458
  throw new DevApiError(404, `No route for credentials/${seg.slice(1).join("/")}`);
@@ -1121,7 +1460,7 @@ async function handleCredentials(req, res, method, loaded, store, seg, url) {
1121
1460
  async function handleSecrets(req, res, method, store, seg) {
1122
1461
  if (seg.length === 1) {
1123
1462
  if (method === "GET") {
1124
- return void sendJson(res, 200, { data: store.listSecrets().map(secretToApi) });
1463
+ return void sendJson(res, 200, { keys: store.listSecrets().map((s) => s.key) });
1125
1464
  }
1126
1465
  if (method === "POST") {
1127
1466
  const body = await readJson(req);
@@ -1143,7 +1482,7 @@ async function handleSecrets(req, res, method, store, seg) {
1143
1482
  }
1144
1483
  if (method === "DELETE") {
1145
1484
  store.deleteSecret(key);
1146
- return void sendJson(res, 200, { deleted: true });
1485
+ return void sendNoContent(res);
1147
1486
  }
1148
1487
  }
1149
1488
  throw new DevApiError(404, `No route for secrets/${seg.slice(1).join("/")}`);
@@ -1159,16 +1498,17 @@ async function handleTemplates(req, res, method, loaded, store, seg) {
1159
1498
  throw new DevApiError(404, `Template '${slug}' not found.`);
1160
1499
  }
1161
1500
  if (seg.length === 2 && method === "GET") {
1162
- return void sendJson(res, 200, templateFullToApi(template));
1501
+ return void sendJson(res, 200, { data: templateFullToApi(template) });
1163
1502
  }
1164
1503
  if (seg[2] === "requirements" && method === "GET") {
1165
- return void sendJson(res, 200, { data: { credentials: [], secrets: [] } });
1504
+ return void sendJson(res, 200, { data: { credentialTypes: [], secrets: [] } });
1166
1505
  }
1167
1506
  if (seg[2] === "instantiate" && method === "POST") {
1168
1507
  const body = await readJson(req);
1169
1508
  const workflow = store.createWorkflow({
1170
1509
  name: body.name ?? String(template.name),
1171
- definition: template.definition
1510
+ blob: template.definition,
1511
+ blobDefinitionVersion: template.blobVersion
1172
1512
  });
1173
1513
  for (const trigger of template.triggers ?? []) {
1174
1514
  store.createTrigger({
@@ -1193,7 +1533,11 @@ async function handleWorkflows(req, res, method, store, seg) {
1193
1533
  const body = await readJson(req);
1194
1534
  const workflow = store.createWorkflow({
1195
1535
  name: body.name ?? "Untitled workflow",
1196
- definition: body.definition ?? {}
1536
+ blob: body.blob ?? {},
1537
+ blobDefinitionVersion: body.blob_definition_version,
1538
+ description: body.description,
1539
+ active: body.active,
1540
+ executionMode: body.execution_mode
1197
1541
  });
1198
1542
  return void sendJson(res, 201, workflowToApi(workflow));
1199
1543
  }
@@ -1234,7 +1578,7 @@ async function handleWorkflows(req, res, method, store, seg) {
1234
1578
  }
1235
1579
  if (triggerId && method === "DELETE") {
1236
1580
  store.deleteTrigger(triggerId);
1237
- return void sendJson(res, 200, { deleted: true });
1581
+ return void sendNoContent(res);
1238
1582
  }
1239
1583
  }
1240
1584
  if (seg.length === 2) {
@@ -1247,7 +1591,14 @@ async function handleWorkflows(req, res, method, store, seg) {
1247
1591
  }
1248
1592
  if (method === "PUT") {
1249
1593
  const body = await readJson(req);
1250
- const updated = store.updateWorkflow(id, { name: body.name, definition: body.definition });
1594
+ const updated = store.updateWorkflow(id, {
1595
+ name: body.name,
1596
+ blob: body.blob,
1597
+ blobDefinitionVersion: body.blob_definition_version,
1598
+ description: body.description,
1599
+ active: body.active,
1600
+ executionMode: body.execution_mode
1601
+ });
1251
1602
  if (!updated) {
1252
1603
  throw new DevApiError(404, `Workflow '${id}' not found.`);
1253
1604
  }
@@ -1255,7 +1606,7 @@ async function handleWorkflows(req, res, method, store, seg) {
1255
1606
  }
1256
1607
  if (method === "DELETE") {
1257
1608
  store.deleteWorkflow(id);
1258
- return void sendJson(res, 200, { deleted: true });
1609
+ return void sendNoContent(res);
1259
1610
  }
1260
1611
  }
1261
1612
  if ((seg[2] === "credentials" || seg[2] === "credential-types") && method === "GET") {
@@ -1266,555 +1617,320 @@ async function handleWorkflows(req, res, method, store, seg) {
1266
1617
 
1267
1618
  // src/index.ts
1268
1619
  var manifestUrl = new URL("../package.json", importMetaUrl);
1269
- var DEVKIT_VERSION = JSON.parse((0, import_node_fs3.readFileSync)(manifestUrl, "utf8")).version;
1270
-
1271
- // src/preview/scaffold.ts
1272
- var import_node_fs4 = require("fs");
1273
- var import_node_path3 = require("path");
1274
-
1275
- // src/preview/templates.ts
1276
- var VERSIONS = {
1277
- nuxt: "^4.0.0",
1278
- vue: "^3.5.0",
1279
- studio: "^0.1.3",
1280
- studioShared: "^0.2.0",
1281
- studioIntegrations: "^0.5.1",
1282
- vueFlowCore: "^1.48.2",
1283
- vueFlowBackground: "^1.3.2",
1284
- vueFlowControls: "^1.1.3",
1285
- vueFlowMinimap: "^1.5.4",
1286
- vueFlowNodeToolbar: "^1.1.1",
1287
- dagre: "^3.0.0",
1288
- lucide: "^1.0.0",
1289
- solarIcons: "^1.2.1",
1290
- // studio-integrations 0.5.x embeds a TipTap rich-text editor and vue-sonner toasts.
1291
- tiptap: "^3.28.0",
1292
- vueSonner: "^2.0.0",
1293
- tailwindVite: "^4.0.0",
1294
- tailwind: "^4.0.0"
1295
- };
1296
- var PACKAGE_JSON = `{
1297
- "name": "integrations-preview-host",
1298
- "private": true,
1299
- "type": "module",
1300
- "scripts": {
1301
- "dev": "nuxt dev",
1302
- "build": "nuxt build"
1303
- },
1304
- "dependencies": {
1305
- "@revenexx/studio": "${VERSIONS.studio}",
1306
- "@revenexx/studio-integrations": "${VERSIONS.studioIntegrations}",
1307
- "@revenexx/studio-shared": "${VERSIONS.studioShared}",
1308
- "@solar-icons/nuxt": "${VERSIONS.solarIcons}",
1309
- "@dagrejs/dagre": "${VERSIONS.dagre}",
1310
- "@tiptap/core": "${VERSIONS.tiptap}",
1311
- "@tiptap/extension-document": "${VERSIONS.tiptap}",
1312
- "@tiptap/extension-history": "${VERSIONS.tiptap}",
1313
- "@tiptap/extension-paragraph": "${VERSIONS.tiptap}",
1314
- "@tiptap/extension-text": "${VERSIONS.tiptap}",
1315
- "@tiptap/pm": "${VERSIONS.tiptap}",
1316
- "@tiptap/vue-3": "${VERSIONS.tiptap}",
1317
- "@vue-flow/background": "${VERSIONS.vueFlowBackground}",
1318
- "@vue-flow/controls": "${VERSIONS.vueFlowControls}",
1319
- "@vue-flow/core": "${VERSIONS.vueFlowCore}",
1320
- "@vue-flow/minimap": "${VERSIONS.vueFlowMinimap}",
1321
- "@vue-flow/node-toolbar": "${VERSIONS.vueFlowNodeToolbar}",
1322
- "lucide-vue-next": "${VERSIONS.lucide}",
1323
- "nuxt": "${VERSIONS.nuxt}",
1324
- "vue": "${VERSIONS.vue}",
1325
- "vue-sonner": "${VERSIONS.vueSonner}"
1326
- },
1327
- "devDependencies": {
1328
- "@tailwindcss/vite": "${VERSIONS.tailwindVite}",
1329
- "tailwindcss": "${VERSIONS.tailwind}"
1330
- }
1331
- }
1332
- `;
1333
- var NUXT_CONFIG = `import tailwindcss from '@tailwindcss/vite';
1334
-
1335
- // Minimal preview host for local integration-node development.
1336
- // Generated by \`integrations-devkit init-preview\` \u2014 safe to edit or delete
1337
- // (it lives under the gitignored .revenexx-dev/).
1338
- export default defineNuxtConfig({
1339
- compatibilityDate: '2025-01-01',
1340
- // SPA: no SSR, so the studio's browser-only composables (localStorage etc.)
1341
- // behave exactly as in the real cockpit, and boot is fast.
1342
- ssr: false,
1343
- // studio-shared 0.2.x ships as a Nuxt MODULE (not a layer) \u2014 it must be
1344
- // registered in 'modules', before studio-integrations which builds on it.
1345
- // @solar-icons/nuxt provides the #solar-icons alias the studio components import.
1346
- modules: ['@revenexx/studio-shared', '@solar-icons/nuxt', '@revenexx/studio-integrations'],
1347
- css: ['~/assets/css/main.css'],
1348
- vite: { plugins: [tailwindcss()] },
1349
- runtimeConfig: {
1350
- public: {
1351
- // Overridden at runtime by NUXT_PUBLIC_* env (see .env / the preview command).
1352
- integrationsApi: '',
1353
- devToken: '',
1354
- devTenant: '',
1355
- },
1356
- },
1357
- });
1358
- `;
1359
- var MAIN_CSS = `@import "tailwindcss";
1360
- @import "@revenexx/studio/tokens";
1361
- @import "@revenexx/studio/fonts";
1362
-
1363
- @source "../../node_modules/@revenexx/studio/dist";
1364
- @source "../../node_modules/@revenexx/studio-shared/components";
1365
- @source "../../node_modules/@revenexx/studio-integrations/dist/runtime";
1366
-
1367
- /* Phase 1: workflow EXECUTION is not wired up in the devkit preview yet, so the
1368
- Workflows surface is hidden until phase 2. This hides the sidebar nav entry
1369
- and any deep links to the workflow editor; the routes are also redirected by
1370
- middleware/hide-workflows.global.ts. */
1371
- a[href^="/integrations/workflows"] { display: none !important; }
1372
- li:has(> a[href^="/integrations/workflows"]) { display: none !important; }
1373
- `;
1374
- var APP_VUE = `<script setup lang="ts">
1375
- import { Toaster } from '@revenexx/studio'
1376
-
1377
- useHead({ title: 'Integration Studio \u2014 devkit preview' })
1378
- </script>
1379
-
1380
- <template>
1381
- <div class="flex h-svh flex-col overflow-hidden bg-[#f3f1fa] text-foreground">
1382
- <NuxtLoadingIndicator color="var(--color-primary, #620DFF)" :height="3" />
1383
- <div class="min-h-0 flex-1 pt-3">
1384
- <NuxtPage />
1385
- </div>
1386
- <Toaster rich-colors position="bottom-right" :duration="3500" close-button />
1387
- </div>
1388
- </template>
1389
- `;
1390
- var INDEX_VUE = `<template>
1391
- <div class="mx-auto flex min-h-full max-w-xl flex-col justify-center gap-6 px-6 py-12">
1392
- <div>
1393
- <p class="text-mono text-muted-foreground">Integrations \xB7 node devkit</p>
1394
- <h1 class="mt-1 text-2xl font-medium">Integration Studio \u2014 Preview</h1>
1395
- <p class="mt-2 text-sm text-muted-foreground">
1396
- Lokaler Host f\xFCr <code>@revenexx/studio-integrations</code> gegen die Mock-API
1397
- deines Node-Pakets. Authentifizierung ist ein festes Dev-Token \u2014 nichts einzugeben.
1398
- </p>
1399
- </div>
1400
-
1401
- <div class="rounded-lg border border-black/[0.06] bg-card p-5 text-sm shadow-sm">
1402
- <p class="text-mono text-muted-foreground">Session</p>
1403
- <dl class="mt-2 grid grid-cols-[7rem_1fr] gap-y-1">
1404
- <dt class="text-muted-foreground">Mock API</dt>
1405
- <dd class="truncate font-mono text-xs leading-5">{{ api }}</dd>
1406
- <dt class="text-muted-foreground">Tenant</dt>
1407
- <dd class="font-mono text-xs leading-5">{{ tenant }}</dd>
1408
- </dl>
1409
- </div>
1410
-
1411
- <div class="rounded-lg border border-black/[0.06] bg-card p-5 shadow-sm">
1412
- <p class="text-mono text-muted-foreground">Einstieg</p>
1413
- <div class="mt-3 flex flex-col gap-4">
1414
- <NuxtLink
1415
- to="/nodes"
1416
- class="inline-flex w-fit items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90"
1417
- >
1418
- Lokale Nodes \xF6ffnen \u2014 Preview + Validierung
1419
- </NuxtLink>
1420
- <div class="flex flex-wrap gap-x-4 gap-y-1.5">
1421
- <NuxtLink
1422
- v-for="link in quickLinks"
1423
- :key="link.to"
1424
- :to="link.to"
1425
- class="text-sm text-primary hover:underline"
1426
- >
1427
- {{ link.label }}
1428
- </NuxtLink>
1429
- </div>
1430
- </div>
1431
- </div>
1432
- </div>
1433
- </template>
1434
-
1435
- <script setup lang="ts">
1436
- const rc = useRuntimeConfig().public
1437
- const api = rc.integrationsApi
1438
- const tenant = (rc.devTenant as string) || 'dev-tenant'
1439
-
1440
- const quickLinks = [
1441
- { to: '/integrations', label: 'Overview' },
1442
- { to: '/integrations/credentials', label: 'Credentials' },
1443
- { to: '/integrations/secrets', label: 'Secrets' },
1444
- { to: '/nodes', label: 'Local nodes' },
1445
- ]
1446
- </script>
1447
- `;
1448
- var NODES_VUE = `<template>
1449
- <div class="ndx-page">
1450
- <div class="ndx-inner">
1451
- <header class="ndx-head">
1452
- <h1>Lokale Nodes</h1>
1453
- <p>Mock-API: <code>{{ apiUrl }}</code></p>
1454
- <p v-if="loadError" class="ndx-err">{{ loadError }}</p>
1455
- </header>
1456
-
1457
- <p v-if="loading">Lade Nodes\u2026</p>
1458
- <p v-else-if="nodes.length === 0">Keine Nodes gefunden. Exportiert dein Paket <code>NODES</code>?</p>
1620
+ var DEVKIT_VERSION = JSON.parse((0, import_node_fs5.readFileSync)(manifestUrl, "utf8")).version;
1459
1621
 
1460
- <ul v-else class="ndx-grid">
1461
- <li v-for="n in nodes" :key="n.slug + '@' + n.version" class="ndx-card" @click="openNode(n)">
1462
- <div class="ndx-card-title">{{ label(n) }}</div>
1463
- <div class="ndx-card-slug">{{ n.slug }} \xB7 v{{ n.version }}</div>
1464
- <div class="ndx-badges">
1465
- <span v-if="n.has_dynamic_options" class="ndx-badge">dynamic options</span>
1466
- <span v-if="n.has_dynamic_schema" class="ndx-badge">dynamic schema</span>
1467
- <span v-if="n.has_dynamic_outputs" class="ndx-badge">dynamic outputs</span>
1468
- </div>
1469
- </li>
1470
- </ul>
1471
- </div>
1472
-
1473
- <!-- REUSE of the exact editor lightbox: studio <Dialog> owns the modal
1474
- chrome, <IntegrationsNodeInspector> is the content \u2014 mirrors
1475
- WorkflowEditor.vue's <Dialog><DialogContent><NodeInspector/> block. -->
1476
- <Dialog :open="!!selection" @update:open="(v) => { if (!v) requestClose() }">
1477
- <DialogContent :show-close-button="false" class="flex h-[min(680px,86vh)] w-[min(1100px,94vw)] max-w-none flex-col gap-0 overflow-hidden rounded-lg p-0 sm:max-w-none">
1478
- <div v-if="result === 'ok'" class="ndx-strip ndx-strip-ok">\u2713 Payload g\xFCltig \u2014 alles gut.</div>
1479
- <div v-else-if="result === 'err'" class="ndx-strip ndx-strip-err">\u2717 Payload ung\xFCltig \u2014 {{ errorCount }} Feld(er) pr\xFCfen (rot markiert).</div>
1480
- <div v-else-if="formError" class="ndx-strip ndx-strip-err">{{ formError }}</div>
1481
- <IntegrationsNodeInspector
1482
- v-if="selection"
1483
- :selection="selection"
1484
- :secret-keys="secretKeys"
1485
- :refused-fields="refused"
1486
- @update="onSubmit"
1487
- @close="requestClose" />
1488
- </DialogContent>
1489
- </Dialog>
1490
- </div>
1491
- </template>
1492
-
1493
- <script setup lang="ts">
1494
- import { computed, onMounted, ref } from 'vue'
1495
- import { Dialog, DialogContent } from '@revenexx/studio'
1496
-
1497
- interface ApiNode {
1498
- name: string | Record<string, string>
1499
- slug: string
1500
- version: string
1501
- manifest?: { name?: string | Record<string, string> }
1502
- has_dynamic_options?: boolean
1503
- has_dynamic_schema?: boolean
1504
- has_dynamic_outputs?: boolean
1622
+ // src/preview/child-env.ts
1623
+ function previewChildEnv(options) {
1624
+ const env = { ...options.base };
1625
+ delete env.PORT;
1626
+ return {
1627
+ ...env,
1628
+ NUXT_PUBLIC_INTEGRATIONS_API: options.apiUrl,
1629
+ NUXT_PUBLIC_DEV_TOKEN: options.base.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
1630
+ NUXT_PUBLIC_DEV_TENANT: options.base.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant",
1631
+ NUXT_PORT: String(options.uiPort),
1632
+ DEVKIT_NUXT_BUILD_DIR: options.buildDir,
1633
+ DEVKIT_VITE_CACHE_DIR: options.viteCacheDir
1634
+ };
1505
1635
  }
1506
1636
 
1507
- const apiUrl = useRuntimeConfig().public.integrationsApi
1508
- const client = useIntegrationsApi()
1509
- // load() fills the reactive catalog the inspector reads via findManifest();
1510
- // resolveLocalized() turns a LocalizedString into the active-locale string.
1511
- const { load, resolveLocalized } = useIntegrationsNodes()
1512
-
1513
- const nodes = ref<ApiNode[]>([])
1514
- const loading = ref(true)
1515
- const loadError = ref<string | null>(null)
1516
-
1517
- const selection = ref<any>(null)
1518
- const secretKeys = ref<string[]>([])
1519
- const refused = ref<Record<string, string>>({})
1520
- const result = ref<string | null>(null)
1521
- const formError = ref<string | null>(null)
1522
- // Set synchronously in onSubmit so the inspector's own Save (it emits update THEN
1523
- // close) does NOT close the dialog \u2014 we keep it open to show the verdict.
1524
- const validating = ref(false)
1525
-
1526
- const errorCount = computed(() => Object.keys(refused.value).length)
1527
-
1528
- function label(n: ApiNode): string {
1529
- return resolveLocalized(n.manifest?.name ?? n.name) || n.slug
1530
- }
1637
+ // src/preview/host.ts
1638
+ var import_node_crypto2 = require("crypto");
1639
+ var import_node_fs6 = require("fs");
1640
+ var import_node_os = require("os");
1641
+ var import_node_path5 = require("path");
1642
+ var import_node_url2 = require("url");
1531
1643
 
1532
- onMounted(async () => {
1533
- await load()
1534
- try {
1535
- const res = await client.get<any>('/nodes')
1536
- nodes.value = (Array.isArray(res) ? res : res?.data ?? []) as ApiNode[]
1537
- } catch (e: any) {
1538
- loadError.value = e?.message ?? 'Nodes konnten nicht geladen werden.'
1539
- } finally {
1540
- loading.value = false
1541
- }
1542
- try {
1543
- const secrets = await client.get<any>('/secrets')
1544
- const list = (Array.isArray(secrets) ? secrets : secrets?.data ?? []) as Array<{ key: string }>
1545
- secretKeys.value = list.map(s => s.key).filter(Boolean)
1546
- } catch {
1547
- // secrets are optional for the preview
1644
+ // src/preview/pid.ts
1645
+ function pidIsAlive(pid) {
1646
+ if (!Number.isInteger(pid) || pid <= 0) {
1647
+ return false;
1548
1648
  }
1549
- })
1550
-
1551
- function openNode(n: ApiNode) {
1552
- refused.value = {}
1553
- result.value = null
1554
- formError.value = null
1555
- // Synthetic WorkflowNode selection (distinguished by nodeSlug); the inspector
1556
- // resolves its manifest from the catalog load() populated above.
1557
- selection.value = { id: 'preview', nodeSlug: n.slug, nodeVersion: n.version, name: label(n), config: {} }
1558
- }
1559
-
1560
- async function onSubmit(draft: any) {
1561
- validating.value = true
1562
- refused.value = {}
1563
- result.value = null
1564
- formError.value = null
1565
1649
  try {
1566
- const slug = encodeURIComponent(draft.nodeSlug)
1567
- const version = encodeURIComponent(draft.nodeVersion || 'latest')
1568
- const res = await client.post<any>(
1569
- '/nodes/' + slug + '/' + version + '/config:validate',
1570
- { config: draft.config ?? {} },
1571
- )
1572
- if (res.valid) {
1573
- result.value = 'ok'
1574
- } else {
1575
- refused.value = Object.fromEntries(
1576
- Object.entries(res.errors ?? {}).map(([k, msgs]) => [k, (msgs as string[]).join(' ')]),
1577
- )
1578
- result.value = 'err'
1579
- }
1580
- } catch (e: any) {
1581
- formError.value = e?.message ?? 'Validierung fehlgeschlagen.'
1582
- } finally {
1583
- validating.value = false
1650
+ process.kill(pid, 0);
1651
+ return true;
1652
+ } catch (err) {
1653
+ return err.code === "EPERM";
1584
1654
  }
1585
1655
  }
1586
1656
 
1587
- // The inspector emits close on both Save and Cancel; the studio Dialog emits it
1588
- // on Esc / backdrop. Hold the close while a Save-validation is in flight so the
1589
- // dialog stays open to show the result; otherwise close (discard).
1590
- function requestClose() {
1591
- if (validating.value) return
1592
- selection.value = null
1593
- refused.value = {}
1594
- result.value = null
1595
- formError.value = null
1596
- }
1597
- </script>
1598
-
1599
- <style scoped>
1600
- /* The app shell (app.vue) is h-svh + overflow-hidden, so this page must own its
1601
- own vertical scroll \u2014 otherwise the node list is clipped and can't scroll. */
1602
- .ndx-page { height: 100%; overflow-y: auto; }
1603
- .ndx-inner { max-width: 60rem; margin: 0 auto; padding: 2rem; font-family: sans-serif; }
1604
- .ndx-head h1 { font-size: 1.5rem; font-weight: 600; }
1605
- .ndx-err { color: #b91c1c; }
1606
- .ndx-grid { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: 1rem; margin-top: 1.5rem; }
1607
- .ndx-card { border: 1px solid #d1d5db; border-radius: 0.5rem; padding: 1rem; cursor: pointer; transition: border-color .15s, box-shadow .15s; }
1608
- .ndx-card:hover { border-color: #6366f1; box-shadow: 0 1px 6px rgba(0,0,0,.08); }
1609
- .ndx-card-title { font-weight: 600; }
1610
- .ndx-card-slug { color: #6b7280; font-size: .85rem; margin-top: .25rem; }
1611
- .ndx-badges { margin-top: .5rem; display: flex; flex-wrap: wrap; gap: .35rem; }
1612
- .ndx-badge { font-size: .7rem; background: #eef2ff; color: #4338ca; border-radius: .25rem; padding: .1rem .4rem; }
1613
-
1614
- /* Verdict strip shown at the top of the reused dialog content (does not close). */
1615
- .ndx-strip { flex: 0 0 auto; padding: .5rem 1rem; font-size: .85rem; font-weight: 600; }
1616
- .ndx-strip-ok { background: #dcfce7; color: #166534; }
1617
- .ndx-strip-err { background: #fee2e2; color: #991b1b; }
1618
- </style>
1619
- `;
1620
- var GITIGNORE = `node_modules/
1657
+ // src/preview/host.ts
1658
+ var INSTALL_MARKER = ".devkit-install-complete";
1659
+ var COPY_MARKER = ".devkit-copy-complete";
1660
+ var INSTALL_LOCK = ".devkit-install.lock";
1661
+ var HOST_GITIGNORE = `node_modules/
1621
1662
  .nuxt/
1663
+ .nuxt-*/
1664
+ .vite-*/
1622
1665
  .output/
1623
1666
  .data/
1667
+ .env*
1668
+ previews/
1669
+ ${COPY_MARKER}
1670
+ ${INSTALL_MARKER}
1671
+ ${INSTALL_LOCK}
1624
1672
  `;
1625
- var CONSOLE_STUBS = `import { ref } from 'vue'
1626
-
1627
- export function useConsoleTenants() {
1628
- return { tenants: ref([]), onlyTenantSlug: ref(null), load: async () => {} }
1673
+ function resolveHostDir(options) {
1674
+ const root = options.cacheRoot ?? process.env.XDG_CACHE_HOME ?? (0, import_node_path5.join)((0, import_node_os.homedir)(), ".cache");
1675
+ return (0, import_node_path5.join)(root, "revenexx", "devkit-preview", options.version);
1629
1676
  }
1630
- export function useActiveMarket() {
1631
- return {
1632
- markets: ref([]),
1633
- activeCode: ref(''),
1634
- isGlobal: ref(true),
1635
- GLOBAL_MARKET_CODE: '__global__',
1636
- fetchMarkets: async () => {},
1677
+ function shippedHostDir() {
1678
+ let dir = (0, import_node_path5.dirname)((0, import_node_url2.fileURLToPath)(importMetaUrl));
1679
+ for (let up = 0; up < 5; up += 1) {
1680
+ const candidate = (0, import_node_path5.join)(dir, "preview-host");
1681
+ if ((0, import_node_fs6.existsSync)((0, import_node_path5.join)(candidate, "nuxt.config.ts"))) {
1682
+ return candidate;
1683
+ }
1684
+ const parent = (0, import_node_path5.dirname)(dir);
1685
+ if (parent === dir) break;
1686
+ dir = parent;
1637
1687
  }
1688
+ throw new Error("Preview host not found: no preview-host/nuxt.config.ts above this module. Reinstall @revenexx/integrations-node-devkit.");
1638
1689
  }
1639
- export function useConsoleSftp() {
1640
- return {
1641
- accounts: ref([]),
1642
- load: async () => {},
1643
- revealPassword: async () => ({}),
1644
- create: async () => ({}),
1645
- refresh: async () => ({}),
1690
+ function materializeHost(options) {
1691
+ const log = options.log ?? (() => {
1692
+ });
1693
+ const source = options.sourceDir ?? shippedHostDir();
1694
+ const dir = (0, import_node_path5.resolve)(options.targetDir);
1695
+ const managed = options.managed ?? false;
1696
+ const intact = managed ? hostIsComplete(dir) && copyIsCurrent(dir, source) : hostExists(dir);
1697
+ const alreadyIntact = intact && !options.force;
1698
+ if (!alreadyIntact) {
1699
+ (0, import_node_fs6.mkdirSync)(dir, { recursive: true });
1700
+ (0, import_node_fs6.rmSync)((0, import_node_path5.join)(dir, COPY_MARKER), { force: true });
1701
+ (0, import_node_fs6.cpSync)(source, dir, { recursive: true, filter: (src) => !isInsideNodeModules(source, src) });
1702
+ (0, import_node_fs6.writeFileSync)((0, import_node_path5.join)(dir, COPY_MARKER), `${sourceFingerprint(source)}
1703
+ ${(/* @__PURE__ */ new Date()).toISOString()}
1704
+ `, "utf-8");
1705
+ (0, import_node_fs6.writeFileSync)((0, import_node_path5.join)(dir, ".gitignore"), HOST_GITIGNORE, "utf-8");
1706
+ log(`Preview host ready in ${dir}`);
1707
+ }
1708
+ const envPath = (0, import_node_path5.join)(dir, options.dotenvName ?? ".env");
1709
+ if (managed || !(0, import_node_fs6.existsSync)(envPath)) {
1710
+ (0, import_node_fs6.writeFileSync)(envPath, envFile(options), "utf-8");
1711
+ }
1712
+ return { dir, copied: !alreadyIntact };
1713
+ }
1714
+ function isInsideNodeModules(source, src) {
1715
+ const rel = (0, import_node_path5.relative)(source, src);
1716
+ return rel !== "" && rel.split(import_node_path5.sep).includes("node_modules");
1717
+ }
1718
+ function sourceFingerprint(source) {
1719
+ const hash = (0, import_node_crypto2.createHash)("sha256");
1720
+ for (const file of listFiles(source, source).sort()) {
1721
+ hash.update(file);
1722
+ hash.update((0, import_node_fs6.readFileSync)((0, import_node_path5.join)(source, file)));
1723
+ }
1724
+ return hash.digest("hex").slice(0, 16);
1725
+ }
1726
+ function listFiles(root, dir) {
1727
+ const files = [];
1728
+ for (const entry of (0, import_node_fs6.readdirSync)(dir, { withFileTypes: true })) {
1729
+ if (entry.name === "node_modules") {
1730
+ continue;
1731
+ }
1732
+ const full = (0, import_node_path5.join)(dir, entry.name);
1733
+ if (entry.isDirectory()) {
1734
+ files.push(...listFiles(root, full));
1735
+ } else if (entry.isFile()) {
1736
+ files.push((0, import_node_path5.relative)(root, full));
1737
+ }
1646
1738
  }
1739
+ return files;
1647
1740
  }
1648
- export function useMailAdmin() {
1649
- return {
1650
- listCredentials: async () => [],
1651
- getCredential: async () => ({}),
1652
- createCredential: async () => ({}),
1741
+ function copyIsCurrent(dir, source) {
1742
+ try {
1743
+ const recorded = (0, import_node_fs6.readFileSync)((0, import_node_path5.join)(dir, COPY_MARKER), "utf-8").split("\n")[0]?.trim();
1744
+ return recorded === sourceFingerprint(source);
1745
+ } catch {
1746
+ return false;
1653
1747
  }
1654
1748
  }
1655
- export function useConsoleApiKeys() {
1656
- return { create: async () => ({ secret: '' }) }
1657
- }
1658
- `;
1659
- var HIDE_WORKFLOWS_MW = `export default defineNuxtRouteMiddleware((to) => {
1660
- if (to.path === '/integrations/workflows' || to.path.startsWith('/integrations/workflows/')) {
1661
- return navigateTo('/integrations')
1662
- }
1663
- })
1664
- `;
1665
- function previewTemplates(options) {
1666
- const env = `# Overrides the Nuxt runtimeConfig.public.* values.
1749
+ function envFile(options) {
1750
+ const name = options.dotenvName ?? ".env";
1751
+ const manual = name === ".env" ? "npm run dev" : `npm run dev -- --dotenv ${name}`;
1752
+ return `# Generated by integrations-devkit \u2014 overrides the Nuxt runtimeConfig.public.* values.
1753
+ # The \`preview\` command also passes these to the Nuxt child process; this file is
1754
+ # what makes a manual \`${manual}\` in this directory work.
1667
1755
  NUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}
1668
- NUXT_PUBLIC_DEV_TOKEN=dev
1669
- NUXT_PUBLIC_DEV_TENANT=dev-tenant
1756
+ NUXT_PUBLIC_DEV_TOKEN=${options.devToken ?? "dev"}
1757
+ NUXT_PUBLIC_DEV_TENANT=${options.devTenant ?? "dev-tenant"}
1670
1758
  `;
1671
- return {
1672
- "package.json": PACKAGE_JSON,
1673
- "nuxt.config.ts": NUXT_CONFIG,
1674
- "assets/css/main.css": MAIN_CSS,
1675
- "app.vue": APP_VUE,
1676
- "pages/index.vue": INDEX_VUE,
1677
- "pages/nodes.vue": NODES_VUE,
1678
- "composables/devkit-console-stubs.ts": CONSOLE_STUBS,
1679
- "middleware/hide-workflows.global.ts": HIDE_WORKFLOWS_MW,
1680
- ".env": env,
1681
- ".gitignore": GITIGNORE
1682
- };
1683
1759
  }
1684
-
1685
- // src/preview/scaffold.ts
1686
- function scaffoldPreview(options) {
1760
+ function consumerKey(consumerDir) {
1761
+ return (0, import_node_crypto2.createHash)("sha256").update(consumerDir).digest("hex").slice(0, 12);
1762
+ }
1763
+ function hostBuildDir(hostDir, consumerDir) {
1764
+ return (0, import_node_path5.join)(hostDir, `.nuxt-${consumerKey(consumerDir)}`);
1765
+ }
1766
+ function hostViteCacheDir(hostDir, consumerDir) {
1767
+ return (0, import_node_path5.join)(hostDir, `.vite-${consumerKey(consumerDir)}`);
1768
+ }
1769
+ function hostDotenvName(consumerDir) {
1770
+ return `.env.${consumerKey(consumerDir)}`;
1771
+ }
1772
+ function hostExists(dir) {
1773
+ return (0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, "package.json")) && (0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, "nuxt.config.ts"));
1774
+ }
1775
+ function hostIsComplete(dir) {
1776
+ return hostExists(dir) && (0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, COPY_MARKER));
1777
+ }
1778
+ function hostNeedsInstall(dir) {
1779
+ const marker = (0, import_node_path5.join)(dir, INSTALL_MARKER);
1780
+ if (!(0, import_node_fs6.existsSync)((0, import_node_path5.join)(dir, "node_modules")) || !(0, import_node_fs6.existsSync)(marker)) {
1781
+ return true;
1782
+ }
1783
+ try {
1784
+ return (0, import_node_fs6.readFileSync)(marker, "utf-8").trim() !== manifestFingerprint(dir);
1785
+ } catch {
1786
+ return true;
1787
+ }
1788
+ }
1789
+ function markHostInstalled(dir) {
1790
+ (0, import_node_fs6.writeFileSync)((0, import_node_path5.join)(dir, INSTALL_MARKER), `${manifestFingerprint(dir)}
1791
+ `, "utf-8");
1792
+ }
1793
+ function clearHostInstallMarker(dir) {
1794
+ (0, import_node_fs6.rmSync)((0, import_node_path5.join)(dir, INSTALL_MARKER), { force: true });
1795
+ }
1796
+ async function withInstallLock(dir, install, options = {}) {
1797
+ const isAlive = options.isAlive ?? pidIsAlive;
1687
1798
  const log = options.log ?? (() => {
1688
1799
  });
1689
- const files = previewTemplates({ integrationsApiUrl: options.integrationsApiUrl });
1690
- const written = [];
1691
- const skipped = [];
1692
- for (const [relative, content] of Object.entries(files)) {
1693
- const target = (0, import_node_path3.resolve)(options.dir, relative);
1694
- if ((0, import_node_fs4.existsSync)(target) && !options.force) {
1695
- skipped.push(relative);
1800
+ const timeoutMs = options.timeoutMs ?? 20 * 6e4;
1801
+ const pollMs = options.pollMs ?? 500;
1802
+ const lockPath = (0, import_node_path5.join)(dir, INSTALL_LOCK);
1803
+ const deadline = Date.now() + timeoutMs;
1804
+ let waitingFor = null;
1805
+ while (!acquire(lockPath)) {
1806
+ const holder = lockHolder(lockPath);
1807
+ if (holder === null || !isAlive(holder)) {
1808
+ (0, import_node_fs6.rmSync)(lockPath, { force: true });
1696
1809
  continue;
1697
1810
  }
1698
- (0, import_node_fs4.mkdirSync)((0, import_node_path3.dirname)(target), { recursive: true });
1699
- (0, import_node_fs4.writeFileSync)(target, content, "utf-8");
1700
- written.push(relative);
1811
+ if (holder !== waitingFor) {
1812
+ waitingFor = holder;
1813
+ log(`Another devkit (PID ${holder}) is installing the preview host's dependencies \u2014 waiting for it to finish\u2026`);
1814
+ }
1815
+ if (Date.now() > deadline) {
1816
+ throw new CliError(`Timed out after ${Math.round(timeoutMs / 6e4)} min waiting for PID ${holder} to finish installing in ${dir}. If that process is gone, delete ${lockPath}.`);
1817
+ }
1818
+ await new Promise((done) => setTimeout(done, pollMs));
1701
1819
  }
1702
- if (written.length > 0) {
1703
- log(`Scaffolded preview host in ${options.dir} (${written.length} file(s)).`);
1820
+ try {
1821
+ if (options.needsInstall && !options.needsInstall()) {
1822
+ return null;
1823
+ }
1824
+ return await install();
1825
+ } finally {
1826
+ (0, import_node_fs6.rmSync)(lockPath, { force: true });
1704
1827
  }
1705
- if (skipped.length > 0) {
1706
- log(`Kept ${skipped.length} existing file(s) (use --force to overwrite).`);
1828
+ }
1829
+ function acquire(lockPath) {
1830
+ try {
1831
+ (0, import_node_fs6.mkdirSync)((0, import_node_path5.dirname)(lockPath), { recursive: true });
1832
+ (0, import_node_fs6.writeFileSync)(lockPath, `${process.pid}
1833
+ ${(/* @__PURE__ */ new Date()).toISOString()}
1834
+ `, { encoding: "utf-8", flag: "wx" });
1835
+ return true;
1836
+ } catch {
1837
+ return false;
1707
1838
  }
1708
- return { dir: options.dir, written, skipped };
1709
1839
  }
1710
- function previewDepsInstalled(dir) {
1711
- return (0, import_node_fs4.existsSync)((0, import_node_path3.join)(dir, "node_modules"));
1840
+ function lockHolder(lockPath) {
1841
+ try {
1842
+ const pid = Number.parseInt((0, import_node_fs6.readFileSync)(lockPath, "utf-8").split("\n")[0] ?? "", 10);
1843
+ return Number.isInteger(pid) ? pid : null;
1844
+ } catch {
1845
+ return null;
1846
+ }
1712
1847
  }
1713
- function previewExists(dir) {
1714
- return (0, import_node_fs4.existsSync)((0, import_node_path3.join)(dir, "package.json")) && (0, import_node_fs4.existsSync)((0, import_node_path3.join)(dir, "nuxt.config.ts"));
1848
+ function manifestFingerprint(dir) {
1849
+ const pkg = JSON.parse((0, import_node_fs6.readFileSync)((0, import_node_path5.join)(dir, "package.json"), "utf-8"));
1850
+ return JSON.stringify({ dependencies: pkg.dependencies ?? {}, devDependencies: pkg.devDependencies ?? {} });
1715
1851
  }
1716
1852
 
1717
- // src/cli.ts
1718
- function parseArgs(argv) {
1719
- const cwd = process.cwd();
1720
- const opts = {
1721
- entry: "",
1722
- seedDir: (0, import_node_path4.resolve)(cwd, "dev/seeds"),
1723
- stateFile: (0, import_node_path4.resolve)(cwd, ".revenexx-dev/state.json"),
1724
- persist: true,
1725
- port: Number.parseInt(process.env.PORT ?? "3555", 10),
1726
- uiDir: null,
1727
- serveUi: true,
1728
- open: false,
1729
- previewDir: (0, import_node_path4.resolve)(cwd, ".revenexx-dev/preview"),
1730
- force: false
1731
- };
1732
- let command = null;
1733
- for (let i = 0; i < argv.length; i++) {
1734
- const arg = argv[i];
1735
- switch (arg) {
1736
- case "reset":
1737
- command = "reset";
1738
- break;
1739
- case "init-preview":
1740
- command = "init-preview";
1741
- break;
1742
- case "preview":
1743
- command = "preview";
1744
- break;
1745
- case "--dir":
1746
- opts.previewDir = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1747
- break;
1748
- case "--force":
1749
- opts.force = true;
1750
- break;
1751
- case "--entry":
1752
- opts.entry = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1753
- break;
1754
- case "--seed":
1755
- opts.seedDir = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1756
- break;
1757
- case "--state":
1758
- opts.stateFile = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1759
- break;
1760
- case "--no-persist":
1761
- opts.persist = false;
1762
- break;
1763
- case "--port":
1764
- opts.port = Number.parseInt(argv[++i] ?? "3555", 10);
1765
- break;
1766
- case "--ui":
1767
- opts.uiDir = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1768
- break;
1769
- case "--no-ui":
1770
- opts.serveUi = false;
1771
- break;
1772
- case "--open":
1773
- opts.open = true;
1774
- break;
1775
- // Both are consumed by loadEnvFile() before parsing; listed here so they
1776
- // do not fall through to the unknown-option branch. A repeated `--env`
1777
- // resolves to the last one, so each occurrence skips its own value.
1778
- case "--env":
1779
- i++;
1780
- break;
1781
- case "--no-env":
1782
- break;
1783
- case "--version":
1784
- case "-v":
1785
- command = "version";
1786
- break;
1787
- default:
1788
- if (arg?.startsWith("--env-file")) {
1789
- if (!arg.includes("=")) {
1790
- i++;
1791
- }
1792
- break;
1793
- }
1794
- if (arg?.startsWith("-")) {
1795
- console.error(`Unknown option: ${arg}`);
1796
- process.exit(1);
1797
- }
1853
+ // src/preview/registry.ts
1854
+ var import_node_fs7 = require("fs");
1855
+ var import_node_path6 = require("path");
1856
+ var REGISTRY_DIR = "previews";
1857
+ function readLivePreviews(hostDir, isAlive = pidIsAlive) {
1858
+ const dir = (0, import_node_path6.join)(hostDir, REGISTRY_DIR);
1859
+ if (!(0, import_node_fs7.existsSync)(dir)) {
1860
+ return [];
1861
+ }
1862
+ const live = [];
1863
+ for (const file of (0, import_node_fs7.readdirSync)(dir)) {
1864
+ if (!file.endsWith(".json")) {
1865
+ continue;
1866
+ }
1867
+ const path = (0, import_node_path6.join)(dir, file);
1868
+ const entry = readEntry(path);
1869
+ if (entry && isAlive(entry.pid)) {
1870
+ live.push(entry);
1871
+ } else {
1872
+ (0, import_node_fs7.rmSync)(path, { force: true });
1798
1873
  }
1799
1874
  }
1800
- if (!opts.entry) {
1801
- const src = (0, import_node_path4.resolve)(cwd, "src/index.ts");
1802
- opts.entry = (0, import_node_fs5.existsSync)(src) ? src : (0, import_node_path4.resolve)(cwd, "dist/index.js");
1875
+ return live.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
1876
+ }
1877
+ function readEntry(path) {
1878
+ try {
1879
+ const parsed = JSON.parse((0, import_node_fs7.readFileSync)(path, "utf-8"));
1880
+ return Number.isInteger(parsed?.pid) ? parsed : null;
1881
+ } catch {
1882
+ return null;
1803
1883
  }
1804
- return { command, options: opts };
1805
1884
  }
1885
+ function registerPreview(hostDir, entry) {
1886
+ const dir = (0, import_node_path6.join)(hostDir, REGISTRY_DIR);
1887
+ (0, import_node_fs7.mkdirSync)(dir, { recursive: true });
1888
+ (0, import_node_fs7.writeFileSync)((0, import_node_path6.join)(dir, `${entry.pid}.json`), `${JSON.stringify(entry, null, 2)}
1889
+ `, "utf-8");
1890
+ }
1891
+ function unregisterPreview(hostDir, pid = process.pid) {
1892
+ (0, import_node_fs7.rmSync)((0, import_node_path6.join)(hostDir, REGISTRY_DIR, `${pid}.json`), { force: true });
1893
+ }
1894
+ function describePreview(entry) {
1895
+ return `${(0, import_node_path6.basename)(entry.cwd)} (PID ${entry.pid}, mock :${entry.mockPort}, UI :${entry.uiPort}) \u2014 ${entry.cwd}`;
1896
+ }
1897
+ function previewConflict(running, options) {
1898
+ const sameRepo = running.find((entry) => entry.cwd === options.cwd);
1899
+ if (sameRepo) {
1900
+ return [
1901
+ `A preview of this very package is already running: ${describePreview(sameRepo)}`,
1902
+ "",
1903
+ "Two previews of one package share a build directory and would serve each other's",
1904
+ "output, so this is refused even with --parallel. Stop that one first."
1905
+ ].join("\n");
1906
+ }
1907
+ if (options.force && running.length > 0) {
1908
+ return `--force reinstalls the host's dependencies, which would pull node_modules out from under the preview still running in ${running[0]?.cwd}. Stop it first.`;
1909
+ }
1910
+ if (running.length > 0 && !options.parallel) {
1911
+ return [
1912
+ `A preview is already running out of ${options.hostDir}:`,
1913
+ ...running.map((entry) => ` ${describePreview(entry)}`),
1914
+ "",
1915
+ "Stop it (Ctrl-C in its terminal), or run this one alongside it with --parallel."
1916
+ ].join("\n");
1917
+ }
1918
+ return null;
1919
+ }
1920
+
1921
+ // src/cli.ts
1806
1922
  function loadSchemas() {
1807
- const here = (0, import_node_url2.fileURLToPath)(new URL(".", importMetaUrl));
1808
- const schemasDir = (0, import_node_path4.resolve)(here, "..", "assets", "schemas");
1923
+ const here = (0, import_node_url3.fileURLToPath)(new URL(".", importMetaUrl));
1924
+ const schemasDir = (0, import_node_path7.resolve)(here, "..", "assets", "schemas");
1809
1925
  const schemas = {};
1810
- if (!(0, import_node_fs5.existsSync)(schemasDir)) {
1926
+ if (!(0, import_node_fs8.existsSync)(schemasDir)) {
1811
1927
  return schemas;
1812
1928
  }
1813
- for (const file of (0, import_node_fs5.readdirSync)(schemasDir)) {
1814
- if ((0, import_node_path4.extname)(file) !== ".json") {
1929
+ for (const file of (0, import_node_fs8.readdirSync)(schemasDir)) {
1930
+ if ((0, import_node_path7.extname)(file) !== ".json") {
1815
1931
  continue;
1816
1932
  }
1817
- const parsed = JSON.parse((0, import_node_fs5.readFileSync)((0, import_node_path4.join)(schemasDir, file), "utf-8"));
1933
+ const parsed = JSON.parse((0, import_node_fs8.readFileSync)((0, import_node_path7.join)(schemasDir, file), "utf-8"));
1818
1934
  const base = file.replace(/\.json$/, "");
1819
1935
  const dash = base.indexOf("-");
1820
1936
  if (dash > 0) {
@@ -1830,15 +1946,15 @@ function loadSchemas() {
1830
1946
  }
1831
1947
  function resolveUiDir(explicit) {
1832
1948
  if (explicit) {
1833
- return (0, import_node_fs5.existsSync)(explicit) ? explicit : null;
1949
+ return (0, import_node_fs8.existsSync)(explicit) ? explicit : null;
1834
1950
  }
1835
1951
  const candidates = ["@revenexx/studio-integrations"];
1836
1952
  const req = (0, import_node_module.createRequire)(importMetaUrl);
1837
1953
  for (const pkg of candidates) {
1838
1954
  try {
1839
1955
  const entry = req.resolve(`${pkg}/package.json`);
1840
- const dist = (0, import_node_path4.resolve)(entry, "..", "dist");
1841
- if ((0, import_node_fs5.existsSync)((0, import_node_path4.join)(dist, "index.html"))) {
1956
+ const dist = (0, import_node_path7.resolve)(entry, "..", "dist");
1957
+ if ((0, import_node_fs8.existsSync)((0, import_node_path7.join)(dist, "index.html"))) {
1842
1958
  return dist;
1843
1959
  }
1844
1960
  } catch {
@@ -1859,17 +1975,17 @@ var MIME = {
1859
1975
  };
1860
1976
  function serveStatic(uiDir, req, res) {
1861
1977
  const url = new URL(req.url ?? "/", "http://localhost");
1862
- const relative = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
1863
- let filePath = (0, import_node_path4.resolve)(uiDir, relative);
1864
- if (!filePath.startsWith(uiDir) || !(0, import_node_fs5.existsSync)(filePath)) {
1865
- filePath = (0, import_node_path4.join)(uiDir, "index.html");
1978
+ const relative2 = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
1979
+ let filePath = (0, import_node_path7.resolve)(uiDir, relative2);
1980
+ if (!filePath.startsWith(uiDir) || !(0, import_node_fs8.existsSync)(filePath)) {
1981
+ filePath = (0, import_node_path7.join)(uiDir, "index.html");
1866
1982
  }
1867
- if (!(0, import_node_fs5.existsSync)(filePath)) {
1983
+ if (!(0, import_node_fs8.existsSync)(filePath)) {
1868
1984
  res.writeHead(404).end("UI build not found");
1869
1985
  return;
1870
1986
  }
1871
- res.writeHead(200, { "Content-Type": MIME[(0, import_node_path4.extname)(filePath)] ?? "application/octet-stream" });
1872
- res.end((0, import_node_fs5.readFileSync)(filePath));
1987
+ res.writeHead(200, { "Content-Type": MIME[(0, import_node_path7.extname)(filePath)] ?? "application/octet-stream" });
1988
+ res.end((0, import_node_fs8.readFileSync)(filePath));
1873
1989
  }
1874
1990
  async function startMock(options) {
1875
1991
  let loaded = await loadPackageFromEntry(options.entry);
@@ -1905,7 +2021,10 @@ async function startMock(options) {
1905
2021
  );
1906
2022
  }
1907
2023
  });
1908
- await new Promise((r) => server.listen(options.port, r));
2024
+ const port = await listenWithFallback(server, { port: options.port, strict: options.portExplicit });
2025
+ if (port !== options.port) {
2026
+ console.log(`Port ${options.port} was taken \u2014 the mock is on ${port} instead.`);
2027
+ }
1909
2028
  const stopWatch = watchAndReload(options.entry, async () => {
1910
2029
  try {
1911
2030
  loaded = await loadPackageFromEntry(options.entry);
@@ -1916,6 +2035,7 @@ async function startMock(options) {
1916
2035
  });
1917
2036
  return {
1918
2037
  uiDir,
2038
+ port,
1919
2039
  dispose() {
1920
2040
  if (options.persist) {
1921
2041
  saveState(options.stateFile, store.toSnapshot());
@@ -1927,7 +2047,7 @@ async function startMock(options) {
1927
2047
  }
1928
2048
  async function run(options) {
1929
2049
  const mock = await startMock(options);
1930
- const urlBase = `http://localhost:${options.port}`;
2050
+ const urlBase = `http://localhost:${mock.port}`;
1931
2051
  console.log(`
1932
2052
  Mock Integrations API ${urlBase}/api/v1`);
1933
2053
  console.log(mock.uiDir ? ` Preview UI ${urlBase}` : ` Preview UI API-only \u2014 set your Nuxt host's integrationsApi to ${urlBase}/api/v1`);
@@ -1943,11 +2063,11 @@ async function run(options) {
1943
2063
  process.on("SIGTERM", shutdown);
1944
2064
  }
1945
2065
  function watchAndReload(entry, onChange) {
1946
- const dir = (0, import_node_path4.resolve)(entry, "..");
2066
+ const dir = (0, import_node_path7.resolve)(entry, "..");
1947
2067
  let timer;
1948
2068
  try {
1949
- const watcher = (0, import_node_fs5.watch)(dir, { recursive: true }, (_event, file) => {
1950
- if (file && /\.[cm]?tsx?$|\.js$/.test(file.toString())) {
2069
+ const watcher = (0, import_node_fs8.watch)(dir, { recursive: true }, (_event, file) => {
2070
+ if (file && isReloadableSource(file.toString())) {
1951
2071
  clearTimeout(timer);
1952
2072
  timer = setTimeout(onChange, 200);
1953
2073
  }
@@ -1966,42 +2086,93 @@ async function runNpmInstall(dir) {
1966
2086
  child.on("error", reject);
1967
2087
  });
1968
2088
  }
1969
- async function preview(options) {
1970
- const dir = options.previewDir;
1971
- const apiUrl = `http://localhost:${options.port}/api/v1`;
1972
- if (!previewExists(dir) || options.force) {
1973
- scaffoldPreview({ dir, integrationsApiUrl: apiUrl, force: options.force, log: (msg) => console.log(msg) });
1974
- }
1975
- if (!previewDepsInstalled(dir)) {
1976
- console.log("Installing preview-host dependencies (first run \u2014 this pulls Nuxt + the studio packages and may take a while)\u2026");
1977
- await runNpmInstall(dir);
2089
+ function noteLegacyPreviewDir() {
2090
+ const legacy = (0, import_node_path7.resolve)(process.cwd(), ".revenexx-dev/preview");
2091
+ if ((0, import_node_fs8.existsSync)(legacy)) {
2092
+ console.log(`Note: ${legacy} is no longer used \u2014 the preview host now lives in a shared cache. You can delete it to reclaim the space.`);
1978
2093
  }
2094
+ }
2095
+ var UI_PORT = 3e3;
2096
+ async function preview(options) {
2097
+ const cwd = process.cwd();
2098
+ const managed = options.previewDir === null;
2099
+ const hostDir = (0, import_node_path7.resolve)(options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION }));
2100
+ const running = readLivePreviews(hostDir);
2101
+ const conflict = previewConflict(running, { cwd, hostDir, parallel: options.parallel, force: options.force });
2102
+ if (conflict) {
2103
+ throw new CliError(conflict);
2104
+ }
2105
+ noteLegacyPreviewDir();
1979
2106
  const mock = await startMock({ ...options, serveUi: false });
1980
- console.log(`
1981
- Mock Integrations API ${apiUrl}`);
1982
- console.log(" Preview UI http://localhost:3000/integrations (Nuxt starting\u2026)\n");
1983
- const { spawn } = await import("child_process");
1984
- const child = spawn("npm", ["run", "dev"], {
1985
- cwd: dir,
1986
- stdio: "inherit",
1987
- env: {
1988
- ...process.env,
1989
- NUXT_PUBLIC_INTEGRATIONS_API: apiUrl,
1990
- NUXT_PUBLIC_DEV_TOKEN: process.env.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
1991
- NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant"
2107
+ const apiUrl = `http://localhost:${mock.port}/api/v1`;
2108
+ try {
2109
+ const { dir } = materializeHost({
2110
+ targetDir: hostDir,
2111
+ integrationsApiUrl: apiUrl,
2112
+ dotenvName: managed ? hostDotenvName(cwd) : void 0,
2113
+ force: options.force,
2114
+ managed,
2115
+ log: (msg) => console.log(msg)
2116
+ });
2117
+ if (options.force) {
2118
+ clearHostInstallMarker(dir);
2119
+ }
2120
+ if (hostNeedsInstall(dir)) {
2121
+ await withInstallLock(
2122
+ dir,
2123
+ async () => {
2124
+ console.log("Installing preview-host dependencies (this pulls Nuxt + the studio packages and may take a while)\u2026");
2125
+ await runNpmInstall(dir);
2126
+ markHostInstalled(dir);
2127
+ },
2128
+ { needsInstall: () => hostNeedsInstall(dir), log: (msg) => console.log(msg) }
2129
+ );
1992
2130
  }
1993
- });
1994
- const shutdown = () => {
1995
- child.kill("SIGTERM");
1996
- mock.dispose();
1997
- process.exit(0);
1998
- };
1999
- process.on("SIGINT", shutdown);
2000
- process.on("SIGTERM", shutdown);
2001
- child.on("exit", (code) => {
2131
+ const uiPort = process.env.NUXT_PORT ? Number(process.env.NUXT_PORT) : await findFreePort(UI_PORT);
2132
+ console.log(`
2133
+ Previewing ${(0, import_node_path7.basename)(cwd)} (${cwd})`);
2134
+ console.log(` Mock Integrations API ${apiUrl}`);
2135
+ if (managed) {
2136
+ console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);
2137
+ }
2138
+ console.log(` Preview UI starting on port ${uiPort} \u2014 Nuxt prints the URL it got, below.`);
2139
+ for (const entry of running) {
2140
+ console.log(` Also running ${describePreview(entry)}`);
2141
+ }
2142
+ console.log("");
2143
+ const { spawn } = await import("child_process");
2144
+ const args = managed ? ["run", "dev", "--", "--dotenv", hostDotenvName(cwd)] : ["run", "dev"];
2145
+ const child = spawn("npm", args, {
2146
+ cwd: dir,
2147
+ stdio: "inherit",
2148
+ env: previewChildEnv({
2149
+ base: process.env,
2150
+ apiUrl,
2151
+ uiPort,
2152
+ buildDir: hostBuildDir(dir, cwd),
2153
+ viteCacheDir: hostViteCacheDir(dir, cwd)
2154
+ })
2155
+ });
2156
+ registerPreview(dir, { pid: process.pid, cwd, mockPort: mock.port, uiPort, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
2157
+ const cleanUp = () => {
2158
+ unregisterPreview(dir);
2159
+ mock.dispose();
2160
+ };
2161
+ const shutdown = () => {
2162
+ child.kill("SIGTERM");
2163
+ cleanUp();
2164
+ process.exit(0);
2165
+ };
2166
+ process.on("SIGINT", shutdown);
2167
+ process.on("SIGTERM", shutdown);
2168
+ child.on("exit", (code) => {
2169
+ cleanUp();
2170
+ process.exit(code ?? 0);
2171
+ });
2172
+ } catch (err) {
2002
2173
  mock.dispose();
2003
- process.exit(code ?? 0);
2004
- });
2174
+ throw err;
2175
+ }
2005
2176
  }
2006
2177
  async function openBrowser(url) {
2007
2178
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
@@ -2010,30 +2181,37 @@ async function openBrowser(url) {
2010
2181
  }
2011
2182
  async function main() {
2012
2183
  const argv = process.argv.slice(2);
2013
- const envFile = loadEnvFile(argv);
2184
+ const envFile2 = loadEnvFile(argv);
2014
2185
  const { command, options } = parseArgs(argv);
2015
2186
  if (command === "version") {
2016
2187
  console.log(DEVKIT_VERSION);
2017
2188
  return;
2018
2189
  }
2019
- if (envFile) {
2020
- console.log(`Loaded env from ${envFile}`);
2190
+ if (envFile2) {
2191
+ console.log(`Loaded env from ${envFile2}`);
2021
2192
  }
2022
2193
  if (command === "reset") {
2023
- const { rmSync } = await import("fs");
2024
- rmSync(options.stateFile, { force: true });
2194
+ const { rmSync: rmSync3 } = await import("fs");
2195
+ rmSync3(options.stateFile, { force: true });
2025
2196
  console.log(`Removed ${options.stateFile}`);
2026
2197
  return;
2027
2198
  }
2028
2199
  if (command === "init-preview") {
2029
- scaffoldPreview({
2030
- dir: options.previewDir,
2200
+ if (options.previewDir === null) {
2201
+ console.error("init-preview needs an explicit target: `integrations-devkit init-preview --dir ./my-preview`.");
2202
+ console.error("It exists to give you an UNMANAGED copy of the preview host to modify. For the normal preview, just run `integrations-devkit preview` \u2014");
2203
+ console.error("that materializes the host into a shared cache and keeps it in step with the devkit version.");
2204
+ process.exit(1);
2205
+ }
2206
+ const { dir } = materializeHost({
2207
+ targetDir: options.previewDir,
2031
2208
  integrationsApiUrl: `http://localhost:${options.port}/api/v1`,
2032
2209
  force: options.force,
2033
2210
  log: (msg) => console.log(msg)
2034
2211
  });
2035
- console.log(`
2036
- Next: \`integrations-devkit preview\` (installs deps + starts mock + Nuxt), or \`cd ${options.previewDir} && npm install && npm run dev\`.`);
2212
+ console.log("\nThis copy is yours and will NOT be updated by devkit upgrades.");
2213
+ console.log(`Run it with: \`cd ${dir} && npm install && npm run dev\` (plus \`integrations-devkit --no-ui\` for the mock),`);
2214
+ console.log(`or \`integrations-devkit preview --dir ${dir}\` to have both started for you.`);
2037
2215
  return;
2038
2216
  }
2039
2217
  if (command === "preview") {
@@ -2043,7 +2221,7 @@ Next: \`integrations-devkit preview\` (installs deps + starts mock + Nuxt), or \
2043
2221
  await run(options);
2044
2222
  }
2045
2223
  main().catch((err) => {
2046
- console.error(err);
2224
+ console.error(err instanceof CliError ? err.message : err);
2047
2225
  process.exit(1);
2048
2226
  });
2049
2227
  //# sourceMappingURL=cli.cjs.map