@revenexx/integrations-node-devkit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,779 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ DEVKIT_VERSION,
4
+ DevStore,
5
+ applySeeds,
6
+ createRequestListener,
7
+ loadPackageFromEntry,
8
+ loadSeedsFromDir,
9
+ loadState,
10
+ saveState
11
+ } from "./chunk-WPZPKJAS.js";
12
+
13
+ // src/cli.ts
14
+ import { existsSync as existsSync2, readdirSync, readFileSync, watch } from "fs";
15
+ import { createServer } from "http";
16
+ import { createRequire } from "module";
17
+ import { extname, join as join2, resolve as resolve2 } from "path";
18
+ import { fileURLToPath } from "url";
19
+
20
+ // src/preview/scaffold.ts
21
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
22
+ import { dirname, join, resolve } from "path";
23
+
24
+ // src/preview/templates.ts
25
+ var VERSIONS = {
26
+ nuxt: "^4.0.0",
27
+ vue: "^3.5.0",
28
+ studio: "^0.1.3",
29
+ studioShared: "^0.2.0",
30
+ studioIntegrations: "^0.5.1",
31
+ vueFlowCore: "^1.48.2",
32
+ vueFlowBackground: "^1.3.2",
33
+ vueFlowControls: "^1.1.3",
34
+ vueFlowMinimap: "^1.5.4",
35
+ vueFlowNodeToolbar: "^1.1.1",
36
+ dagre: "^3.0.0",
37
+ lucide: "^1.0.0",
38
+ solarIcons: "^1.2.1",
39
+ // studio-integrations 0.5.x embeds a TipTap rich-text editor and vue-sonner toasts.
40
+ tiptap: "^3.28.0",
41
+ vueSonner: "^2.0.0",
42
+ tailwindVite: "^4.0.0",
43
+ tailwind: "^4.0.0"
44
+ };
45
+ var PACKAGE_JSON = `{
46
+ "name": "integrations-preview-host",
47
+ "private": true,
48
+ "type": "module",
49
+ "scripts": {
50
+ "dev": "nuxt dev",
51
+ "build": "nuxt build"
52
+ },
53
+ "dependencies": {
54
+ "@revenexx/studio": "${VERSIONS.studio}",
55
+ "@revenexx/studio-integrations": "${VERSIONS.studioIntegrations}",
56
+ "@revenexx/studio-shared": "${VERSIONS.studioShared}",
57
+ "@solar-icons/nuxt": "${VERSIONS.solarIcons}",
58
+ "@dagrejs/dagre": "${VERSIONS.dagre}",
59
+ "@tiptap/core": "${VERSIONS.tiptap}",
60
+ "@tiptap/extension-document": "${VERSIONS.tiptap}",
61
+ "@tiptap/extension-history": "${VERSIONS.tiptap}",
62
+ "@tiptap/extension-paragraph": "${VERSIONS.tiptap}",
63
+ "@tiptap/extension-text": "${VERSIONS.tiptap}",
64
+ "@tiptap/pm": "${VERSIONS.tiptap}",
65
+ "@tiptap/vue-3": "${VERSIONS.tiptap}",
66
+ "@vue-flow/background": "${VERSIONS.vueFlowBackground}",
67
+ "@vue-flow/controls": "${VERSIONS.vueFlowControls}",
68
+ "@vue-flow/core": "${VERSIONS.vueFlowCore}",
69
+ "@vue-flow/minimap": "${VERSIONS.vueFlowMinimap}",
70
+ "@vue-flow/node-toolbar": "${VERSIONS.vueFlowNodeToolbar}",
71
+ "lucide-vue-next": "${VERSIONS.lucide}",
72
+ "nuxt": "${VERSIONS.nuxt}",
73
+ "vue": "${VERSIONS.vue}",
74
+ "vue-sonner": "${VERSIONS.vueSonner}"
75
+ },
76
+ "devDependencies": {
77
+ "@tailwindcss/vite": "${VERSIONS.tailwindVite}",
78
+ "tailwindcss": "${VERSIONS.tailwind}"
79
+ }
80
+ }
81
+ `;
82
+ var NUXT_CONFIG = `import tailwindcss from '@tailwindcss/vite';
83
+
84
+ // Minimal preview host for local integration-node development.
85
+ // Generated by \`integrations-devkit init-preview\` \u2014 safe to edit or delete
86
+ // (it lives under the gitignored .revenexx-dev/).
87
+ export default defineNuxtConfig({
88
+ compatibilityDate: '2025-01-01',
89
+ // SPA: no SSR, so the studio's browser-only composables (localStorage etc.)
90
+ // behave exactly as in the real cockpit, and boot is fast.
91
+ ssr: false,
92
+ // studio-shared 0.2.x ships as a Nuxt MODULE (not a layer) \u2014 it must be
93
+ // registered in 'modules', before studio-integrations which builds on it.
94
+ // @solar-icons/nuxt provides the #solar-icons alias the studio components import.
95
+ modules: ['@revenexx/studio-shared', '@solar-icons/nuxt', '@revenexx/studio-integrations'],
96
+ css: ['~/assets/css/main.css'],
97
+ vite: { plugins: [tailwindcss()] },
98
+ runtimeConfig: {
99
+ public: {
100
+ // Overridden at runtime by NUXT_PUBLIC_* env (see .env / the preview command).
101
+ integrationsApi: '',
102
+ devToken: '',
103
+ devTenant: '',
104
+ },
105
+ },
106
+ });
107
+ `;
108
+ var MAIN_CSS = `@import "tailwindcss";
109
+ @import "@revenexx/studio/tokens";
110
+ @import "@revenexx/studio/fonts";
111
+
112
+ @source "../../node_modules/@revenexx/studio/dist";
113
+ @source "../../node_modules/@revenexx/studio-shared/components";
114
+ @source "../../node_modules/@revenexx/studio-integrations/dist/runtime";
115
+
116
+ /* Phase 1: workflow EXECUTION is not wired up in the devkit preview yet, so the
117
+ Workflows surface is hidden until phase 2. This hides the sidebar nav entry
118
+ and any deep links to the workflow editor; the routes are also redirected by
119
+ middleware/hide-workflows.global.ts. */
120
+ a[href^="/integrations/workflows"] { display: none !important; }
121
+ li:has(> a[href^="/integrations/workflows"]) { display: none !important; }
122
+ `;
123
+ var APP_VUE = `<script setup lang="ts">
124
+ import { Toaster } from '@revenexx/studio'
125
+
126
+ useHead({ title: 'Integration Studio \u2014 devkit preview' })
127
+ </script>
128
+
129
+ <template>
130
+ <div class="flex h-svh flex-col overflow-hidden bg-[#f3f1fa] text-foreground">
131
+ <NuxtLoadingIndicator color="var(--color-primary, #620DFF)" :height="3" />
132
+ <div class="min-h-0 flex-1 pt-3">
133
+ <NuxtPage />
134
+ </div>
135
+ <Toaster rich-colors position="bottom-right" :duration="3500" close-button />
136
+ </div>
137
+ </template>
138
+ `;
139
+ var INDEX_VUE = `<template>
140
+ <div class="mx-auto flex min-h-full max-w-xl flex-col justify-center gap-6 px-6 py-12">
141
+ <div>
142
+ <p class="text-mono text-muted-foreground">Integrations \xB7 node devkit</p>
143
+ <h1 class="mt-1 text-2xl font-medium">Integration Studio \u2014 Preview</h1>
144
+ <p class="mt-2 text-sm text-muted-foreground">
145
+ Lokaler Host f\xFCr <code>@revenexx/studio-integrations</code> gegen die Mock-API
146
+ deines Node-Pakets. Authentifizierung ist ein festes Dev-Token \u2014 nichts einzugeben.
147
+ </p>
148
+ </div>
149
+
150
+ <div class="rounded-lg border border-black/[0.06] bg-card p-5 text-sm shadow-sm">
151
+ <p class="text-mono text-muted-foreground">Session</p>
152
+ <dl class="mt-2 grid grid-cols-[7rem_1fr] gap-y-1">
153
+ <dt class="text-muted-foreground">Mock API</dt>
154
+ <dd class="truncate font-mono text-xs leading-5">{{ api }}</dd>
155
+ <dt class="text-muted-foreground">Tenant</dt>
156
+ <dd class="font-mono text-xs leading-5">{{ tenant }}</dd>
157
+ </dl>
158
+ </div>
159
+
160
+ <div class="rounded-lg border border-black/[0.06] bg-card p-5 shadow-sm">
161
+ <p class="text-mono text-muted-foreground">Einstieg</p>
162
+ <div class="mt-3 flex flex-col gap-4">
163
+ <NuxtLink
164
+ to="/nodes"
165
+ 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"
166
+ >
167
+ Lokale Nodes \xF6ffnen \u2014 Preview + Validierung
168
+ </NuxtLink>
169
+ <div class="flex flex-wrap gap-x-4 gap-y-1.5">
170
+ <NuxtLink
171
+ v-for="link in quickLinks"
172
+ :key="link.to"
173
+ :to="link.to"
174
+ class="text-sm text-primary hover:underline"
175
+ >
176
+ {{ link.label }}
177
+ </NuxtLink>
178
+ </div>
179
+ </div>
180
+ </div>
181
+ </div>
182
+ </template>
183
+
184
+ <script setup lang="ts">
185
+ const rc = useRuntimeConfig().public
186
+ const api = rc.integrationsApi
187
+ const tenant = (rc.devTenant as string) || 'dev-tenant'
188
+
189
+ const quickLinks = [
190
+ { to: '/integrations', label: 'Overview' },
191
+ { to: '/integrations/credentials', label: 'Credentials' },
192
+ { to: '/integrations/secrets', label: 'Secrets' },
193
+ { to: '/nodes', label: 'Local nodes' },
194
+ ]
195
+ </script>
196
+ `;
197
+ var NODES_VUE = `<template>
198
+ <div class="ndx-page">
199
+ <div class="ndx-inner">
200
+ <header class="ndx-head">
201
+ <h1>Lokale Nodes</h1>
202
+ <p>Mock-API: <code>{{ apiUrl }}</code></p>
203
+ <p v-if="loadError" class="ndx-err">{{ loadError }}</p>
204
+ </header>
205
+
206
+ <p v-if="loading">Lade Nodes\u2026</p>
207
+ <p v-else-if="nodes.length === 0">Keine Nodes gefunden. Exportiert dein Paket <code>NODES</code>?</p>
208
+
209
+ <ul v-else class="ndx-grid">
210
+ <li v-for="n in nodes" :key="n.slug + '@' + n.version" class="ndx-card" @click="openNode(n)">
211
+ <div class="ndx-card-title">{{ label(n) }}</div>
212
+ <div class="ndx-card-slug">{{ n.slug }} \xB7 v{{ n.version }}</div>
213
+ <div class="ndx-badges">
214
+ <span v-if="n.has_dynamic_options" class="ndx-badge">dynamic options</span>
215
+ <span v-if="n.has_dynamic_schema" class="ndx-badge">dynamic schema</span>
216
+ <span v-if="n.has_dynamic_outputs" class="ndx-badge">dynamic outputs</span>
217
+ </div>
218
+ </li>
219
+ </ul>
220
+ </div>
221
+
222
+ <!-- REUSE of the exact editor lightbox: studio <Dialog> owns the modal
223
+ chrome, <IntegrationsNodeInspector> is the content \u2014 mirrors
224
+ WorkflowEditor.vue's <Dialog><DialogContent><NodeInspector/> block. -->
225
+ <Dialog :open="!!selection" @update:open="(v) => { if (!v) requestClose() }">
226
+ <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">
227
+ <div v-if="result === 'ok'" class="ndx-strip ndx-strip-ok">\u2713 Payload g\xFCltig \u2014 alles gut.</div>
228
+ <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>
229
+ <div v-else-if="formError" class="ndx-strip ndx-strip-err">{{ formError }}</div>
230
+ <IntegrationsNodeInspector
231
+ v-if="selection"
232
+ :selection="selection"
233
+ :secret-keys="secretKeys"
234
+ :refused-fields="refused"
235
+ @update="onSubmit"
236
+ @close="requestClose" />
237
+ </DialogContent>
238
+ </Dialog>
239
+ </div>
240
+ </template>
241
+
242
+ <script setup lang="ts">
243
+ import { computed, onMounted, ref } from 'vue'
244
+ import { Dialog, DialogContent } from '@revenexx/studio'
245
+
246
+ interface ApiNode {
247
+ name: string | Record<string, string>
248
+ slug: string
249
+ version: string
250
+ manifest?: { name?: string | Record<string, string> }
251
+ has_dynamic_options?: boolean
252
+ has_dynamic_schema?: boolean
253
+ has_dynamic_outputs?: boolean
254
+ }
255
+
256
+ const apiUrl = useRuntimeConfig().public.integrationsApi
257
+ const client = useIntegrationsApi()
258
+ // load() fills the reactive catalog the inspector reads via findManifest();
259
+ // resolveLocalized() turns a LocalizedString into the active-locale string.
260
+ const { load, resolveLocalized } = useIntegrationsNodes()
261
+
262
+ const nodes = ref<ApiNode[]>([])
263
+ const loading = ref(true)
264
+ const loadError = ref<string | null>(null)
265
+
266
+ const selection = ref<any>(null)
267
+ const secretKeys = ref<string[]>([])
268
+ const refused = ref<Record<string, string>>({})
269
+ const result = ref<string | null>(null)
270
+ const formError = ref<string | null>(null)
271
+ // Set synchronously in onSubmit so the inspector's own Save (it emits update THEN
272
+ // close) does NOT close the dialog \u2014 we keep it open to show the verdict.
273
+ const validating = ref(false)
274
+
275
+ const errorCount = computed(() => Object.keys(refused.value).length)
276
+
277
+ function label(n: ApiNode): string {
278
+ return resolveLocalized(n.manifest?.name ?? n.name) || n.slug
279
+ }
280
+
281
+ onMounted(async () => {
282
+ await load()
283
+ try {
284
+ const res = await client.get<any>('/nodes')
285
+ nodes.value = (Array.isArray(res) ? res : res?.data ?? []) as ApiNode[]
286
+ } catch (e: any) {
287
+ loadError.value = e?.message ?? 'Nodes konnten nicht geladen werden.'
288
+ } finally {
289
+ loading.value = false
290
+ }
291
+ try {
292
+ const secrets = await client.get<any>('/secrets')
293
+ const list = (Array.isArray(secrets) ? secrets : secrets?.data ?? []) as Array<{ key: string }>
294
+ secretKeys.value = list.map(s => s.key).filter(Boolean)
295
+ } catch {
296
+ // secrets are optional for the preview
297
+ }
298
+ })
299
+
300
+ function openNode(n: ApiNode) {
301
+ refused.value = {}
302
+ result.value = null
303
+ formError.value = null
304
+ // Synthetic WorkflowNode selection (distinguished by nodeSlug); the inspector
305
+ // resolves its manifest from the catalog load() populated above.
306
+ selection.value = { id: 'preview', nodeSlug: n.slug, nodeVersion: n.version, name: label(n), config: {} }
307
+ }
308
+
309
+ async function onSubmit(draft: any) {
310
+ validating.value = true
311
+ refused.value = {}
312
+ result.value = null
313
+ formError.value = null
314
+ try {
315
+ const slug = encodeURIComponent(draft.nodeSlug)
316
+ const version = encodeURIComponent(draft.nodeVersion || 'latest')
317
+ const res = await client.post<any>(
318
+ '/nodes/' + slug + '/' + version + '/config:validate',
319
+ { config: draft.config ?? {} },
320
+ )
321
+ if (res.valid) {
322
+ result.value = 'ok'
323
+ } else {
324
+ refused.value = Object.fromEntries(
325
+ Object.entries(res.errors ?? {}).map(([k, msgs]) => [k, (msgs as string[]).join(' ')]),
326
+ )
327
+ result.value = 'err'
328
+ }
329
+ } catch (e: any) {
330
+ formError.value = e?.message ?? 'Validierung fehlgeschlagen.'
331
+ } finally {
332
+ validating.value = false
333
+ }
334
+ }
335
+
336
+ // The inspector emits close on both Save and Cancel; the studio Dialog emits it
337
+ // on Esc / backdrop. Hold the close while a Save-validation is in flight so the
338
+ // dialog stays open to show the result; otherwise close (discard).
339
+ function requestClose() {
340
+ if (validating.value) return
341
+ selection.value = null
342
+ refused.value = {}
343
+ result.value = null
344
+ formError.value = null
345
+ }
346
+ </script>
347
+
348
+ <style scoped>
349
+ /* The app shell (app.vue) is h-svh + overflow-hidden, so this page must own its
350
+ own vertical scroll \u2014 otherwise the node list is clipped and can't scroll. */
351
+ .ndx-page { height: 100%; overflow-y: auto; }
352
+ .ndx-inner { max-width: 60rem; margin: 0 auto; padding: 2rem; font-family: sans-serif; }
353
+ .ndx-head h1 { font-size: 1.5rem; font-weight: 600; }
354
+ .ndx-err { color: #b91c1c; }
355
+ .ndx-grid { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: 1rem; margin-top: 1.5rem; }
356
+ .ndx-card { border: 1px solid #d1d5db; border-radius: 0.5rem; padding: 1rem; cursor: pointer; transition: border-color .15s, box-shadow .15s; }
357
+ .ndx-card:hover { border-color: #6366f1; box-shadow: 0 1px 6px rgba(0,0,0,.08); }
358
+ .ndx-card-title { font-weight: 600; }
359
+ .ndx-card-slug { color: #6b7280; font-size: .85rem; margin-top: .25rem; }
360
+ .ndx-badges { margin-top: .5rem; display: flex; flex-wrap: wrap; gap: .35rem; }
361
+ .ndx-badge { font-size: .7rem; background: #eef2ff; color: #4338ca; border-radius: .25rem; padding: .1rem .4rem; }
362
+
363
+ /* Verdict strip shown at the top of the reused dialog content (does not close). */
364
+ .ndx-strip { flex: 0 0 auto; padding: .5rem 1rem; font-size: .85rem; font-weight: 600; }
365
+ .ndx-strip-ok { background: #dcfce7; color: #166534; }
366
+ .ndx-strip-err { background: #fee2e2; color: #991b1b; }
367
+ </style>
368
+ `;
369
+ var GITIGNORE = `node_modules/
370
+ .nuxt/
371
+ .output/
372
+ .data/
373
+ `;
374
+ var CONSOLE_STUBS = `import { ref } from 'vue'
375
+
376
+ export function useConsoleTenants() {
377
+ return { tenants: ref([]), onlyTenantSlug: ref(null), load: async () => {} }
378
+ }
379
+ export function useActiveMarket() {
380
+ return {
381
+ markets: ref([]),
382
+ activeCode: ref(''),
383
+ isGlobal: ref(true),
384
+ GLOBAL_MARKET_CODE: '__global__',
385
+ fetchMarkets: async () => {},
386
+ }
387
+ }
388
+ export function useConsoleSftp() {
389
+ return {
390
+ accounts: ref([]),
391
+ load: async () => {},
392
+ revealPassword: async () => ({}),
393
+ create: async () => ({}),
394
+ refresh: async () => ({}),
395
+ }
396
+ }
397
+ export function useMailAdmin() {
398
+ return {
399
+ listCredentials: async () => [],
400
+ getCredential: async () => ({}),
401
+ createCredential: async () => ({}),
402
+ }
403
+ }
404
+ export function useConsoleApiKeys() {
405
+ return { create: async () => ({ secret: '' }) }
406
+ }
407
+ `;
408
+ var HIDE_WORKFLOWS_MW = `export default defineNuxtRouteMiddleware((to) => {
409
+ if (to.path === '/integrations/workflows' || to.path.startsWith('/integrations/workflows/')) {
410
+ return navigateTo('/integrations')
411
+ }
412
+ })
413
+ `;
414
+ function previewTemplates(options) {
415
+ const env = `# Overrides the Nuxt runtimeConfig.public.* values.
416
+ NUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}
417
+ NUXT_PUBLIC_DEV_TOKEN=dev
418
+ NUXT_PUBLIC_DEV_TENANT=dev-tenant
419
+ `;
420
+ return {
421
+ "package.json": PACKAGE_JSON,
422
+ "nuxt.config.ts": NUXT_CONFIG,
423
+ "assets/css/main.css": MAIN_CSS,
424
+ "app.vue": APP_VUE,
425
+ "pages/index.vue": INDEX_VUE,
426
+ "pages/nodes.vue": NODES_VUE,
427
+ "composables/devkit-console-stubs.ts": CONSOLE_STUBS,
428
+ "middleware/hide-workflows.global.ts": HIDE_WORKFLOWS_MW,
429
+ ".env": env,
430
+ ".gitignore": GITIGNORE
431
+ };
432
+ }
433
+
434
+ // src/preview/scaffold.ts
435
+ function scaffoldPreview(options) {
436
+ const log = options.log ?? (() => {
437
+ });
438
+ const files = previewTemplates({ integrationsApiUrl: options.integrationsApiUrl });
439
+ const written = [];
440
+ const skipped = [];
441
+ for (const [relative, content] of Object.entries(files)) {
442
+ const target = resolve(options.dir, relative);
443
+ if (existsSync(target) && !options.force) {
444
+ skipped.push(relative);
445
+ continue;
446
+ }
447
+ mkdirSync(dirname(target), { recursive: true });
448
+ writeFileSync(target, content, "utf-8");
449
+ written.push(relative);
450
+ }
451
+ if (written.length > 0) {
452
+ log(`Scaffolded preview host in ${options.dir} (${written.length} file(s)).`);
453
+ }
454
+ if (skipped.length > 0) {
455
+ log(`Kept ${skipped.length} existing file(s) (use --force to overwrite).`);
456
+ }
457
+ return { dir: options.dir, written, skipped };
458
+ }
459
+ function previewDepsInstalled(dir) {
460
+ return existsSync(join(dir, "node_modules"));
461
+ }
462
+ function previewExists(dir) {
463
+ return existsSync(join(dir, "package.json")) && existsSync(join(dir, "nuxt.config.ts"));
464
+ }
465
+
466
+ // src/cli.ts
467
+ function parseArgs(argv) {
468
+ const cwd = process.cwd();
469
+ const opts = {
470
+ entry: "",
471
+ seedDir: resolve2(cwd, "dev/seeds"),
472
+ stateFile: resolve2(cwd, ".revenexx-dev/state.json"),
473
+ persist: true,
474
+ port: Number.parseInt(process.env.PORT ?? "3555", 10),
475
+ uiDir: null,
476
+ serveUi: true,
477
+ open: false,
478
+ previewDir: resolve2(cwd, ".revenexx-dev/preview"),
479
+ force: false
480
+ };
481
+ let command = null;
482
+ for (let i = 0; i < argv.length; i++) {
483
+ const arg = argv[i];
484
+ switch (arg) {
485
+ case "reset":
486
+ command = "reset";
487
+ break;
488
+ case "init-preview":
489
+ command = "init-preview";
490
+ break;
491
+ case "preview":
492
+ command = "preview";
493
+ break;
494
+ case "--dir":
495
+ opts.previewDir = resolve2(cwd, argv[++i] ?? "");
496
+ break;
497
+ case "--force":
498
+ opts.force = true;
499
+ break;
500
+ case "--entry":
501
+ opts.entry = resolve2(cwd, argv[++i] ?? "");
502
+ break;
503
+ case "--seed":
504
+ opts.seedDir = resolve2(cwd, argv[++i] ?? "");
505
+ break;
506
+ case "--state":
507
+ opts.stateFile = resolve2(cwd, argv[++i] ?? "");
508
+ break;
509
+ case "--no-persist":
510
+ opts.persist = false;
511
+ break;
512
+ case "--port":
513
+ opts.port = Number.parseInt(argv[++i] ?? "3555", 10);
514
+ break;
515
+ case "--ui":
516
+ opts.uiDir = resolve2(cwd, argv[++i] ?? "");
517
+ break;
518
+ case "--no-ui":
519
+ opts.serveUi = false;
520
+ break;
521
+ case "--open":
522
+ opts.open = true;
523
+ break;
524
+ case "--version":
525
+ case "-v":
526
+ command = "version";
527
+ break;
528
+ default:
529
+ if (arg?.startsWith("-")) {
530
+ console.error(`Unknown option: ${arg}`);
531
+ process.exit(1);
532
+ }
533
+ }
534
+ }
535
+ if (!opts.entry) {
536
+ const src = resolve2(cwd, "src/index.ts");
537
+ opts.entry = existsSync2(src) ? src : resolve2(cwd, "dist/index.js");
538
+ }
539
+ return { command, options: opts };
540
+ }
541
+ function loadSchemas() {
542
+ const here = fileURLToPath(new URL(".", import.meta.url));
543
+ const schemasDir = resolve2(here, "..", "assets", "schemas");
544
+ const schemas = {};
545
+ if (!existsSync2(schemasDir)) {
546
+ return schemas;
547
+ }
548
+ for (const file of readdirSync(schemasDir)) {
549
+ if (extname(file) !== ".json") {
550
+ continue;
551
+ }
552
+ const parsed = JSON.parse(readFileSync(join2(schemasDir, file), "utf-8"));
553
+ const base = file.replace(/\.json$/, "");
554
+ const dash = base.indexOf("-");
555
+ if (dash > 0) {
556
+ const domain = base.slice(0, dash);
557
+ const version = base.slice(dash + 1);
558
+ schemas[`${domain}/${version}`] = parsed;
559
+ schemas[domain] = parsed;
560
+ } else {
561
+ schemas[base] = parsed;
562
+ }
563
+ }
564
+ return schemas;
565
+ }
566
+ function resolveUiDir(explicit) {
567
+ if (explicit) {
568
+ return existsSync2(explicit) ? explicit : null;
569
+ }
570
+ const candidates = ["@revenexx/studio-integrations"];
571
+ const req = createRequire(import.meta.url);
572
+ for (const pkg of candidates) {
573
+ try {
574
+ const entry = req.resolve(`${pkg}/package.json`);
575
+ const dist = resolve2(entry, "..", "dist");
576
+ if (existsSync2(join2(dist, "index.html"))) {
577
+ return dist;
578
+ }
579
+ } catch {
580
+ }
581
+ }
582
+ return null;
583
+ }
584
+ var MIME = {
585
+ ".html": "text/html",
586
+ ".js": "text/javascript",
587
+ ".mjs": "text/javascript",
588
+ ".css": "text/css",
589
+ ".json": "application/json",
590
+ ".svg": "image/svg+xml",
591
+ ".png": "image/png",
592
+ ".ico": "image/x-icon",
593
+ ".woff2": "font/woff2"
594
+ };
595
+ function serveStatic(uiDir, req, res) {
596
+ const url = new URL(req.url ?? "/", "http://localhost");
597
+ const relative = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
598
+ let filePath = resolve2(uiDir, relative);
599
+ if (!filePath.startsWith(uiDir) || !existsSync2(filePath)) {
600
+ filePath = join2(uiDir, "index.html");
601
+ }
602
+ if (!existsSync2(filePath)) {
603
+ res.writeHead(404).end("UI build not found");
604
+ return;
605
+ }
606
+ res.writeHead(200, { "Content-Type": MIME[extname(filePath)] ?? "application/octet-stream" });
607
+ res.end(readFileSync(filePath));
608
+ }
609
+ async function startMock(options) {
610
+ let loaded = await loadPackageFromEntry(options.entry);
611
+ console.log(`Loaded ${loaded.nodes.length} node(s), ${loaded.credentials.length} credential(s), ${loaded.templates.length} template(s) from ${options.entry}`);
612
+ const store = new DevStore();
613
+ applySeeds(store, await loadSeedsFromDir(options.seedDir));
614
+ if (options.persist) {
615
+ const state = loadState(options.stateFile);
616
+ if (state) {
617
+ store.mergeSnapshot(state);
618
+ console.log(`Restored session from ${options.stateFile}`);
619
+ }
620
+ let timer;
621
+ store.setOnMutation(() => {
622
+ clearTimeout(timer);
623
+ timer = setTimeout(() => saveState(options.stateFile, store.toSnapshot()), 150);
624
+ });
625
+ }
626
+ const schemas = loadSchemas();
627
+ const apiListener = createRequestListener({ getPackage: () => loaded, store, schemas });
628
+ const uiDir = options.serveUi ? resolveUiDir(options.uiDir) : null;
629
+ const server = createServer((req, res) => {
630
+ const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
631
+ if (pathname.startsWith("/api/") || pathname === "/health") {
632
+ apiListener(req, res);
633
+ } else if (uiDir) {
634
+ serveStatic(uiDir, req, res);
635
+ } else {
636
+ res.writeHead(404, { "Content-Type": "application/json" }).end(
637
+ JSON.stringify({
638
+ message: "API-only. Point your Nuxt host (studio-integrations) integrationsApi at this URL, or pass --ui <static-build-dir>. CORS is open."
639
+ })
640
+ );
641
+ }
642
+ });
643
+ await new Promise((r) => server.listen(options.port, r));
644
+ const stopWatch = watchAndReload(options.entry, async () => {
645
+ try {
646
+ loaded = await loadPackageFromEntry(options.entry);
647
+ console.log(`\u21BB Reloaded package (${loaded.nodes.length} nodes, ${loaded.credentials.length} credentials).`);
648
+ } catch (err) {
649
+ console.error(`Reload failed: ${err.message}`);
650
+ }
651
+ });
652
+ return {
653
+ uiDir,
654
+ dispose() {
655
+ if (options.persist) {
656
+ saveState(options.stateFile, store.toSnapshot());
657
+ }
658
+ stopWatch?.();
659
+ server.close();
660
+ }
661
+ };
662
+ }
663
+ async function run(options) {
664
+ const mock = await startMock(options);
665
+ const urlBase = `http://localhost:${options.port}`;
666
+ console.log(`
667
+ Mock Integrations API ${urlBase}/api/v1`);
668
+ console.log(mock.uiDir ? ` Preview UI ${urlBase}` : ` Preview UI API-only \u2014 set your Nuxt host's integrationsApi to ${urlBase}/api/v1`);
669
+ console.log("\n Watching for changes. Ctrl-C to stop.\n");
670
+ if (options.open && mock.uiDir) {
671
+ void openBrowser(urlBase);
672
+ }
673
+ const shutdown = () => {
674
+ mock.dispose();
675
+ process.exit(0);
676
+ };
677
+ process.on("SIGINT", shutdown);
678
+ process.on("SIGTERM", shutdown);
679
+ }
680
+ function watchAndReload(entry, onChange) {
681
+ const dir = resolve2(entry, "..");
682
+ let timer;
683
+ try {
684
+ const watcher = watch(dir, { recursive: true }, (_event, file) => {
685
+ if (file && /\.[cm]?tsx?$|\.js$/.test(file.toString())) {
686
+ clearTimeout(timer);
687
+ timer = setTimeout(onChange, 200);
688
+ }
689
+ });
690
+ return () => watcher.close();
691
+ } catch {
692
+ console.warn("Hot-reload unavailable on this platform; restart to pick up changes.");
693
+ return void 0;
694
+ }
695
+ }
696
+ async function runNpmInstall(dir) {
697
+ const { spawn } = await import("child_process");
698
+ await new Promise((resolvePromise, reject) => {
699
+ const child = spawn("npm", ["install"], { cwd: dir, stdio: "inherit" });
700
+ child.on("exit", (code) => code === 0 ? resolvePromise() : reject(new Error(`npm install exited with code ${code}`)));
701
+ child.on("error", reject);
702
+ });
703
+ }
704
+ async function preview(options) {
705
+ const dir = options.previewDir;
706
+ const apiUrl = `http://localhost:${options.port}/api/v1`;
707
+ if (!previewExists(dir) || options.force) {
708
+ scaffoldPreview({ dir, integrationsApiUrl: apiUrl, force: options.force, log: (msg) => console.log(msg) });
709
+ }
710
+ if (!previewDepsInstalled(dir)) {
711
+ console.log("Installing preview-host dependencies (first run \u2014 this pulls Nuxt + the studio packages and may take a while)\u2026");
712
+ await runNpmInstall(dir);
713
+ }
714
+ const mock = await startMock({ ...options, serveUi: false });
715
+ console.log(`
716
+ Mock Integrations API ${apiUrl}`);
717
+ console.log(" Preview UI http://localhost:3000/integrations (Nuxt starting\u2026)\n");
718
+ const { spawn } = await import("child_process");
719
+ const child = spawn("npm", ["run", "dev"], {
720
+ cwd: dir,
721
+ stdio: "inherit",
722
+ env: {
723
+ ...process.env,
724
+ NUXT_PUBLIC_INTEGRATIONS_API: apiUrl,
725
+ NUXT_PUBLIC_DEV_TOKEN: process.env.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
726
+ NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant"
727
+ }
728
+ });
729
+ const shutdown = () => {
730
+ child.kill("SIGTERM");
731
+ mock.dispose();
732
+ process.exit(0);
733
+ };
734
+ process.on("SIGINT", shutdown);
735
+ process.on("SIGTERM", shutdown);
736
+ child.on("exit", (code) => {
737
+ mock.dispose();
738
+ process.exit(code ?? 0);
739
+ });
740
+ }
741
+ async function openBrowser(url) {
742
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
743
+ const { spawn } = await import("child_process");
744
+ spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
745
+ }
746
+ async function main() {
747
+ const { command, options } = parseArgs(process.argv.slice(2));
748
+ if (command === "version") {
749
+ console.log(DEVKIT_VERSION);
750
+ return;
751
+ }
752
+ if (command === "reset") {
753
+ const { rmSync } = await import("fs");
754
+ rmSync(options.stateFile, { force: true });
755
+ console.log(`Removed ${options.stateFile}`);
756
+ return;
757
+ }
758
+ if (command === "init-preview") {
759
+ scaffoldPreview({
760
+ dir: options.previewDir,
761
+ integrationsApiUrl: `http://localhost:${options.port}/api/v1`,
762
+ force: options.force,
763
+ log: (msg) => console.log(msg)
764
+ });
765
+ console.log(`
766
+ Next: \`integrations-devkit preview\` (installs deps + starts mock + Nuxt), or \`cd ${options.previewDir} && npm install && npm run dev\`.`);
767
+ return;
768
+ }
769
+ if (command === "preview") {
770
+ await preview(options);
771
+ return;
772
+ }
773
+ await run(options);
774
+ }
775
+ main().catch((err) => {
776
+ console.error(err);
777
+ process.exit(1);
778
+ });
779
+ //# sourceMappingURL=cli.js.map