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