@mndw/cli 0.0.0-stage → 0.1.1

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.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/meta.json +1821 -0
  4. package/dist/mndw.js +3993 -0
  5. package/host-dev/assets/_virtual_sandbox-manifest-DbTeSIus.js +1 -0
  6. package/host-dev/assets/_virtual_sandbox-plugin-Cg-1CvkF.js +1 -0
  7. package/host-dev/assets/index-CADLhduS.js +94 -0
  8. package/host-dev/assets/index-TmL5gfki.css +1 -0
  9. package/host-dev/assets/sandbox-url-D9gV-Yo0.js +1 -0
  10. package/host-dev/assets/sprite-DIkKar2y.svg +189 -0
  11. package/host-dev/assets/ticker-pool.worker-DJA1ERT2.js +1 -0
  12. package/host-dev/index.html +33 -0
  13. package/host-dev/shared/angular-common@21.2.18.js +30 -0
  14. package/host-dev/shared/angular-compiler@21.2.18.js +84 -0
  15. package/host-dev/shared/angular-core@21.2.18.js +122 -0
  16. package/host-dev/shared/angular-platform-browser@21.2.18.js +34 -0
  17. package/host-dev/shared/d3@7.9.0.js +5 -0
  18. package/host-dev/shared/hash-wasm@4.12.0.js +10 -0
  19. package/host-dev/shared/mndw-ui@0.1.1.js +1656 -0
  20. package/host-dev/shared/rci-tools-core@0.6.0.js +15 -0
  21. package/host-dev/shared/rxjs-operators@7.8.2.js +3 -0
  22. package/host-dev/shared/rxjs@7.8.2.js +3 -0
  23. package/host-dev/shared/vue@3.5.39.js +56 -0
  24. package/host-dev/shared/zone@0.15.1.js +11 -0
  25. package/package.json +77 -3
  26. package/templates/angular/src/app.component.ts +57 -0
  27. package/templates/angular/src/index.ts +21 -0
  28. package/templates/angular/src/l10n.test.ts +50 -0
  29. package/templates/angular/src/table.test.ts +59 -0
  30. package/templates/angular/tsconfig.json +18 -0
  31. package/templates/backend/main.sh +7 -0
  32. package/templates/go/backend/cmd/__MNDW_NAME__d/main.go +20 -0
  33. package/templates/go/backend/go.mod +6 -0
  34. package/templates/go/backend/integration_test.go +174 -0
  35. package/templates/go/backend/internal/httpapi/server.go +87 -0
  36. package/templates/go/backend/internal/httpapi/server_test.go +63 -0
  37. package/templates/go/gitignore +6 -0
  38. package/templates/go/i18n/en.json +8 -0
  39. package/templates/go/i18n/ru.json +8 -0
  40. package/templates/go/manifest.json +25 -0
  41. package/templates/go/package.json +20 -0
  42. package/templates/go/src/index.css +31 -0
  43. package/templates/go/src/index.test.ts +59 -0
  44. package/templates/go/src/index.ts +92 -0
  45. package/templates/go/src/l10n.test.ts +66 -0
  46. package/templates/go/src/test-helpers.ts +6 -0
  47. package/templates/svelte/src/App.svelte +102 -0
  48. package/templates/svelte/src/TableNameCell.svelte +10 -0
  49. package/templates/svelte/src/index.ts +14 -0
  50. package/templates/svelte/src/l10n.test.ts +45 -0
  51. package/templates/svelte/src/table.test.ts +53 -0
  52. package/templates/svelte/vitest.config.ts +9 -0
  53. package/templates/vanilla/src/index.css +31 -0
  54. package/templates/vanilla/src/index.ts +65 -0
  55. package/templates/vanilla/src/l10n.test.ts +44 -0
  56. package/templates/vue/src/App.vue +80 -0
  57. package/templates/vue/src/TableNameCell.vue +12 -0
  58. package/templates/vue/src/env.d.ts +6 -0
  59. package/templates/vue/src/index.ts +16 -0
  60. package/templates/vue/src/l10n.test.ts +45 -0
  61. package/templates/vue/src/table.test.ts +53 -0
  62. package/templates/vue/vitest.config.ts +6 -0
package/dist/mndw.js ADDED
@@ -0,0 +1,3993 @@
1
+ #!/usr/bin/env node
2
+ import {createRequire as __mndwCreateRequire} from "node:module";
3
+ const require = __mndwCreateRequire(import.meta.url);
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __commonJS = (cb, mod) => function __require() {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+
30
+ // ../../build/svelte-compiler-options.js
31
+ var require_svelte_compiler_options = __commonJS({
32
+ "../../build/svelte-compiler-options.js"(exports, module) {
33
+ "use strict";
34
+ var IGNORED_MNDW_BUTTON_WARNING_CODES = /* @__PURE__ */ new Set([
35
+ "a11y_click_events_have_key_events",
36
+ "a11y_no_static_element_interactions"
37
+ ]);
38
+ function isMndwButtonA11yWarning2(warning) {
39
+ return IGNORED_MNDW_BUTTON_WARNING_CODES.has(warning.code ?? "") && (warning.message ?? "").includes("<mndw-button>");
40
+ }
41
+ module.exports = { isMndwButtonA11yWarning: isMndwButtonA11yWarning2 };
42
+ }
43
+ });
44
+
45
+ // src/index.ts
46
+ import { Command, Option } from "commander";
47
+ import { resolve as resolve20 } from "node:path";
48
+
49
+ // ../../frontend/sdk-internal/src/manifest-schema.ts
50
+ import { z as z4 } from "zod";
51
+
52
+ // ../../frontend/sdk-internal/src/page-routes.ts
53
+ var RESERVED_PAGE_ROUTES = ["/", "/login", "/packages", "/packages/services", "/settings"];
54
+ var reservedPageRouteSet = new Set(RESERVED_PAGE_ROUTES);
55
+ function isReservedPageRoute(route) {
56
+ return reservedPageRouteSet.has(route);
57
+ }
58
+
59
+ // ../../frontend/sdk/src/event-schema.ts
60
+ import { z } from "zod";
61
+ var ulidSchema = z.string().regex(/^[0-9A-HJKMNP-TV-Z]{26}$/);
62
+ var nonEmptyString = z.string().min(1);
63
+ var integer = z.number().int();
64
+ var nonNegativeInteger = integer.nonnegative();
65
+ var MaxEventPayloadBytes = 4 * 1024;
66
+ var eventSourceSchema = z.enum(["hook", "log", "internal"]);
67
+ var EVENT_PERMISSION_PATTERN = /^events:(\*|[a-z][a-z0-9]*(?:,[a-z][a-z0-9]*)*)$/;
68
+ var eventPermissionSchema = z.string().regex(EVENT_PERMISSION_PATTERN);
69
+ var eventBranch = (topic, source, payload) => {
70
+ const sourceSchema = typeof source === "string" ? z.literal(source) : source;
71
+ return z.object({
72
+ id: ulidSchema,
73
+ ts: integer,
74
+ topic: z.literal(topic),
75
+ source: sourceSchema,
76
+ payload
77
+ }).strict();
78
+ };
79
+ var stringPayload = (shape) => {
80
+ return z.object(shape).strict();
81
+ };
82
+ var eventSchema = z.union([
83
+ eventBranch(
84
+ "wan.connected",
85
+ z.union([z.literal("hook"), z.literal("log")]),
86
+ stringPayload({
87
+ interface: nonEmptyString,
88
+ address: nonEmptyString,
89
+ mask: nonEmptyString,
90
+ gateway: nonEmptyString
91
+ })
92
+ ),
93
+ eventBranch(
94
+ "wan.disconnected",
95
+ z.union([z.literal("hook"), z.literal("log")]),
96
+ stringPayload({ interface: nonEmptyString })
97
+ ),
98
+ eventBranch(
99
+ "net.ip_changed",
100
+ z.union([z.literal("hook"), z.literal("log")]),
101
+ z.object({
102
+ address: nonEmptyString,
103
+ mask: nonEmptyString,
104
+ link: nonEmptyString,
105
+ connected: z.boolean()
106
+ }).strict()
107
+ ),
108
+ eventBranch(
109
+ "net.dhcp_lease",
110
+ "log",
111
+ stringPayload({
112
+ mac: nonEmptyString,
113
+ ip: nonEmptyString,
114
+ hostname: nonEmptyString,
115
+ action: nonEmptyString
116
+ })
117
+ ),
118
+ eventBranch("net.dns_changed", "log", z.object({ resolvers: z.array(nonEmptyString) }).strict()),
119
+ eventBranch(
120
+ "wifi.client_join",
121
+ "log",
122
+ stringPayload({
123
+ mac: nonEmptyString,
124
+ band: nonEmptyString,
125
+ ssid: nonEmptyString,
126
+ iface: nonEmptyString
127
+ })
128
+ ),
129
+ eventBranch(
130
+ "wifi.client_leave",
131
+ "log",
132
+ stringPayload({
133
+ mac: nonEmptyString,
134
+ band: nonEmptyString,
135
+ ssid: nonEmptyString,
136
+ iface: nonEmptyString
137
+ })
138
+ ),
139
+ eventBranch(
140
+ "firewall.rebuilt",
141
+ "hook",
142
+ stringPayload({
143
+ table_type: nonEmptyString,
144
+ table: nonEmptyString
145
+ })
146
+ ),
147
+ eventBranch(
148
+ "usb.attached",
149
+ "hook",
150
+ stringPayload({
151
+ device: nonEmptyString,
152
+ model: nonEmptyString,
153
+ vendor: nonEmptyString,
154
+ port: nonEmptyString
155
+ })
156
+ ),
157
+ eventBranch(
158
+ "usb.detached",
159
+ "hook",
160
+ stringPayload({
161
+ device: nonEmptyString,
162
+ port: nonEmptyString
163
+ })
164
+ ),
165
+ eventBranch(
166
+ "fs.mounted",
167
+ "hook",
168
+ stringPayload({
169
+ fs_type: nonEmptyString,
170
+ label: nonEmptyString,
171
+ directory: nonEmptyString
172
+ })
173
+ ),
174
+ eventBranch(
175
+ "fs.unmounted",
176
+ "hook",
177
+ stringPayload({
178
+ label: nonEmptyString,
179
+ directory: nonEmptyString
180
+ })
181
+ ),
182
+ eventBranch("clock.synced", "hook", z.object({ offset_ms: integer.optional() }).strict()),
183
+ eventBranch(
184
+ "schedule.fired",
185
+ "hook",
186
+ z.object({
187
+ name: nonEmptyString,
188
+ action: nonEmptyString,
189
+ elapsed: nonNegativeInteger
190
+ }).strict()
191
+ ),
192
+ eventBranch(
193
+ "button.pressed",
194
+ "hook",
195
+ stringPayload({
196
+ button: nonEmptyString,
197
+ gesture: nonEmptyString
198
+ })
199
+ ),
200
+ eventBranch(
201
+ "auth.login",
202
+ "log",
203
+ z.object({
204
+ user: nonEmptyString,
205
+ ip: nonEmptyString,
206
+ success: z.boolean()
207
+ }).strict()
208
+ ),
209
+ eventBranch("firmware.available", "log", stringPayload({ version: nonEmptyString })),
210
+ eventBranch(
211
+ "plugin.installed",
212
+ "internal",
213
+ stringPayload({
214
+ name: nonEmptyString,
215
+ version: nonEmptyString
216
+ })
217
+ ),
218
+ eventBranch("plugin.removed", "internal", stringPayload({ name: nonEmptyString })),
219
+ eventBranch(
220
+ "plugin.approved",
221
+ "internal",
222
+ stringPayload({
223
+ name: nonEmptyString,
224
+ version: nonEmptyString
225
+ })
226
+ ),
227
+ eventBranch("plugin.started", "internal", stringPayload({ name: nonEmptyString })),
228
+ eventBranch(
229
+ "plugin.stopped",
230
+ "internal",
231
+ z.object({
232
+ name: nonEmptyString,
233
+ reason: nonEmptyString
234
+ }).strict()
235
+ ),
236
+ eventBranch(
237
+ "daemon.started",
238
+ "internal",
239
+ z.object({
240
+ version: nonEmptyString,
241
+ uptime_ms: nonNegativeInteger
242
+ }).strict()
243
+ ),
244
+ eventBranch("daemon.stopping", "internal", stringPayload({ reason: nonEmptyString })),
245
+ eventBranch("daemon.updated", "internal", stringPayload({ version: nonEmptyString })),
246
+ eventBranch(
247
+ "storage.low",
248
+ "internal",
249
+ z.object({
250
+ path: z.literal("/opt"),
251
+ available_bytes: nonNegativeInteger,
252
+ threshold_bytes: nonNegativeInteger
253
+ }).strict()
254
+ )
255
+ ]).superRefine((event, context) => {
256
+ const encoded = new TextEncoder().encode(JSON.stringify(event.payload));
257
+ if (encoded.length > MaxEventPayloadBytes) {
258
+ context.addIssue({ code: "custom", message: `payload exceeds ${MaxEventPayloadBytes} bytes` });
259
+ }
260
+ });
261
+
262
+ // ../../frontend/sdk/src/i18n-format.ts
263
+ import IntlMessageFormat from "intl-messageformat";
264
+
265
+ // ../../frontend/sdk/src/permissions.ts
266
+ import { z as z2 } from "zod";
267
+ var PERSISTENT_RCI_PERMISSIONS = ["persistent-rci-session:read", "persistent-rci-session:write"];
268
+ var persistentRciPermissionSchema = z2.enum(PERSISTENT_RCI_PERMISSIONS);
269
+ var pluginPermissionSchema = z2.union([persistentRciPermissionSchema, eventPermissionSchema]);
270
+
271
+ // ../../frontend/sdk/src/palette.ts
272
+ import {
273
+ PALETTE_CONTRAST_PAIRS,
274
+ PALETTE_CSS_VARIABLES,
275
+ contrastRatio,
276
+ paletteToCss
277
+ } from "@mndw/palette-core";
278
+ var TOKENS = PALETTE_CSS_VARIABLES.map((entry) => entry.token);
279
+
280
+ // ../../frontend/sdk/src/backend-client.ts
281
+ import { z as z3 } from "zod";
282
+ var isRecord = (value) => {
283
+ return value !== null && typeof value === "object" && !Array.isArray(value);
284
+ };
285
+ var backendBlockerSchema = z3.object({
286
+ permission: persistentRciPermissionSchema,
287
+ reason: z3.string().min(1),
288
+ prerequisite: z3.string().min(1).optional()
289
+ });
290
+ var retryAfterSchema = z3.number().int().nonnegative().nullable();
291
+ var blockedStatusSchema = z3.object({
292
+ kind: z3.enum(["exec", "service"]),
293
+ state: z3.literal("blocked"),
294
+ retryAfterSeconds: retryAfterSchema,
295
+ blockers: z3.array(backendBlockerSchema).min(1)
296
+ });
297
+ var incompatibleStatusSchema = z3.object({
298
+ kind: z3.enum(["exec", "service"]),
299
+ state: z3.literal("incompatible"),
300
+ retryAfterSeconds: retryAfterSchema,
301
+ requiredProtocol: z3.number().int(),
302
+ supportedProtocols: z3.array(z3.number().int())
303
+ });
304
+ var plainStatusSchema = z3.object({
305
+ kind: z3.enum(["exec", "service"]),
306
+ state: z3.enum(["ready", "starting", "unavailable", "maintenance", "disabled", "not-approved"]),
307
+ retryAfterSeconds: retryAfterSchema
308
+ });
309
+ var rejectVariantOnlyFields = (value) => {
310
+ if (!isRecord(value)) {
311
+ return value;
312
+ }
313
+ const forbiddenByState = {
314
+ blocked: ["requiredProtocol", "supportedProtocols"],
315
+ incompatible: ["blockers"]
316
+ };
317
+ const forbidden = forbiddenByState[String(value.state)] ?? ["blockers", "requiredProtocol", "supportedProtocols"];
318
+ if (forbidden.some((key) => Object.prototype.hasOwnProperty.call(value, key))) {
319
+ throw new Error("backend status contains fields for a different variant");
320
+ }
321
+ return value;
322
+ };
323
+ var backendStatusSchema = z3.preprocess(
324
+ rejectVariantOnlyFields,
325
+ z3.discriminatedUnion("state", [blockedStatusSchema, incompatibleStatusSchema, plainStatusSchema])
326
+ );
327
+
328
+ // ../../frontend/sdk-internal/src/manifest-schema.ts
329
+ var pluginNameSchema = z4.string().regex(/^[a-z0-9][a-z0-9-]*$/, {
330
+ message: "name must be lowercase alphanumeric with hyphens (e.g. my-widget)"
331
+ });
332
+ var safeRelativePath = (value) => {
333
+ return !value.startsWith("/") && !value.includes("..") && !value.includes("\\") && !value.split("/").some((segment) => segment === "." || segment === "..");
334
+ };
335
+ var hasFileName = (value) => {
336
+ const parts = value.split("/").filter(Boolean);
337
+ return Boolean(parts[parts.length - 1]);
338
+ };
339
+ var safeRelativePathSchema = z4.string().min(1).refine(safeRelativePath, { message: "must be a safe relative path" });
340
+ var pluginEntrySchema = safeRelativePathSchema.refine(hasFileName, { message: "entry must include a file name" });
341
+ var canonicalLocale = (value) => {
342
+ try {
343
+ if (typeof Intl.getCanonicalLocales === "function") {
344
+ return Intl.getCanonicalLocales(value)[0];
345
+ }
346
+ if (typeof Intl.Locale === "function") {
347
+ return new Intl.Locale(value).toString();
348
+ }
349
+ } catch {
350
+ }
351
+ return void 0;
352
+ };
353
+ var localeTagSchema = z4.string().min(1).superRefine((value, ctx) => {
354
+ const canonical = canonicalLocale(value);
355
+ if (canonical === void 0) {
356
+ ctx.addIssue({ code: "custom", message: "must be a valid BCP-47 locale tag" });
357
+ } else if (canonical !== value) {
358
+ ctx.addIssue({ code: "custom", message: `must use canonical BCP-47 spelling (${canonical})` });
359
+ }
360
+ });
361
+ var catalogPathSchema = safeRelativePathSchema.refine((value) => value.endsWith(".json"), { message: "catalog path must end with .json" });
362
+ var i18nSchema = z4.object({
363
+ defaultLocale: localeTagSchema,
364
+ locales: z4.record(z4.string(), catalogPathSchema)
365
+ }).strict().superRefine((i18n, ctx) => {
366
+ const localeKeys = Object.keys(i18n.locales);
367
+ if (localeKeys.length === 0) {
368
+ ctx.addIssue({ code: "custom", path: ["locales"], message: "locales must contain at least one locale" });
369
+ }
370
+ const canonicalKeys = /* @__PURE__ */ new Map();
371
+ for (const key of localeKeys) {
372
+ const canonical = canonicalLocale(key);
373
+ if (canonical === void 0) {
374
+ ctx.addIssue({ code: "custom", path: ["locales", key], message: "must be a valid BCP-47 locale tag" });
375
+ continue;
376
+ }
377
+ if (canonical !== key) {
378
+ ctx.addIssue({
379
+ code: "custom",
380
+ path: ["locales", key],
381
+ message: `must use canonical BCP-47 spelling (${canonical})`
382
+ });
383
+ }
384
+ const previousKey = canonicalKeys.get(canonical);
385
+ if (previousKey !== void 0 && previousKey !== key) {
386
+ ctx.addIssue({
387
+ code: "custom",
388
+ path: ["locales", key],
389
+ message: `canonical locale collides with ${previousKey}`
390
+ });
391
+ } else {
392
+ canonicalKeys.set(canonical, key);
393
+ }
394
+ }
395
+ const canonicalDefault = canonicalLocale(i18n.defaultLocale);
396
+ if (canonicalDefault !== void 0 && !canonicalKeys.has(canonicalDefault)) {
397
+ ctx.addIssue({ code: "custom", path: ["defaultLocale"], message: "defaultLocale must be present in locales" });
398
+ }
399
+ });
400
+ var packageSchema = z4.string().regex(/^[a-z0-9][a-z0-9+_.-]*$/);
401
+ var accessSchema = z4.enum(["session", "public"]).default("session");
402
+ var methodSchema = z4.string().transform((method) => method.toUpperCase()).pipe(z4.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]));
403
+ var safeBackendRoutePath = (value) => {
404
+ if (value.length === 0 || value.startsWith("/") || value.includes("\\") || value.includes("?") || value.includes("#")) {
405
+ return false;
406
+ }
407
+ let decoded;
408
+ try {
409
+ decoded = decodeURIComponent(value);
410
+ } catch {
411
+ return false;
412
+ }
413
+ if (decoded !== value || decoded.includes("%") || decoded.startsWith("/") || decoded.includes("\\")) {
414
+ return false;
415
+ }
416
+ const segments = decoded.split("/");
417
+ return segments.every((segment) => segment.length > 0 && segment !== "." && segment !== "..") && segments[0] !== "_mndw";
418
+ };
419
+ var commandSchema = safeRelativePathSchema.refine(hasFileName, { message: "command must include a file name" }).refine((command) => {
420
+ return !command.split("/").some((segment) => segment === "." || segment === "..");
421
+ }, { message: "command must not contain dot segments" });
422
+ var literalArgumentSchema = z4.string().min(1).refine((value) => {
423
+ return [...value].every((character) => {
424
+ const codePoint = character.codePointAt(0) ?? 0;
425
+ return codePoint > 31 && codePoint !== 127;
426
+ });
427
+ }, { message: "args must not contain control characters" });
428
+ var httpRouteSchema = z4.object({
429
+ id: z4.string().min(1),
430
+ transport: z4.literal("http"),
431
+ method: methodSchema,
432
+ path: z4.string().refine(safeBackendRoutePath, { message: "path must be canonical and safe" }),
433
+ access: accessSchema
434
+ });
435
+ var websocketRouteSchema = z4.object({
436
+ id: z4.string().min(1),
437
+ transport: z4.literal("websocket"),
438
+ path: z4.string().refine(safeBackendRoutePath, { message: "path must be canonical and safe" }),
439
+ access: accessSchema,
440
+ protocols: z4.array(z4.string().min(1)).optional()
441
+ });
442
+ var execRouteSchema = httpRouteSchema.extend({ command: commandSchema });
443
+ var validateRoutes = (routes, ctx) => {
444
+ const ids = routes.map((route) => route.id);
445
+ if (new Set(ids).size !== ids.length) {
446
+ ctx.addIssue({ code: "custom", message: "backend.routes contains duplicate id" });
447
+ }
448
+ const tuples = routes.map((route) => {
449
+ return route.transport === "http" ? `${route.transport}:${route.method}:${route.path}` : `${route.transport}:${route.path}`;
450
+ });
451
+ if (new Set(tuples).size !== tuples.length) {
452
+ ctx.addIssue({ code: "custom", message: "backend.routes contains duplicate route tuple" });
453
+ }
454
+ for (const route of routes) {
455
+ if (route.transport === "http" && route.access === "public" && !["GET", "HEAD"].includes(route.method ?? "")) {
456
+ ctx.addIssue({ code: "custom", message: "public HTTP routes may only use GET or HEAD" });
457
+ }
458
+ }
459
+ };
460
+ var execBackendSchema = z4.object({
461
+ kind: z4.literal("exec"),
462
+ packages: z4.array(packageSchema).optional(),
463
+ routes: z4.array(execRouteSchema).min(1)
464
+ }).strict().superRefine((backend, ctx) => {
465
+ validateRoutes(backend.routes, ctx);
466
+ });
467
+ var serviceBackendSchema = z4.object({
468
+ kind: z4.literal("service"),
469
+ protocolVersion: z4.number().int().positive(),
470
+ command: commandSchema,
471
+ args: z4.array(literalArgumentSchema).optional(),
472
+ packages: z4.array(packageSchema).optional(),
473
+ routes: z4.array(z4.union([httpRouteSchema, websocketRouteSchema])).min(1)
474
+ }).strict().superRefine((backend, ctx) => {
475
+ validateRoutes(backend.routes, ctx);
476
+ });
477
+ var backendSchema = z4.union([execBackendSchema, serviceBackendSchema]);
478
+ var gridColumns = z4.number().int().positive().max(12);
479
+ var gridRows = z4.number().int().positive();
480
+ var versionSchema = z4.literal(1).describe("Manifest format version. Must be 1.");
481
+ var nameSchema = pluginNameSchema.describe("Unique plugin id used as the on-disk folder and URL segment.");
482
+ var versionField = z4.string().min(1).describe("Semver-ish version string.");
483
+ var labelField = z4.string().min(1).describe("Human-readable name shown in the dashboard or navigation.");
484
+ var entryField = pluginEntrySchema.describe("Relative path to the bundled entry module.");
485
+ var iconField = z4.string().optional().describe("Optional icon name.");
486
+ var permissionSchema = pluginPermissionSchema;
487
+ var permissionsSchema = z4.array(permissionSchema).superRefine((permissions, ctx) => {
488
+ if (new Set(permissions).size !== permissions.length) {
489
+ ctx.addIssue({ code: "custom", message: "permissions contains duplicate permission" });
490
+ }
491
+ });
492
+ var sizeSchema = z4.object({
493
+ w: gridColumns,
494
+ h: gridRows,
495
+ minW: gridColumns.optional(),
496
+ minH: gridRows.optional()
497
+ }).refine((size) => size.minW === void 0 || size.minW <= size.w, {
498
+ message: "size.minW must be less than or equal to size.w",
499
+ path: ["minW"]
500
+ }).refine((size) => size.minH === void 0 || size.minH <= size.h, {
501
+ message: "size.minH must be less than or equal to size.h",
502
+ path: ["minH"]
503
+ });
504
+ var pageRouteSchema = z4.string().regex(/^\/[^/?#*]+$/).refine((route) => !isReservedPageRoute(route), { message: "route is reserved by the host" });
505
+ var baseFields = {
506
+ manifestVersion: versionSchema,
507
+ name: nameSchema,
508
+ version: versionField,
509
+ label: labelField,
510
+ entry: entryField,
511
+ icon: iconField,
512
+ permissions: permissionsSchema.optional(),
513
+ i18n: i18nSchema.optional(),
514
+ backend: backendSchema.optional()
515
+ };
516
+ var widgetManifestSchema = z4.object({
517
+ ...baseFields,
518
+ type: z4.literal("widget"),
519
+ size: sizeSchema,
520
+ fixedHeight: z4.boolean().optional()
521
+ });
522
+ var pageManifestSchema = z4.object({
523
+ ...baseFields,
524
+ type: z4.literal("page"),
525
+ route: pageRouteSchema
526
+ });
527
+ var pluginManifestSchema = z4.discriminatedUnion("type", [widgetManifestSchema, pageManifestSchema]);
528
+
529
+ // ../../frontend/sdk-internal/src/manifest-validator.ts
530
+ var ManifestValidationError = class extends Error {
531
+ issues;
532
+ constructor(pluginName, issues) {
533
+ const formattedIssues = issues.map((issue) => {
534
+ const path3 = issue.path.length === 0 ? "<root>" : issue.path.join(".");
535
+ return { path: path3, message: issue.message };
536
+ });
537
+ const reason = formattedIssues.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
538
+ super(`Invalid manifest for "${pluginName}": ${reason}`);
539
+ this.issues = formattedIssues;
540
+ }
541
+ };
542
+ function validateManifest(data) {
543
+ const result = pluginManifestSchema.safeParse(data);
544
+ if (!result.success) {
545
+ const pluginName = typeof data === "object" && data !== null ? typeof data.name === "string" ? data.name : "unknown" : "unknown";
546
+ throw new ManifestValidationError(pluginName, result.error.issues);
547
+ }
548
+ return result.data;
549
+ }
550
+
551
+ // ../../frontend/sdk-internal/src/mws-member-schema.ts
552
+ import { z as z5 } from "zod";
553
+ var mwsMemberFocusedSchema = z5.object({
554
+ "cid": z5.string().optional(),
555
+ "mac": z5.string().optional(),
556
+ "ip": z5.string().optional(),
557
+ "fqdn": z5.string().optional(),
558
+ "fqdn-certificate-valid": z5.boolean().optional(),
559
+ "capabilities": z5.record(z5.string(), z5.unknown()).optional()
560
+ }).passthrough();
561
+
562
+ // ../../frontend/sdk-internal/src/shared-dependencies.ts
563
+ var SHARED_DEPENDENCIES = [
564
+ {
565
+ specifiers: ["@rci-tools/core"],
566
+ bundle: "rci-tools-core",
567
+ version: "0.6.0",
568
+ entryPoint: "@rci-tools/core",
569
+ external: ["rxjs", "hash-wasm"],
570
+ framework: "base"
571
+ },
572
+ {
573
+ specifiers: ["rxjs"],
574
+ bundle: "rxjs",
575
+ version: "7.8.2",
576
+ entryPoint: "rxjs",
577
+ framework: "base"
578
+ },
579
+ {
580
+ specifiers: ["rxjs/operators"],
581
+ bundle: "rxjs-operators",
582
+ version: "7.8.2",
583
+ entryPoint: "rxjs/operators",
584
+ framework: "base"
585
+ },
586
+ {
587
+ specifiers: ["hash-wasm"],
588
+ bundle: "hash-wasm",
589
+ version: "4.12.0",
590
+ entryPoint: "hash-wasm",
591
+ framework: "base"
592
+ },
593
+ {
594
+ specifiers: ["d3"],
595
+ bundle: "d3",
596
+ version: "7.9.0",
597
+ entryPoint: "d3",
598
+ framework: "base"
599
+ },
600
+ {
601
+ specifiers: ["@mndw/ui"],
602
+ bundle: "mndw-ui",
603
+ version: "0.1.1",
604
+ entryPoint: "@mndw/ui",
605
+ external: ["d3"],
606
+ framework: "base"
607
+ },
608
+ {
609
+ specifiers: ["vue"],
610
+ bundle: "vue",
611
+ version: "3.5.39",
612
+ entryPoint: "vue",
613
+ banner: "var __VUE_OPTIONS_API__=true,__VUE_PROD_DEVTOOLS__=false,__VUE_PROD_HYDRATION_MISMATCH_DETAILS__=false;",
614
+ framework: "vue"
615
+ },
616
+ {
617
+ specifiers: ["zone.js"],
618
+ bundle: "zone",
619
+ version: "0.15.1",
620
+ entryPoint: "zone.js",
621
+ framework: "angular"
622
+ },
623
+ {
624
+ // `@angular/core` and `@angular/core/rxjs-interop` MUST share one file, or rxjs-interop inlines
625
+ // Angular internals and breaks DI with duplicate class identities.
626
+ specifiers: ["@angular/core", "@angular/core/rxjs-interop"],
627
+ bundle: "angular-core",
628
+ version: "21.2.18",
629
+ stdin: "export * from '@angular/core'; export * from '@angular/core/rxjs-interop';",
630
+ external: ["rxjs", "rxjs/operators", "@angular/compiler"],
631
+ framework: "angular"
632
+ },
633
+ {
634
+ // All Angular bundles keep `@angular/core` external — inlining core internals here yields
635
+ // duplicate DI class identities and "No provider found" errors.
636
+ specifiers: ["@angular/common"],
637
+ bundle: "angular-common",
638
+ version: "21.2.18",
639
+ entryPoint: "@angular/common",
640
+ external: ["rxjs", "@angular/compiler", "@angular/core"],
641
+ framework: "angular"
642
+ },
643
+ {
644
+ specifiers: ["@angular/platform-browser"],
645
+ bundle: "angular-platform-browser",
646
+ version: "21.2.18",
647
+ entryPoint: "@angular/platform-browser",
648
+ external: ["rxjs", "@angular/compiler", "@angular/core"],
649
+ framework: "angular"
650
+ },
651
+ {
652
+ specifiers: ["@angular/compiler"],
653
+ bundle: "angular-compiler",
654
+ version: "21.2.18",
655
+ entryPoint: "@angular/compiler",
656
+ external: ["rxjs"],
657
+ framework: "angular"
658
+ }
659
+ ];
660
+ var versionedBundleUrl = (entry) => `/shared/${entry.bundle}@${entry.version}.js`;
661
+ var sharedImportMap = () => {
662
+ return Object.fromEntries(
663
+ SHARED_DEPENDENCIES.flatMap((entry) => entry.specifiers.map((specifier) => [specifier, versionedBundleUrl(entry)]))
664
+ );
665
+ };
666
+ var pluginDependencies = (framework) => {
667
+ return SHARED_DEPENDENCIES.filter((entry) => entry.framework === "base" || entry.framework === framework).flatMap((entry) => entry.specifiers);
668
+ };
669
+ var sharedDependencyVersions = () => {
670
+ return Object.fromEntries(
671
+ SHARED_DEPENDENCIES.flatMap((entry) => entry.specifiers.map((specifier) => [specifier, entry.version]))
672
+ );
673
+ };
674
+
675
+ // ../../frontend/sdk-internal/src/scripts/manifest-schema-document.ts
676
+ import { z as z6 } from "zod";
677
+
678
+ // src/create.ts
679
+ import { chmodSync, existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, readdirSync, rmSync, writeFileSync } from "node:fs";
680
+ import { dirname as dirname4, isAbsolute, join as join2, relative, resolve as resolve4 } from "node:path";
681
+ import crossSpawn from "cross-spawn";
682
+
683
+ // src/errors.ts
684
+ var CliError = class extends Error {
685
+ };
686
+
687
+ // src/cli-package-root.ts
688
+ import { readFileSync } from "node:fs";
689
+ import { dirname, resolve } from "node:path";
690
+ function cliPackageRoot(startDir = import.meta.dirname) {
691
+ let directory = resolve(startDir);
692
+ for (; ; ) {
693
+ try {
694
+ const parsed = JSON.parse(readFileSync(resolve(directory, "package.json"), "utf8"));
695
+ if (parsed.name === "@mndw/cli") {
696
+ return directory;
697
+ }
698
+ } catch {
699
+ }
700
+ const parent = dirname(directory);
701
+ if (parent === directory) {
702
+ throw new Error(`Could not locate @mndw/cli package root above ${startDir}`);
703
+ }
704
+ directory = parent;
705
+ }
706
+ }
707
+
708
+ // src/lock.ts
709
+ import { existsSync, readFileSync as readFileSync2 } from "node:fs";
710
+ import { createRequire } from "node:module";
711
+ import { dirname as dirname2, join, resolve as resolve2 } from "node:path";
712
+ var LOCK_VERSION = 1;
713
+ function resolveSdkVersion(pluginDir) {
714
+ if (pluginDir !== void 0) {
715
+ let directory = resolve2(pluginDir);
716
+ for (; ; ) {
717
+ const packageJsonPath = join(directory, "node_modules", "@mndw", "sdk", "package.json");
718
+ if (existsSync(packageJsonPath)) {
719
+ const parsed = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
720
+ if (parsed.name === "@mndw/sdk") {
721
+ if (typeof parsed.version !== "string") {
722
+ throw new CliError("@mndw/sdk package.json has no version");
723
+ }
724
+ return parsed.version;
725
+ }
726
+ }
727
+ const parent = dirname2(directory);
728
+ if (parent === directory) {
729
+ break;
730
+ }
731
+ directory = parent;
732
+ }
733
+ }
734
+ const require2 = createRequire(import.meta.url);
735
+ let dir = dirname2(require2.resolve("@mndw/sdk"));
736
+ for (; ; ) {
737
+ const packageJsonPath = join(dir, "package.json");
738
+ if (existsSync(packageJsonPath)) {
739
+ const parsed = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
740
+ if (parsed.name === "@mndw/sdk") {
741
+ if (typeof parsed.version !== "string") {
742
+ throw new CliError("@mndw/sdk package.json has no version");
743
+ }
744
+ return parsed.version;
745
+ }
746
+ }
747
+ const parent = dirname2(dir);
748
+ if (parent === dir) {
749
+ throw new CliError("Could not locate the @mndw/sdk package root");
750
+ }
751
+ dir = parent;
752
+ }
753
+ }
754
+ function packageNameOf(specifier) {
755
+ const segments = specifier.split("/");
756
+ return specifier.startsWith("@") ? `${segments[0]}/${segments[1]}` : segments[0];
757
+ }
758
+ function findBundledSharedDependencies(metafile, specifiers) {
759
+ const packages = [...new Set(specifiers.map(packageNameOf))];
760
+ const found = /* @__PURE__ */ new Set();
761
+ for (const input of Object.keys(metafile.inputs)) {
762
+ for (const packageName of packages) {
763
+ if (input.startsWith(`node_modules/${packageName}/`) || input.includes(`/node_modules/${packageName}/`)) {
764
+ found.add(packageName);
765
+ }
766
+ }
767
+ }
768
+ return [...found].sort();
769
+ }
770
+ function buildLock(manifest, framework, pluginDir) {
771
+ const versions = sharedDependencyVersions();
772
+ const specifiers = [...pluginDependencies(framework)].sort();
773
+ const sharedDependencies = {};
774
+ for (const specifier of specifiers) {
775
+ sharedDependencies[specifier] = versions[specifier];
776
+ }
777
+ return {
778
+ lockVersion: LOCK_VERSION,
779
+ plugin: { name: manifest.name, version: manifest.version },
780
+ framework,
781
+ sdkVersion: resolveSdkVersion(pluginDir),
782
+ sharedDependencies
783
+ };
784
+ }
785
+ function serializeLock(lock) {
786
+ return `${JSON.stringify(lock, null, 2)}
787
+ `;
788
+ }
789
+
790
+ // src/package-manager.ts
791
+ import { existsSync as existsSync2 } from "node:fs";
792
+ import { dirname as dirname3, resolve as resolve3 } from "node:path";
793
+ var LOCKFILES = [
794
+ { file: "pnpm-lock.yaml", manager: "pnpm" },
795
+ { file: "yarn.lock", manager: "yarn" },
796
+ { file: "bun.lock", manager: "bun" },
797
+ { file: "bun.lockb", manager: "bun" },
798
+ { file: "package-lock.json", manager: "npm" }
799
+ ];
800
+ var PACKAGE_MANAGERS = ["pnpm", "npm", "yarn", "bun"];
801
+ function detectPackageManager(options = {}) {
802
+ const env = options.env ?? process.env;
803
+ const userAgent = env.npm_config_user_agent;
804
+ const firstToken = userAgent?.trim().split(/\s+/)[0];
805
+ const agentName = firstToken?.split("/")[0];
806
+ if (PACKAGE_MANAGERS.includes(agentName)) {
807
+ return agentName;
808
+ }
809
+ let directory = resolve3(options.cwd ?? process.cwd());
810
+ while (true) {
811
+ for (const lockfile of LOCKFILES) {
812
+ if (existsSync2(resolve3(directory, lockfile.file))) {
813
+ return lockfile.manager;
814
+ }
815
+ }
816
+ const parent = dirname3(directory);
817
+ if (parent === directory) {
818
+ break;
819
+ }
820
+ directory = parent;
821
+ }
822
+ return "npm";
823
+ }
824
+
825
+ // src/prompt-framework.ts
826
+ import { createInterface } from "node:readline/promises";
827
+ var FRAMEWORKS = ["svelte", "vue", "angular", "vanilla"];
828
+ var MENU = "Choose a framework: 1) svelte (default) 2) vue 3) angular 4) vanilla";
829
+ async function promptFramework(io) {
830
+ const readline = createInterface({ input: io.input, output: io.output });
831
+ const lines = readline[Symbol.asyncIterator]();
832
+ try {
833
+ for (let attempt = 0; attempt < 3; attempt += 1) {
834
+ io.output.write(`${MENU}
835
+ `);
836
+ const line = await lines.next();
837
+ if (line.done) {
838
+ return "svelte";
839
+ }
840
+ const answer = line.value.trim().toLowerCase();
841
+ if (answer === "") {
842
+ return "svelte";
843
+ }
844
+ const numeric = Number.parseInt(answer, 10);
845
+ const selected = Number.isInteger(numeric) && String(numeric) === answer ? FRAMEWORKS[numeric - 1] : void 0;
846
+ if (selected !== void 0) {
847
+ return selected;
848
+ }
849
+ if (FRAMEWORKS.includes(answer)) {
850
+ return answer;
851
+ }
852
+ }
853
+ return "svelte";
854
+ } finally {
855
+ readline.close();
856
+ }
857
+ }
858
+
859
+ // src/create.ts
860
+ var CLI_PACKAGE_ROOT = cliPackageRoot();
861
+ var REPO_ROOT = resolve4(CLI_PACKAGE_ROOT, "..", "..");
862
+ var SDK_SCHEMA_PATH = resolve4(REPO_ROOT, "frontend", "sdk", "manifest.schema.json");
863
+ var TEMPLATES_DIR = resolve4(CLI_PACKAGE_ROOT, "templates");
864
+ var CLI_PACKAGE_JSON = resolve4(CLI_PACKAGE_ROOT, "package.json");
865
+ function toLabel(name) {
866
+ return name.split("-").filter((segment) => segment.length > 0).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)).join(" ");
867
+ }
868
+ function normalize(options) {
869
+ const name = options.name;
870
+ return {
871
+ name,
872
+ type: options.type ?? "widget",
873
+ framework: options.framework ?? "svelte",
874
+ outDir: options.outDir,
875
+ label: options.label ?? toLabel(name),
876
+ route: options.route ?? `/${name}`,
877
+ backend: options.backend
878
+ };
879
+ }
880
+ function isInsideRepo(outDir) {
881
+ const rel = relative(REPO_ROOT, resolve4(outDir));
882
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
883
+ }
884
+ function schemaReference(outDir) {
885
+ if (!isInsideRepo(outDir)) {
886
+ return "./node_modules/@mndw/sdk/manifest.schema.json";
887
+ }
888
+ const relativePath = relative(resolve4(outDir), SDK_SCHEMA_PATH);
889
+ return relativePath.split(/[/\\]/).join("/");
890
+ }
891
+ function buildManifest(options) {
892
+ const normalized = normalize(options);
893
+ const manifest = {
894
+ $schema: schemaReference(normalized.outDir),
895
+ manifestVersion: 1,
896
+ name: normalized.name,
897
+ version: "0.1.0",
898
+ type: normalized.type,
899
+ label: normalized.label,
900
+ entry: "index.js"
901
+ };
902
+ if (normalized.type === "widget") {
903
+ manifest.size = { w: 4, h: 3, minW: 2, minH: 2 };
904
+ } else {
905
+ manifest.route = normalized.route;
906
+ }
907
+ if (normalized.backend === "go") {
908
+ manifest.backend = {
909
+ kind: "service",
910
+ protocolVersion: 1,
911
+ command: `backend/${normalized.name}d`,
912
+ routes: [{ id: "hello", transport: "http", method: "GET", path: "hello" }]
913
+ };
914
+ } else if (normalized.backend === "sh") {
915
+ manifest.backend = {
916
+ kind: "exec",
917
+ routes: [{ id: "hello", transport: "http", method: "GET", path: "hello", command: "backend/main.sh" }]
918
+ };
919
+ }
920
+ return manifest;
921
+ }
922
+ var UI_WORKSPACE_PACKAGES = {
923
+ "@mndw/ui": "frontend/ui",
924
+ "@mndw/ui-svelte": "frontend/ui-svelte",
925
+ "@mndw/ui-vue": "frontend/ui-vue",
926
+ "@mndw/ui-angular": "frontend/ui-angular"
927
+ };
928
+ function packageRange(name, dependencies, devDependencies) {
929
+ const range = dependencies[name] ?? devDependencies[name];
930
+ if (range === void 0) {
931
+ throw new CliError(`CLI package is missing dependency range for ${name}`);
932
+ }
933
+ return range;
934
+ }
935
+ function publishedWorkspaceRange(name, range) {
936
+ if (!range.startsWith("workspace:")) {
937
+ return range;
938
+ }
939
+ const protocolRange = range.slice("workspace:".length);
940
+ if (protocolRange !== "*" && protocolRange !== "^" && protocolRange !== "~") {
941
+ throw new CliError(`CLI package has unsupported workspace range for ${name}: ${range}`);
942
+ }
943
+ const packageJsonPath = resolve4(REPO_ROOT, UI_WORKSPACE_PACKAGES[name], "package.json");
944
+ const packageJson = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
945
+ const version = packageJson.version;
946
+ if (version === void 0 || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
947
+ throw new CliError(`Workspace package ${name} must declare an exact semver version`);
948
+ }
949
+ if (protocolRange === "*") {
950
+ return version;
951
+ }
952
+ return `${protocolRange}${version}`;
953
+ }
954
+ function caretRange(name, value) {
955
+ if (value === void 0 || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value)) {
956
+ throw new CliError(`CLI package devDependency ${name} must be an exact semver version`);
957
+ }
958
+ return `^${value}`;
959
+ }
960
+ function readCliMetadata(metadata) {
961
+ const parsed = metadata ?? JSON.parse(readFileSync3(CLI_PACKAGE_JSON, "utf8"));
962
+ const dependencies = parsed.dependencies ?? {};
963
+ const devDependencies = parsed.devDependencies ?? {};
964
+ const svelteRange = packageRange("svelte", dependencies, devDependencies);
965
+ const uiRange = publishedWorkspaceRange("@mndw/ui", packageRange("@mndw/ui", dependencies, devDependencies));
966
+ const uiWrapperRanges = {
967
+ svelte: publishedWorkspaceRange(
968
+ "@mndw/ui-svelte",
969
+ packageRange("@mndw/ui-svelte", dependencies, devDependencies)
970
+ ),
971
+ vue: publishedWorkspaceRange("@mndw/ui-vue", packageRange("@mndw/ui-vue", dependencies, devDependencies)),
972
+ angular: publishedWorkspaceRange(
973
+ "@mndw/ui-angular",
974
+ packageRange("@mndw/ui-angular", dependencies, devDependencies)
975
+ )
976
+ };
977
+ return {
978
+ version: parsed.version ?? "0.0.0",
979
+ uiRange,
980
+ uiWrapperRanges,
981
+ svelteRange,
982
+ svelteVitePluginRange: packageRange("@sveltejs/vite-plugin-svelte", dependencies, devDependencies),
983
+ vueRange: packageRange("vue", dependencies, devDependencies),
984
+ vueVitePluginRange: packageRange("@vitejs/plugin-vue", dependencies, devDependencies),
985
+ angular: {
986
+ "@angular/core": packageRange("@angular/core", dependencies, devDependencies),
987
+ "@angular/common": packageRange("@angular/common", dependencies, devDependencies),
988
+ "@angular/platform-browser": packageRange("@angular/platform-browser", dependencies, devDependencies),
989
+ "@angular/compiler": packageRange("@angular/compiler", dependencies, devDependencies),
990
+ "zone.js": packageRange("zone.js", dependencies, devDependencies),
991
+ "typescript": packageRange("typescript", dependencies, devDependencies)
992
+ },
993
+ viteRange: packageRange("vite", dependencies, devDependencies),
994
+ vitestRange: caretRange("vitest", packageRange("vitest", dependencies, devDependencies)),
995
+ happyDomRange: caretRange("happy-dom", packageRange("happy-dom", dependencies, devDependencies))
996
+ };
997
+ }
998
+ function buildPackageJson(normalized) {
999
+ const inside = isInsideRepo(normalized.outDir);
1000
+ const cli = readCliMetadata();
1001
+ const sharedVersions = sharedDependencyVersions();
1002
+ const sdkRange = inside ? "workspace:*" : `^${resolveSdkVersion()}`;
1003
+ const devDependencies = {
1004
+ "@mndw/sdk": sdkRange,
1005
+ "@mndw/cli": inside ? "workspace:*" : `^${cli.version}`,
1006
+ "@rci-tools/core": caretRange("@rci-tools/core", sharedVersions["@rci-tools/core"]),
1007
+ "happy-dom": cli.happyDomRange,
1008
+ "rxjs": caretRange("rxjs", sharedVersions.rxjs),
1009
+ "vitest": cli.vitestRange
1010
+ };
1011
+ const dependencies = {};
1012
+ if (normalized.framework === "svelte") {
1013
+ dependencies["@mndw/ui"] = inside ? "workspace:*" : cli.uiRange;
1014
+ dependencies["@mndw/ui-svelte"] = inside ? "workspace:*" : cli.uiWrapperRanges.svelte;
1015
+ devDependencies.svelte = cli.svelteRange;
1016
+ devDependencies["@sveltejs/vite-plugin-svelte"] = cli.svelteVitePluginRange;
1017
+ devDependencies.vite = cli.viteRange;
1018
+ } else if (normalized.framework === "vue") {
1019
+ dependencies["@mndw/ui"] = inside ? "workspace:*" : cli.uiRange;
1020
+ dependencies["@mndw/ui-vue"] = inside ? "workspace:*" : cli.uiWrapperRanges.vue;
1021
+ devDependencies.vue = cli.vueRange;
1022
+ devDependencies["@vitejs/plugin-vue"] = cli.vueVitePluginRange;
1023
+ devDependencies.vite = cli.viteRange;
1024
+ } else if (normalized.framework === "angular") {
1025
+ dependencies["@mndw/ui"] = inside ? "workspace:*" : cli.uiRange;
1026
+ dependencies["@mndw/ui-angular"] = inside ? "workspace:*" : cli.uiWrapperRanges.angular;
1027
+ Object.assign(devDependencies, cli.angular);
1028
+ }
1029
+ return {
1030
+ name: `@mndw/plugin-${normalized.name}`,
1031
+ version: "0.1.0",
1032
+ private: true,
1033
+ type: "module",
1034
+ scripts: { test: "vitest run" },
1035
+ dependencies,
1036
+ devDependencies
1037
+ };
1038
+ }
1039
+ function renderPlaceholders(contents, normalized) {
1040
+ return contents.replaceAll("__MNDW_LABEL__", normalized.label).replaceAll("__MNDW_NAME__", normalized.name).replaceAll("__MNDW_ROUTE__", normalized.route).replaceAll("__MNDW_SCHEMA__", schemaReference(normalized.outDir));
1041
+ }
1042
+ function walkTemplate(dir, prefix) {
1043
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
1044
+ const abs = join2(dir, entry.name);
1045
+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
1046
+ return entry.isDirectory() ? walkTemplate(abs, rel) : [{ rel, abs }];
1047
+ });
1048
+ }
1049
+ function templateOutputPath(path3) {
1050
+ return path3.split("/").map((part) => part === "gitignore" ? ".gitignore" : part).join("/");
1051
+ }
1052
+ function renderTemplateDir(framework, normalized) {
1053
+ return walkTemplate(join2(TEMPLATES_DIR, framework), "").map(({ rel, abs }) => ({
1054
+ path: renderPlaceholders(templateOutputPath(rel), normalized),
1055
+ contents: renderPlaceholders(readFileSync3(abs, "utf8"), normalized)
1056
+ }));
1057
+ }
1058
+ function renderGoTemplate(normalized) {
1059
+ const generatedDevDependencies = buildPackageJson(normalized).devDependencies;
1060
+ return walkTemplate(join2(TEMPLATES_DIR, "go"), "").map(({ rel, abs }) => {
1061
+ let contents = renderPlaceholders(readFileSync3(abs, "utf8"), normalized);
1062
+ if (rel === "package.json") {
1063
+ const packageJson = JSON.parse(contents);
1064
+ packageJson.devDependencies["@mndw/cli"] = generatedDevDependencies["@mndw/cli"];
1065
+ packageJson.devDependencies["@mndw/sdk"] = generatedDevDependencies["@mndw/sdk"];
1066
+ contents = `${JSON.stringify(packageJson, null, 2)}
1067
+ `;
1068
+ }
1069
+ return { path: renderPlaceholders(templateOutputPath(rel), normalized), contents };
1070
+ });
1071
+ }
1072
+ function renderBackendFile(normalized) {
1073
+ const source = readFileSync3(join2(TEMPLATES_DIR, "backend", "main.sh"), "utf8");
1074
+ return { path: "backend/main.sh", contents: renderPlaceholders(source, normalized), executable: true };
1075
+ }
1076
+ function planCreate(options) {
1077
+ const normalized = normalize(options);
1078
+ const files = normalized.backend === "go" ? renderGoTemplate(normalized) : [
1079
+ { path: "manifest.json", contents: `${JSON.stringify(buildManifest(options), null, 2)}
1080
+ ` },
1081
+ { path: "package.json", contents: `${JSON.stringify(buildPackageJson(normalized), null, 2)}
1082
+ ` },
1083
+ ...renderTemplateDir(normalized.framework, normalized)
1084
+ ];
1085
+ if (normalized.backend === "sh") {
1086
+ files.push(renderBackendFile(normalized));
1087
+ }
1088
+ return {
1089
+ name: normalized.name,
1090
+ type: normalized.type,
1091
+ framework: normalized.framework,
1092
+ label: normalized.label,
1093
+ route: normalized.route,
1094
+ outDir: normalized.outDir,
1095
+ files
1096
+ };
1097
+ }
1098
+ function assertSupportedOptions(options) {
1099
+ const type = options.type ?? "widget";
1100
+ if (type !== "widget" && type !== "page") {
1101
+ throw new CliError(`Invalid --type "${type}": expected "widget" or "page"`);
1102
+ }
1103
+ const framework = options.framework ?? "svelte";
1104
+ if (framework !== "vanilla" && framework !== "svelte" && framework !== "vue" && framework !== "angular") {
1105
+ throw new CliError(
1106
+ `Invalid --framework "${framework}": expected "vanilla", "svelte", "vue", or "angular"`
1107
+ );
1108
+ }
1109
+ if (options.backend !== void 0 && options.backend !== "sh" && options.backend !== "go") {
1110
+ throw new CliError(`Invalid --backend "${String(options.backend)}": expected "sh" or "go"`);
1111
+ }
1112
+ if (options.backend === "go") {
1113
+ if (framework !== "vanilla" || type !== "page") {
1114
+ throw new CliError("--backend go requires --framework vanilla and --type page");
1115
+ }
1116
+ }
1117
+ }
1118
+ function ensureDir(dir, created) {
1119
+ if (existsSync3(dir)) {
1120
+ return;
1121
+ }
1122
+ ensureDir(dirname4(dir), created);
1123
+ mkdirSync(dir);
1124
+ created.push(dir);
1125
+ }
1126
+ function writePlan(outDir, plan) {
1127
+ const createdFiles = [];
1128
+ const createdDirs = [];
1129
+ try {
1130
+ ensureDir(outDir, createdDirs);
1131
+ for (const file of plan.files) {
1132
+ const dest = join2(outDir, file.path);
1133
+ ensureDir(dirname4(dest), createdDirs);
1134
+ writeFileSync(dest, file.contents);
1135
+ createdFiles.push(dest);
1136
+ if (file.executable === true) {
1137
+ chmodSync(dest, 493);
1138
+ }
1139
+ }
1140
+ } catch (error) {
1141
+ for (const file of createdFiles.reverse()) {
1142
+ rmSync(file, { force: true });
1143
+ }
1144
+ for (const dir of createdDirs.reverse()) {
1145
+ rmSync(dir, { recursive: true, force: true });
1146
+ }
1147
+ throw error;
1148
+ }
1149
+ }
1150
+ function createPlugin(options) {
1151
+ assertSupportedOptions(options);
1152
+ const plan = planCreate(options);
1153
+ const outDir = resolve4(options.outDir);
1154
+ const manifestFile = plan.files.find((file) => file.path === "manifest.json");
1155
+ try {
1156
+ validateManifest(JSON.parse(manifestFile === void 0 ? "{}" : manifestFile.contents));
1157
+ } catch (error) {
1158
+ if (error instanceof ManifestValidationError) {
1159
+ throw new CliError(`Cannot create plugin "${options.name}": ${error.message}`);
1160
+ }
1161
+ throw error;
1162
+ }
1163
+ if (existsSync3(outDir) && readdirSync(outDir).length > 0) {
1164
+ throw new CliError(`Refusing to write: ${outDir} already exists and is not empty`);
1165
+ }
1166
+ writePlan(outDir, plan);
1167
+ return { outDir, plan };
1168
+ }
1169
+ function runInstall(command, cwd, spawn) {
1170
+ return new Promise((resolvePromise, rejectPromise) => {
1171
+ let child;
1172
+ try {
1173
+ child = spawn(command, ["install"], { cwd, stdio: "inherit" });
1174
+ } catch (error) {
1175
+ const detail = error instanceof Error ? `: ${error.message}` : "";
1176
+ rejectPromise(new CliError(`Failed to run ${command} install${detail}`));
1177
+ return;
1178
+ }
1179
+ child.once("error", (error) => {
1180
+ rejectPromise(new CliError(`Failed to run ${command} install: ${error.message}`));
1181
+ });
1182
+ child.once("close", (code, signal) => {
1183
+ if (code === 0) {
1184
+ resolvePromise();
1185
+ return;
1186
+ }
1187
+ const reason = code === null ? `signal ${signal ?? "unknown"}` : `exit code ${code}`;
1188
+ rejectPromise(new CliError(`${command} install failed with ${reason}`));
1189
+ });
1190
+ });
1191
+ }
1192
+ async function create(options, dependencies = {}) {
1193
+ const stdin = dependencies.stdin ?? process.stdin;
1194
+ const stdout = dependencies.stdout ?? process.stdout;
1195
+ let framework = options.framework;
1196
+ if (framework === void 0) {
1197
+ framework = stdin.isTTY === true && stdout.isTTY === true ? await promptFramework({ input: stdin, output: stdout }) : "svelte";
1198
+ }
1199
+ const result = createPlugin({ ...options, framework });
1200
+ if (isInsideRepo(result.outDir)) {
1201
+ stdout.write("Run pnpm install from the repository root.\n");
1202
+ return result;
1203
+ }
1204
+ if (options.noInstall !== true) {
1205
+ const command = detectPackageManager({ env: dependencies.env, cwd: dependencies.cwd });
1206
+ const spawn = dependencies.spawn ?? crossSpawn;
1207
+ await runInstall(command, result.outDir, spawn);
1208
+ }
1209
+ return result;
1210
+ }
1211
+
1212
+ // src/dev.ts
1213
+ import { existsSync as existsSync5, mkdtempSync as mkdtempSync3, readdirSync as readdirSync4, rmSync as rmSync4, symlinkSync } from "node:fs";
1214
+ import { tmpdir as tmpdir2 } from "node:os";
1215
+ import { basename, dirname as dirname6, join as join10, resolve as resolve14 } from "node:path";
1216
+ import { fileURLToPath } from "node:url";
1217
+ import crossSpawn3 from "cross-spawn";
1218
+
1219
+ // src/dev-reload.ts
1220
+ import { mkdirSync as mkdirSync2, mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
1221
+ import { join as join3, resolve as resolve5 } from "node:path";
1222
+ function createReloadSentinel(repoRoot, deps = {}) {
1223
+ const makeDir = deps.makeDir ?? ((dir) => mkdirSync2(dir, { recursive: true }));
1224
+ const makeSessionDir = deps.makeSessionDir ?? ((prefix) => mkdtempSync(prefix));
1225
+ const writeFile = deps.writeFile ?? ((path3, contents) => writeFileSync2(path3, contents));
1226
+ const removeDir = deps.removeDir ?? ((dir) => rmSync2(dir, { recursive: true, force: true }));
1227
+ const parentDir = join3(resolve5(repoRoot), ".dev-data", "mndw-dev-reload");
1228
+ makeDir(parentDir);
1229
+ const sessionDir = makeSessionDir(join3(parentDir, "session-"));
1230
+ const sentinelPath = join3(sessionDir, "sentinel");
1231
+ let counter = 0;
1232
+ let cleaned = false;
1233
+ writeFile(sentinelPath, "0\n");
1234
+ return {
1235
+ path: sentinelPath,
1236
+ touch: () => {
1237
+ counter++;
1238
+ writeFile(sentinelPath, `${counter}
1239
+ `);
1240
+ },
1241
+ cleanup: () => {
1242
+ if (cleaned) {
1243
+ return;
1244
+ }
1245
+ cleaned = true;
1246
+ try {
1247
+ removeDir(sessionDir);
1248
+ } catch {
1249
+ }
1250
+ }
1251
+ };
1252
+ }
1253
+ async function restartService(options, deps = {}) {
1254
+ const controller = new AbortController();
1255
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 5e3);
1256
+ const daemonUrl = options.daemonUrl.replace(/\/$/, "");
1257
+ try {
1258
+ const response = await (deps.fetch ?? fetch)(
1259
+ `${daemonUrl}/api/mgmt/restart`,
1260
+ {
1261
+ method: "POST",
1262
+ headers: { "Content-Type": "application/json" },
1263
+ body: JSON.stringify({ name: options.pluginName }),
1264
+ signal: controller.signal
1265
+ }
1266
+ );
1267
+ return response.status === 200;
1268
+ } catch {
1269
+ return false;
1270
+ } finally {
1271
+ clearTimeout(timeout);
1272
+ }
1273
+ }
1274
+
1275
+ // src/dev-session.ts
1276
+ import { join as join4 } from "node:path";
1277
+ import crossSpawn2 from "cross-spawn";
1278
+ function asError(error, fallback) {
1279
+ if (error instanceof Error) {
1280
+ return error;
1281
+ }
1282
+ if (typeof error === "string") {
1283
+ return new Error(error);
1284
+ }
1285
+ if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") {
1286
+ return new Error(String(error));
1287
+ }
1288
+ return new Error(fallback);
1289
+ }
1290
+ function timeoutError(baseUrl) {
1291
+ return new Error(`mndw dev: timed out waiting for mndwd at ${baseUrl}`);
1292
+ }
1293
+ function abortError(signal) {
1294
+ return asError(signal.reason, "mndw dev: daemon readiness aborted");
1295
+ }
1296
+ function delay(ms, signal) {
1297
+ return new Promise((resolveDelay, rejectDelay) => {
1298
+ const state = {};
1299
+ const onAbort = () => {
1300
+ if (state.timer !== void 0) {
1301
+ clearTimeout(state.timer);
1302
+ }
1303
+ signal.removeEventListener("abort", onAbort);
1304
+ rejectDelay(abortError(signal));
1305
+ };
1306
+ const onTimer = () => {
1307
+ signal.removeEventListener("abort", onAbort);
1308
+ resolveDelay();
1309
+ };
1310
+ if (signal.aborted) {
1311
+ rejectDelay(abortError(signal));
1312
+ return;
1313
+ }
1314
+ state.timer = setTimeout(onTimer, ms);
1315
+ signal.addEventListener("abort", onAbort, { once: true });
1316
+ });
1317
+ }
1318
+ function buildDevDaemonArgs(config) {
1319
+ const args = [
1320
+ "--listen",
1321
+ config.listen,
1322
+ "--dev",
1323
+ "--opkg",
1324
+ "stub",
1325
+ "--builtin-plugins-dir",
1326
+ config.builtinDir,
1327
+ "--data-dir",
1328
+ config.dataDir,
1329
+ "--user-plugins-dir",
1330
+ config.userDir
1331
+ ];
1332
+ if (config.hostDevice !== void 0) {
1333
+ args.push("--controller-url", config.hostDevice);
1334
+ }
1335
+ return args;
1336
+ }
1337
+ function buildDevHostEnv(config, sentinelPath) {
1338
+ const env = {
1339
+ ...config.env,
1340
+ MNDW_DAEMON: config.daemonUrl,
1341
+ MNDW_BUILTIN_PLUGINS_DIR: config.builtinDir,
1342
+ MNDW_USER_PLUGINS_DIR: config.userDir,
1343
+ MNDW_DEV_RELOAD_SENTINEL: sentinelPath
1344
+ };
1345
+ if (config.sandboxPlugin === void 0) {
1346
+ delete env.MNDW_SANDBOX_PLUGIN;
1347
+ } else {
1348
+ env.MNDW_SANDBOX_PLUGIN = config.sandboxPlugin;
1349
+ }
1350
+ if (config.hostDevice === void 0) {
1351
+ delete env.MNDW_HOST_DEVICE;
1352
+ } else {
1353
+ env.MNDW_HOST_DEVICE = config.hostDevice;
1354
+ }
1355
+ return env;
1356
+ }
1357
+ async function waitForDevDaemon(options, fetchDaemon = fetch) {
1358
+ if (options.signal.aborted) {
1359
+ throw abortError(options.signal);
1360
+ }
1361
+ const timeoutMs = options.timeoutMs ?? 3e4;
1362
+ const deadline = Date.now() + timeoutMs;
1363
+ for (; ; ) {
1364
+ const remaining = deadline - Date.now();
1365
+ if (remaining <= 0) {
1366
+ throw timeoutError(options.baseUrl);
1367
+ }
1368
+ const request = new AbortController();
1369
+ const timer = setTimeout(() => request.abort(), remaining);
1370
+ const abortRequest = () => request.abort(options.signal.reason);
1371
+ options.signal.addEventListener("abort", abortRequest, { once: true });
1372
+ try {
1373
+ const response = await fetchDaemon(`${options.baseUrl}/api/mgmt/list`, { signal: request.signal });
1374
+ if (response.ok) {
1375
+ const payload = await response.json();
1376
+ if (!options.signal.aborted && !request.signal.aborted && Date.now() < deadline && options.isReady(payload)) {
1377
+ return;
1378
+ }
1379
+ }
1380
+ } catch (_error) {
1381
+ if (options.signal.aborted) {
1382
+ throw abortError(options.signal);
1383
+ }
1384
+ if (request.signal.aborted) {
1385
+ throw timeoutError(options.baseUrl);
1386
+ }
1387
+ } finally {
1388
+ clearTimeout(timer);
1389
+ options.signal.removeEventListener("abort", abortRequest);
1390
+ }
1391
+ if (options.signal.aborted) {
1392
+ throw abortError(options.signal);
1393
+ }
1394
+ const remainingAfterResponse = deadline - Date.now();
1395
+ if (remainingAfterResponse <= 0) {
1396
+ throw timeoutError(options.baseUrl);
1397
+ }
1398
+ await delay(Math.min(250, remainingAfterResponse), options.signal);
1399
+ }
1400
+ }
1401
+ function defaultSpawn(command, args, options) {
1402
+ return crossSpawn2(command, args, {
1403
+ cwd: options.cwd,
1404
+ detached: options.detached,
1405
+ env: options.env,
1406
+ stdio: "inherit"
1407
+ });
1408
+ }
1409
+ function defaultSubscribeShutdown(handler) {
1410
+ process.on("SIGINT", handler);
1411
+ process.on("SIGTERM", handler);
1412
+ return () => {
1413
+ process.off("SIGINT", handler);
1414
+ process.off("SIGTERM", handler);
1415
+ };
1416
+ }
1417
+ function defaultKillProcessGroup(processGroupId, signal) {
1418
+ process.kill(processGroupId, signal);
1419
+ }
1420
+ async function runDevSession(config, deps = {}) {
1421
+ const platform = deps.platform ?? process.platform;
1422
+ const spawn = deps.spawn ?? defaultSpawn;
1423
+ const killProcessGroup = deps.killProcessGroup ?? defaultKillProcessGroup;
1424
+ const subscribeShutdown = deps.subscribeShutdown ?? defaultSubscribeShutdown;
1425
+ const makeReloadSentinel = deps.createReloadSentinel ?? createReloadSentinel;
1426
+ const fetchDaemon = deps.fetch ?? fetch;
1427
+ const children = [];
1428
+ const readinessAbort = new AbortController();
1429
+ let reloadSentinel;
1430
+ let hostHandle;
1431
+ let watcher;
1432
+ let unsubscribeShutdown;
1433
+ let terminal = false;
1434
+ let terminalCause;
1435
+ let terminalChild;
1436
+ let resolveFinished = () => void 0;
1437
+ let rejectFinished = () => void 0;
1438
+ const finished = new Promise((resolveFinishedPromise, rejectFinishedPromise) => {
1439
+ resolveFinished = resolveFinishedPromise;
1440
+ rejectFinished = rejectFinishedPromise;
1441
+ });
1442
+ const terminate = (record) => {
1443
+ try {
1444
+ if (record.role === "daemon" && platform !== "win32" && record.child.pid !== void 0) {
1445
+ killProcessGroup(-record.child.pid, "SIGTERM");
1446
+ } else {
1447
+ record.child.kill("SIGTERM");
1448
+ }
1449
+ } catch {
1450
+ }
1451
+ };
1452
+ const cleanupResources = async () => {
1453
+ let cleanupFailure;
1454
+ const recordCleanupFailure = (error, fallback) => {
1455
+ if (cleanupFailure === void 0) {
1456
+ cleanupFailure = asError(error, fallback);
1457
+ }
1458
+ };
1459
+ try {
1460
+ await watcher?.close();
1461
+ } catch (error) {
1462
+ recordCleanupFailure(error, "mndw dev: failed to close watcher");
1463
+ }
1464
+ try {
1465
+ await hostHandle?.close();
1466
+ } catch (error) {
1467
+ recordCleanupFailure(error, "mndw dev: failed to close host");
1468
+ }
1469
+ try {
1470
+ reloadSentinel?.cleanup();
1471
+ } catch (error) {
1472
+ recordCleanupFailure(error, "mndw dev: failed to clean reload sentinel");
1473
+ }
1474
+ try {
1475
+ unsubscribeShutdown?.();
1476
+ } catch (error) {
1477
+ recordCleanupFailure(error, "mndw dev: failed to unsubscribe shutdown handlers");
1478
+ }
1479
+ if (terminalCause !== void 0) {
1480
+ throw terminalCause;
1481
+ }
1482
+ if (cleanupFailure !== void 0) {
1483
+ throw cleanupFailure;
1484
+ }
1485
+ };
1486
+ const beginShutdown = (stoppedChild, cause) => {
1487
+ if (terminal) {
1488
+ return;
1489
+ }
1490
+ terminal = true;
1491
+ terminalCause = cause;
1492
+ terminalChild = stoppedChild;
1493
+ readinessAbort.abort(cause);
1494
+ for (const record of children) {
1495
+ if (record.child !== stoppedChild) {
1496
+ terminate(record);
1497
+ }
1498
+ }
1499
+ const cleanupPromise = Promise.resolve().then(cleanupResources);
1500
+ cleanupPromise.then(resolveFinished, rejectFinished);
1501
+ };
1502
+ const attachChild = (record) => {
1503
+ record.child.on("exit", (code) => {
1504
+ const cause = code === 0 ? void 0 : new Error(`mndw dev: ${record.role} exited with code ${code ?? "unknown"}`);
1505
+ beginShutdown(record.child, cause);
1506
+ });
1507
+ record.child.on("error", (error) => {
1508
+ beginShutdown(record.child, asError(error, `mndw dev: ${record.role} failed`));
1509
+ });
1510
+ };
1511
+ try {
1512
+ reloadSentinel = makeReloadSentinel(config.repoRoot);
1513
+ unsubscribeShutdown = subscribeShutdown(() => beginShutdown());
1514
+ if (terminal) {
1515
+ await finished;
1516
+ return;
1517
+ }
1518
+ const daemon = {
1519
+ child: spawn(
1520
+ config.daemon.command,
1521
+ [...config.daemon.args, ...buildDevDaemonArgs(config)],
1522
+ {
1523
+ cwd: config.daemon.cwd,
1524
+ detached: platform !== "win32",
1525
+ env: { ...config.env, MNDW_PLUGIN_RUNTIME_ROOT: join4(config.dataDir, "plugin-runtime") }
1526
+ }
1527
+ ),
1528
+ role: "daemon"
1529
+ };
1530
+ children.push(daemon);
1531
+ attachChild(daemon);
1532
+ if (terminal) {
1533
+ if (terminalChild !== daemon.child) {
1534
+ terminate(daemon);
1535
+ }
1536
+ await finished;
1537
+ return;
1538
+ }
1539
+ await waitForDevDaemon({
1540
+ baseUrl: config.daemonUrl,
1541
+ signal: readinessAbort.signal,
1542
+ isReady: config.isReady
1543
+ }, fetchDaemon);
1544
+ if (terminal) {
1545
+ await finished;
1546
+ return;
1547
+ }
1548
+ const hostEnv = buildDevHostEnv(config, reloadSentinel.path);
1549
+ if (config.launchHost !== void 0) {
1550
+ hostHandle = config.launchHost(hostEnv);
1551
+ void hostHandle.exited.then((code) => {
1552
+ const cause = code === 0 ? void 0 : new Error(`mndw dev: host exited with code ${code ?? "unknown"}`);
1553
+ beginShutdown(void 0, cause);
1554
+ }, (error) => {
1555
+ beginShutdown(void 0, asError(error, "mndw dev: host failed"));
1556
+ });
1557
+ } else {
1558
+ const host = {
1559
+ child: spawn("pnpm", ["--filter", "@mndw/host", "dev"], {
1560
+ cwd: config.repoRoot,
1561
+ env: hostEnv
1562
+ }),
1563
+ role: "host"
1564
+ };
1565
+ children.push(host);
1566
+ attachChild(host);
1567
+ if (terminal) {
1568
+ if (terminalChild !== host.child) {
1569
+ terminate(host);
1570
+ }
1571
+ await finished;
1572
+ return;
1573
+ }
1574
+ }
1575
+ watcher = config.createWatcher({
1576
+ daemonUrl: config.daemonUrl,
1577
+ touchSentinel: () => {
1578
+ if (hostHandle !== void 0) {
1579
+ hostHandle.reload();
1580
+ } else {
1581
+ reloadSentinel?.touch();
1582
+ }
1583
+ }
1584
+ });
1585
+ } catch (error) {
1586
+ if (!terminal) {
1587
+ beginShutdown(void 0, asError(error, "mndw dev: session failed"));
1588
+ }
1589
+ }
1590
+ await finished;
1591
+ }
1592
+
1593
+ // src/daemon-binary.ts
1594
+ import { createRequire as createRequire2 } from "node:module";
1595
+ import { dirname as dirname5, resolve as resolvePath } from "node:path";
1596
+
1597
+ // src/mndwd-platforms.ts
1598
+ var MNDWD_PLATFORMS = [
1599
+ {
1600
+ packageName: "@mndw/mndwd-darwin-arm64",
1601
+ os: "darwin",
1602
+ cpu: "arm64",
1603
+ goos: "darwin",
1604
+ goarch: "arm64",
1605
+ binary: "mndwd"
1606
+ },
1607
+ {
1608
+ packageName: "@mndw/mndwd-darwin-x64",
1609
+ os: "darwin",
1610
+ cpu: "x64",
1611
+ goos: "darwin",
1612
+ goarch: "amd64",
1613
+ binary: "mndwd"
1614
+ },
1615
+ {
1616
+ packageName: "@mndw/mndwd-linux-x64",
1617
+ os: "linux",
1618
+ cpu: "x64",
1619
+ goos: "linux",
1620
+ goarch: "amd64",
1621
+ binary: "mndwd"
1622
+ },
1623
+ {
1624
+ packageName: "@mndw/mndwd-linux-arm64",
1625
+ os: "linux",
1626
+ cpu: "arm64",
1627
+ goos: "linux",
1628
+ goarch: "arm64",
1629
+ binary: "mndwd"
1630
+ },
1631
+ {
1632
+ packageName: "@mndw/mndwd-win32-x64",
1633
+ os: "win32",
1634
+ cpu: "x64",
1635
+ goos: "windows",
1636
+ goarch: "amd64",
1637
+ binary: "mndwd.exe"
1638
+ }
1639
+ ];
1640
+ function mndwdPlatformFor(platform, arch) {
1641
+ return MNDWD_PLATFORMS.find((entry) => entry.os === platform && entry.cpu === arch);
1642
+ }
1643
+
1644
+ // src/daemon-binary.ts
1645
+ var nodeRequire = createRequire2(import.meta.url);
1646
+ function resolvePackagedDaemon(deps = {}) {
1647
+ const platform = deps.platform ?? process.platform;
1648
+ const arch = deps.arch ?? process.arch;
1649
+ const target = mndwdPlatformFor(platform, arch);
1650
+ if (target === void 0) {
1651
+ const supported = MNDWD_PLATFORMS.map((entry) => `${entry.os}/${entry.cpu}`).join(", ");
1652
+ throw new CliError(
1653
+ `mndw dev: no prebuilt mndwd for ${platform}/${arch}; supported: ${supported}. Pass --daemon <path>.`
1654
+ );
1655
+ }
1656
+ let packageJsonPath;
1657
+ try {
1658
+ packageJsonPath = (deps.resolve ?? ((specifier) => nodeRequire.resolve(specifier)))(
1659
+ `${target.packageName}/package.json`
1660
+ );
1661
+ } catch {
1662
+ throw new CliError(
1663
+ `mndw dev: ${target.packageName} is not installed. Reinstall @mndw/cli without --no-optional (with npm, delete package-lock.json and node_modules first: npm can drop optional platform packages from a lockfile made on another OS), or pass --daemon <path>.`
1664
+ );
1665
+ }
1666
+ return resolvePath(dirname5(packageJsonPath), "bin", target.binary);
1667
+ }
1668
+
1669
+ // src/go-backend-build.ts
1670
+ import { spawnSync } from "node:child_process";
1671
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
1672
+ import { join as join5, resolve as resolve6 } from "node:path";
1673
+
1674
+ // src/go-target.ts
1675
+ var PRODUCT_TARGETS = ["aarch64", "mips", "mipsel"];
1676
+ function isProductTarget(value) {
1677
+ return PRODUCT_TARGETS.includes(value);
1678
+ }
1679
+ var GO_TARGETS = {
1680
+ aarch64: { GOARCH: "arm64" },
1681
+ mips: { GOARCH: "mips", GOMIPS: "softfloat" },
1682
+ mipsel: { GOARCH: "mipsle", GOMIPS: "softfloat" }
1683
+ };
1684
+ function goTargetEnvironment(target) {
1685
+ return {
1686
+ ...process.env,
1687
+ ...GO_TARGETS[target],
1688
+ GOOS: "linux",
1689
+ CGO_ENABLED: "0"
1690
+ };
1691
+ }
1692
+
1693
+ // src/go-backend-build.ts
1694
+ var defaultSpawn2 = (command, args, options) => spawnSync(command, args, { cwd: options.cwd, env: options.env, stdio: "inherit" });
1695
+ function buildGoBackend(options) {
1696
+ const { plugin, backendDir, binaryName, entryPackage, target, outDir } = options;
1697
+ if (target === void 0 !== (outDir === void 0)) {
1698
+ throw new CliError(`${plugin}: cross build requires both --target and --out-dir`);
1699
+ }
1700
+ const crossMode = target !== void 0 && outDir !== void 0;
1701
+ const destinationDir = crossMode ? resolve6(outDir) : resolve6(backendDir);
1702
+ const binaryPath = join5(destinationDir, binaryName);
1703
+ const env = crossMode ? { ...goTargetEnvironment(target), GOWORK: "off" } : { ...process.env, GOWORK: "off", CGO_ENABLED: "0" };
1704
+ if (crossMode) {
1705
+ mkdirSync3(destinationDir, { recursive: true });
1706
+ }
1707
+ const result = (options.spawn ?? defaultSpawn2)("go", [
1708
+ "build",
1709
+ "-ldflags",
1710
+ "-s -w",
1711
+ "-o",
1712
+ binaryPath,
1713
+ entryPackage
1714
+ ], { cwd: resolve6(backendDir), env });
1715
+ if (result.error) {
1716
+ throw new CliError(`go build failed for ${plugin} (${binaryName}): ${result.error.message}`);
1717
+ }
1718
+ if (result.signal !== null && result.signal !== void 0) {
1719
+ throw new CliError(`go build for ${plugin} (${binaryName}) terminated by signal ${result.signal}`);
1720
+ }
1721
+ if (result.status !== 0) {
1722
+ throw new CliError(`go build for ${plugin} (${binaryName}) exited with status ${result.status}`);
1723
+ }
1724
+ if (!crossMode) {
1725
+ return { binaryPath };
1726
+ }
1727
+ if (target === void 0 || outDir === void 0) {
1728
+ throw new CliError(`${plugin}: cross build requires both --target and --out-dir`);
1729
+ }
1730
+ const artifactPath = join5(destinationDir, "backend-artifact.json");
1731
+ const artifact = {
1732
+ plugin,
1733
+ target,
1734
+ binaries: [{ source: binaryName, destination: `backend/${binaryName}` }]
1735
+ };
1736
+ writeFileSync3(
1737
+ artifactPath,
1738
+ `${JSON.stringify(artifact, null, 2)}
1739
+ `
1740
+ );
1741
+ return { binaryPath, artifactPath };
1742
+ }
1743
+
1744
+ // src/device-address.ts
1745
+ var INVALID_ADDRESS = "expected an IP, host[:port] or http(s) URL";
1746
+ function normalizeDeviceAddress(input) {
1747
+ const value = input.trim();
1748
+ try {
1749
+ if (value === "") {
1750
+ throw new Error("empty address");
1751
+ }
1752
+ const candidate = /^[a-z][a-z\d+.-]*:\/\//i.test(value) ? value : `http://${value}`;
1753
+ const url = new URL(candidate);
1754
+ if (!["http:", "https:"].includes(url.protocol) || url.hostname === "" || !["", "/"].includes(url.pathname) || url.search !== "" || url.hash !== "" || url.username !== "" || url.password !== "") {
1755
+ throw new Error("address must be an origin");
1756
+ }
1757
+ return url.origin;
1758
+ } catch {
1759
+ throw new CliError(`Invalid --addr "${input}": ${INVALID_ADDRESS}`);
1760
+ }
1761
+ }
1762
+
1763
+ // src/framework.ts
1764
+ import { readFileSync as readFileSync4, readdirSync as readdirSync2 } from "node:fs";
1765
+ import { join as join6 } from "node:path";
1766
+ function hasExtension(dir, ext) {
1767
+ let entries;
1768
+ try {
1769
+ entries = readdirSync2(dir, { withFileTypes: true });
1770
+ } catch {
1771
+ return false;
1772
+ }
1773
+ for (const entry of entries) {
1774
+ if (entry.isDirectory()) {
1775
+ if (hasExtension(join6(dir, entry.name), ext)) {
1776
+ return true;
1777
+ }
1778
+ continue;
1779
+ }
1780
+ if (entry.isFile() && entry.name.endsWith(ext)) {
1781
+ return true;
1782
+ }
1783
+ }
1784
+ return false;
1785
+ }
1786
+ function detectFramework(pluginDir) {
1787
+ const src = join6(pluginDir, "src");
1788
+ const hasAngular = hasAngularTsconfig(pluginDir);
1789
+ const hasVue = hasExtension(src, ".vue");
1790
+ const hasSvelte = hasExtension(src, ".svelte");
1791
+ if ([hasAngular, hasVue, hasSvelte].filter(Boolean).length > 1) {
1792
+ throw new CliError(
1793
+ "mixed framework sources: a plugin must use a single framework (found more than one of an Angular tsconfig / a .vue file / a .svelte file)"
1794
+ );
1795
+ }
1796
+ if (hasAngular) {
1797
+ return "angular";
1798
+ }
1799
+ if (hasVue) {
1800
+ return "vue";
1801
+ }
1802
+ if (hasSvelte) {
1803
+ return "svelte";
1804
+ }
1805
+ return "vanilla";
1806
+ }
1807
+ function hasAngularTsconfig(pluginDir) {
1808
+ let raw;
1809
+ try {
1810
+ raw = readFileSync4(join6(pluginDir, "tsconfig.json"), "utf8");
1811
+ } catch {
1812
+ return false;
1813
+ }
1814
+ let parsed;
1815
+ try {
1816
+ parsed = JSON.parse(raw);
1817
+ } catch {
1818
+ throw new CliError(`Invalid tsconfig.json in ${pluginDir}: not valid JSON`);
1819
+ }
1820
+ return parsed !== null && typeof parsed === "object" && "angularCompilerOptions" in parsed;
1821
+ }
1822
+
1823
+ // src/manifest.ts
1824
+ import { readFileSync as readFileSync6, statSync as statSync2 } from "node:fs";
1825
+ import { resolve as resolve9 } from "node:path";
1826
+
1827
+ // src/paths.ts
1828
+ import { resolve as resolve7 } from "node:path";
1829
+ function resolvePluginDir(pluginDir) {
1830
+ return resolve7(process.cwd(), pluginDir);
1831
+ }
1832
+
1833
+ // src/source-entry.ts
1834
+ import { statSync } from "node:fs";
1835
+ import { extname, isAbsolute as isAbsolute3, join as join8, relative as relative2, resolve as resolve8, sep } from "node:path";
1836
+
1837
+ // src/plugin-package.ts
1838
+ import { readFileSync as readFileSync5 } from "node:fs";
1839
+ import { isAbsolute as isAbsolute2, join as join7 } from "node:path";
1840
+ function isRecord2(value) {
1841
+ return typeof value === "object" && value !== null;
1842
+ }
1843
+ function isSafeRelativePath(value) {
1844
+ if (value.length === 0 || isAbsolute2(value) || value.startsWith("/") || value.startsWith("\\")) {
1845
+ return false;
1846
+ }
1847
+ return !value.split(/[\\/]/u).some((segment) => segment === "" || segment === "." || segment === "..");
1848
+ }
1849
+ function validateBackendAssets(packagePath, value) {
1850
+ if (!Array.isArray(value) || value.length === 0) {
1851
+ throw new CliError(`Plugin package mndw.backendAssets at ${packagePath} must be a non-empty array`);
1852
+ }
1853
+ const seen = /* @__PURE__ */ new Set();
1854
+ for (const asset of value) {
1855
+ if (typeof asset !== "string" || !isSafeRelativePath(asset)) {
1856
+ throw new CliError(`Plugin package mndw.backendAssets at ${packagePath} must contain safe relative paths`);
1857
+ }
1858
+ if (seen.has(asset)) {
1859
+ throw new CliError(`Plugin package mndw.backendAssets at ${packagePath} contains duplicate path: ${asset}`);
1860
+ }
1861
+ seen.add(asset);
1862
+ }
1863
+ }
1864
+ function readPluginPackage(pluginDir) {
1865
+ const packagePath = join7(pluginDir, "package.json");
1866
+ let contents;
1867
+ try {
1868
+ contents = readFileSync5(packagePath, "utf8");
1869
+ } catch (error) {
1870
+ if (error instanceof Error && error.code === "ENOENT") {
1871
+ return null;
1872
+ }
1873
+ if (error instanceof Error) {
1874
+ throw new CliError(`Failed to read plugin package at ${packagePath}: ${error.message}`);
1875
+ }
1876
+ throw error;
1877
+ }
1878
+ let parsed;
1879
+ try {
1880
+ parsed = JSON.parse(contents);
1881
+ } catch (error) {
1882
+ if (error instanceof SyntaxError) {
1883
+ throw new CliError(`Failed to parse plugin package at ${packagePath}: ${error.message}`);
1884
+ }
1885
+ throw error;
1886
+ }
1887
+ if (!isRecord2(parsed) || Array.isArray(parsed)) {
1888
+ throw new CliError(`Plugin package at ${packagePath} must contain a JSON object`);
1889
+ }
1890
+ if (isRecord2(parsed.mndw) && parsed.mndw.backendAssets !== void 0) {
1891
+ validateBackendAssets(packagePath, parsed.mndw.backendAssets);
1892
+ }
1893
+ return parsed;
1894
+ }
1895
+
1896
+ // src/source-entry.ts
1897
+ var DEFAULT_SOURCE_ENTRY = "src/index.ts";
1898
+ function validateSourceEntry(pluginDir, sourceEntry) {
1899
+ const normalized = sourceEntry.replaceAll("\\", "/");
1900
+ if (normalized !== sourceEntry || isAbsolute3(sourceEntry) || !normalized.startsWith("src/")) {
1901
+ throw new CliError(`Invalid production entry path: ${sourceEntry}`);
1902
+ }
1903
+ const sourcePath = resolve8(pluginDir, sourceEntry);
1904
+ const sourceRelative = relative2(pluginDir, sourcePath).split(sep).join("/");
1905
+ if (sourceRelative !== sourceEntry || !sourceRelative.startsWith("src/")) {
1906
+ throw new CliError(`Invalid production entry path: ${sourceEntry}`);
1907
+ }
1908
+ if (extname(sourceEntry) !== ".ts") {
1909
+ throw new CliError(`Production entry must be a TypeScript file: ${sourceEntry}`);
1910
+ }
1911
+ try {
1912
+ if (!statSync(sourcePath).isFile()) {
1913
+ throw new CliError(`Production entry is not a regular file: ${sourcePath}`);
1914
+ }
1915
+ } catch (error) {
1916
+ if (error instanceof CliError) {
1917
+ throw error;
1918
+ }
1919
+ if (error instanceof Error && typeof error.code === "string") {
1920
+ const code = error.code;
1921
+ const message = code === "ENOENT" ? `Missing production entry at ${sourcePath}` : `Failed to inspect production entry at ${sourcePath}: ${error.message}`;
1922
+ throw new CliError(message);
1923
+ }
1924
+ throw error;
1925
+ }
1926
+ return sourceEntry;
1927
+ }
1928
+ function resolveProductionSourceEntry(pluginDir) {
1929
+ const packageMetadata = readPluginPackage(pluginDir);
1930
+ const mndw = packageMetadata?.mndw;
1931
+ if (mndw === void 0) {
1932
+ return validateSourceEntry(pluginDir, DEFAULT_SOURCE_ENTRY);
1933
+ }
1934
+ if (typeof mndw !== "object" || mndw === null || Array.isArray(mndw)) {
1935
+ throw new CliError(`Plugin package mndw configuration at ${join8(pluginDir, "package.json")} must be an object`);
1936
+ }
1937
+ const configured = mndw.productionEntry;
1938
+ if (configured === void 0) {
1939
+ return validateSourceEntry(pluginDir, DEFAULT_SOURCE_ENTRY);
1940
+ }
1941
+ if (typeof configured !== "string" || configured.length === 0) {
1942
+ throw new CliError(
1943
+ `Plugin package productionEntry at ${join8(pluginDir, "package.json")} must be a non-empty string`
1944
+ );
1945
+ }
1946
+ return validateSourceEntry(pluginDir, configured);
1947
+ }
1948
+ function resolveDevelopmentSourceEntry(pluginDir) {
1949
+ return validateSourceEntry(pluginDir, DEFAULT_SOURCE_ENTRY);
1950
+ }
1951
+
1952
+ // src/manifest.ts
1953
+ var knownManifestKeys = /* @__PURE__ */ new Set([
1954
+ "$schema",
1955
+ ...pluginManifestSchema.options.flatMap((option) => Object.keys(option.shape))
1956
+ ]);
1957
+ function unknownManifestKeys(raw) {
1958
+ return Object.keys(raw).filter((key) => !knownManifestKeys.has(key)).map((key) => `unknown manifest key "${key}" is ignored`);
1959
+ }
1960
+ function readManifest(pluginDir) {
1961
+ const resolvedPluginDir = resolvePluginDir(pluginDir);
1962
+ const path3 = resolve9(resolvedPluginDir, "manifest.json");
1963
+ let contents;
1964
+ try {
1965
+ contents = readFileSync6(path3, "utf8");
1966
+ } catch (error) {
1967
+ if (error instanceof Error && typeof error.code === "string") {
1968
+ throw new CliError(`Failed to read manifest at ${path3}: ${error.message}`);
1969
+ }
1970
+ throw error;
1971
+ }
1972
+ let manifest;
1973
+ let warnings;
1974
+ try {
1975
+ const raw = JSON.parse(contents);
1976
+ manifest = validateManifest(raw);
1977
+ warnings = unknownManifestKeys(raw);
1978
+ } catch (error) {
1979
+ if (error instanceof SyntaxError) {
1980
+ throw new CliError(`Failed to parse manifest at ${path3}: ${error.message}`);
1981
+ }
1982
+ throw error;
1983
+ }
1984
+ const sourceEntryPath = resolve9(resolvedPluginDir, "src/index.ts");
1985
+ try {
1986
+ if (!statSync2(sourceEntryPath).isFile()) {
1987
+ throw new CliError(`Source entry is not a regular file: ${sourceEntryPath}`);
1988
+ }
1989
+ } catch (error) {
1990
+ if (error instanceof CliError) {
1991
+ throw error;
1992
+ }
1993
+ if (error instanceof Error && typeof error.code === "string") {
1994
+ const code = error.code;
1995
+ const message = code === "ENOENT" ? `Missing source entry at ${sourceEntryPath}` : `Failed to inspect source entry at ${sourceEntryPath}: ${error.message}`;
1996
+ throw new CliError(message);
1997
+ }
1998
+ throw error;
1999
+ }
2000
+ resolveProductionSourceEntry(resolvedPluginDir);
2001
+ return { manifest, path: path3, warnings };
2002
+ }
2003
+
2004
+ // src/dev-server/start.ts
2005
+ import { resolve as resolve13 } from "node:path";
2006
+
2007
+ // ../../frontend/angular-compiler/src/vite.ts
2008
+ import fs from "node:fs";
2009
+ import path from "node:path";
2010
+
2011
+ // ../../frontend/angular-compiler/src/index.ts
2012
+ import { cpSync, existsSync as existsSync4, mkdirSync as mkdirSync4, mkdtempSync as mkdtempSync2, readFileSync as readFileSync7, readdirSync as readdirSync3, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
2013
+ import { tmpdir } from "node:os";
2014
+ import { join as join9, posix, relative as relative3, resolve as resolve10 } from "node:path";
2015
+ import {
2016
+ EmitFlags,
2017
+ createCompilerHost,
2018
+ formatDiagnostics,
2019
+ performCompilation,
2020
+ readConfiguration
2021
+ } from "@angular/compiler-cli";
2022
+ import { compileString } from "sass";
2023
+ var COMPILER_NODE_MODULES = resolve10(import.meta.dirname, "..", "node_modules");
2024
+ var AngularCompilerError = class extends Error {
2025
+ constructor(message) {
2026
+ super(message);
2027
+ this.name = "AngularCompilerError";
2028
+ }
2029
+ };
2030
+ function compileAngular(pluginDir, sourceEntry = "src/index.ts") {
2031
+ const compiler = createAngularCompiler(pluginDir, { includeComponentStylesInGlobal: true });
2032
+ try {
2033
+ const output = compiler.compileInitial();
2034
+ const entryPath = output.sourceToOutput(resolve10(pluginDir, sourceEntry));
2035
+ if (entryPath === void 0 || !existsSync4(entryPath)) {
2036
+ compiler.dispose();
2037
+ throw new AngularCompilerError(`Angular compilation produced no ${sourceEntry} output in ${output.outputDir}`);
2038
+ }
2039
+ return {
2040
+ entryPath,
2041
+ cacheDir: output.outputDir,
2042
+ globalStylesPath: output.globalStylesPath,
2043
+ cleanup: () => compiler.dispose()
2044
+ };
2045
+ } catch (error) {
2046
+ compiler.dispose();
2047
+ throw error;
2048
+ }
2049
+ }
2050
+ function createAngularCompiler(pluginDir, options = {}) {
2051
+ validatePlugin(pluginDir);
2052
+ const staging = mkdtempSync2(join9(tmpdir(), "mndw-ng-stage-"));
2053
+ let current;
2054
+ let program;
2055
+ let disposed = false;
2056
+ const dispose = () => {
2057
+ if (disposed) {
2058
+ return;
2059
+ }
2060
+ disposed = true;
2061
+ rmSync3(staging, { recursive: true, force: true });
2062
+ if (current !== void 0) {
2063
+ rmSync3(current.outputDir, { recursive: true, force: true });
2064
+ current = void 0;
2065
+ }
2066
+ };
2067
+ const compile = (changedFiles, initial) => {
2068
+ if (disposed) {
2069
+ throw new AngularCompilerError("Angular compiler has been disposed");
2070
+ }
2071
+ const stagedSources = stageSources(
2072
+ pluginDir,
2073
+ staging,
2074
+ changedFiles,
2075
+ initial,
2076
+ options.includeComponentStylesInGlobal === true
2077
+ );
2078
+ const outputDir = mkdtempSync2(join9(tmpdir(), "mndw-ng-cache-"));
2079
+ try {
2080
+ if (current !== void 0) {
2081
+ cpSync(current.outputDir, outputDir, { recursive: true });
2082
+ }
2083
+ const configuration = readConfiguration(join9(staging, "tsconfig.json"));
2084
+ const diagnostics = [...configuration.errors];
2085
+ if (diagnostics.length > 0) {
2086
+ throw compilationError(diagnostics);
2087
+ }
2088
+ const options2 = {
2089
+ ...configuration.options,
2090
+ outDir: outputDir,
2091
+ declaration: false,
2092
+ declarationMap: false,
2093
+ sourceMap: false
2094
+ };
2095
+ const result = performCompilation({
2096
+ rootNames: configuration.rootNames,
2097
+ options: options2,
2098
+ host: createCompilerHost({ options: options2 }),
2099
+ oldProgram: program,
2100
+ emitFlags: EmitFlags.JS,
2101
+ forceEmit: true,
2102
+ modifiedResourceFiles: initial ? null : stagedSources.modifiedResourceFiles
2103
+ });
2104
+ const allDiagnostics = [...result.diagnostics];
2105
+ if (allDiagnostics.length > 0) {
2106
+ throw compilationError(allDiagnostics);
2107
+ }
2108
+ if (result.emitResult?.emitSkipped === true || result.program === void 0) {
2109
+ throw new AngularCompilerError("Angular compilation emitted no JavaScript output");
2110
+ }
2111
+ const globalStylesPath = writeGlobalStyles(stagedSources.styles, outputDir);
2112
+ const next = {
2113
+ outputDir,
2114
+ globalStylesPath,
2115
+ sourceToOutput: (sourcePath) => sourceToOutput(pluginDir, outputDir, sourcePath)
2116
+ };
2117
+ const previous = current;
2118
+ current = next;
2119
+ program = result.program;
2120
+ if (previous !== void 0) {
2121
+ rmSync3(previous.outputDir, { recursive: true, force: true });
2122
+ }
2123
+ return next;
2124
+ } catch (error) {
2125
+ rmSync3(outputDir, { recursive: true, force: true });
2126
+ throw error;
2127
+ }
2128
+ };
2129
+ const compileInitial = () => {
2130
+ return compile([], true);
2131
+ };
2132
+ const update = (changedFiles) => {
2133
+ if (current === void 0) {
2134
+ return compileInitial();
2135
+ }
2136
+ return compile(changedFiles, false);
2137
+ };
2138
+ return {
2139
+ compileInitial,
2140
+ update,
2141
+ currentOutput: () => current,
2142
+ dispose
2143
+ };
2144
+ }
2145
+ function validatePlugin(pluginDir) {
2146
+ const tsconfigPath = join9(pluginDir, "tsconfig.json");
2147
+ if (!existsSync4(tsconfigPath)) {
2148
+ throw new AngularCompilerError(`Angular plugin at ${pluginDir} is missing tsconfig.json`);
2149
+ }
2150
+ let tsconfig;
2151
+ try {
2152
+ tsconfig = JSON.parse(readFileSync7(tsconfigPath, "utf8"));
2153
+ } catch {
2154
+ throw new AngularCompilerError(`Invalid tsconfig.json in ${pluginDir}: not valid JSON`);
2155
+ }
2156
+ if (tsconfig === null || typeof tsconfig !== "object" || !("angularCompilerOptions" in tsconfig)) {
2157
+ throw new AngularCompilerError(`Angular plugin at ${pluginDir} is missing angularCompilerOptions in tsconfig.json`);
2158
+ }
2159
+ if ("extends" in tsconfig) {
2160
+ throw new AngularCompilerError(`Angular plugin tsconfig.json must be standalone (no "extends"): ${tsconfigPath}`);
2161
+ }
2162
+ if (!existsSync4(join9(pluginDir, "src"))) {
2163
+ throw new AngularCompilerError(`Angular plugin at ${pluginDir} is missing src/`);
2164
+ }
2165
+ validateCompileInputs(tsconfig, tsconfigPath);
2166
+ }
2167
+ function stageSources(pluginDir, staging, changedFiles, initial, includeComponentStylesInGlobal) {
2168
+ if (initial) {
2169
+ writeStagedTsconfig(readFileSync7(join9(pluginDir, "tsconfig.json"), "utf8"), staging, pluginDir);
2170
+ cpSync(join9(pluginDir, "src"), join9(staging, "src"), { recursive: true });
2171
+ } else {
2172
+ for (const changedFile of changedFiles) {
2173
+ const sourceFile = resolve10(changedFile);
2174
+ const sourceRoot = resolve10(pluginDir, "src");
2175
+ const sourceRelative = relative3(sourceRoot, sourceFile);
2176
+ if (sourceRelative.startsWith("..")) {
2177
+ continue;
2178
+ }
2179
+ const stagedFile = join9(staging, "src", sourceRelative);
2180
+ if (existsSync4(sourceFile)) {
2181
+ mkdirSync4(resolve10(stagedFile, ".."), { recursive: true });
2182
+ cpSync(sourceFile, stagedFile);
2183
+ } else {
2184
+ rmSync3(stagedFile, { force: true });
2185
+ if (sourceRelative.endsWith(".scss")) {
2186
+ rmSync3(stagedFile.replace(/\.scss$/, ".css"), { force: true });
2187
+ }
2188
+ }
2189
+ }
2190
+ }
2191
+ const compiledStyles = compileScss(join9(staging, "src"), includeComponentStylesInGlobal);
2192
+ if (initial) {
2193
+ return { modifiedResourceFiles: /* @__PURE__ */ new Set(), styles: compiledStyles.styles };
2194
+ }
2195
+ for (const changedFile of changedFiles) {
2196
+ const sourceFile = resolve10(changedFile);
2197
+ const sourceRelative = relative3(resolve10(pluginDir, "src"), sourceFile);
2198
+ if (!sourceRelative.startsWith("..")) {
2199
+ compiledStyles.modifiedResourceFiles.add(join9(staging, "src", sourceRelative));
2200
+ }
2201
+ }
2202
+ return compiledStyles;
2203
+ }
2204
+ function writeStagedTsconfig(tsconfigJson, staging, pluginDir) {
2205
+ const config = JSON.parse(tsconfigJson);
2206
+ const sourceCompilerOptions = config.compilerOptions;
2207
+ const compilerOptions = sourceCompilerOptions !== null && typeof sourceCompilerOptions === "object" ? sourceCompilerOptions : {};
2208
+ const sourcePaths = compilerOptions.paths;
2209
+ const paths = sourcePaths !== null && typeof sourcePaths === "object" ? sourcePaths : {};
2210
+ writeFileSync4(
2211
+ join9(staging, "tsconfig.json"),
2212
+ `${JSON.stringify(
2213
+ {
2214
+ ...config,
2215
+ compilerOptions: {
2216
+ ...compilerOptions,
2217
+ baseUrl: compilerOptions.baseUrl ?? staging,
2218
+ paths: {
2219
+ "@angular/core/testing": [join9(COMPILER_NODE_MODULES, "@angular/core/types/testing.d.ts")],
2220
+ "@angular/core/rxjs-interop": [join9(COMPILER_NODE_MODULES, "@angular/core/types/rxjs-interop.d.ts")],
2221
+ "@angular/platform-browser/testing": [
2222
+ join9(COMPILER_NODE_MODULES, "@angular/platform-browser/types/testing.d.ts")
2223
+ ],
2224
+ "d3": [
2225
+ join9(pluginDir, "node_modules/@types/d3/index.d.ts"),
2226
+ join9(pluginDir, "node_modules/d3"),
2227
+ join9(COMPILER_NODE_MODULES, "d3")
2228
+ ],
2229
+ "@mndw/sdk/*": [
2230
+ join9(pluginDir, "node_modules/@mndw/sdk/src/*"),
2231
+ join9(COMPILER_NODE_MODULES, "@mndw/sdk/src/*")
2232
+ ],
2233
+ "*": [join9(pluginDir, "node_modules/*"), join9(COMPILER_NODE_MODULES, "*")],
2234
+ ...paths
2235
+ }
2236
+ }
2237
+ },
2238
+ null,
2239
+ 2
2240
+ )}
2241
+ `
2242
+ );
2243
+ }
2244
+ function validateCompileInputs(tsconfig, tsconfigPath) {
2245
+ const config = tsconfig;
2246
+ for (const field of ["include", "files"]) {
2247
+ if (!(field in config)) {
2248
+ continue;
2249
+ }
2250
+ const value = config[field];
2251
+ if (!Array.isArray(value)) {
2252
+ throw new AngularCompilerError(
2253
+ `Angular plugin tsconfig field "${field}" must be an array of strings: ${tsconfigPath}`
2254
+ );
2255
+ }
2256
+ for (const rawEntry of value) {
2257
+ if (typeof rawEntry !== "string") {
2258
+ throw new AngularCompilerError(
2259
+ `Angular plugin tsconfig field "${field}" must be an array of strings: ${tsconfigPath}`
2260
+ );
2261
+ }
2262
+ const normalized = rawEntry.replaceAll("\\", "/");
2263
+ const resolved = posix.normalize(`/${normalized}`);
2264
+ if (resolved !== "/src" && !resolved.startsWith("/src/")) {
2265
+ throw new AngularCompilerError(`Angular plugin tsconfig ${field} entry must resolve within src: ${rawEntry}`);
2266
+ }
2267
+ }
2268
+ }
2269
+ }
2270
+ function compileScss(srcDir, includeComponentStylesInGlobal) {
2271
+ const modified = /* @__PURE__ */ new Set();
2272
+ const styles = [];
2273
+ const componentStyles = /* @__PURE__ */ new Set();
2274
+ for (const file of walk(srcDir)) {
2275
+ if (!file.endsWith(".ts")) {
2276
+ continue;
2277
+ }
2278
+ const source = readFileSync7(file, "utf8");
2279
+ const references = source.matchAll(/['"]([^'"]+\.scss)['"]/g);
2280
+ for (const [, reference] of references) {
2281
+ if (reference !== void 0) {
2282
+ componentStyles.add(resolve10(file, "..", reference));
2283
+ }
2284
+ }
2285
+ }
2286
+ for (const file of walk(srcDir)) {
2287
+ if (file.endsWith(".scss")) {
2288
+ const cssFile = file.replace(/\.scss$/, ".css");
2289
+ const css = compileString(readFileSync7(file, "utf8"), { loadPaths: [srcDir] }).css;
2290
+ writeFileSync4(cssFile, css);
2291
+ modified.add(cssFile);
2292
+ if (includeComponentStylesInGlobal || !componentStyles.has(file)) {
2293
+ styles.push(css);
2294
+ }
2295
+ }
2296
+ }
2297
+ for (const file of walk(srcDir)) {
2298
+ if (file.endsWith(".ts")) {
2299
+ const source = readFileSync7(file, "utf8");
2300
+ if (source.includes(".scss")) {
2301
+ writeFileSync4(file, source.replaceAll(".scss", ".css"));
2302
+ modified.add(file);
2303
+ }
2304
+ }
2305
+ }
2306
+ return { modifiedResourceFiles: modified, styles };
2307
+ }
2308
+ function writeGlobalStyles(styles, outputDir) {
2309
+ const nonEmptyStyles = styles.filter((css) => css.length > 0);
2310
+ const globalStylesPath = join9(outputDir, "styles.css");
2311
+ if (nonEmptyStyles.length === 0) {
2312
+ rmSync3(globalStylesPath, { force: true });
2313
+ return void 0;
2314
+ }
2315
+ writeFileSync4(globalStylesPath, `${nonEmptyStyles.join("\n")}
2316
+ `);
2317
+ return globalStylesPath;
2318
+ }
2319
+ function sourceToOutput(pluginDir, outputDir, sourcePath) {
2320
+ const sourceRoot = resolve10(pluginDir, "src");
2321
+ const absoluteSourcePath = resolve10(sourcePath);
2322
+ const sourceRelative = relative3(sourceRoot, absoluteSourcePath);
2323
+ if (sourceRelative.startsWith("..") || !sourceRelative.endsWith(".ts")) {
2324
+ return void 0;
2325
+ }
2326
+ return join9(outputDir, sourceRelative.replace(/\.ts$/, ".js"));
2327
+ }
2328
+ function compilationError(diagnostics) {
2329
+ return new AngularCompilerError(`Angular compilation failed
2330
+ ${formatDiagnostics(diagnostics)}`);
2331
+ }
2332
+ function walk(dir) {
2333
+ return readdirSync3(dir, { withFileTypes: true }).flatMap((entry) => {
2334
+ const full = join9(dir, entry.name);
2335
+ return entry.isDirectory() ? walk(full) : [full];
2336
+ });
2337
+ }
2338
+
2339
+ // ../../frontend/angular-compiler/src/vite.ts
2340
+ var GLOBAL_STYLES_PREFIX = "virtual:mndw-angular-global-styles:";
2341
+ var defaultDeps = {
2342
+ createCompiler: createAngularCompiler,
2343
+ readFileSync: (filePath) => fs.readFileSync(filePath, "utf8")
2344
+ };
2345
+ function angularSandboxPlugin(pluginDir, deps = {}) {
2346
+ const resolvedPluginDir = path.resolve(pluginDir);
2347
+ const sourceDir = path.join(resolvedPluginDir, "src");
2348
+ const mergedDeps = { ...defaultDeps, ...deps };
2349
+ const compiler = mergedDeps.createCompiler(resolvedPluginDir);
2350
+ let output;
2351
+ try {
2352
+ output = compiler.compileInitial();
2353
+ } catch (error) {
2354
+ compiler.dispose();
2355
+ throw error;
2356
+ }
2357
+ const globalStylesId = `${GLOBAL_STYLES_PREFIX}${encodeURIComponent(resolvedPluginDir)}`;
2358
+ const resolvedGlobalStylesId = `\0${globalStylesId}.js`;
2359
+ const isSourceFile = (id) => {
2360
+ const sourcePath = path.resolve(stripQuery(id));
2361
+ const relativePath = path.relative(sourceDir, sourcePath);
2362
+ return !relativePath.startsWith("..") && path.extname(sourcePath) === ".ts" && !sourcePath.endsWith(".d.ts");
2363
+ };
2364
+ const transform = (_code, id) => {
2365
+ const sourcePath = path.resolve(stripQuery(id));
2366
+ if (!isSourceFile(sourcePath)) {
2367
+ return null;
2368
+ }
2369
+ const outputPath = output.sourceToOutput(sourcePath);
2370
+ if (outputPath === void 0 || !fs.existsSync(outputPath)) {
2371
+ return null;
2372
+ }
2373
+ let compiled = mergedDeps.readFileSync(outputPath);
2374
+ if (sourcePath === path.join(sourceDir, "index.ts") && output.globalStylesPath !== void 0) {
2375
+ compiled = `${compiled}
2376
+ import ${JSON.stringify(globalStylesId)};
2377
+ `;
2378
+ }
2379
+ return { code: compiled, map: null };
2380
+ };
2381
+ const handleHotUpdate = ({ file, server }) => {
2382
+ const sourcePath = path.resolve(stripQuery(file));
2383
+ if (!isAngularResource(sourcePath, sourceDir)) {
2384
+ return void 0;
2385
+ }
2386
+ try {
2387
+ output = compiler.update([sourcePath]);
2388
+ } catch (error) {
2389
+ server.config.logger.error(`[mndw-angular] ${errorMessage(error)}`);
2390
+ return [];
2391
+ }
2392
+ const affected = [...server.moduleGraph.idToModuleMap.values()].filter((module) => module.id !== null && isSourceFile(module.id));
2393
+ const globalStylesModule = server.moduleGraph.getModuleById(resolvedGlobalStylesId);
2394
+ if (globalStylesModule !== void 0) {
2395
+ affected.push(globalStylesModule);
2396
+ }
2397
+ for (const module of affected) {
2398
+ server.moduleGraph.invalidateModule(module);
2399
+ }
2400
+ return affected;
2401
+ };
2402
+ return {
2403
+ name: "mndw-angular-sandbox",
2404
+ enforce: "pre",
2405
+ resolveId(id) {
2406
+ if (id === globalStylesId) {
2407
+ return resolvedGlobalStylesId;
2408
+ }
2409
+ return void 0;
2410
+ },
2411
+ load(id) {
2412
+ if (id !== resolvedGlobalStylesId) {
2413
+ return void 0;
2414
+ }
2415
+ const css = output.globalStylesPath === void 0 ? "" : mergedDeps.readFileSync(output.globalStylesPath);
2416
+ const styleKey = JSON.stringify(globalStylesId);
2417
+ return `const css = ${JSON.stringify(css)};
2418
+ const key = ${styleKey};
2419
+ if (typeof document !== 'undefined') {
2420
+ let style = document.querySelector('style[data-mndw-angular-global="' + key + '"]');
2421
+ if (style === null) {
2422
+ style = document.createElement('style');
2423
+ style.setAttribute('data-mndw-angular-global', key);
2424
+ document.head.appendChild(style);
2425
+ }
2426
+ style.textContent = css;
2427
+ }
2428
+ export default css;
2429
+ `;
2430
+ },
2431
+ transform,
2432
+ handleHotUpdate,
2433
+ configureServer(server) {
2434
+ server.httpServer?.once("close", () => compiler.dispose());
2435
+ },
2436
+ closeBundle() {
2437
+ compiler.dispose();
2438
+ }
2439
+ };
2440
+ }
2441
+ function stripQuery(id) {
2442
+ return id.split("?", 1)[0];
2443
+ }
2444
+ function isAngularResource(file, sourceDir) {
2445
+ const relativePath = path.relative(sourceDir, file);
2446
+ return !relativePath.startsWith("..") && [".ts", ".html", ".scss", ".css"].includes(path.extname(file));
2447
+ }
2448
+ function errorMessage(error) {
2449
+ return error instanceof Error ? error.message : String(error);
2450
+ }
2451
+
2452
+ // src/dev-server/start.ts
2453
+ import { svelte } from "@sveltejs/vite-plugin-svelte";
2454
+ import vue from "@vitejs/plugin-vue";
2455
+ import { createServer } from "vite";
2456
+
2457
+ // ../../frontend/sdk-internal/src/dev-proxies.ts
2458
+ function devProxies(options) {
2459
+ const deviceUrl = new URL(options.deviceUrl);
2460
+ function deviceProxy(apiPath) {
2461
+ return {
2462
+ target: options.deviceUrl,
2463
+ changeOrigin: true,
2464
+ configure: (proxy) => {
2465
+ proxy.on("proxyReq", (proxyReq) => {
2466
+ proxyReq.setHeader("Host", deviceUrl.host);
2467
+ proxyReq.setHeader("Origin", deviceUrl.origin);
2468
+ });
2469
+ proxy.on("error", (err) => {
2470
+ console.error(`[vite proxy] [${apiPath}] error:`, err.message);
2471
+ });
2472
+ }
2473
+ };
2474
+ }
2475
+ function daemonProxy(ws = false) {
2476
+ return { target: options.daemonUrl, changeOrigin: false, ws };
2477
+ }
2478
+ return {
2479
+ "/rci": deviceProxy("/rci"),
2480
+ "/auth": deviceProxy("/auth"),
2481
+ "/api": daemonProxy(),
2482
+ "/ws": daemonProxy(true)
2483
+ };
2484
+ }
2485
+
2486
+ // src/dev-server/plugin-modules.ts
2487
+ import { resolve as resolve11 } from "node:path";
2488
+
2489
+ // ../../frontend/sdk-internal/src/dev-sandbox.ts
2490
+ import fs2 from "node:fs";
2491
+ import path2 from "node:path";
2492
+ var defaultFs = {
2493
+ existsSync: (filePath) => fs2.existsSync(filePath),
2494
+ readFileSync: (filePath) => fs2.readFileSync(filePath, "utf-8")
2495
+ };
2496
+ function renderSandboxModule(resolvedPath) {
2497
+ const entry = path2.join(resolvedPath, "src", "index.ts");
2498
+ return `export {createInstance} from ${JSON.stringify(entry)};`;
2499
+ }
2500
+ function renderSandboxManifest(resolvedPath, deps = defaultFs) {
2501
+ const manifestPath = path2.join(resolvedPath, "manifest.json");
2502
+ if (!deps.existsSync(manifestPath)) {
2503
+ throw new Error(`[mndw-sandbox] No manifest.json found at ${manifestPath}`);
2504
+ }
2505
+ const raw = deps.readFileSync(manifestPath);
2506
+ let parsed;
2507
+ try {
2508
+ parsed = JSON.parse(raw);
2509
+ } catch (err) {
2510
+ throw new Error(`[mndw-sandbox] manifest.json is not valid JSON: ${err.message}`);
2511
+ }
2512
+ const catalogBaseUrl = `/@fs${resolvedPath.replace(/\/$/, "")}`;
2513
+ return `export const __catalogBaseUrl = ${JSON.stringify(catalogBaseUrl)};
2514
+ export default ${JSON.stringify(parsed)};`;
2515
+ }
2516
+
2517
+ // src/dev-server/plugin-modules.ts
2518
+ var PLUGIN_URL = "/@mndw-dev/plugin.js";
2519
+ var MANIFEST_URL = "/@mndw-dev/manifest.js";
2520
+ var PLUGIN_ID = "\0mndw-dev:plugin";
2521
+ var MANIFEST_ID = "\0mndw-dev:manifest";
2522
+ function moduleWrapper(source, event) {
2523
+ return `${source}
2524
+ if (import.meta.hot) import.meta.hot.accept((m) => window.dispatchEvent(new CustomEvent(${JSON.stringify(event)}, {detail: m})));`;
2525
+ }
2526
+ function pluginModules(pluginDir) {
2527
+ const root = resolve11(pluginDir);
2528
+ const manifestPath = resolve11(root, "manifest.json");
2529
+ let server;
2530
+ const getModule = (id) => {
2531
+ return server?.environments.client.moduleGraph.getModuleById(id);
2532
+ };
2533
+ return {
2534
+ name: "mndw-dev-plugin-modules",
2535
+ resolveId(source) {
2536
+ if (source === PLUGIN_URL) {
2537
+ return PLUGIN_ID;
2538
+ }
2539
+ if (source === MANIFEST_URL) {
2540
+ return MANIFEST_ID;
2541
+ }
2542
+ return void 0;
2543
+ },
2544
+ load(id) {
2545
+ if (id === PLUGIN_ID) {
2546
+ return moduleWrapper(renderSandboxModule(root), "mndw:dev-plugin-update");
2547
+ }
2548
+ if (id === MANIFEST_ID) {
2549
+ const rendered = renderSandboxManifest(root).replace(
2550
+ /export const __catalogBaseUrl = [^;]+;/,
2551
+ 'export const __catalogBaseUrl = "/";'
2552
+ );
2553
+ return moduleWrapper(rendered, "mndw:dev-manifest-update");
2554
+ }
2555
+ return void 0;
2556
+ },
2557
+ configureServer(viteServer) {
2558
+ server = viteServer;
2559
+ viteServer.watcher.add(manifestPath);
2560
+ },
2561
+ hotUpdate(context) {
2562
+ const file = resolve11(context.file);
2563
+ if (file === manifestPath) {
2564
+ const manifestModule = getModule(MANIFEST_ID);
2565
+ if (manifestModule === void 0) {
2566
+ return void 0;
2567
+ }
2568
+ server?.environments.client.moduleGraph.invalidateModule(manifestModule);
2569
+ return [manifestModule];
2570
+ }
2571
+ const sourceRoot = resolve11(root, "src");
2572
+ const relativePath = file.slice(sourceRoot.length);
2573
+ const isSourceFile = file.startsWith(`${sourceRoot}/`) || file.startsWith(`${sourceRoot}\\`);
2574
+ const isFrameworkComponent = isSourceFile && [".vue", ".svelte"].includes(relativePath.slice(relativePath.lastIndexOf(".")));
2575
+ if (!isFrameworkComponent) {
2576
+ return void 0;
2577
+ }
2578
+ const wrapper = getModule(PLUGIN_ID);
2579
+ if (wrapper === void 0) {
2580
+ return void 0;
2581
+ }
2582
+ const updated = [.../* @__PURE__ */ new Set([...context.modules, wrapper])];
2583
+ for (const module of updated) {
2584
+ server?.environments.client.moduleGraph.invalidateModule(module);
2585
+ }
2586
+ return updated;
2587
+ }
2588
+ };
2589
+ }
2590
+
2591
+ // src/dev-server/prebuilt-host.ts
2592
+ import { createReadStream, readFileSync as readFileSync8, statSync as statSync3 } from "node:fs";
2593
+ import { extname as extname2, relative as relative4, resolve as resolve12, sep as sep2 } from "node:path";
2594
+ var CONTENT_TYPES = {
2595
+ ".css": "text/css; charset=utf-8",
2596
+ ".html": "text/html; charset=utf-8",
2597
+ ".ico": "image/x-icon",
2598
+ ".js": "text/javascript; charset=utf-8",
2599
+ ".json": "application/json; charset=utf-8",
2600
+ ".mjs": "text/javascript; charset=utf-8",
2601
+ ".png": "image/png",
2602
+ ".svg": "image/svg+xml",
2603
+ ".woff2": "font/woff2"
2604
+ };
2605
+ function isWithin(root, path3) {
2606
+ const rel = relative4(root, path3);
2607
+ return rel === "" || !rel.startsWith(`..${sep2}`) && rel !== "..";
2608
+ }
2609
+ function existingFile(path3) {
2610
+ try {
2611
+ return statSync3(path3).isFile();
2612
+ } catch {
2613
+ return false;
2614
+ }
2615
+ }
2616
+ function prebuiltHost(dir) {
2617
+ const hostRoot = resolve12(dir);
2618
+ return {
2619
+ name: "mndw-dev-prebuilt-host",
2620
+ configureServer(server) {
2621
+ const pluginRoot = resolve12(server.config.root);
2622
+ server.middlewares.use((request, response, next) => {
2623
+ if (request.method !== "GET" || request.url === void 0) {
2624
+ next();
2625
+ return;
2626
+ }
2627
+ const rawPath = request.url.split("?", 1)[0] ?? "/";
2628
+ let pathname;
2629
+ try {
2630
+ pathname = decodeURIComponent(rawPath);
2631
+ } catch {
2632
+ response.statusCode = 404;
2633
+ response.end();
2634
+ return;
2635
+ }
2636
+ const hostPath = resolve12(hostRoot, `.${pathname}`);
2637
+ if (!isWithin(hostRoot, hostPath)) {
2638
+ response.statusCode = 404;
2639
+ response.end();
2640
+ return;
2641
+ }
2642
+ if (pathname === "/") {
2643
+ void sendIndex(request.url, response, server, hostRoot);
2644
+ return;
2645
+ }
2646
+ if (pathname.startsWith("/assets/") || pathname.startsWith("/shared/")) {
2647
+ if (existingFile(hostPath)) {
2648
+ response.statusCode = 200;
2649
+ response.setHeader("Content-Type", CONTENT_TYPES[extname2(hostPath)] ?? "application/octet-stream");
2650
+ createReadStream(hostPath).pipe(response);
2651
+ return;
2652
+ }
2653
+ next();
2654
+ return;
2655
+ }
2656
+ const pluginPath = resolve12(pluginRoot, `.${pathname}`);
2657
+ if (existingFile(hostPath) || existingFile(pluginPath)) {
2658
+ next();
2659
+ return;
2660
+ }
2661
+ if ((request.headers.accept ?? "").includes("text/html")) {
2662
+ void sendIndex(request.url, response, server, hostRoot);
2663
+ return;
2664
+ }
2665
+ next();
2666
+ });
2667
+ }
2668
+ };
2669
+ }
2670
+ async function sendIndex(url, response, server, hostRoot) {
2671
+ const indexPath = resolve12(hostRoot, "index.html");
2672
+ if (!isWithin(hostRoot, indexPath) || !existingFile(indexPath)) {
2673
+ response.statusCode = 404;
2674
+ response.end();
2675
+ return;
2676
+ }
2677
+ try {
2678
+ const sourceHtml = readFileSync8(indexPath, "utf8");
2679
+ const htmlWithIgnoredAssets = sourceHtml.replace(
2680
+ /<script\b(?=[^>]*\btype\s*=\s*["']module["'])(?=[^>]*\bsrc\s*=\s*["']\/assets\/)(?![^>]*\bvite-ignore\b)[^>]*>/gi,
2681
+ (script) => script.replace(/^<script\b/i, "<script vite-ignore")
2682
+ );
2683
+ const html = await server.transformIndexHtml(url, htmlWithIgnoredAssets);
2684
+ response.statusCode = 200;
2685
+ response.setHeader("Content-Type", "text/html; charset=utf-8");
2686
+ response.end(html);
2687
+ } catch {
2688
+ response.statusCode = 500;
2689
+ response.end("Failed to transform prebuilt host index.html");
2690
+ }
2691
+ }
2692
+
2693
+ // src/dev-server/shared-externals.ts
2694
+ function sharedExternals(framework) {
2695
+ const urls = sharedImportMap();
2696
+ let config;
2697
+ let server;
2698
+ const externals = new Set(pluginDependencies(framework));
2699
+ return {
2700
+ name: "mndw-dev-shared-externals",
2701
+ enforce: "pre",
2702
+ configResolved(resolved) {
2703
+ config = resolved;
2704
+ },
2705
+ configureServer(viteServer) {
2706
+ server = viteServer;
2707
+ },
2708
+ resolveId(source) {
2709
+ if (!externals.has(source)) {
2710
+ return void 0;
2711
+ }
2712
+ const target = urls[source];
2713
+ if (target === void 0) {
2714
+ return void 0;
2715
+ }
2716
+ const configuredOrigin = config?.server.origin;
2717
+ const resolvedUrl = server?.resolvedUrls?.local[0];
2718
+ const origin = configuredOrigin || resolvedUrl || "http://localhost:5173";
2719
+ return { id: new URL(target, origin).href, external: true };
2720
+ }
2721
+ };
2722
+ }
2723
+
2724
+ // src/dev-server/start.ts
2725
+ async function startPluginDevServer(options) {
2726
+ const frameworkPlugins = options.framework === "svelte" ? [svelte()] : options.framework === "vue" ? [vue({ isProduction: true })] : options.framework === "angular" ? [angularSandboxPlugin(options.pluginDir)] : [];
2727
+ const server = await createServer({
2728
+ root: options.pluginDir,
2729
+ cacheDir: resolve13(options.pluginDir, "node_modules", `.vite-${options.framework}-dev`),
2730
+ configFile: false,
2731
+ appType: "custom",
2732
+ plugins: [
2733
+ ...frameworkPlugins,
2734
+ sharedExternals(options.framework),
2735
+ pluginModules(options.pluginDir),
2736
+ prebuiltHost(options.hostBundleDir)
2737
+ ],
2738
+ optimizeDeps: { exclude: pluginDependencies(options.framework) },
2739
+ server: {
2740
+ host: "127.0.0.1",
2741
+ port: options.port,
2742
+ strictPort: true,
2743
+ proxy: devProxies({
2744
+ deviceUrl: options.deviceUrl ?? "http://192.168.1.1",
2745
+ daemonUrl: options.daemonUrl
2746
+ })
2747
+ }
2748
+ });
2749
+ try {
2750
+ await server.listen();
2751
+ } catch (error) {
2752
+ await server.close();
2753
+ throw error;
2754
+ }
2755
+ const url = server.resolvedUrls?.local[0] ?? `http://127.0.0.1:${options.port}`;
2756
+ return {
2757
+ url,
2758
+ reload: () => server.ws.send({ type: "full-reload" }),
2759
+ close: () => server.close()
2760
+ };
2761
+ }
2762
+
2763
+ // src/watch.ts
2764
+ import chokidar from "chokidar";
2765
+ var DEFAULT_DEBOUNCE_MS = 150;
2766
+ var ON_RESULT_TIMEOUT_MS = 1e4;
2767
+ var BASELINE_IGNORES = [
2768
+ "**/node_modules/**",
2769
+ "**/dist/**",
2770
+ "**/.git/**",
2771
+ "**/.dev-data/**",
2772
+ "**/.cache/go-build/**",
2773
+ "**/.gocache/**",
2774
+ "**/go-build/**"
2775
+ ];
2776
+ function createChokidarWatcher(paths, options) {
2777
+ const watcher = chokidar.watch([...paths], {
2778
+ ignored: [...options.ignored],
2779
+ ignoreInitial: true,
2780
+ followSymlinks: false,
2781
+ awaitWriteFinish: options.awaitWriteFinish
2782
+ });
2783
+ let listener;
2784
+ const forward = (changedPath) => listener?.(changedPath);
2785
+ watcher.on("add", forward);
2786
+ watcher.on("change", forward);
2787
+ watcher.on("error", (error) => {
2788
+ console.error("[mndw dev] source watcher error:", error);
2789
+ });
2790
+ return {
2791
+ onChange: (nextListener) => {
2792
+ listener = nextListener;
2793
+ },
2794
+ close: () => watcher.close()
2795
+ };
2796
+ }
2797
+ function asError2(error) {
2798
+ return error instanceof Error ? error : new Error(String(error));
2799
+ }
2800
+ function watchAndBuild(opts, deps = {}) {
2801
+ const createWatcher = deps.createWatcher ?? createChokidarWatcher;
2802
+ const setTimer = deps.setTimer ?? setTimeout;
2803
+ const clearTimer = deps.clearTimer ?? clearTimeout;
2804
+ const sourceWatcher = createWatcher(opts.paths, {
2805
+ ignored: [.../* @__PURE__ */ new Set([...BASELINE_IGNORES, ...opts.ignore ?? []])],
2806
+ followSymlinks: false,
2807
+ awaitWriteFinish: { stabilityThreshold: 75, pollInterval: 10 }
2808
+ });
2809
+ const pendingPaths = /* @__PURE__ */ new Set();
2810
+ const debounceMs = opts.debounceMs ?? DEFAULT_DEBOUNCE_MS;
2811
+ let debounceTimer;
2812
+ let running = false;
2813
+ let closed = false;
2814
+ let generationCounter = 0;
2815
+ let currentGeneration = 0;
2816
+ let closePromise;
2817
+ const listeners = /* @__PURE__ */ new Set();
2818
+ const schedule = () => {
2819
+ if (closed) {
2820
+ return;
2821
+ }
2822
+ if (debounceTimer !== void 0) {
2823
+ clearTimer(debounceTimer);
2824
+ }
2825
+ debounceTimer = setTimer(() => {
2826
+ debounceTimer = void 0;
2827
+ void drain();
2828
+ }, debounceMs);
2829
+ };
2830
+ const drain = async () => {
2831
+ if (closed || running || pendingPaths.size === 0) {
2832
+ return;
2833
+ }
2834
+ running = true;
2835
+ const changed = [...pendingPaths];
2836
+ pendingPaths.clear();
2837
+ const generation = ++generationCounter;
2838
+ currentGeneration = generation;
2839
+ let invalidated = false;
2840
+ const context = {
2841
+ generation,
2842
+ isCurrent: () => !closed && !invalidated && currentGeneration === generation
2843
+ };
2844
+ let outcome;
2845
+ try {
2846
+ outcome = {
2847
+ ok: true,
2848
+ value: await opts.build(changed),
2849
+ changed,
2850
+ generation
2851
+ };
2852
+ } catch (error) {
2853
+ outcome = { ok: false, error: asError2(error), changed, generation };
2854
+ }
2855
+ let timeoutTimer;
2856
+ let completed = false;
2857
+ const resultPromise = Promise.resolve().then(() => opts.onResult(outcome, context)).catch((error) => {
2858
+ console.error("[mndw dev] watch result handler failed:", asError2(error));
2859
+ }).then(() => {
2860
+ completed = true;
2861
+ });
2862
+ const timeoutPromise = new Promise((resolveTimeout) => {
2863
+ timeoutTimer = setTimer(resolveTimeout, ON_RESULT_TIMEOUT_MS);
2864
+ });
2865
+ await Promise.race([resultPromise, timeoutPromise]);
2866
+ if (timeoutTimer !== void 0) {
2867
+ clearTimer(timeoutTimer);
2868
+ }
2869
+ if (!completed) {
2870
+ invalidated = true;
2871
+ console.error(`[mndw dev] watch result handler exceeded ${ON_RESULT_TIMEOUT_MS} ms; ignoring late side effects`);
2872
+ }
2873
+ running = false;
2874
+ if (!closed && pendingPaths.size > 0) {
2875
+ void drain();
2876
+ }
2877
+ };
2878
+ sourceWatcher.onChange((changedPath) => {
2879
+ if (closed) {
2880
+ return;
2881
+ }
2882
+ pendingPaths.add(changedPath);
2883
+ schedule();
2884
+ for (const listener of listeners) {
2885
+ listener(changedPath);
2886
+ }
2887
+ });
2888
+ return {
2889
+ onChange: (listener) => {
2890
+ listeners.add(listener);
2891
+ },
2892
+ close: () => {
2893
+ if (closePromise !== void 0) {
2894
+ return closePromise;
2895
+ }
2896
+ closed = true;
2897
+ currentGeneration = 0;
2898
+ pendingPaths.clear();
2899
+ if (debounceTimer !== void 0) {
2900
+ clearTimer(debounceTimer);
2901
+ debounceTimer = void 0;
2902
+ }
2903
+ closePromise = sourceWatcher.close();
2904
+ return closePromise;
2905
+ }
2906
+ };
2907
+ }
2908
+
2909
+ // src/dev.ts
2910
+ function resolveDaemonLaunch(daemonArgs, options, ctx) {
2911
+ if (options.daemonBinary !== void 0) {
2912
+ if (!ctx.binaryExists(options.daemonBinary)) {
2913
+ throw new CliError(`mndw dev: --daemon binary not found: ${options.daemonBinary}`);
2914
+ }
2915
+ return { command: options.daemonBinary, args: daemonArgs };
2916
+ }
2917
+ if (ctx.daemonPackageDir !== null) {
2918
+ return { command: "go", args: ["run", "./cmd/mndwd", ...daemonArgs], cwd: ctx.daemonPackageDir };
2919
+ }
2920
+ return { command: (ctx.resolvePackagedDaemon ?? resolvePackagedDaemon)(), args: daemonArgs };
2921
+ }
2922
+ function defaultFindDaemonPackageDir() {
2923
+ const daemonDir = resolve14(cliPackageRoot(), "..", "..", "daemon", "mndwd");
2924
+ return existsSync5(join10(daemonDir, "go.mod")) ? daemonDir : null;
2925
+ }
2926
+ function defaultSymlinkDir(platform, link = symlinkSync) {
2927
+ return (target, linkPath) => link(target, linkPath, platform === "win32" ? "junction" : "dir");
2928
+ }
2929
+ function prebuiltHostLauncher(pluginDir, hostBundleDir, port, framework) {
2930
+ return (env) => {
2931
+ let serverHandle;
2932
+ let resolveExit = () => void 0;
2933
+ let closing = false;
2934
+ const exited = new Promise((resolveExitPromise) => {
2935
+ resolveExit = resolveExitPromise;
2936
+ });
2937
+ const starting = startPluginDevServer({
2938
+ pluginDir,
2939
+ hostBundleDir,
2940
+ port,
2941
+ deviceUrl: env.MNDW_HOST_DEVICE,
2942
+ daemonUrl: env.MNDW_DAEMON ?? "http://127.0.0.1:9090",
2943
+ framework
2944
+ }).then(async (handle) => {
2945
+ serverHandle = handle;
2946
+ if (closing) {
2947
+ await handle.close();
2948
+ resolveExit(0);
2949
+ }
2950
+ return handle;
2951
+ }).catch((error) => {
2952
+ resolveExit(1);
2953
+ throw error;
2954
+ });
2955
+ void starting.catch(() => void 0);
2956
+ return {
2957
+ exited,
2958
+ reload: () => serverHandle?.reload(),
2959
+ close: async () => {
2960
+ closing = true;
2961
+ try {
2962
+ const handle = await starting;
2963
+ await handle.close();
2964
+ } catch {
2965
+ }
2966
+ resolveExit(0);
2967
+ }
2968
+ };
2969
+ };
2970
+ }
2971
+ var defaultGoBuildSpawn = (command, args, options) => {
2972
+ return crossSpawn3.sync(command, args, { cwd: options.cwd, env: options.env, stdio: "inherit" });
2973
+ };
2974
+ function backendWatchPaths(options) {
2975
+ const backend = options.manifest.backend;
2976
+ if (backend === void 0) {
2977
+ return { paths: [], ignores: [] };
2978
+ }
2979
+ const backendDir = join10(options.pluginSourceDir, "backend");
2980
+ const paths = [join10(backendDir, "**/*.go")];
2981
+ const ignores = [
2982
+ "**/.dev-data/**",
2983
+ join10(backendDir, "go.sum"),
2984
+ join10(backendDir, ".cache", "**"),
2985
+ join10(backendDir, ".gocache", "**")
2986
+ ];
2987
+ try {
2988
+ const sourceDirectories = (directory) => {
2989
+ const directories = [];
2990
+ for (const entry of readdirSync4(directory, { withFileTypes: true })) {
2991
+ if (!entry.isDirectory() || [".cache", ".gocache", "dist", "node_modules"].includes(entry.name)) {
2992
+ continue;
2993
+ }
2994
+ const child = join10(directory, entry.name);
2995
+ directories.push(child, ...sourceDirectories(child));
2996
+ }
2997
+ return directories;
2998
+ };
2999
+ const commandDir = join10(backendDir, "cmd");
3000
+ paths.push(...sourceDirectories(backendDir));
3001
+ for (const entry of readdirSync4(commandDir, { withFileTypes: true })) {
3002
+ if (entry.isDirectory()) {
3003
+ ignores.push(join10(backendDir, entry.name));
3004
+ }
3005
+ }
3006
+ } catch {
3007
+ }
3008
+ if (backend.kind === "service") {
3009
+ paths.push(resolve14(options.pluginSourceDir, backend.command));
3010
+ } else {
3011
+ for (const route of backend.routes) {
3012
+ paths.push(resolve14(options.pluginSourceDir, route.command));
3013
+ }
3014
+ }
3015
+ return { paths: [...new Set(paths)], ignores: [...new Set(ignores)] };
3016
+ }
3017
+ function closedWatchHandle() {
3018
+ return { onChange: () => void 0, close: () => Promise.resolve() };
3019
+ }
3020
+ function watchPluginBackend(options, deps = {}) {
3021
+ if (options.manifest.backend === void 0) {
3022
+ return closedWatchHandle();
3023
+ }
3024
+ const buildBackend = deps.buildBackend ?? defaultBuildGoBackend;
3025
+ const watchBackend = deps.watchBackend ?? watchAndBuild;
3026
+ const restart = deps.restartService ?? restartService;
3027
+ const touchSentinel = deps.touchSentinel ?? (() => void 0);
3028
+ const fetchImpl = deps.fetch ?? fetch;
3029
+ const { paths, ignores } = backendWatchPaths(options);
3030
+ const backend = {
3031
+ paths,
3032
+ ignore: ignores,
3033
+ build: () => Promise.resolve(buildBackend(options.pluginSourceDir)).then((result) => {
3034
+ if (!result.success) {
3035
+ throw new CliError(`mndw dev: Go backend rebuild failed: ${result.error ?? "unknown error"}`);
3036
+ }
3037
+ return result;
3038
+ }),
3039
+ onResult: async (result, context) => {
3040
+ if (!result.ok) {
3041
+ console.error(`[mndw dev] Backend rebuild failed: ${result.error.message}`);
3042
+ return;
3043
+ }
3044
+ if (!context.isCurrent()) {
3045
+ return;
3046
+ }
3047
+ if (options.manifest.backend?.kind === "service") {
3048
+ const restarted = await restart({
3049
+ daemonUrl: options.daemonUrl,
3050
+ pluginName: options.pluginName,
3051
+ timeoutMs: 5e3
3052
+ }, { fetch: fetchImpl });
3053
+ if (!context.isCurrent()) {
3054
+ return;
3055
+ }
3056
+ if (!restarted) {
3057
+ console.error(`[mndw dev] Service restart failed for ${options.pluginName}; keeping last reload suppressed`);
3058
+ return;
3059
+ }
3060
+ }
3061
+ if (context.isCurrent()) {
3062
+ touchSentinel();
3063
+ }
3064
+ }
3065
+ };
3066
+ return watchBackend(backend);
3067
+ }
3068
+ function defaultBuildGoBackend(pluginSourceDir, runBuild = defaultGoBuildSpawn) {
3069
+ const backendDir = join10(pluginSourceDir, "backend");
3070
+ const goModPath = join10(backendDir, "go.mod");
3071
+ const cmdDir = join10(backendDir, "cmd");
3072
+ if (!existsSync5(goModPath) || !existsSync5(cmdDir)) {
3073
+ return { success: true, skipped: true };
3074
+ }
3075
+ const commandNames = readdirSync4(cmdDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
3076
+ if (commandNames.length === 0) {
3077
+ return { success: true, skipped: true };
3078
+ }
3079
+ try {
3080
+ for (const commandName of commandNames) {
3081
+ buildGoBackend({
3082
+ plugin: basename(resolve14(pluginSourceDir)),
3083
+ backendDir,
3084
+ binaryName: commandName,
3085
+ entryPackage: `./cmd/${commandName}`,
3086
+ spawn: runBuild
3087
+ });
3088
+ }
3089
+ } catch (error) {
3090
+ return { success: false, skipped: false, error: error instanceof Error ? error.message : String(error) };
3091
+ }
3092
+ return { success: true, skipped: false };
3093
+ }
3094
+ async function runDev(pluginDir, options = {}, deps = {}) {
3095
+ const repoRoot = deps.repoRoot ?? resolve14(dirname6(fileURLToPath(import.meta.url)), "..", "..", "..");
3096
+ const loadManifest = deps.readManifest ?? readManifest;
3097
+ const makeTempDir = deps.makeTempDir ?? ((prefix) => mkdtempSync3(join10(tmpdir2(), prefix)));
3098
+ const symlinkDir = deps.symlinkDir ?? defaultSymlinkDir(deps.platform ?? process.platform);
3099
+ const removeDir = deps.removeDir ?? ((dir) => rmSync4(dir, { recursive: true, force: true }));
3100
+ const findDaemonPackageDir = deps.findDaemonPackageDir ?? defaultFindDaemonPackageDir;
3101
+ const fileExists = deps.fileExists ?? existsSync5;
3102
+ const buildBackend = deps.buildGoBackend ?? defaultBuildGoBackend;
3103
+ const baseEnv = deps.env ?? process.env;
3104
+ const { manifest } = loadManifest(pluginDir);
3105
+ if ((deps.platform ?? process.platform) === "win32" && manifest.backend !== void 0) {
3106
+ throw new CliError(
3107
+ "mndw dev: plugins with a backend need WSL on Windows. Open a WSL terminal and run mndw dev there."
3108
+ );
3109
+ }
3110
+ const pluginName = manifest.name;
3111
+ const pluginSourceDir = resolvePluginDir(pluginDir);
3112
+ const framework = detectFramework(pluginSourceDir);
3113
+ const requestedDevice = options.addr ?? options.hostDevice;
3114
+ const hostDevice = requestedDevice === void 0 ? baseEnv.MNDW_HOST_DEVICE : normalizeDeviceAddress(requestedDevice);
3115
+ const daemonPackageDir = findDaemonPackageDir();
3116
+ let launchHost = deps.launchHost;
3117
+ if (options.prebuiltHost === true || daemonPackageDir === null) {
3118
+ const hostBundleDir = join10((deps.cliPackageRoot ?? cliPackageRoot)(), "host-dev");
3119
+ if (!fileExists(join10(hostBundleDir, "index.html"))) {
3120
+ throw new CliError(
3121
+ `mndw dev: prebuilt host not found at ${hostBundleDir}; run pnpm --filter @mndw/cli build:host-dev`
3122
+ );
3123
+ }
3124
+ launchHost ??= prebuiltHostLauncher(pluginSourceDir, hostBundleDir, options.uiPort ?? 5173, framework);
3125
+ }
3126
+ const port = options.port ?? 9090;
3127
+ const listen = `127.0.0.1:${port}`;
3128
+ const daemonUrl = `http://127.0.0.1:${port}`;
3129
+ const tempDirs = [];
3130
+ const track = (dir) => {
3131
+ tempDirs.push(dir);
3132
+ return dir;
3133
+ };
3134
+ const cleanupDirs = () => {
3135
+ for (const dir of [...tempDirs].reverse()) {
3136
+ try {
3137
+ removeDir(dir);
3138
+ } catch {
3139
+ }
3140
+ }
3141
+ };
3142
+ try {
3143
+ const builtinDir = track(makeTempDir("mndw-dev-builtin-"));
3144
+ const dataDir = track(makeTempDir("d-"));
3145
+ const userDir = track(makeTempDir("mndw-dev-user-"));
3146
+ try {
3147
+ symlinkDir(pluginSourceDir, join10(builtinDir, pluginName));
3148
+ } catch (err) {
3149
+ throw new CliError(
3150
+ `mndw dev could not symlink the plugin into a temporary builtin root: ${err.message}. Symlinks are required (source is never copied).`
3151
+ );
3152
+ }
3153
+ const buildResult = buildBackend(pluginSourceDir);
3154
+ if (!buildResult.success) {
3155
+ throw new CliError(`mndw dev: Go backend build failed: ${buildResult.error ?? "unknown error"}`);
3156
+ }
3157
+ if (!buildResult.skipped) {
3158
+ console.log("[mndw dev] Built Go backend");
3159
+ }
3160
+ const launch = resolveDaemonLaunch([], options, {
3161
+ daemonPackageDir,
3162
+ binaryExists: fileExists,
3163
+ resolvePackagedDaemon: deps.resolvePackagedDaemon
3164
+ });
3165
+ const isReady = (payload) => {
3166
+ if (typeof payload !== "object" || payload === null || !("plugins" in payload)) {
3167
+ return false;
3168
+ }
3169
+ return Array.isArray(payload.plugins) && payload.plugins.some((plugin) => {
3170
+ return typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === pluginName;
3171
+ });
3172
+ };
3173
+ await runDevSession({
3174
+ repoRoot,
3175
+ daemon: launch,
3176
+ listen,
3177
+ daemonUrl,
3178
+ builtinDir,
3179
+ dataDir,
3180
+ userDir,
3181
+ env: baseEnv,
3182
+ hostDevice,
3183
+ sandboxPlugin: pluginSourceDir,
3184
+ launchHost,
3185
+ isReady,
3186
+ createWatcher: ({ daemonUrl: watcherDaemonUrl, touchSentinel }) => {
3187
+ return watchPluginBackend({
3188
+ manifest,
3189
+ pluginSourceDir,
3190
+ pluginName,
3191
+ daemonUrl: watcherDaemonUrl
3192
+ }, {
3193
+ buildBackend,
3194
+ touchSentinel,
3195
+ fetch: deps.session?.fetch,
3196
+ restartService: deps.restartService,
3197
+ watchBackend: deps.watchBackend
3198
+ });
3199
+ }
3200
+ }, deps.session);
3201
+ } finally {
3202
+ cleanupDirs();
3203
+ }
3204
+ }
3205
+
3206
+ // src/i18n-validator.ts
3207
+ import { readFileSync as readFileSync9 } from "node:fs";
3208
+ import { isAbsolute as isAbsolute4, relative as relative5, resolve as resolve15, sep as sep3 } from "node:path";
3209
+ import { parse } from "@formatjs/icu-messageformat-parser";
3210
+ function isRecord3(value) {
3211
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3212
+ }
3213
+ function invalidCatalog(manifest, locale, declaredPath, reason) {
3214
+ throw new CliError(`Invalid catalog for ${manifest.name} locale ${locale} at ${declaredPath}: ${reason}`);
3215
+ }
3216
+ function resolveCatalogPath(pluginDir, manifest, locale, declaredPath) {
3217
+ const resolvedPluginDir = resolve15(pluginDir);
3218
+ const catalogPath = resolve15(resolvedPluginDir, declaredPath);
3219
+ const relativePath = relative5(resolvedPluginDir, catalogPath);
3220
+ if (isAbsolute4(relativePath) || relativePath === ".." || relativePath.startsWith(`..${sep3}`)) {
3221
+ invalidCatalog(manifest, locale, declaredPath, "path escapes the plugin directory");
3222
+ }
3223
+ return catalogPath;
3224
+ }
3225
+ function readCatalog(pluginDir, manifest, locale, declaredPath) {
3226
+ const catalogPath = resolveCatalogPath(pluginDir, manifest, locale, declaredPath);
3227
+ let source;
3228
+ try {
3229
+ source = readFileSync9(catalogPath, "utf8");
3230
+ } catch (error) {
3231
+ const detail = error instanceof Error ? error.message : String(error);
3232
+ invalidCatalog(manifest, locale, declaredPath, `file cannot be read: ${detail}`);
3233
+ }
3234
+ let value;
3235
+ try {
3236
+ value = JSON.parse(source);
3237
+ } catch (error) {
3238
+ const detail = error instanceof Error ? error.message : String(error);
3239
+ invalidCatalog(manifest, locale, declaredPath, `invalid JSON: ${detail}`);
3240
+ }
3241
+ if (!isRecord3(value)) {
3242
+ invalidCatalog(manifest, locale, declaredPath, "catalog must be a non-null JSON object");
3243
+ }
3244
+ const catalog = {};
3245
+ flattenCatalog(value, manifest, locale, declaredPath, "", catalog);
3246
+ return catalog;
3247
+ }
3248
+ function flattenCatalog(value, manifest, locale, declaredPath, prefix, catalog) {
3249
+ for (const [key, message] of Object.entries(value)) {
3250
+ const fullKey = prefix === "" ? key : `${prefix}.${key}`;
3251
+ if (typeof message === "string") {
3252
+ try {
3253
+ parse(message);
3254
+ } catch (error) {
3255
+ const detail = error instanceof Error ? error.message : String(error);
3256
+ invalidCatalog(manifest, locale, declaredPath, `invalid ICU message for key ${fullKey}: ${detail}`);
3257
+ }
3258
+ if (catalog[fullKey] !== void 0) {
3259
+ invalidCatalog(manifest, locale, declaredPath, `duplicate key ${fullKey}`);
3260
+ }
3261
+ catalog[fullKey] = message;
3262
+ continue;
3263
+ }
3264
+ if (isRecord3(message)) {
3265
+ flattenCatalog(message, manifest, locale, declaredPath, fullKey, catalog);
3266
+ continue;
3267
+ }
3268
+ invalidCatalog(manifest, locale, declaredPath, `value for key ${fullKey} must be a string or object`);
3269
+ }
3270
+ }
3271
+ function parityWarnings(manifest, defaultLocale, defaultCatalog, locale, catalog) {
3272
+ const warnings = [];
3273
+ const defaultKeys = Object.keys(defaultCatalog).sort();
3274
+ const localeKeys = Object.keys(catalog).sort();
3275
+ for (const key of defaultKeys) {
3276
+ if (!(key in catalog)) {
3277
+ warnings.push(`${manifest.name} locale ${locale} is missing key ${key} from ${defaultLocale}`);
3278
+ }
3279
+ }
3280
+ for (const key of localeKeys) {
3281
+ if (!(key in defaultCatalog)) {
3282
+ warnings.push(`${manifest.name} locale ${locale} has extra key ${key} not present in ${defaultLocale}`);
3283
+ }
3284
+ }
3285
+ return warnings;
3286
+ }
3287
+ function validatePluginCatalogs(pluginDir, manifest, options) {
3288
+ if (manifest.i18n === void 0) {
3289
+ return [];
3290
+ }
3291
+ const i18n = manifest.i18n;
3292
+ const entries = Object.entries(manifest.i18n.locales).sort(([left], [right]) => left.localeCompare(right));
3293
+ const catalogs = /* @__PURE__ */ new Map();
3294
+ for (const [locale, declaredPath] of entries) {
3295
+ catalogs.set(locale, readCatalog(pluginDir, manifest, locale, declaredPath));
3296
+ }
3297
+ const defaultCatalog = catalogs.get(i18n.defaultLocale);
3298
+ if (defaultCatalog === void 0) {
3299
+ throw new CliError(
3300
+ `Invalid catalog for ${manifest.name}: default locale ${i18n.defaultLocale} was not loaded`
3301
+ );
3302
+ }
3303
+ const warnings = entries.filter(([locale]) => locale !== i18n.defaultLocale).flatMap(([locale]) => {
3304
+ const catalog = catalogs.get(locale);
3305
+ return catalog === void 0 ? [] : parityWarnings(manifest, i18n.defaultLocale, defaultCatalog, locale, catalog);
3306
+ });
3307
+ if (options.strict && warnings.length > 0) {
3308
+ throw new CliError(warnings.join("\n"));
3309
+ }
3310
+ return warnings;
3311
+ }
3312
+
3313
+ // src/pack.ts
3314
+ import { createHash } from "node:crypto";
3315
+ import {
3316
+ chmodSync as chmodSync2,
3317
+ existsSync as existsSync8,
3318
+ mkdirSync as mkdirSync5,
3319
+ mkdtempSync as mkdtempSync4,
3320
+ readFileSync as readFileSync10,
3321
+ readdirSync as readdirSync5,
3322
+ realpathSync,
3323
+ rmSync as rmSync6,
3324
+ statSync as statSync5,
3325
+ writeFileSync as writeFileSync5
3326
+ } from "node:fs";
3327
+ import { basename as basename2, dirname as dirname8, extname as extname3, isAbsolute as isAbsolute5, join as join12, relative as relative6, resolve as resolve17, sep as sep4 } from "node:path";
3328
+ import crossSpawn4 from "cross-spawn";
3329
+ import { build } from "esbuild";
3330
+ import esbuildSvelte from "esbuild-svelte";
3331
+ import vuePlugin from "unplugin-vue/esbuild";
3332
+ var import_svelte_compiler_options = __toESM(require_svelte_compiler_options(), 1);
3333
+
3334
+ // src/angular-compiler.ts
3335
+ function compileAngular2(pluginDir, sourceEntry = "src/index.ts") {
3336
+ try {
3337
+ return compileAngular(pluginDir, sourceEntry);
3338
+ } catch (error) {
3339
+ if (error instanceof AngularCompilerError) {
3340
+ throw new CliError(error.message);
3341
+ }
3342
+ throw error;
3343
+ }
3344
+ }
3345
+
3346
+ // src/cli-node-paths.ts
3347
+ import { existsSync as existsSync6, statSync as statSync4 } from "node:fs";
3348
+ import { dirname as dirname7, join as join11, resolve as resolve16 } from "node:path";
3349
+ function cliNodePaths(root = cliPackageRoot()) {
3350
+ const paths = [];
3351
+ let directory = resolve16(root);
3352
+ for (; ; ) {
3353
+ const modules = join11(directory, "node_modules");
3354
+ if (existsSync6(modules) && statSync4(modules).isDirectory()) {
3355
+ paths.push(modules);
3356
+ }
3357
+ const parent = dirname7(directory);
3358
+ if (parent === directory) {
3359
+ return paths;
3360
+ }
3361
+ directory = parent;
3362
+ }
3363
+ }
3364
+ function packNodePaths(pluginDir, cliRoot = cliPackageRoot()) {
3365
+ return [.../* @__PURE__ */ new Set([...cliNodePaths(pluginDir), ...cliNodePaths(cliRoot)])];
3366
+ }
3367
+
3368
+ // src/promote-directory.ts
3369
+ import { existsSync as existsSync7, renameSync, rmSync as rmSync5 } from "node:fs";
3370
+ function promoteDirectory(source, destination) {
3371
+ const backup = `${destination}.previous`;
3372
+ const hadExisting = existsSync7(destination);
3373
+ const hadBackup = existsSync7(backup);
3374
+ if (hadExisting && hadBackup) {
3375
+ rmSync5(backup, { recursive: true, force: true });
3376
+ }
3377
+ if (hadExisting) {
3378
+ renameSync(destination, backup);
3379
+ }
3380
+ try {
3381
+ renameSync(source, destination);
3382
+ } catch (error) {
3383
+ if (hadExisting || hadBackup) {
3384
+ renameSync(backup, destination);
3385
+ }
3386
+ throw error;
3387
+ }
3388
+ if (hadExisting || hadBackup) {
3389
+ rmSync5(backup, { recursive: true, force: true });
3390
+ }
3391
+ }
3392
+
3393
+ // src/pack.ts
3394
+ async function packPlugin(pluginDir, options = {}) {
3395
+ const resolvedDir = resolvePluginDir(pluginDir);
3396
+ const { manifest } = readManifest(pluginDir);
3397
+ const warnings = validatePluginCatalogs(resolvedDir, manifest, { strict: false });
3398
+ const sourceEntry = options.development ? resolveDevelopmentSourceEntry(resolvedDir) : resolveProductionSourceEntry(resolvedDir);
3399
+ const framework = detectFramework(resolvedDir);
3400
+ const outDir = options.outDir === void 0 ? join12(resolvedDir, "dist") : resolve17(process.cwd(), options.outDir);
3401
+ const defaultOutDir = join12(resolvedDir, "dist");
3402
+ if (outDir !== defaultOutDir && pathsOverlap(resolvedDir, outDir)) {
3403
+ throw new CliError(`Output directory overlaps plugin source: ${outDir}`);
3404
+ }
3405
+ let angularCompile;
3406
+ const entryPoint = framework === "angular" ? (angularCompile = compileAngular2(resolvedDir, sourceEntry)).entryPath : join12(resolvedDir, sourceEntry);
3407
+ try {
3408
+ const styleEntry = angularCompile === void 0 ? void 0 : join12(angularCompile.cacheDir, "styles.css");
3409
+ const entryPoints = styleEntry !== void 0 && existsSync8(styleEntry) ? [entryPoint, styleEntry] : [entryPoint];
3410
+ const result = await build({
3411
+ entryPoints,
3412
+ outdir: outDir,
3413
+ bundle: true,
3414
+ format: "esm",
3415
+ platform: "browser",
3416
+ target: "es2022",
3417
+ write: false,
3418
+ metafile: true,
3419
+ logLevel: "silent",
3420
+ nodePaths: packNodePaths(resolvedDir),
3421
+ external: pluginDependencies(framework),
3422
+ plugins: framework === "svelte" ? [
3423
+ esbuildSvelte({
3424
+ compilerOptions: {
3425
+ css: "external",
3426
+ warningFilter: (warning) => !(0, import_svelte_compiler_options.isMndwButtonA11yWarning)(warning)
3427
+ }
3428
+ })
3429
+ ] : framework === "vue" ? [vuePlugin({ sourceMap: false })] : []
3430
+ });
3431
+ const jsOutputs = result.outputFiles.filter((file) => file.path.endsWith(".js"));
3432
+ const jsOutput = jsOutputs.find((file) => file.path === join12(outDir, "index.js")) ?? jsOutputs[0];
3433
+ if (jsOutput === void 0) {
3434
+ throw new CliError("esbuild produced no JavaScript bundle");
3435
+ }
3436
+ const cssOutput = result.outputFiles.find((file) => file.path.endsWith(".css"));
3437
+ const bundledShared = findBundledSharedDependencies(result.metafile, pluginDependencies(framework));
3438
+ if (bundledShared.length > 0) {
3439
+ throw new CliError(
3440
+ `Packed bundle must not include host-shared dependencies: ${bundledShared.join(", ")}`
3441
+ );
3442
+ }
3443
+ const lock = serializeLock(buildLock(manifest, framework, resolvedDir));
3444
+ const pkg = readPluginPackage(resolvedDir);
3445
+ const buildScript = pkg?.mndw?.backendBuildScript;
3446
+ if (typeof buildScript === "string" && options.backendOverride === void 0 && options.skipBackendBuild !== true) {
3447
+ const runner = options.runBackendBuild ?? ((script, runnerOptions) => crossSpawn4.sync("pnpm", ["run", script], {
3448
+ cwd: runnerOptions.cwd,
3449
+ stdio: "inherit"
3450
+ }));
3451
+ const buildResult = runner(buildScript, { cwd: resolvedDir });
3452
+ if (buildResult.error || buildResult.status !== 0) {
3453
+ throw new CliError(`Host backend build failed for ${manifest.name} (script "${buildScript}")`);
3454
+ }
3455
+ }
3456
+ const auxiliaryBackendAssets = pkg?.mndw?.backendAssets ?? [];
3457
+ const overrideAssets = options.backendOverride === void 0 ? void 0 : collectBackendOverrideAssets(manifest, resolvedDir, options.backendOverride, auxiliaryBackendAssets);
3458
+ const backendAssets = options.backendOverride === void 0 ? collectBackendAssets(manifest, resolvedDir, auxiliaryBackendAssets) : overrideAssets?.assets ?? [];
3459
+ const backendMetadata = options.backendOverride === void 0 ? void 0 : {
3460
+ target: options.backendOverride.target,
3461
+ files: (overrideAssets?.overrideAssets ?? []).map((asset) => ({
3462
+ path: asset.rel,
3463
+ sha256: createHash("sha256").update(asset.contents).digest("hex")
3464
+ }))
3465
+ };
3466
+ const artifact = {
3467
+ schemaVersion: 1,
3468
+ plugin: manifest.name,
3469
+ entry: manifest.entry,
3470
+ staticBackends: backendAssetRelPaths(manifest),
3471
+ ...backendMetadata === void 0 ? {} : { backend: backendMetadata }
3472
+ };
3473
+ const catalogAssets = collectCatalogAssets(manifest, resolvedDir);
3474
+ const workerReferences = collectWorkerReferences(manifest.entry, result.metafile);
3475
+ const workerAssets = await buildWorkerAssets(workerReferences, outDir, resolvedDir, framework);
3476
+ const mainBundle = rewriteWorkerSpecifiers(jsOutput.contents, workerReferences);
3477
+ const parent = dirname8(outDir);
3478
+ mkdirSync5(parent, { recursive: true });
3479
+ const staging = mkdtempSync4(join12(parent, ".mndw-pack-"));
3480
+ try {
3481
+ writeStaged(staging, manifest.entry, mainBundle);
3482
+ if (cssOutput !== void 0) {
3483
+ writeStaged(staging, "index.css", Buffer.from(cssOutput.contents));
3484
+ }
3485
+ writeStaged(staging, "manifest.json", Buffer.from(`${JSON.stringify(manifest, null, 2)}
3486
+ `));
3487
+ writeStaged(staging, "mndw.lock.json", Buffer.from(lock));
3488
+ writeStaged(
3489
+ staging,
3490
+ "mndw-artifact.json",
3491
+ Buffer.from(`${JSON.stringify(artifact, null, 2)}
3492
+ `)
3493
+ );
3494
+ for (const output of jsOutputs) {
3495
+ if (output !== jsOutput) {
3496
+ const rel = relative6(outDir, output.path);
3497
+ if (isAbsolute5(rel) || rel === ".." || rel.startsWith(`..${sep4}`)) {
3498
+ throw new CliError(`esbuild output escapes plugin directory: ${output.path}`);
3499
+ }
3500
+ writeStaged(staging, rel, Buffer.from(output.contents));
3501
+ }
3502
+ }
3503
+ for (const asset of workerAssets) {
3504
+ writeStaged(staging, asset.rel, asset.contents);
3505
+ }
3506
+ for (const asset of backendAssets) {
3507
+ writeStaged(staging, asset.rel, asset.contents, asset.mode);
3508
+ }
3509
+ for (const asset of catalogAssets) {
3510
+ writeStaged(staging, asset.rel, asset.contents);
3511
+ }
3512
+ promoteDirectory(staging, outDir);
3513
+ } catch (error) {
3514
+ rmSync6(staging, { recursive: true, force: true });
3515
+ throw error;
3516
+ }
3517
+ return {
3518
+ outDir,
3519
+ framework,
3520
+ manifest,
3521
+ manifestPath: join12(outDir, "manifest.json"),
3522
+ entryPath: join12(outDir, manifest.entry),
3523
+ warnings
3524
+ };
3525
+ } finally {
3526
+ angularCompile?.cleanup();
3527
+ }
3528
+ }
3529
+ function backendAssetRelPaths(manifest) {
3530
+ const backend = manifest.backend;
3531
+ if (backend === void 0) {
3532
+ return [];
3533
+ }
3534
+ const paths = [];
3535
+ if (backend.kind === "exec") {
3536
+ for (const route of backend.routes) {
3537
+ paths.push(route.command);
3538
+ }
3539
+ } else {
3540
+ paths.push(backend.command);
3541
+ }
3542
+ return [...new Set(paths)];
3543
+ }
3544
+ function allBackendAssetRelPaths(manifest, auxiliaryAssets) {
3545
+ return [.../* @__PURE__ */ new Set([...backendAssetRelPaths(manifest), ...auxiliaryAssets])];
3546
+ }
3547
+ var WORKER_URL_PATTERN = /new\s+Worker\s*\(\s*new\s+URL\s*\(\s*(['"])([^'"]+)\1\s*,\s*import\.meta\.url\s*\)/g;
3548
+ function collectWorkerReferences(manifestEntry, metafile) {
3549
+ const references = [];
3550
+ const outputOwners = /* @__PURE__ */ new Map();
3551
+ for (const input of Object.keys(metafile.inputs)) {
3552
+ const inputPath = resolve17(process.cwd(), input);
3553
+ if (!existsSync8(inputPath)) {
3554
+ continue;
3555
+ }
3556
+ const realInputPath = realpathSync(inputPath);
3557
+ const source = readFileSync10(realInputPath, "utf8");
3558
+ for (const match of source.matchAll(WORKER_URL_PATTERN)) {
3559
+ const sourceSpecifier = match[2];
3560
+ if (!sourceSpecifier?.endsWith(".worker.ts")) {
3561
+ continue;
3562
+ }
3563
+ const sourcePath = resolve17(dirname8(realInputPath), sourceSpecifier);
3564
+ if (!existsSync8(sourcePath)) {
3565
+ throw new CliError(`Missing worker source: ${sourcePath}`);
3566
+ }
3567
+ const outputRel = join12(dirname8(manifestEntry), `${basename2(sourcePath, extname3(sourcePath))}.js`);
3568
+ const previousOwner = outputOwners.get(outputRel);
3569
+ if (previousOwner !== void 0 && previousOwner !== sourcePath) {
3570
+ throw new CliError(`Worker output path collision: ${outputRel}`);
3571
+ }
3572
+ outputOwners.set(outputRel, sourcePath);
3573
+ const runtimePath = relative6(dirname8(manifestEntry), outputRel).split(sep4).join("/");
3574
+ if (references.some((reference) => reference.sourcePath === sourcePath)) {
3575
+ continue;
3576
+ }
3577
+ references.push({
3578
+ outputRel,
3579
+ runtimeSpecifier: runtimePath.startsWith(".") ? runtimePath : `./${runtimePath}`,
3580
+ sourcePath,
3581
+ sourceSpecifier
3582
+ });
3583
+ }
3584
+ }
3585
+ return references;
3586
+ }
3587
+ async function buildWorkerAssets(references, outDir, pluginDir, framework) {
3588
+ const assets = [];
3589
+ const built = /* @__PURE__ */ new Set();
3590
+ for (const reference of references) {
3591
+ if (built.has(reference.outputRel)) {
3592
+ continue;
3593
+ }
3594
+ const result = await build({
3595
+ entryPoints: [reference.sourcePath],
3596
+ outdir: outDir,
3597
+ bundle: true,
3598
+ format: "esm",
3599
+ platform: "browser",
3600
+ target: "es2022",
3601
+ write: false,
3602
+ logLevel: "silent",
3603
+ nodePaths: packNodePaths(pluginDir),
3604
+ external: pluginDependencies(framework)
3605
+ });
3606
+ const output = result.outputFiles.find((file) => file.path.endsWith(".js"));
3607
+ if (output === void 0) {
3608
+ throw new CliError(`esbuild produced no JavaScript bundle for worker: ${reference.sourcePath}`);
3609
+ }
3610
+ assets.push({ rel: reference.outputRel, contents: Buffer.from(output.contents) });
3611
+ built.add(reference.outputRel);
3612
+ }
3613
+ return assets;
3614
+ }
3615
+ function rewriteWorkerSpecifiers(contents, references) {
3616
+ let source = Buffer.from(contents).toString("utf8");
3617
+ for (const reference of references) {
3618
+ source = source.replaceAll(reference.sourceSpecifier, reference.runtimeSpecifier);
3619
+ }
3620
+ return Buffer.from(source);
3621
+ }
3622
+ function collectBackendAssets(manifest, pluginDir, auxiliaryAssets) {
3623
+ return allBackendAssetRelPaths(manifest, auxiliaryAssets).map(
3624
+ (rel) => collectSourceBackendAsset(rel, pluginDir, auxiliaryAssets.includes(rel) ? "package metadata" : "manifest")
3625
+ );
3626
+ }
3627
+ function collectBackendOverrideAssets(manifest, pluginDir, override, auxiliaryAssets) {
3628
+ const manifestAssets = backendAssetRelPaths(manifest);
3629
+ const auxiliaryAssetSet = new Set(auxiliaryAssets);
3630
+ const declared = new Set(allBackendAssetRelPaths(manifest, auxiliaryAssets));
3631
+ const destinations = /* @__PURE__ */ new Set();
3632
+ const sourceRoot = resolve17(override.sourceRoot);
3633
+ if (declared.size === 0) {
3634
+ throw new CliError(`Backend override supplied for plugin without a declared backend: ${manifest.name}`);
3635
+ }
3636
+ const overrideAssets = override.files.map((file) => {
3637
+ if (destinations.has(file.destination)) {
3638
+ throw new CliError(`Duplicate target backend destination: ${file.destination}`);
3639
+ }
3640
+ if (!declared.has(file.destination)) {
3641
+ throw new CliError(`Target backend destination is not declared as a backend asset: ${file.destination}`);
3642
+ }
3643
+ const source = resolve17(file.source);
3644
+ const sourceRelative = relative6(sourceRoot, source);
3645
+ if (sourceRelative.startsWith("..") || isAbsolute5(sourceRelative) || !existsSync8(source) || !statSync5(source).isFile()) {
3646
+ throw new CliError(`Target backend source is outside its build output: ${source}`);
3647
+ }
3648
+ destinations.add(file.destination);
3649
+ return {
3650
+ rel: file.destination,
3651
+ contents: readFileSync10(source),
3652
+ mode: file.mode ?? 493
3653
+ };
3654
+ });
3655
+ const assets = [];
3656
+ for (const destination of manifestAssets) {
3657
+ const overrideAsset = overrideAssets.find((asset) => asset.rel === destination);
3658
+ assets.push(overrideAsset ?? collectSourceBackendAsset(destination, pluginDir, "manifest"));
3659
+ }
3660
+ for (const destination of auxiliaryAssetSet) {
3661
+ const overrideAsset = overrideAssets.find((asset) => asset.rel === destination);
3662
+ if (overrideAsset === void 0) {
3663
+ throw new CliError(`Target backend override is missing auxiliary destination: ${destination}`);
3664
+ }
3665
+ assets.push(overrideAsset);
3666
+ }
3667
+ return { assets, overrideAssets };
3668
+ }
3669
+ function collectSourceBackendAsset(rel, pluginDir, declaredBy) {
3670
+ const source = safeJoin(pluginDir, rel);
3671
+ try {
3672
+ const stat = statSync5(source);
3673
+ if (!stat.isFile()) {
3674
+ throw new CliError(`Backend asset is not a regular file: ${source}`);
3675
+ }
3676
+ return { rel, contents: readFileSync10(source), mode: 493 };
3677
+ } catch (error) {
3678
+ if (error instanceof CliError) {
3679
+ throw error;
3680
+ }
3681
+ throw new CliError(`Missing backend asset "${rel}" declared by ${declaredBy}: ${source}`);
3682
+ }
3683
+ }
3684
+ function collectCatalogAssets(manifest, pluginDir) {
3685
+ if (manifest.i18n === void 0) {
3686
+ return [];
3687
+ }
3688
+ return Object.values(manifest.i18n.locales).map((rel) => {
3689
+ const source = safeJoin(pluginDir, rel);
3690
+ try {
3691
+ const stat = statSync5(source);
3692
+ if (!stat.isFile()) {
3693
+ throw new CliError(`Catalog is not a regular file: ${source}`);
3694
+ }
3695
+ return { rel, contents: readFileSync10(source) };
3696
+ } catch (error) {
3697
+ if (error instanceof CliError) {
3698
+ throw error;
3699
+ }
3700
+ throw new CliError(`Missing catalog declared in manifest: ${source}`);
3701
+ }
3702
+ });
3703
+ }
3704
+ function writeStaged(root, rel, contents, mode) {
3705
+ const dest = safeJoin(root, rel);
3706
+ mkdirSync5(dirname8(dest), { recursive: true });
3707
+ writeFileSync5(dest, contents);
3708
+ if (mode !== void 0) {
3709
+ chmodSync2(dest, mode);
3710
+ }
3711
+ }
3712
+ function safeJoin(root, rel) {
3713
+ const resolvedRoot = resolve17(root);
3714
+ const dest = resolve17(resolvedRoot, rel);
3715
+ if (dest !== resolvedRoot && !dest.startsWith(resolvedRoot + sep4)) {
3716
+ throw new CliError(`Unsafe relative path escapes plugin directory: ${rel}`);
3717
+ }
3718
+ return dest;
3719
+ }
3720
+ function pathsOverlap(first, second) {
3721
+ return first === second || first.startsWith(second + sep4) || second.startsWith(first + sep4);
3722
+ }
3723
+
3724
+ // src/backend-build-run.ts
3725
+ import { readFileSync as readFileSync11 } from "node:fs";
3726
+ import { isAbsolute as isAbsolute6, join as join13, resolve as resolve18 } from "node:path";
3727
+ function nonEmptyString2(value) {
3728
+ return typeof value === "string" && value.length > 0;
3729
+ }
3730
+ function readJson(path3, label) {
3731
+ try {
3732
+ return JSON.parse(readFileSync11(path3, "utf8"));
3733
+ } catch (error) {
3734
+ throw new CliError(`failed to read ${label} at ${path3}: ${error.message}`);
3735
+ }
3736
+ }
3737
+ function parseBackendBuildArgs(rawArgs) {
3738
+ const args = rawArgs[0] === "--" ? rawArgs.slice(1) : rawArgs;
3739
+ let target;
3740
+ let outDir;
3741
+ let index = 0;
3742
+ while (index < args.length) {
3743
+ const flag = args[index];
3744
+ const value = args[index + 1];
3745
+ if (value === void 0) {
3746
+ throw new CliError(`build-backend: missing value for ${flag}`);
3747
+ }
3748
+ if (value.length === 0) {
3749
+ throw new CliError(`build-backend: ${flag} must be a non-empty value`);
3750
+ }
3751
+ if (flag === "--target") {
3752
+ if (target !== void 0) {
3753
+ throw new CliError("build-backend: duplicate --target");
3754
+ }
3755
+ target = value;
3756
+ } else if (flag === "--out-dir") {
3757
+ if (outDir !== void 0) {
3758
+ throw new CliError("build-backend: duplicate --out-dir");
3759
+ }
3760
+ outDir = value;
3761
+ } else {
3762
+ throw new CliError(`build-backend: unexpected argument ${flag}`);
3763
+ }
3764
+ index += 2;
3765
+ }
3766
+ if (target === void 0 !== (outDir === void 0)) {
3767
+ throw new CliError("build-backend: --target and --out-dir must be provided together");
3768
+ }
3769
+ return { target, outDir };
3770
+ }
3771
+ function isRecord4(value) {
3772
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3773
+ }
3774
+ function isSafeBinaryName(value) {
3775
+ return nonEmptyString2(value) && !isAbsolute6(value) && !value.includes("/") && !value.includes("\\") && value !== "." && value !== "..";
3776
+ }
3777
+ function isSafeEntryPackage(value) {
3778
+ return nonEmptyString2(value) && !isAbsolute6(value) && !value.startsWith("\\") && !value.includes("\\") && !value.split("/").includes("..");
3779
+ }
3780
+ function readBackendBuildConfig(pluginDir) {
3781
+ const dir = resolve18(pluginDir);
3782
+ const manifestValue = readJson(join13(dir, "manifest.json"), "manifest.json");
3783
+ const packageValue = readJson(join13(dir, "package.json"), "package.json");
3784
+ if (!isRecord4(manifestValue)) {
3785
+ throw new CliError(`manifest.json in ${dir} must contain a JSON object`);
3786
+ }
3787
+ if (!isRecord4(packageValue)) {
3788
+ throw new CliError(`package.json in ${dir} must contain a JSON object`);
3789
+ }
3790
+ const plugin = manifestValue.name;
3791
+ const mndw = isRecord4(packageValue.mndw) ? packageValue.mndw : void 0;
3792
+ const backend = mndw !== void 0 && isRecord4(mndw.backend) ? mndw.backend : void 0;
3793
+ const binaryName = backend?.binaryName;
3794
+ const entryPackage = backend?.entryPackage;
3795
+ if (!nonEmptyString2(plugin)) {
3796
+ throw new CliError(`manifest.json in ${dir} must set a non-empty "name"`);
3797
+ }
3798
+ if (!isSafeBinaryName(binaryName)) {
3799
+ throw new CliError(`mndw.backend in ${dir}/package.json must set a safe binaryName`);
3800
+ }
3801
+ if (!isSafeEntryPackage(entryPackage)) {
3802
+ throw new CliError(`mndw.backend in ${dir}/package.json must set a safe relative entryPackage`);
3803
+ }
3804
+ return { plugin, binaryName, entryPackage };
3805
+ }
3806
+ function runBuildBackendCommand(options) {
3807
+ const { target, outDir } = parseBackendBuildArgs(options.args);
3808
+ let productTarget;
3809
+ if (target !== void 0) {
3810
+ if (!isProductTarget(target)) {
3811
+ throw new CliError(`unknown product target: ${target}`);
3812
+ }
3813
+ productTarget = target;
3814
+ }
3815
+ const config = readBackendBuildConfig(options.pluginDir);
3816
+ buildGoBackend({
3817
+ plugin: config.plugin,
3818
+ backendDir: join13(resolve18(options.pluginDir), "backend"),
3819
+ binaryName: config.binaryName,
3820
+ entryPackage: config.entryPackage,
3821
+ target: productTarget,
3822
+ outDir,
3823
+ spawn: options.spawn
3824
+ });
3825
+ }
3826
+
3827
+ // src/zip.ts
3828
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
3829
+ import { dirname as dirname9, join as join14, resolve as resolve19 } from "node:path";
3830
+ import { zipSync } from "fflate";
3831
+ function backendCommandPaths(manifest) {
3832
+ const backend = manifest.backend;
3833
+ if (backend === void 0) {
3834
+ return /* @__PURE__ */ new Set();
3835
+ }
3836
+ if (backend.kind === "exec") {
3837
+ return new Set(backend.routes.map((route) => route.command));
3838
+ }
3839
+ return /* @__PURE__ */ new Set([backend.command]);
3840
+ }
3841
+ function collectFiles(dir) {
3842
+ const files = {};
3843
+ const walk2 = (current, prefix) => {
3844
+ for (const entry of readdirSync6(current, { withFileTypes: true })) {
3845
+ if (entry.name.startsWith(".")) {
3846
+ continue;
3847
+ }
3848
+ const absolute = join14(current, entry.name);
3849
+ const relative7 = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
3850
+ if (entry.isDirectory()) {
3851
+ walk2(absolute, relative7);
3852
+ } else if (entry.isFile()) {
3853
+ files[relative7] = readFileSync12(absolute);
3854
+ }
3855
+ }
3856
+ };
3857
+ walk2(dir, "");
3858
+ return files;
3859
+ }
3860
+ function zipDirectory(dir, executables = /* @__PURE__ */ new Set()) {
3861
+ const files = {};
3862
+ for (const [path3, contents] of Object.entries(collectFiles(dir))) {
3863
+ const perm = executables.has(path3) ? 493 : 420;
3864
+ files[path3] = [contents, { os: 3, attrs: (32768 + perm) * 65536 }];
3865
+ }
3866
+ return zipSync(files, { level: 9 });
3867
+ }
3868
+ async function zipPlugin(pluginDir, options = {}) {
3869
+ const { output, ...packOptions } = options;
3870
+ const pack = await packPlugin(pluginDir, packOptions);
3871
+ const archive = zipDirectory(pack.outDir, backendCommandPaths(pack.manifest));
3872
+ const outputPath = output === void 0 ? join14(resolvePluginDir(pluginDir), `${pack.manifest.name}.zip`) : resolve19(process.cwd(), output);
3873
+ mkdirSync6(dirname9(outputPath), { recursive: true });
3874
+ writeFileSync6(outputPath, archive);
3875
+ return { outputPath, pack };
3876
+ }
3877
+
3878
+ // src/index.ts
3879
+ function rethrowManifestError(pluginDir, error) {
3880
+ if (error instanceof ManifestValidationError) {
3881
+ throw new CliError(
3882
+ `Invalid manifest at ${resolve20(resolvePluginDir(pluginDir), "manifest.json")}: ${error.message}`
3883
+ );
3884
+ }
3885
+ throw error;
3886
+ }
3887
+ function createProgram() {
3888
+ const program = new Command();
3889
+ program.name("mndw");
3890
+ program.command("create <name>").option("--type <type>", "plugin type: widget|page", "widget").option("--framework <framework>", "UI framework: vanilla|svelte|vue|angular").option("--out <dir>", "output directory (default: ./<name>)").option("--route <route>", "page route (page type only; default /<name>)").option("--label <label>", "human-readable label (default derived from name)").option("--backend <runtime>", 'include a backend starter ("sh" or "go")').option("--no-install", "skip dependency installation").action(async (name, options) => {
3891
+ const outDir = resolve20(process.cwd(), options.out ?? name);
3892
+ const result = await create({
3893
+ name,
3894
+ outDir,
3895
+ type: options.type,
3896
+ framework: options.framework,
3897
+ route: options.route,
3898
+ label: options.label,
3899
+ backend: options.backend,
3900
+ noInstall: options.install === false
3901
+ });
3902
+ process.stdout.write(
3903
+ `Created ${result.plan.type} plugin ${result.plan.name} (${result.plan.framework}) \u2192 ${result.outDir}
3904
+ `
3905
+ );
3906
+ });
3907
+ program.command("dev <plugin-dir>").description("run a local daemon + host that load the plugin from source with HMR").option("--daemon <binary>", "path to a prebuilt mndwd binary (required outside a source checkout)").option("--port <port>", "local daemon port (default 9090)", (value) => Number.parseInt(value, 10)).option("--addr <device>", "Keenetic device IP, host[:port], or http(s) URL").addOption(new Option("--host-device <url>", "compatibility alias for --addr").hideHelp()).option("--ui-port <port>", "local UI dev-server port", (value) => Number.parseInt(value, 10), 5173).addOption(new Option("--prebuilt-host", "use the packaged dev host").hideHelp()).action(async (pluginDir, options) => {
3908
+ if (options.addr !== void 0 && options.hostDevice !== void 0 && options.addr !== options.hostDevice) {
3909
+ throw new CliError("--addr and --host-device cannot be used with different values");
3910
+ }
3911
+ await runDev(pluginDir, {
3912
+ daemonBinary: options.daemon,
3913
+ port: options.port,
3914
+ addr: options.addr ?? options.hostDevice,
3915
+ uiPort: options.uiPort,
3916
+ prebuiltHost: options.prebuiltHost
3917
+ });
3918
+ });
3919
+ program.command("validate <plugin-dir>").option("--strict", "treat catalog key-parity warnings as errors").action((pluginDir, options) => {
3920
+ let result;
3921
+ try {
3922
+ result = readManifest(pluginDir);
3923
+ } catch (error) {
3924
+ rethrowManifestError(pluginDir, error);
3925
+ }
3926
+ const warnings = [
3927
+ ...result.warnings,
3928
+ ...validatePluginCatalogs(resolvePluginDir(pluginDir), result.manifest, {
3929
+ strict: options.strict === true
3930
+ })
3931
+ ];
3932
+ for (const warning of warnings) {
3933
+ process.stdout.write(`Warning: ${warning}
3934
+ `);
3935
+ }
3936
+ process.stdout.write(`Validated ${result.manifest.name}: ${result.path}
3937
+ `);
3938
+ });
3939
+ program.command("pack <plugin-dir>").option("--out-dir <dir>", "output directory (default: <plugin-dir>/dist)").option("--dev", "pack the development entry instead of the configured production entry").option("--skip-backend-build", "skip package backend build hook for an already-built dev artifact").action(async (pluginDir, options) => {
3940
+ let result;
3941
+ try {
3942
+ result = await packPlugin(pluginDir, {
3943
+ outDir: options.outDir,
3944
+ development: options.dev,
3945
+ skipBackendBuild: options.skipBackendBuild
3946
+ });
3947
+ } catch (error) {
3948
+ rethrowManifestError(pluginDir, error);
3949
+ }
3950
+ for (const warning of result.warnings) {
3951
+ process.stdout.write(`Warning: ${warning}
3952
+ `);
3953
+ }
3954
+ process.stdout.write(`Packed ${result.manifest.name} (${result.framework}) \u2192 ${result.outDir}
3955
+ `);
3956
+ });
3957
+ program.command("zip <plugin-dir>").option("--out-dir <dir>", "pack output directory (default: <plugin-dir>/dist)").option("--output <file>", "archive destination (default: <plugin-dir>/<plugin-name>.zip)").action(async (pluginDir, options) => {
3958
+ let result;
3959
+ try {
3960
+ result = await zipPlugin(pluginDir, { outDir: options.outDir, output: options.output });
3961
+ } catch (error) {
3962
+ rethrowManifestError(pluginDir, error);
3963
+ }
3964
+ process.stdout.write(`Zipped ${result.pack.manifest.name} \u2192 ${result.outputPath}
3965
+ `);
3966
+ });
3967
+ program.command("build-backend").description(
3968
+ "build the current plugin's Go backend (name from manifest.json, binary/entry from package.json mndw.backend)"
3969
+ ).allowUnknownOption().allowExcessArguments().action((_options, command) => {
3970
+ runBuildBackendCommand({ pluginDir: process.cwd(), args: command.args });
3971
+ });
3972
+ return program;
3973
+ }
3974
+ async function run(argv = process.argv) {
3975
+ try {
3976
+ await createProgram().parseAsync(argv);
3977
+ } catch (error) {
3978
+ if (error instanceof CliError || error instanceof ManifestValidationError) {
3979
+ process.stderr.write(`${error.message}
3980
+ `);
3981
+ process.exitCode = 1;
3982
+ return;
3983
+ }
3984
+ throw error;
3985
+ }
3986
+ }
3987
+ if (import.meta.main) {
3988
+ void run();
3989
+ }
3990
+ export {
3991
+ createProgram,
3992
+ run
3993
+ };