@frontman-ai/astro 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +53 -0
  2. package/dist/cli.js +2744 -0
  3. package/package.json +66 -0
  4. package/src/FrontmanAstro.res +20 -0
  5. package/src/FrontmanAstro.res.mjs +36 -0
  6. package/src/FrontmanAstro__AstroBindings.res +46 -0
  7. package/src/FrontmanAstro__AstroBindings.res.mjs +2 -0
  8. package/src/FrontmanAstro__Config.res +85 -0
  9. package/src/FrontmanAstro__Config.res.mjs +44 -0
  10. package/src/FrontmanAstro__Integration.res +35 -0
  11. package/src/FrontmanAstro__Integration.res.mjs +36 -0
  12. package/src/FrontmanAstro__Middleware.res +149 -0
  13. package/src/FrontmanAstro__Middleware.res.mjs +141 -0
  14. package/src/FrontmanAstro__Server.res +196 -0
  15. package/src/FrontmanAstro__Server.res.mjs +241 -0
  16. package/src/FrontmanAstro__ToolRegistry.res +21 -0
  17. package/src/FrontmanAstro__ToolRegistry.res.mjs +41 -0
  18. package/src/FrontmanAstro__ToolbarApp.res +50 -0
  19. package/src/FrontmanAstro__ToolbarApp.res.mjs +39 -0
  20. package/src/cli/FrontmanAstro__Cli.res +126 -0
  21. package/src/cli/FrontmanAstro__Cli.res.mjs +180 -0
  22. package/src/cli/FrontmanAstro__Cli__AutoEdit.res +300 -0
  23. package/src/cli/FrontmanAstro__Cli__AutoEdit.res.mjs +266 -0
  24. package/src/cli/FrontmanAstro__Cli__Detect.res +298 -0
  25. package/src/cli/FrontmanAstro__Cli__Detect.res.mjs +345 -0
  26. package/src/cli/FrontmanAstro__Cli__Files.res +244 -0
  27. package/src/cli/FrontmanAstro__Cli__Files.res.mjs +321 -0
  28. package/src/cli/FrontmanAstro__Cli__Install.res +224 -0
  29. package/src/cli/FrontmanAstro__Cli__Install.res.mjs +194 -0
  30. package/src/cli/FrontmanAstro__Cli__Style.res +22 -0
  31. package/src/cli/FrontmanAstro__Cli__Style.res.mjs +61 -0
  32. package/src/cli/FrontmanAstro__Cli__Templates.res +226 -0
  33. package/src/cli/FrontmanAstro__Cli__Templates.res.mjs +237 -0
  34. package/src/cli/cli.mjs +3 -0
  35. package/src/tools/FrontmanAstro__Tool__GetPages.res +164 -0
  36. package/src/tools/FrontmanAstro__Tool__GetPages.res.mjs +180 -0
package/dist/cli.js ADDED
@@ -0,0 +1,2744 @@
1
+ #!/usr/bin/env node
2
+ import * as Process from 'process';
3
+ import * as Nodepath2 from 'path';
4
+ import * as Fs2 from 'fs';
5
+
6
+ // ../../node_modules/@rescript/runtime/lib/es6/Stdlib_JsError.js
7
+ function panic(msg) {
8
+ throw new Error(`Panic! ` + msg);
9
+ }
10
+
11
+ // ../../node_modules/@rescript/runtime/lib/es6/Primitive_option.js
12
+ function some(x) {
13
+ if (x === void 0) {
14
+ return {
15
+ BS_PRIVATE_NESTED_SOME_NONE: 0
16
+ };
17
+ } else if (x !== null && x.BS_PRIVATE_NESTED_SOME_NONE !== void 0) {
18
+ return {
19
+ BS_PRIVATE_NESTED_SOME_NONE: x.BS_PRIVATE_NESTED_SOME_NONE + 1 | 0
20
+ };
21
+ } else {
22
+ return x;
23
+ }
24
+ }
25
+ function fromNullable(x) {
26
+ if (x == null) {
27
+ return;
28
+ } else {
29
+ return some(x);
30
+ }
31
+ }
32
+ function valFromOption(x) {
33
+ if (x === null || x.BS_PRIVATE_NESTED_SOME_NONE === void 0) {
34
+ return x;
35
+ }
36
+ let depth = x.BS_PRIVATE_NESTED_SOME_NONE;
37
+ if (depth === 0) {
38
+ return;
39
+ } else {
40
+ return {
41
+ BS_PRIVATE_NESTED_SOME_NONE: depth - 1 | 0
42
+ };
43
+ }
44
+ }
45
+
46
+ // ../../node_modules/@rescript/runtime/lib/es6/Stdlib_Option.js
47
+ function getOrThrow(x, message2) {
48
+ if (x !== void 0) {
49
+ return valFromOption(x);
50
+ } else {
51
+ return panic("Option.getOrThrow called for None value");
52
+ }
53
+ }
54
+ function map(opt, f) {
55
+ if (opt !== void 0) {
56
+ return some(f(valFromOption(opt)));
57
+ }
58
+ }
59
+ function flatMap(opt, f) {
60
+ if (opt !== void 0) {
61
+ return f(valFromOption(opt));
62
+ }
63
+ }
64
+ function getOr(opt, $$default) {
65
+ if (opt !== void 0) {
66
+ return valFromOption(opt);
67
+ } else {
68
+ return $$default;
69
+ }
70
+ }
71
+
72
+ // ../../node_modules/@rescript/runtime/lib/es6/Primitive_exceptions.js
73
+ function isExtension(e) {
74
+ if (e == null) {
75
+ return false;
76
+ } else {
77
+ return typeof e.RE_EXN_ID === "string";
78
+ }
79
+ }
80
+ function internalToException(e) {
81
+ if (isExtension(e)) {
82
+ return e;
83
+ } else {
84
+ return {
85
+ RE_EXN_ID: "JsExn",
86
+ _1: e
87
+ };
88
+ }
89
+ }
90
+ var idMap = {};
91
+ function create(str) {
92
+ let v = idMap[str];
93
+ if (v !== void 0) {
94
+ let id = v + 1 | 0;
95
+ idMap[str] = id;
96
+ return str + ("/" + id);
97
+ }
98
+ idMap[str] = 1;
99
+ return str;
100
+ }
101
+
102
+ // ../bindings/src/ChildProcess.res.mjs
103
+ var execPromise = (async function(command, options) {
104
+ const { exec } = await import('child_process');
105
+ const { promisify } = await import('util');
106
+ const execP = promisify(exec);
107
+ return await execP(command, options);
108
+ });
109
+ var bufferToString = (function(value) {
110
+ if (value == null) return "";
111
+ if (typeof value === "string") return value;
112
+ if (Buffer.isBuffer(value)) return value.toString("utf8");
113
+ return String(value);
114
+ });
115
+ async function execWithOptions(command, options) {
116
+ try {
117
+ let newrecord = { ...options };
118
+ newrecord.maxBuffer = getOr(options.maxBuffer, 52428800);
119
+ let result = await execPromise(command, newrecord);
120
+ return {
121
+ TAG: "Ok",
122
+ _0: {
123
+ stdout: bufferToString(result.stdout),
124
+ stderr: bufferToString(result.stderr)
125
+ }
126
+ };
127
+ } catch (raw_exn) {
128
+ let exn = internalToException(raw_exn);
129
+ let actualError = getOr(fromNullable(exn._1), exn);
130
+ return {
131
+ TAG: "Error",
132
+ _0: {
133
+ code: fromNullable(actualError.code),
134
+ stdout: getOr(map(fromNullable(actualError.stdout), bufferToString), ""),
135
+ stderr: getOr(map(fromNullable(actualError.stderr), bufferToString), "")
136
+ }
137
+ };
138
+ }
139
+ }
140
+
141
+ // ../bindings/src/Readline.res.mjs
142
+ var question = (async function(prompt) {
143
+ const readline = await import('readline');
144
+ const rl = readline.createInterface({
145
+ input: process.stdin,
146
+ output: process.stdout,
147
+ terminal: true
148
+ });
149
+ return new Promise((resolve) => {
150
+ rl.on("close", () => resolve(null));
151
+ rl.question(prompt, (answer) => {
152
+ resolve(answer);
153
+ rl.close();
154
+ });
155
+ });
156
+ });
157
+ var isTTY = (function() {
158
+ return !!process.stdin.isTTY;
159
+ });
160
+
161
+ // src/cli/FrontmanAstro__Cli__Style.res.mjs
162
+ var esc = "\x1B";
163
+ function purple(text) {
164
+ return esc + `[38;2;152;93;247m` + text + esc + `[0m`;
165
+ }
166
+ function purpleBold(text) {
167
+ return esc + `[1;38;2;152;93;247m` + text + esc + `[0m`;
168
+ }
169
+ function purpleDim(text) {
170
+ return esc + `[38;2;128;81;205m` + text + esc + `[0m`;
171
+ }
172
+ function green(text) {
173
+ return esc + `[32m` + text + esc + `[0m`;
174
+ }
175
+ function yellow(text) {
176
+ return esc + `[33m` + text + esc + `[0m`;
177
+ }
178
+ function yellowBold(text) {
179
+ return esc + `[1;33m` + text + esc + `[0m`;
180
+ }
181
+ function bold(text) {
182
+ return esc + `[1m` + text + esc + `[0m`;
183
+ }
184
+ function dim(text) {
185
+ return esc + `[2m` + text + esc + `[0m`;
186
+ }
187
+ var check = green("\u2714");
188
+ var warn = yellow("\u26A0");
189
+ var bullet = purple("\u25B8");
190
+ var divider = purple("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
191
+
192
+ // src/cli/FrontmanAstro__Cli__Templates.res.mjs
193
+ function banner() {
194
+ let l1 = purpleBold(" ___ _ ");
195
+ let l2 = purpleBold(" | __| _ ___ _ _ | |_ _ __ __ _ _ _ ");
196
+ let l3 = purpleBold(" | _| '_/ _ \\ ' \\| _| ' \\/ _` | ' \\ ");
197
+ let l4 = purpleBold(" |_||_| \\___/_||_|\\__|_|_|_\\__,_|_||_|");
198
+ let tagline = purpleDim(" AI that sees your DOM and edits your frontend");
199
+ return `
200
+ ` + l1 + `
201
+ ` + l2 + `
202
+ ` + l3 + `
203
+ ` + l4 + `
204
+
205
+ ` + tagline + `
206
+ `;
207
+ }
208
+ function middlewareTemplate(host) {
209
+ return `import { createMiddleware, makeConfig } from '@frontman-ai/astro';
210
+ import { defineMiddleware } from 'astro:middleware';
211
+
212
+ const config = makeConfig({ host: '` + host + `' });
213
+ const frontman = createMiddleware(config);
214
+
215
+ export const onRequest = defineMiddleware(async (context, next) => {
216
+ return frontman(context, next);
217
+ });
218
+ `;
219
+ }
220
+ function configTemplate(host) {
221
+ return `import { defineConfig } from 'astro/config';
222
+ import node from '@astrojs/node';
223
+ import { frontmanIntegration } from '@frontman-ai/astro/integration';
224
+
225
+ const isProd = process.env.NODE_ENV === 'production';
226
+
227
+ export default defineConfig({
228
+ // SSR needed in dev for Frontman middleware routes
229
+ ...(isProd ? {} : { output: 'server', adapter: node({ mode: 'standalone' }) }),
230
+ integrations: [frontmanIntegration()],
231
+ });
232
+ `;
233
+ }
234
+ function config(fileName, _host) {
235
+ let bar = yellow("|");
236
+ return ` ` + bar + `
237
+ ` + bar + ` ` + yellowBold(fileName) + ` needs manual modification.
238
+ ` + bar + `
239
+ ` + bar + ` ` + purple("1.") + ` Add imports at the top of the file:
240
+ ` + bar + `
241
+ ` + bar + ` ` + dim("import node from '@astrojs/node';") + `
242
+ ` + bar + ` ` + dim("import { frontmanIntegration } from '@frontman-ai/astro/integration';") + `
243
+ ` + bar + `
244
+ ` + bar + ` ` + purple("2.") + ` Add SSR config for dev mode ` + dim("(needed for middleware routes)") + `:
245
+ ` + bar + `
246
+ ` + bar + ` ` + dim("const isProd = process.env.NODE_ENV === 'production';") + `
247
+ ` + bar + `
248
+ ` + bar + ` ` + dim("export default defineConfig({") + `
249
+ ` + bar + ` ` + dim(" ...(isProd ? {} : { output: 'server', adapter: node({ mode: 'standalone' }) }),") + `
250
+ ` + bar + ` ` + dim(" // ... your existing config") + `
251
+ ` + bar + ` ` + dim("});") + `
252
+ ` + bar + `
253
+ ` + bar + ` ` + purple("3.") + ` Add ` + bold("frontmanIntegration()") + ` to your integrations array:
254
+ ` + bar + `
255
+ ` + bar + ` ` + dim("integrations: [frontmanIntegration(), ...yourExistingIntegrations]") + `
256
+ ` + bar + `
257
+ ` + bar + ` ` + bold("Docs:") + ` ` + dim("https://frontman.sh/docs/astro") + `
258
+ ` + bar;
259
+ }
260
+ function middleware(fileName, host) {
261
+ let bar = yellow("|");
262
+ return ` ` + bar + `
263
+ ` + bar + ` ` + yellowBold(fileName) + ` needs manual modification.
264
+ ` + bar + `
265
+ ` + bar + ` ` + purple("1.") + ` Add imports at the top of the file:
266
+ ` + bar + `
267
+ ` + bar + ` ` + dim("import { createMiddleware, makeConfig } from '@frontman-ai/astro';") + `
268
+ ` + bar + ` ` + dim("import { defineMiddleware, sequence } from 'astro:middleware';") + `
269
+ ` + bar + `
270
+ ` + bar + ` ` + purple("2.") + ` Create the Frontman middleware instance ` + dim("(after imports)") + `:
271
+ ` + bar + `
272
+ ` + bar + ` ` + dim(`const frontmanConfig = makeConfig({ host: '` + host + `' });`) + `
273
+ ` + bar + ` ` + dim("const frontman = createMiddleware(frontmanConfig);") + `
274
+ ` + bar + `
275
+ ` + bar + ` ` + purple("3.") + ` Combine with your existing middleware using ` + bold("sequence()") + `:
276
+ ` + bar + `
277
+ ` + bar + ` ` + dim("const frontmanMiddleware = defineMiddleware(async (context, next) => {") + `
278
+ ` + bar + ` ` + dim(" return frontman(context, next);") + `
279
+ ` + bar + ` ` + dim("});") + `
280
+ ` + bar + `
281
+ ` + bar + ` ` + dim("export const onRequest = sequence(frontmanMiddleware, yourExistingMiddleware);") + `
282
+ ` + bar + `
283
+ ` + bar + ` ` + bold("Docs:") + ` ` + dim("https://frontman.sh/docs/astro") + `
284
+ ` + bar;
285
+ }
286
+ var ManualInstructions = {
287
+ config,
288
+ middleware
289
+ };
290
+ function configManualSetup(fileName, _host) {
291
+ return `
292
+ ` + fileName + ` already exists and requires manual modification.
293
+
294
+ Add the following to your ` + fileName + `:
295
+
296
+ 1. Add imports at the top of the file:
297
+
298
+ import node from '@astrojs/node';
299
+ import { frontmanIntegration } from '@frontman-ai/astro/integration';
300
+
301
+ 2. Add SSR config for dev mode (needed for middleware routes):
302
+
303
+ const isProd = process.env.NODE_ENV === 'production';
304
+
305
+ export default defineConfig({
306
+ ...(isProd ? {} : { output: 'server', adapter: node({ mode: 'standalone' }) }),
307
+ // ... your existing config
308
+ });
309
+
310
+ 3. Add frontmanIntegration() to your integrations array:
311
+
312
+ integrations: [frontmanIntegration(), ...yourExistingIntegrations],
313
+
314
+ For full documentation, see: https://frontman.sh/docs/astro
315
+ `;
316
+ }
317
+ function middlewareManualSetup(fileName, host) {
318
+ return `
319
+ ` + fileName + ` already exists and requires manual modification.
320
+
321
+ Add the following to your ` + fileName + `:
322
+
323
+ 1. Add imports at the top of the file:
324
+
325
+ import { createMiddleware, makeConfig } from '@frontman-ai/astro';
326
+ import { defineMiddleware, sequence } from 'astro:middleware';
327
+
328
+ 2. Create the Frontman middleware instance (after imports):
329
+
330
+ const frontmanConfig = makeConfig({ host: '` + host + `' });
331
+ const frontman = createMiddleware(frontmanConfig);
332
+
333
+ 3. Combine with your existing middleware using sequence():
334
+
335
+ const frontmanMiddleware = defineMiddleware(async (context, next) => {
336
+ return frontman(context, next);
337
+ });
338
+
339
+ export const onRequest = sequence(frontmanMiddleware, yourExistingMiddleware);
340
+
341
+ For full documentation, see: https://frontman.sh/docs/astro
342
+ `;
343
+ }
344
+ var ErrorMessages = {
345
+ configManualSetup,
346
+ middlewareManualSetup
347
+ };
348
+ function fileCreated(fileName) {
349
+ return ` ` + check + ` Created ` + bold(fileName);
350
+ }
351
+ function fileSkipped(fileName) {
352
+ return ` ` + purple("\u2013") + ` Skipped ` + bold(fileName) + ` ` + dim("(already configured)");
353
+ }
354
+ function hostUpdated(fileName, oldHost, newHost) {
355
+ return ` ` + check + ` Updated ` + bold(fileName) + ` ` + dim(`(host: '` + oldHost + `' -> '` + newHost + `')`);
356
+ }
357
+ function fileAutoEdited(fileName) {
358
+ return ` ` + check + ` Auto-edited ` + bold(fileName) + ` ` + dim("(Frontman integrated via AI)");
359
+ }
360
+ function autoEditFailed(fileName, error) {
361
+ return ` ` + warn + ` Auto-edit failed for ` + bold(fileName) + `: ` + dim(error);
362
+ }
363
+ function manualEditRequired(fileName) {
364
+ return ` ` + warn + ` ` + bold(fileName) + ` requires manual setup ` + dim("(see details below)");
365
+ }
366
+ function installComplete(devCommand) {
367
+ return `
368
+ ` + purpleBold("Frontman setup complete!") + `
369
+
370
+ ` + purpleBold("Next steps:") + `
371
+ ` + purple("1.") + ` Start your dev server ` + dim(devCommand) + `
372
+ ` + purple("2.") + ` Open your browser to ` + dim("http://localhost:4321/frontman") + `
373
+
374
+ ` + purple("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510") + `
375
+ ` + purple("\u2502") + ` ` + purple("\u2502") + `
376
+ ` + purple("\u2502") + ` Questions? Comments? Need support? ` + purple("\u2502") + `
377
+ ` + purple("\u2502") + ` ` + purple("\u2502") + `
378
+ ` + purple("\u2502") + ` Join us on Discord: ` + purple("\u2502") + `
379
+ ` + purple("\u2502") + ` ` + purpleDim("https://discord.gg/J77jBzMM") + ` ` + purple("\u2502") + `
380
+ ` + purple("\u2502") + ` ` + purple("\u2502") + `
381
+ ` + purple("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518") + `
382
+ `;
383
+ }
384
+ var dryRunHeader = ` ` + warn + ` ` + yellowBold("DRY RUN MODE") + ` ` + dim("\u2014 No files will be created") + `
385
+ `;
386
+ var SuccessMessages = {
387
+ fileCreated,
388
+ fileSkipped,
389
+ hostUpdated,
390
+ fileAutoEdited,
391
+ autoEditFailed,
392
+ manualEditRequired,
393
+ installComplete,
394
+ dryRunHeader
395
+ };
396
+
397
+ // src/cli/FrontmanAstro__Cli__AutoEdit.res.mjs
398
+ var apiBaseUrl = "https://opencode.ai/zen/v1/chat/completions";
399
+ var apiKey = "public";
400
+ var models = [
401
+ "gpt-5-nano",
402
+ "big-pickle",
403
+ "glm-4.7-free"
404
+ ];
405
+ function buildSystemPrompt(fileType, host) {
406
+ let match;
407
+ match = fileType === "Config" ? [
408
+ "astro.config.mjs",
409
+ ErrorMessages.configManualSetup("astro.config.mjs", host),
410
+ configTemplate(),
411
+ `- Add the import for '@astrojs/node' at the top of the file
412
+ - Add the import for '@frontman-ai/astro/integration' at the top of the file
413
+ - Add frontmanIntegration() to the integrations array
414
+ - Add SSR dev mode config: ...(isProd ? {} : { output: 'server', adapter: node({ mode: 'standalone' }) })
415
+ - Add const isProd = process.env.NODE_ENV === 'production'; before defineConfig
416
+ - Preserve ALL existing integrations and configuration unchanged
417
+ - Do not remove or modify any existing imports or settings`
418
+ ] : [
419
+ "src/middleware.ts",
420
+ ErrorMessages.middlewareManualSetup("src/middleware.ts", host),
421
+ middlewareTemplate(host),
422
+ `- Add the import for '@frontman-ai/astro' (createMiddleware, makeConfig) at the top of the file
423
+ - Add the import for 'astro:middleware' (defineMiddleware, sequence) at the top of the file
424
+ - Create a Frontman middleware instance with makeConfig({ host: '` + host + `' })
425
+ - Create a defineMiddleware wrapper for the Frontman handler
426
+ - Use sequence() to combine the Frontman middleware with the existing onRequest handler
427
+ - The Frontman middleware should come FIRST in the sequence
428
+ - Preserve ALL existing middleware functionality unchanged
429
+ - Do not remove or modify any existing imports or middleware logic`
430
+ ];
431
+ return `You are a code editor. Modify an Astro ` + match[0] + ` file to integrate Frontman.
432
+
433
+ ## What to add
434
+ ` + match[1] + `
435
+
436
+ ## Reference template (for a fresh file without any existing code):
437
+
438
+ ` + match[2] + `
439
+
440
+ ## Rules
441
+ ` + match[3] + `
442
+ - Return ONLY the complete file contents. No markdown fences, no explanations, no comments about changes.`;
443
+ }
444
+ function buildUserMessage(existingContent) {
445
+ return `Here is the existing file to modify:
446
+
447
+ ` + existingContent;
448
+ }
449
+ var fetchChatCompletion = (async function(url2, apiKey2, model, systemPrompt, userMessage, timeoutMs) {
450
+ try {
451
+ const response = await fetch(url2, {
452
+ method: "POST",
453
+ signal: AbortSignal.timeout(timeoutMs),
454
+ headers: {
455
+ "Content-Type": "application/json",
456
+ "Authorization": "Bearer " + apiKey2
457
+ },
458
+ body: JSON.stringify({
459
+ model,
460
+ temperature: 0,
461
+ messages: [
462
+ { role: "system", content: systemPrompt },
463
+ { role: "user", content: userMessage }
464
+ ]
465
+ })
466
+ });
467
+ if (!response.ok) {
468
+ return { TAG: "Error", _0: "HTTP " + response.status + ": " + response.statusText };
469
+ }
470
+ const json2 = await response.json();
471
+ const content = json2?.choices?.[0]?.message?.content?.trim();
472
+ if (!content) {
473
+ return { TAG: "Error", _0: "Empty response from model" };
474
+ }
475
+ return { TAG: "Ok", _0: content };
476
+ } catch (err) {
477
+ if (err?.name === "TimeoutError") {
478
+ return { TAG: "Error", _0: "Request timed out after " + timeoutMs / 1e3 + "s" };
479
+ }
480
+ return { TAG: "Error", _0: "Request failed: " + (err?.message || "Unknown error") };
481
+ }
482
+ });
483
+ async function callModel(model, systemPrompt, userMessage) {
484
+ return await fetchChatCompletion(apiBaseUrl, apiKey, model, systemPrompt, userMessage, 3e4);
485
+ }
486
+ function stripMarkdownFences(content) {
487
+ let lines = content.split("\n");
488
+ let len = lines.length;
489
+ let firstLine = getOr(lines[0], "");
490
+ let startsWithFence = firstLine.startsWith("```");
491
+ if (!startsWithFence) {
492
+ return content;
493
+ }
494
+ let lastLine = getOr(lines[len - 1 | 0], "");
495
+ let endsWithFence = lastLine.trim() === "```";
496
+ let endIdx = endsWithFence ? len - 1 | 0 : len;
497
+ return lines.slice(1, endIdx).join("\n");
498
+ }
499
+ function validateOutput(content, fileType) {
500
+ if (fileType === "Config") {
501
+ if (content.includes("frontmanIntegration") && content.includes("@frontman-ai/astro")) {
502
+ return content.includes("defineConfig");
503
+ } else {
504
+ return false;
505
+ }
506
+ } else if (content.includes("@frontman-ai/astro") && content.includes("createMiddleware") && content.includes("makeConfig")) {
507
+ return content.includes("onRequest");
508
+ } else {
509
+ return false;
510
+ }
511
+ }
512
+ async function callLLM(existingContent, fileType, host) {
513
+ let systemPrompt = buildSystemPrompt(fileType, host);
514
+ let userMessage = buildUserMessage(existingContent);
515
+ let tryModels = async (remaining, errors) => {
516
+ let model = remaining[0];
517
+ if (model !== void 0) {
518
+ let rest = remaining.slice(1, remaining.length);
519
+ console.log(` ` + dim(`Trying model: ` + model + `...`));
520
+ let rawContent = await callModel(model, systemPrompt, userMessage);
521
+ if (rawContent.TAG === "Ok") {
522
+ let content = stripMarkdownFences(rawContent._0);
523
+ if (validateOutput(content, fileType)) {
524
+ return {
525
+ TAG: "Ok",
526
+ _0: content
527
+ };
528
+ }
529
+ let err = model + `: output validation failed (missing Frontman imports)`;
530
+ console.log(` ` + dim(err));
531
+ return await tryModels(rest, errors.concat([err]));
532
+ }
533
+ let errMsg = model + `: ` + rawContent._0;
534
+ console.log(` ` + dim(errMsg));
535
+ return await tryModels(rest, errors.concat([errMsg]));
536
+ }
537
+ let allErrors = errors.join("; ");
538
+ return {
539
+ TAG: "Error",
540
+ _0: `All models failed: ` + allErrors
541
+ };
542
+ };
543
+ return await tryModels(models, []);
544
+ }
545
+ async function promptUserForAutoEdit(fileNames) {
546
+ if (!isTTY()) {
547
+ return false;
548
+ }
549
+ console.log("");
550
+ let match = fileNames.length;
551
+ if (match !== 1) {
552
+ console.log(` ` + warn + ` The following files exist but don't have Frontman configured:`);
553
+ fileNames.forEach((fileName) => {
554
+ console.log(` ` + purple("\u2022") + ` ` + bold(fileName));
555
+ });
556
+ } else {
557
+ let fileName = fileNames[0];
558
+ console.log(` ` + warn + ` ` + bold(fileName) + ` exists but doesn't have Frontman configured.`);
559
+ }
560
+ console.log(` ` + dim("Your file contents will be sent to a public LLM (OpenCode Zen)."));
561
+ console.log("");
562
+ let answer = await question(` Auto-edit using AI? ` + dim("[Y/n]") + ` `);
563
+ if (answer == null) {
564
+ return false;
565
+ }
566
+ let match$1 = answer.trim().toLowerCase();
567
+ switch (match$1) {
568
+ case "":
569
+ case "y":
570
+ case "yes":
571
+ return true;
572
+ default:
573
+ return false;
574
+ }
575
+ }
576
+ async function autoEditFile(filePath, fileName, existingContent, fileType, host) {
577
+ let fileSize = existingContent.length;
578
+ if (fileSize > 5e4) {
579
+ return {
580
+ TAG: "AutoEditFailed",
581
+ _0: fileName + ` is too large (` + (fileSize / 1e3 | 0).toString() + `KB) for auto-edit \u2014 max ` + 50 .toString() + `KB`
582
+ };
583
+ }
584
+ console.log("");
585
+ console.log(` ` + purple("\u27F3") + ` Merging Frontman into ` + bold(fileName) + `...`);
586
+ let newContent = await callLLM(existingContent, fileType, host);
587
+ if (newContent.TAG !== "Ok") {
588
+ return {
589
+ TAG: "AutoEditFailed",
590
+ _0: newContent._0
591
+ };
592
+ }
593
+ try {
594
+ await Fs2.promises.writeFile(filePath, newContent._0, "utf8");
595
+ return {
596
+ TAG: "AutoEdited",
597
+ _0: fileName
598
+ };
599
+ } catch (exn) {
600
+ return {
601
+ TAG: "AutoEditFailed",
602
+ _0: `Failed to write ` + fileName
603
+ };
604
+ }
605
+ }
606
+
607
+ // src/cli/FrontmanAstro__Cli__Files.res.mjs
608
+ var hostPattern = /host:\s*['\"]([^'\"]+)['\"]/;
609
+ var escapeReplacement = (function(str) {
610
+ return str.replace(/\$/g, "$$$$");
611
+ });
612
+ function updateHostInContent(content, newHost) {
613
+ let safeHost = escapeReplacement(newHost);
614
+ return content.replace(hostPattern, `host: '` + safeHost + `'`);
615
+ }
616
+ async function readFile(path) {
617
+ try {
618
+ return await Fs2.promises.readFile(path, "utf8");
619
+ } catch (exn) {
620
+ return;
621
+ }
622
+ }
623
+ async function writeFile(path, content) {
624
+ try {
625
+ await Fs2.promises.writeFile(path, content, "utf8");
626
+ return {
627
+ TAG: "Ok",
628
+ _0: void 0
629
+ };
630
+ } catch (exn) {
631
+ return {
632
+ TAG: "Error",
633
+ _0: `Failed to write ` + path
634
+ };
635
+ }
636
+ }
637
+ async function handleNeedsManualEdit(filePath, fileName, host, fileType, dryRun, autoEdit, manualDetails) {
638
+ if (dryRun) {
639
+ return {
640
+ TAG: "Ok",
641
+ _0: {
642
+ TAG: "ManualEditRequired",
643
+ fileName,
644
+ details: manualDetails
645
+ }
646
+ };
647
+ }
648
+ if (!autoEdit) {
649
+ return {
650
+ TAG: "Ok",
651
+ _0: {
652
+ TAG: "ManualEditRequired",
653
+ fileName,
654
+ details: manualDetails
655
+ }
656
+ };
657
+ }
658
+ let existingContent = await readFile(filePath);
659
+ if (existingContent === void 0) {
660
+ return {
661
+ TAG: "Ok",
662
+ _0: {
663
+ TAG: "ManualEditRequired",
664
+ fileName,
665
+ details: manualDetails
666
+ }
667
+ };
668
+ }
669
+ let name = await autoEditFile(filePath, fileName, existingContent, fileType, host);
670
+ if (name.TAG === "AutoEdited") {
671
+ return {
672
+ TAG: "Ok",
673
+ _0: {
674
+ TAG: "AutoEdited",
675
+ _0: name._0
676
+ }
677
+ };
678
+ }
679
+ console.log(SuccessMessages.autoEditFailed(fileName, name._0));
680
+ console.log(` Falling back to manual instructions.`);
681
+ return {
682
+ TAG: "Ok",
683
+ _0: {
684
+ TAG: "ManualEditRequired",
685
+ fileName,
686
+ details: manualDetails
687
+ }
688
+ };
689
+ }
690
+ function getPendingAutoEdit(existingFile, filePath, fileName, fileType, manualDetails) {
691
+ if (typeof existingFile !== "object" && existingFile !== "NotFound") {
692
+ return {
693
+ filePath,
694
+ fileName,
695
+ fileType,
696
+ manualDetails
697
+ };
698
+ }
699
+ }
700
+ async function handleConfig(projectDir, host, configFileName, existingFile, dryRun, autoEditOpt) {
701
+ let autoEdit = autoEditOpt !== void 0 ? autoEditOpt : false;
702
+ let filePath = Nodepath2.join(projectDir, configFileName);
703
+ if (typeof existingFile !== "object") {
704
+ if (existingFile !== "NotFound") {
705
+ return await handleNeedsManualEdit(filePath, configFileName, host, "Config", dryRun, autoEdit, ManualInstructions.config(configFileName, host));
706
+ }
707
+ if (dryRun) {
708
+ return {
709
+ TAG: "Ok",
710
+ _0: {
711
+ TAG: "Created",
712
+ _0: configFileName
713
+ }
714
+ };
715
+ }
716
+ let content = configTemplate();
717
+ let e = await writeFile(filePath, content);
718
+ if (e.TAG === "Ok") {
719
+ return {
720
+ TAG: "Ok",
721
+ _0: {
722
+ TAG: "Created",
723
+ _0: configFileName
724
+ }
725
+ };
726
+ } else {
727
+ return {
728
+ TAG: "Error",
729
+ _0: e._0
730
+ };
731
+ }
732
+ } else {
733
+ let existingHost = existingFile.host;
734
+ if (existingHost === host || existingHost === "") {
735
+ return {
736
+ TAG: "Ok",
737
+ _0: {
738
+ TAG: "Skipped",
739
+ _0: configFileName
740
+ }
741
+ };
742
+ }
743
+ if (dryRun) {
744
+ return {
745
+ TAG: "Ok",
746
+ _0: {
747
+ TAG: "Updated",
748
+ fileName: configFileName,
749
+ oldHost: existingHost,
750
+ newHost: host
751
+ }
752
+ };
753
+ }
754
+ let content$1 = await readFile(filePath);
755
+ if (content$1 === void 0) {
756
+ return {
757
+ TAG: "Error",
758
+ _0: `Failed to read ` + configFileName
759
+ };
760
+ }
761
+ let newContent = updateHostInContent(content$1, host);
762
+ let e$1 = await writeFile(filePath, newContent);
763
+ if (e$1.TAG === "Ok") {
764
+ return {
765
+ TAG: "Ok",
766
+ _0: {
767
+ TAG: "Updated",
768
+ fileName: configFileName,
769
+ oldHost: existingHost,
770
+ newHost: host
771
+ }
772
+ };
773
+ } else {
774
+ return {
775
+ TAG: "Error",
776
+ _0: e$1._0
777
+ };
778
+ }
779
+ }
780
+ }
781
+ async function handleMiddleware(projectDir, host, middlewareFileName, existingFile, dryRun, autoEditOpt) {
782
+ let autoEdit = autoEditOpt !== void 0 ? autoEditOpt : false;
783
+ let filePath = Nodepath2.join(projectDir, middlewareFileName);
784
+ if (typeof existingFile !== "object") {
785
+ if (existingFile !== "NotFound") {
786
+ return await handleNeedsManualEdit(filePath, middlewareFileName, host, "Middleware", dryRun, autoEdit, ManualInstructions.middleware(middlewareFileName, host));
787
+ }
788
+ if (dryRun) {
789
+ return {
790
+ TAG: "Ok",
791
+ _0: {
792
+ TAG: "Created",
793
+ _0: middlewareFileName
794
+ }
795
+ };
796
+ }
797
+ let srcDir = Nodepath2.join(projectDir, "src");
798
+ await Fs2.promises.mkdir(srcDir, {
799
+ recursive: true
800
+ });
801
+ let content = middlewareTemplate(host);
802
+ let e = await writeFile(filePath, content);
803
+ if (e.TAG === "Ok") {
804
+ return {
805
+ TAG: "Ok",
806
+ _0: {
807
+ TAG: "Created",
808
+ _0: middlewareFileName
809
+ }
810
+ };
811
+ } else {
812
+ return {
813
+ TAG: "Error",
814
+ _0: e._0
815
+ };
816
+ }
817
+ } else {
818
+ let existingHost = existingFile.host;
819
+ if (existingHost === host || existingHost === "") {
820
+ return {
821
+ TAG: "Ok",
822
+ _0: {
823
+ TAG: "Skipped",
824
+ _0: middlewareFileName
825
+ }
826
+ };
827
+ }
828
+ if (dryRun) {
829
+ return {
830
+ TAG: "Ok",
831
+ _0: {
832
+ TAG: "Updated",
833
+ fileName: middlewareFileName,
834
+ oldHost: existingHost,
835
+ newHost: host
836
+ }
837
+ };
838
+ }
839
+ let content$1 = await readFile(filePath);
840
+ if (content$1 === void 0) {
841
+ return {
842
+ TAG: "Error",
843
+ _0: `Failed to read ` + middlewareFileName
844
+ };
845
+ }
846
+ let newContent = updateHostInContent(content$1, host);
847
+ let e$1 = await writeFile(filePath, newContent);
848
+ if (e$1.TAG === "Ok") {
849
+ return {
850
+ TAG: "Ok",
851
+ _0: {
852
+ TAG: "Updated",
853
+ fileName: middlewareFileName,
854
+ oldHost: existingHost,
855
+ newHost: host
856
+ }
857
+ };
858
+ } else {
859
+ return {
860
+ TAG: "Error",
861
+ _0: e$1._0
862
+ };
863
+ }
864
+ }
865
+ }
866
+ function formatResult(result) {
867
+ switch (result.TAG) {
868
+ case "Created":
869
+ return SuccessMessages.fileCreated(result._0);
870
+ case "Updated":
871
+ return SuccessMessages.hostUpdated(result.fileName, result.oldHost, result.newHost);
872
+ case "Skipped":
873
+ return SuccessMessages.fileSkipped(result._0);
874
+ case "ManualEditRequired":
875
+ return SuccessMessages.manualEditRequired(result.fileName);
876
+ case "AutoEdited":
877
+ return SuccessMessages.fileAutoEdited(result._0);
878
+ }
879
+ }
880
+
881
+ // ../../node_modules/sury/src/Sury.res.mjs
882
+ function capitalize(string3) {
883
+ return string3.slice(0, 1).toUpperCase() + string3.slice(1);
884
+ }
885
+ var copy = ((d2) => ({ ...d2 }));
886
+ function fromString(string3) {
887
+ let _idx = 0;
888
+ while (true) {
889
+ let idx = _idx;
890
+ let match = string3[idx];
891
+ if (match === void 0) {
892
+ return `"` + string3 + `"`;
893
+ }
894
+ switch (match) {
895
+ case '"':
896
+ case "\n":
897
+ return JSON.stringify(string3);
898
+ default:
899
+ _idx = idx + 1 | 0;
900
+ continue;
901
+ }
902
+ }
903
+ }
904
+ function toArray2(path) {
905
+ if (path === "") {
906
+ return [];
907
+ } else {
908
+ return JSON.parse(path.split(`"]["`).join(`","`));
909
+ }
910
+ }
911
+ var vendor = "sury";
912
+ var s = Symbol(vendor);
913
+ var $$Error = /* @__PURE__ */ create("Sury.Error");
914
+ var constField = "const";
915
+ function has(acc, flag) {
916
+ return (acc & flag) !== 0;
917
+ }
918
+ var flags = {
919
+ unknown: 1,
920
+ string: 2,
921
+ number: 4,
922
+ boolean: 8,
923
+ undefined: 16,
924
+ null: 32,
925
+ object: 64,
926
+ array: 128,
927
+ union: 256,
928
+ ref: 512,
929
+ bigint: 1024,
930
+ nan: 2048,
931
+ "function": 4096,
932
+ instance: 8192,
933
+ never: 16384,
934
+ symbol: 32768
935
+ };
936
+ function stringify(unknown2) {
937
+ let tagFlag = flags[typeof unknown2];
938
+ if (tagFlag & 16) {
939
+ return "undefined";
940
+ }
941
+ if (!(tagFlag & 64)) {
942
+ if (tagFlag & 2) {
943
+ return `"` + unknown2 + `"`;
944
+ } else if (tagFlag & 1024) {
945
+ return unknown2 + `n`;
946
+ } else {
947
+ return unknown2.toString();
948
+ }
949
+ }
950
+ if (unknown2 === null) {
951
+ return "null";
952
+ }
953
+ if (Array.isArray(unknown2)) {
954
+ let string3 = "[";
955
+ for (let i = 0, i_finish = unknown2.length; i < i_finish; ++i) {
956
+ if (i !== 0) {
957
+ string3 = string3 + ", ";
958
+ }
959
+ string3 = string3 + stringify(unknown2[i]);
960
+ }
961
+ return string3 + "]";
962
+ }
963
+ if (unknown2.constructor !== Object) {
964
+ return Object.prototype.toString.call(unknown2);
965
+ }
966
+ let keys = Object.keys(unknown2);
967
+ let string$1 = "{ ";
968
+ for (let i$1 = 0, i_finish$1 = keys.length; i$1 < i_finish$1; ++i$1) {
969
+ let key = keys[i$1];
970
+ let value = unknown2[key];
971
+ string$1 = string$1 + key + `: ` + stringify(value) + `; `;
972
+ }
973
+ return string$1 + "}";
974
+ }
975
+ function toExpression(schema3) {
976
+ let tag = schema3.type;
977
+ let $$const = schema3.const;
978
+ let name = schema3.name;
979
+ if (name !== void 0) {
980
+ return name;
981
+ }
982
+ if ($$const !== void 0) {
983
+ return stringify($$const);
984
+ }
985
+ let format = schema3.format;
986
+ let anyOf = schema3.anyOf;
987
+ if (anyOf !== void 0) {
988
+ return anyOf.map(toExpression).join(" | ");
989
+ }
990
+ if (format !== void 0) {
991
+ return format;
992
+ }
993
+ switch (tag) {
994
+ case "nan":
995
+ return "NaN";
996
+ case "object":
997
+ let additionalItems = schema3.additionalItems;
998
+ let properties = schema3.properties;
999
+ let locations = Object.keys(properties);
1000
+ if (locations.length === 0) {
1001
+ if (typeof additionalItems === "object") {
1002
+ return `{ [key: string]: ` + toExpression(additionalItems) + `; }`;
1003
+ } else {
1004
+ return `{}`;
1005
+ }
1006
+ } else {
1007
+ return `{ ` + locations.map((location) => location + `: ` + toExpression(properties[location]) + `;`).join(" ") + ` }`;
1008
+ }
1009
+ default:
1010
+ if (schema3.b) {
1011
+ return tag;
1012
+ }
1013
+ switch (tag) {
1014
+ case "instance":
1015
+ return schema3.class.name;
1016
+ case "array":
1017
+ let additionalItems$1 = schema3.additionalItems;
1018
+ let items = schema3.items;
1019
+ if (typeof additionalItems$1 !== "object") {
1020
+ return `[` + items.map((item) => toExpression(item.schema)).join(", ") + `]`;
1021
+ }
1022
+ let itemName = toExpression(additionalItems$1);
1023
+ return (additionalItems$1.type === "union" ? `(` + itemName + `)` : itemName) + "[]";
1024
+ default:
1025
+ return tag;
1026
+ }
1027
+ }
1028
+ }
1029
+ var SuryError = class extends Error {
1030
+ constructor(code, flag, path) {
1031
+ super();
1032
+ this.flag = flag;
1033
+ this.code = code;
1034
+ this.path = path;
1035
+ }
1036
+ };
1037
+ var d = Object.defineProperty;
1038
+ var p = SuryError.prototype;
1039
+ d(p, "message", {
1040
+ get() {
1041
+ return message(this);
1042
+ }
1043
+ });
1044
+ d(p, "reason", {
1045
+ get() {
1046
+ return reason(this);
1047
+ }
1048
+ });
1049
+ d(p, "name", { value: "SuryError" });
1050
+ d(p, "s", { value: s });
1051
+ d(p, "_1", {
1052
+ get() {
1053
+ return this;
1054
+ }
1055
+ });
1056
+ d(p, "RE_EXN_ID", {
1057
+ value: $$Error
1058
+ });
1059
+ var Schema = function(type) {
1060
+ this.type = type;
1061
+ };
1062
+ var sp = /* @__PURE__ */ Object.create(null);
1063
+ d(sp, "with", {
1064
+ get() {
1065
+ return (fn, ...args) => fn(this, ...args);
1066
+ }
1067
+ });
1068
+ Schema.prototype = sp;
1069
+ function getOrRethrow(exn) {
1070
+ if (exn && exn.s === s) {
1071
+ return exn;
1072
+ }
1073
+ throw exn;
1074
+ }
1075
+ function reason(error, nestedLevelOpt) {
1076
+ let nestedLevel = nestedLevelOpt !== void 0 ? nestedLevelOpt : 0;
1077
+ let reason$1 = error.code;
1078
+ if (typeof reason$1 !== "object") {
1079
+ return "Encountered unexpected async transform or refine. Use parseAsyncOrThrow operation instead";
1080
+ }
1081
+ switch (reason$1.TAG) {
1082
+ case "OperationFailed":
1083
+ return reason$1._0;
1084
+ case "InvalidOperation":
1085
+ return reason$1.description;
1086
+ case "InvalidType":
1087
+ let unionErrors = reason$1.unionErrors;
1088
+ let m = `Expected ` + toExpression(reason$1.expected) + `, received ` + stringify(reason$1.received);
1089
+ if (unionErrors !== void 0) {
1090
+ let lineBreak = `
1091
+ ` + " ".repeat(nestedLevel << 1);
1092
+ let reasonsDict = {};
1093
+ for (let idx = 0, idx_finish = unionErrors.length; idx < idx_finish; ++idx) {
1094
+ let error$1 = unionErrors[idx];
1095
+ let reason$2 = reason(error$1, nestedLevel + 1);
1096
+ let nonEmptyPath = error$1.path;
1097
+ let location = nonEmptyPath === "" ? "" : `At ` + nonEmptyPath + `: `;
1098
+ let line = `- ` + location + reason$2;
1099
+ if (!reasonsDict[line]) {
1100
+ reasonsDict[line] = 1;
1101
+ m = m + lineBreak + line;
1102
+ }
1103
+ }
1104
+ }
1105
+ return m;
1106
+ case "UnsupportedTransformation":
1107
+ return `Unsupported transformation from ` + toExpression(reason$1.from) + ` to ` + toExpression(reason$1.to);
1108
+ case "ExcessField":
1109
+ return `Unrecognized key "` + reason$1._0 + `"`;
1110
+ case "InvalidJsonSchema":
1111
+ return toExpression(reason$1._0) + ` is not valid JSON`;
1112
+ }
1113
+ }
1114
+ function message(error) {
1115
+ let op = error.flag;
1116
+ let text = "Failed ";
1117
+ if (op & 2) {
1118
+ text = text + "async ";
1119
+ }
1120
+ text = text + (op & 1 ? op & 4 ? "asserting" : "parsing" : "converting");
1121
+ if (op & 8) {
1122
+ text = text + " to JSON" + (op & 16 ? " string" : "");
1123
+ }
1124
+ let nonEmptyPath = error.path;
1125
+ let tmp = nonEmptyPath === "" ? "" : ` at ` + nonEmptyPath;
1126
+ return text + tmp + `: ` + reason(error, void 0);
1127
+ }
1128
+ var globalConfig = {
1129
+ a: "strip"};
1130
+ var shakenRef = "as";
1131
+ var shakenTraps = {
1132
+ get: (target, prop) => {
1133
+ let l = target[shakenRef];
1134
+ if (l === void 0) {
1135
+ return target[prop];
1136
+ }
1137
+ if (prop === shakenRef) {
1138
+ return target[prop];
1139
+ }
1140
+ let l$1 = valFromOption(l);
1141
+ let message2 = `Schema S.` + l$1 + ` is not enabled. To start using it, add S.enable` + capitalize(l$1) + `() at the project root.`;
1142
+ throw new Error(`[Sury] ` + message2);
1143
+ }
1144
+ };
1145
+ function shaken(apiName) {
1146
+ let mut = new Schema("never");
1147
+ mut[shakenRef] = apiName;
1148
+ return new Proxy(mut, shakenTraps);
1149
+ }
1150
+ var unknown = new Schema("unknown");
1151
+ var string = new Schema("string");
1152
+ var int = new Schema("number");
1153
+ int.format = "int32";
1154
+ var unit = new Schema("undefined");
1155
+ unit.const = void 0;
1156
+ var copyWithoutCache = ((schema3) => {
1157
+ let c = new Schema(schema3.type);
1158
+ for (let k in schema3) {
1159
+ if (k > "a" || k === "$ref" || k === "$defs") {
1160
+ c[k] = schema3[k];
1161
+ }
1162
+ }
1163
+ return c;
1164
+ });
1165
+ function updateOutput(schema3, fn) {
1166
+ let root = copyWithoutCache(schema3);
1167
+ let mut = root;
1168
+ while (mut.to) {
1169
+ let next = copyWithoutCache(mut.to);
1170
+ mut.to = next;
1171
+ mut = next;
1172
+ }
1173
+ fn(mut);
1174
+ return root;
1175
+ }
1176
+ function embed(b, value) {
1177
+ let e = b.g.e;
1178
+ let l = e.length;
1179
+ e[l] = value;
1180
+ return `e[` + l + `]`;
1181
+ }
1182
+ function inlineConst(b, schema3) {
1183
+ let tagFlag = flags[schema3.type];
1184
+ let $$const = schema3.const;
1185
+ if (tagFlag & 16) {
1186
+ return "void 0";
1187
+ } else if (tagFlag & 2) {
1188
+ return fromString($$const);
1189
+ } else if (tagFlag & 1024) {
1190
+ return $$const + "n";
1191
+ } else if (tagFlag & 45056) {
1192
+ return embed(b, schema3.const);
1193
+ } else {
1194
+ return $$const;
1195
+ }
1196
+ }
1197
+ function inlineLocation(b, location) {
1198
+ let key = `"` + location + `"`;
1199
+ let i = b.g[key];
1200
+ if (i !== void 0) {
1201
+ return i;
1202
+ }
1203
+ let inlinedLocation = fromString(location);
1204
+ b.g[key] = inlinedLocation;
1205
+ return inlinedLocation;
1206
+ }
1207
+ function secondAllocate(v) {
1208
+ let b = this;
1209
+ b.l = b.l + "," + v;
1210
+ }
1211
+ function initialAllocate(v) {
1212
+ let b = this;
1213
+ b.l = v;
1214
+ b.a = secondAllocate;
1215
+ }
1216
+ function rootScope(flag, defs) {
1217
+ let global2 = {
1218
+ c: "",
1219
+ l: "",
1220
+ a: initialAllocate,
1221
+ v: -1,
1222
+ o: flag,
1223
+ f: "",
1224
+ e: [],
1225
+ d: defs
1226
+ };
1227
+ global2.g = global2;
1228
+ return global2;
1229
+ }
1230
+ function allocateScope(b) {
1231
+ delete b.a;
1232
+ let varsAllocation = b.l;
1233
+ if (varsAllocation === "") {
1234
+ return b.f + b.c;
1235
+ } else {
1236
+ return b.f + `let ` + varsAllocation + `;` + b.c;
1237
+ }
1238
+ }
1239
+ function varWithoutAllocation(global2) {
1240
+ let newCounter = global2.v + 1;
1241
+ global2.v = newCounter;
1242
+ return `v` + newCounter;
1243
+ }
1244
+ function _var(_b) {
1245
+ return this.i;
1246
+ }
1247
+ function _notVar(b) {
1248
+ let val2 = this;
1249
+ let v = varWithoutAllocation(b.g);
1250
+ let i = val2.i;
1251
+ if (i === "") {
1252
+ val2.b.a(v);
1253
+ } else if (b.a !== void 0) {
1254
+ b.a(v + `=` + i);
1255
+ } else {
1256
+ b.c = b.c + (v + `=` + i + `;`);
1257
+ b.g.a(v);
1258
+ }
1259
+ val2.v = _var;
1260
+ val2.i = v;
1261
+ return v;
1262
+ }
1263
+ function allocateVal(b, schema3) {
1264
+ let v = varWithoutAllocation(b.g);
1265
+ b.a(v);
1266
+ return {
1267
+ b,
1268
+ v: _var,
1269
+ i: v,
1270
+ f: 0,
1271
+ type: schema3.type
1272
+ };
1273
+ }
1274
+ function val(b, initial, schema3) {
1275
+ return {
1276
+ b,
1277
+ v: _notVar,
1278
+ i: initial,
1279
+ f: 0,
1280
+ type: schema3.type
1281
+ };
1282
+ }
1283
+ function constVal(b, schema3) {
1284
+ return {
1285
+ b,
1286
+ v: _notVar,
1287
+ i: inlineConst(b, schema3),
1288
+ f: 0,
1289
+ type: schema3.type,
1290
+ const: schema3.const
1291
+ };
1292
+ }
1293
+ function objectJoin(inlinedLocation, value) {
1294
+ return inlinedLocation + `:` + value + `,`;
1295
+ }
1296
+ function arrayJoin(_inlinedLocation, value) {
1297
+ return value + ",";
1298
+ }
1299
+ function make(b, isArray) {
1300
+ return {
1301
+ b,
1302
+ v: _notVar,
1303
+ i: "",
1304
+ f: 0,
1305
+ type: isArray ? "array" : "object",
1306
+ properties: {},
1307
+ additionalItems: "strict",
1308
+ j: isArray ? arrayJoin : objectJoin,
1309
+ c: 0,
1310
+ r: ""
1311
+ };
1312
+ }
1313
+ function add(objectVal, location, val2) {
1314
+ let inlinedLocation = inlineLocation(objectVal.b, location);
1315
+ objectVal.properties[location] = val2;
1316
+ if (val2.f & 2) {
1317
+ objectVal.r = objectVal.r + val2.i + ",";
1318
+ objectVal.i = objectVal.i + objectVal.j(inlinedLocation, `a[` + objectVal.c++ + `]`);
1319
+ } else {
1320
+ objectVal.i = objectVal.i + objectVal.j(inlinedLocation, val2.i);
1321
+ }
1322
+ }
1323
+ function complete(objectVal, isArray) {
1324
+ objectVal.i = isArray ? "[" + objectVal.i + "]" : "{" + objectVal.i + "}";
1325
+ if (objectVal.c) {
1326
+ objectVal.f = objectVal.f | 2;
1327
+ objectVal.i = `Promise.all([` + objectVal.r + `]).then(a=>(` + objectVal.i + `))`;
1328
+ }
1329
+ objectVal.additionalItems = "strict";
1330
+ return objectVal;
1331
+ }
1332
+ function set(b, input, val2) {
1333
+ if (input === val2) {
1334
+ return "";
1335
+ }
1336
+ let inputVar = input.v(b);
1337
+ let match = input.f & 2;
1338
+ let match$1 = val2.f & 2;
1339
+ if (match) {
1340
+ if (!match$1) {
1341
+ return inputVar + `=Promise.resolve(` + val2.i + `)`;
1342
+ }
1343
+ } else if (match$1) {
1344
+ input.f = input.f | 2;
1345
+ return inputVar + `=` + val2.i;
1346
+ }
1347
+ return inputVar + `=` + val2.i;
1348
+ }
1349
+ function get(b, targetVal, location) {
1350
+ let properties = targetVal.properties;
1351
+ let val2 = properties[location];
1352
+ if (val2 !== void 0) {
1353
+ return val2;
1354
+ }
1355
+ let schema3 = targetVal.additionalItems;
1356
+ let schema$1;
1357
+ if (schema3 === "strip" || schema3 === "strict") {
1358
+ if (schema3 === "strip") {
1359
+ throw new Error(`[Sury] The schema doesn't have additional items`);
1360
+ }
1361
+ throw new Error(`[Sury] The schema doesn't have additional items`);
1362
+ } else {
1363
+ schema$1 = schema3;
1364
+ }
1365
+ let val$1 = {
1366
+ b,
1367
+ v: _notVar,
1368
+ i: targetVal.v(b) + (`[` + fromString(location) + `]`),
1369
+ f: 0,
1370
+ type: schema$1.type
1371
+ };
1372
+ properties[location] = val$1;
1373
+ return val$1;
1374
+ }
1375
+ function setInlined(b, input, inlined) {
1376
+ return input.v(b) + `=` + inlined;
1377
+ }
1378
+ function map2(inlinedFn, input) {
1379
+ return {
1380
+ b: input.b,
1381
+ v: _notVar,
1382
+ i: inlinedFn + `(` + input.i + `)`,
1383
+ f: 0,
1384
+ type: "unknown"
1385
+ };
1386
+ }
1387
+ function $$throw(b, code, path) {
1388
+ throw new SuryError(code, b.g.o, path);
1389
+ }
1390
+ function failWithArg(b, path, fn, arg) {
1391
+ return embed(b, (arg2) => $$throw(b, fn(arg2), path)) + `(` + arg + `)`;
1392
+ }
1393
+ function withPathPrepend(b, input, path, maybeDynamicLocationVar, appendSafe, fn) {
1394
+ if (path === "" && maybeDynamicLocationVar === void 0) {
1395
+ return fn(b, input, path);
1396
+ }
1397
+ try {
1398
+ let $$catch = (b2, errorVar2) => {
1399
+ b2.c = errorVar2 + `.path=` + fromString(path) + `+` + (maybeDynamicLocationVar !== void 0 ? `'["'+` + maybeDynamicLocationVar + `+'"]'+` : "") + errorVar2 + `.path`;
1400
+ };
1401
+ let fn$1 = (b2) => fn(b2, input, "");
1402
+ let prevCode = b.c;
1403
+ b.c = "";
1404
+ let errorVar = varWithoutAllocation(b.g);
1405
+ let maybeResolveVal = $$catch(b, errorVar);
1406
+ let catchCode = `if(` + (errorVar + `&&` + errorVar + `.s===s`) + `){` + b.c;
1407
+ b.c = "";
1408
+ let bb = {
1409
+ c: "",
1410
+ l: "",
1411
+ a: initialAllocate,
1412
+ f: "",
1413
+ g: b.g
1414
+ };
1415
+ let fnOutput = fn$1(bb);
1416
+ b.c = b.c + allocateScope(bb);
1417
+ let isNoop = fnOutput.i === input.i && b.c === "";
1418
+ if (appendSafe !== void 0) ;
1419
+ if (isNoop) {
1420
+ return fnOutput;
1421
+ }
1422
+ let isAsync2 = fnOutput.f & 2;
1423
+ let output = input === fnOutput ? input : appendSafe !== void 0 ? fnOutput : {
1424
+ b,
1425
+ v: _notVar,
1426
+ i: "",
1427
+ f: isAsync2 ? 2 : 0,
1428
+ type: "unknown"
1429
+ };
1430
+ let catchCode$1 = maybeResolveVal !== void 0 ? (catchLocation) => catchCode + (catchLocation === 1 ? `return ` + maybeResolveVal.i : set(b, output, maybeResolveVal)) + (`}else{throw ` + errorVar + `}`) : (param) => catchCode + `}throw ` + errorVar;
1431
+ b.c = prevCode + (`try{` + b.c + (isAsync2 ? setInlined(b, output, fnOutput.i + `.catch(` + errorVar + `=>{` + catchCode$1(1) + `})`) : set(b, output, fnOutput)) + `}catch(` + errorVar + `){` + catchCode$1(0) + `}`);
1432
+ return output;
1433
+ } catch (exn) {
1434
+ let error = getOrRethrow(exn);
1435
+ throw new SuryError(error.code, error.flag, path + "[]" + error.path);
1436
+ }
1437
+ }
1438
+ function validation(b, inputVar, schema3, negative) {
1439
+ let eq = "!==" ;
1440
+ let and_ = "||" ;
1441
+ let exp = "!" ;
1442
+ let tag = schema3.type;
1443
+ let tagFlag = flags[tag];
1444
+ if (tagFlag & 2048) {
1445
+ return exp + (`Number.isNaN(` + inputVar + `)`);
1446
+ }
1447
+ if (constField in schema3) {
1448
+ return inputVar + eq + inlineConst(b, schema3);
1449
+ }
1450
+ if (tagFlag & 4) {
1451
+ return `typeof ` + inputVar + eq + `"` + tag + `"`;
1452
+ }
1453
+ if (tagFlag & 64) {
1454
+ return `typeof ` + inputVar + eq + `"` + tag + `"` + and_ + exp + inputVar;
1455
+ }
1456
+ if (tagFlag & 128) {
1457
+ return exp + `Array.isArray(` + inputVar + `)`;
1458
+ }
1459
+ if (!(tagFlag & 8192)) {
1460
+ return `typeof ` + inputVar + eq + `"` + tag + `"`;
1461
+ }
1462
+ let c = inputVar + ` instanceof ` + embed(b, schema3.class);
1463
+ {
1464
+ return `!(` + c + `)`;
1465
+ }
1466
+ }
1467
+ function refinement(b, inputVar, schema3, negative) {
1468
+ let eq = "!==" ;
1469
+ let and_ = "||" ;
1470
+ let not_ = "" ;
1471
+ let lt = ">" ;
1472
+ let gt = "<" ;
1473
+ let match = schema3.type;
1474
+ let tag;
1475
+ let exit2 = 0;
1476
+ let match$1 = schema3.const;
1477
+ if (match$1 !== void 0) {
1478
+ return "";
1479
+ }
1480
+ let match$2 = schema3.format;
1481
+ if (match$2 !== void 0) {
1482
+ switch (match$2) {
1483
+ case "int32":
1484
+ return and_ + inputVar + lt + `2147483647` + and_ + inputVar + gt + `-2147483648` + and_ + inputVar + `%1` + eq + `0`;
1485
+ case "port":
1486
+ case "json":
1487
+ exit2 = 2;
1488
+ break;
1489
+ }
1490
+ } else {
1491
+ exit2 = 2;
1492
+ }
1493
+ if (exit2 === 2) {
1494
+ switch (match) {
1495
+ case "number":
1496
+ {
1497
+ return and_ + not_ + `Number.isNaN(` + inputVar + `)`;
1498
+ }
1499
+ case "array":
1500
+ case "object":
1501
+ tag = match;
1502
+ break;
1503
+ default:
1504
+ return "";
1505
+ }
1506
+ }
1507
+ let additionalItems = schema3.additionalItems;
1508
+ let items = schema3.items;
1509
+ let length2 = items.length;
1510
+ let code = tag === "array" ? additionalItems === "strip" || additionalItems === "strict" ? additionalItems === "strip" ? and_ + inputVar + `.length` + gt + length2 : and_ + inputVar + `.length` + eq + length2 : "" : additionalItems === "strip" ? "" : and_ + not_ + `Array.isArray(` + inputVar + `)`;
1511
+ for (let idx = 0, idx_finish = items.length; idx < idx_finish; ++idx) {
1512
+ let match$3 = items[idx];
1513
+ let location = match$3.location;
1514
+ let item = match$3.schema;
1515
+ let itemCode;
1516
+ if (constField in item || schema3.unnest) {
1517
+ let inlinedLocation = inlineLocation(b, location);
1518
+ itemCode = validation(b, inputVar + (`[` + inlinedLocation + `]`), item);
1519
+ } else if (item.items) {
1520
+ let inlinedLocation$1 = inlineLocation(b, location);
1521
+ let inputVar$1 = inputVar + (`[` + inlinedLocation$1 + `]`);
1522
+ itemCode = validation(b, inputVar$1, item) + refinement(b, inputVar$1, item);
1523
+ } else {
1524
+ itemCode = "";
1525
+ }
1526
+ if (itemCode !== "") {
1527
+ code = code + and_ + itemCode;
1528
+ }
1529
+ }
1530
+ return code;
1531
+ }
1532
+ function makeRefinedOf(b, input, schema3) {
1533
+ let mut = {
1534
+ b,
1535
+ v: input.v,
1536
+ i: input.i,
1537
+ f: input.f,
1538
+ type: schema3.type
1539
+ };
1540
+ let loop = (mut2, schema4) => {
1541
+ if (constField in schema4) {
1542
+ mut2.const = schema4.const;
1543
+ }
1544
+ let items = schema4.items;
1545
+ if (items === void 0) {
1546
+ return;
1547
+ }
1548
+ let properties = {};
1549
+ items.forEach((item) => {
1550
+ let schema5 = item.schema;
1551
+ let isConst = constField in schema5;
1552
+ if (!(isConst || schema5.items)) {
1553
+ return;
1554
+ }
1555
+ let tmp;
1556
+ if (isConst) {
1557
+ tmp = inlineConst(b, schema5);
1558
+ } else {
1559
+ let inlinedLocation = inlineLocation(b, item.location);
1560
+ tmp = mut2.v(b) + (`[` + inlinedLocation + `]`);
1561
+ }
1562
+ let mut$1 = {
1563
+ b: mut2.b,
1564
+ v: _notVar,
1565
+ i: tmp,
1566
+ f: 0,
1567
+ type: schema5.type
1568
+ };
1569
+ loop(mut$1, schema5);
1570
+ properties[item.location] = mut$1;
1571
+ });
1572
+ mut2.properties = properties;
1573
+ mut2.additionalItems = unknown;
1574
+ };
1575
+ loop(mut, schema3);
1576
+ return mut;
1577
+ }
1578
+ function typeFilterCode(b, schema3, input, path) {
1579
+ if (schema3.noValidation || flags[schema3.type] & 17153) {
1580
+ return "";
1581
+ }
1582
+ let inputVar = input.v(b);
1583
+ return `if(` + validation(b, inputVar, schema3) + refinement(b, inputVar, schema3) + `){` + failWithArg(b, path, (input2) => ({
1584
+ TAG: "InvalidType",
1585
+ expected: schema3,
1586
+ received: input2
1587
+ }), inputVar) + `}`;
1588
+ }
1589
+ function unsupportedTransform(b, from, target, path) {
1590
+ return $$throw(b, {
1591
+ TAG: "UnsupportedTransformation",
1592
+ from,
1593
+ to: target
1594
+ }, path);
1595
+ }
1596
+ function noopOperation(i) {
1597
+ return i;
1598
+ }
1599
+ function setHas(has2, tag) {
1600
+ has2[tag === "union" || tag === "ref" ? "unknown" : tag] = true;
1601
+ }
1602
+ var jsonName = `JSON`;
1603
+ var jsonString = shaken("jsonString");
1604
+ function inputToString(b, input) {
1605
+ return val(b, `""+` + input.i, string);
1606
+ }
1607
+ function parse(prevB, schema3, inputArg, path) {
1608
+ let b = {
1609
+ c: "",
1610
+ l: "",
1611
+ a: initialAllocate,
1612
+ f: "",
1613
+ g: prevB.g
1614
+ };
1615
+ if (schema3.$defs) {
1616
+ b.g.d = schema3.$defs;
1617
+ }
1618
+ let input = inputArg;
1619
+ let isFromLiteral = constField in input;
1620
+ let isSchemaLiteral = constField in schema3;
1621
+ let isSameTag = input.type === schema3.type;
1622
+ let schemaTagFlag = flags[schema3.type];
1623
+ let inputTagFlag = flags[input.type];
1624
+ let isUnsupported = false;
1625
+ if (!(schemaTagFlag & 257 || schema3.format === "json")) {
1626
+ if (schema3.name === jsonName && !(inputTagFlag & 1)) {
1627
+ if (!(inputTagFlag & 14)) {
1628
+ if (inputTagFlag & 1024) {
1629
+ input = inputToString(b, input);
1630
+ } else {
1631
+ isUnsupported = true;
1632
+ }
1633
+ }
1634
+ } else if (isSchemaLiteral) {
1635
+ if (isFromLiteral) {
1636
+ if (input.const !== schema3.const) {
1637
+ input = constVal(b, schema3);
1638
+ }
1639
+ } else if (inputTagFlag & 2 && schemaTagFlag & 3132) {
1640
+ let inputVar = input.v(b);
1641
+ b.f = schema3.noValidation ? "" : input.i + `==="` + schema3.const + `"||` + failWithArg(b, path, (input2) => ({
1642
+ TAG: "InvalidType",
1643
+ expected: schema3,
1644
+ received: input2
1645
+ }), inputVar) + `;`;
1646
+ input = constVal(b, schema3);
1647
+ } else if (schema3.noValidation) {
1648
+ input = constVal(b, schema3);
1649
+ } else {
1650
+ b.f = typeFilterCode(prevB, schema3, input, path);
1651
+ input.type = schema3.type;
1652
+ input.const = schema3.const;
1653
+ }
1654
+ } else if (isFromLiteral && !isSchemaLiteral) {
1655
+ if (!isSameTag) {
1656
+ if (schemaTagFlag & 2 && inputTagFlag & 3132) {
1657
+ let $$const = "" + input.const;
1658
+ input = {
1659
+ b,
1660
+ v: _notVar,
1661
+ i: `"` + $$const + `"`,
1662
+ f: 0,
1663
+ type: "string",
1664
+ const: $$const
1665
+ };
1666
+ } else {
1667
+ isUnsupported = true;
1668
+ }
1669
+ }
1670
+ } else if (inputTagFlag & 1) {
1671
+ let ref = schema3.$ref;
1672
+ if (ref !== void 0) {
1673
+ let defs = b.g.d;
1674
+ let identifier = ref.slice(8);
1675
+ let def = defs[identifier];
1676
+ let flag = schema3.noValidation ? (b.g.o | 1) ^ 1 : b.g.o;
1677
+ let fn = def[flag];
1678
+ let recOperation;
1679
+ if (fn !== void 0) {
1680
+ let fn$1 = valFromOption(fn);
1681
+ recOperation = fn$1 === 0 ? embed(b, def) + (`[` + flag + `]`) : embed(b, fn$1);
1682
+ } else {
1683
+ def[flag] = 0;
1684
+ let fn$2 = internalCompile(def, flag, b.g.d);
1685
+ def[flag] = fn$2;
1686
+ recOperation = embed(b, fn$2);
1687
+ }
1688
+ input = withPathPrepend(b, input, path, void 0, void 0, (param, input2, param$1) => {
1689
+ let output = map2(recOperation, input2);
1690
+ if (def.isAsync === void 0) {
1691
+ let defsMut = copy(defs);
1692
+ defsMut[identifier] = unknown;
1693
+ isAsyncInternal(def, defsMut);
1694
+ }
1695
+ if (def.isAsync) {
1696
+ output.f = output.f | 2;
1697
+ }
1698
+ return output;
1699
+ });
1700
+ input.v(b);
1701
+ } else {
1702
+ if (b.g.o & 1) {
1703
+ b.f = typeFilterCode(prevB, schema3, input, path);
1704
+ }
1705
+ let refined = makeRefinedOf(b, input, schema3);
1706
+ input.type = refined.type;
1707
+ input.i = refined.i;
1708
+ input.v = refined.v;
1709
+ input.additionalItems = refined.additionalItems;
1710
+ input.properties = refined.properties;
1711
+ if (constField in refined) {
1712
+ input.const = refined.const;
1713
+ }
1714
+ }
1715
+ } else if (schemaTagFlag & 2 && inputTagFlag & 1036) {
1716
+ input = inputToString(b, input);
1717
+ } else if (!isSameTag) {
1718
+ if (inputTagFlag & 2) {
1719
+ let inputVar$1 = input.v(b);
1720
+ if (schemaTagFlag & 8) {
1721
+ let output = allocateVal(b, schema3);
1722
+ b.c = b.c + (`(` + output.i + `=` + inputVar$1 + `==="true")||` + inputVar$1 + `==="false"||` + failWithArg(b, path, (input2) => ({
1723
+ TAG: "InvalidType",
1724
+ expected: schema3,
1725
+ received: input2
1726
+ }), inputVar$1) + `;`);
1727
+ input = output;
1728
+ } else if (schemaTagFlag & 4) {
1729
+ let output$1 = val(b, `+` + inputVar$1, schema3);
1730
+ let outputVar = output$1.v(b);
1731
+ let match = schema3.format;
1732
+ b.c = b.c + (match !== void 0 ? `(` + refinement(b, outputVar, schema3).slice(2) + `)` : `Number.isNaN(` + outputVar + `)`) + (`&&` + failWithArg(b, path, (input2) => ({
1733
+ TAG: "InvalidType",
1734
+ expected: schema3,
1735
+ received: input2
1736
+ }), inputVar$1) + `;`);
1737
+ input = output$1;
1738
+ } else if (schemaTagFlag & 1024) {
1739
+ let output$2 = allocateVal(b, schema3);
1740
+ b.c = b.c + (`try{` + output$2.i + `=BigInt(` + inputVar$1 + `)}catch(_){` + failWithArg(b, path, (input2) => ({
1741
+ TAG: "InvalidType",
1742
+ expected: schema3,
1743
+ received: input2
1744
+ }), inputVar$1) + `}`);
1745
+ input = output$2;
1746
+ } else {
1747
+ isUnsupported = true;
1748
+ }
1749
+ } else if (inputTagFlag & 4 && schemaTagFlag & 1024) {
1750
+ input = val(b, `BigInt(` + input.i + `)`, schema3);
1751
+ } else {
1752
+ isUnsupported = true;
1753
+ }
1754
+ }
1755
+ }
1756
+ if (isUnsupported) {
1757
+ unsupportedTransform(b, input, schema3, path);
1758
+ }
1759
+ let compiler = schema3.compiler;
1760
+ if (compiler !== void 0) {
1761
+ input = compiler(b, input, schema3, path);
1762
+ }
1763
+ if (input.t !== true) {
1764
+ let refiner = schema3.refiner;
1765
+ if (refiner !== void 0) {
1766
+ b.c = b.c + refiner(b, input.v(b), schema3, path);
1767
+ }
1768
+ }
1769
+ let to2 = schema3.to;
1770
+ if (to2 !== void 0) {
1771
+ let parser = schema3.parser;
1772
+ if (parser !== void 0) {
1773
+ input = parser(b, input, schema3, path);
1774
+ }
1775
+ if (input.t !== true) {
1776
+ input = parse(b, to2, input, path);
1777
+ }
1778
+ }
1779
+ prevB.c = prevB.c + allocateScope(b);
1780
+ return input;
1781
+ }
1782
+ function isAsyncInternal(schema3, defs) {
1783
+ try {
1784
+ let b = rootScope(2, defs);
1785
+ let input = {
1786
+ b,
1787
+ v: _var,
1788
+ i: "i",
1789
+ f: 0,
1790
+ type: "unknown"
1791
+ };
1792
+ let output = parse(b, schema3, input, "");
1793
+ let isAsync2 = has(output.f, 2);
1794
+ schema3.isAsync = isAsync2;
1795
+ return isAsync2;
1796
+ } catch (exn) {
1797
+ getOrRethrow(exn);
1798
+ return false;
1799
+ }
1800
+ }
1801
+ function internalCompile(schema3, flag, defs) {
1802
+ let b = rootScope(flag, defs);
1803
+ if (flag & 8) {
1804
+ let output = reverse(schema3);
1805
+ jsonableValidation(output, output, "", flag);
1806
+ }
1807
+ let input = {
1808
+ b,
1809
+ v: _var,
1810
+ i: "i",
1811
+ f: 0,
1812
+ type: "unknown"
1813
+ };
1814
+ let schema$1 = flag & 4 ? updateOutput(schema3, (mut) => {
1815
+ let t = new Schema(unit.type);
1816
+ t.const = unit.const;
1817
+ t.noValidation = true;
1818
+ mut.to = t;
1819
+ }) : flag & 16 ? updateOutput(schema3, (mut) => {
1820
+ mut.to = jsonString;
1821
+ }) : schema3;
1822
+ let output$1 = parse(b, schema$1, input, "");
1823
+ let code = allocateScope(b);
1824
+ let isAsync2 = has(output$1.f, 2);
1825
+ schema$1.isAsync = isAsync2;
1826
+ if (code === "" && output$1 === input && !(flag & 2)) {
1827
+ return noopOperation;
1828
+ }
1829
+ let inlinedOutput = output$1.i;
1830
+ if (flag & 2 && !isAsync2 && !defs) {
1831
+ inlinedOutput = `Promise.resolve(` + inlinedOutput + `)`;
1832
+ }
1833
+ let inlinedFunction = `i=>{` + code + `return ` + inlinedOutput + `}`;
1834
+ let ctxVarValue1 = b.g.e;
1835
+ return new Function("e", "s", `return ` + inlinedFunction)(ctxVarValue1, s);
1836
+ }
1837
+ function reverse(schema3) {
1838
+ let reversedHead;
1839
+ let current = schema3;
1840
+ while (current) {
1841
+ let mut = copyWithoutCache(current);
1842
+ let next = mut.to;
1843
+ let to2 = reversedHead;
1844
+ if (to2 !== void 0) {
1845
+ mut.to = to2;
1846
+ } else {
1847
+ delete mut.to;
1848
+ }
1849
+ let parser = mut.parser;
1850
+ let serializer = mut.serializer;
1851
+ if (serializer !== void 0) {
1852
+ mut.parser = serializer;
1853
+ } else {
1854
+ delete mut.parser;
1855
+ }
1856
+ if (parser !== void 0) {
1857
+ mut.serializer = parser;
1858
+ } else {
1859
+ delete mut.serializer;
1860
+ }
1861
+ let fromDefault = mut.fromDefault;
1862
+ let $$default = mut.default;
1863
+ if ($$default !== void 0) {
1864
+ mut.fromDefault = $$default;
1865
+ } else {
1866
+ delete mut.fromDefault;
1867
+ }
1868
+ if (fromDefault !== void 0) {
1869
+ mut.default = fromDefault;
1870
+ } else {
1871
+ delete mut.default;
1872
+ }
1873
+ let items = mut.items;
1874
+ if (items !== void 0) {
1875
+ let properties = {};
1876
+ let newItems = new Array(items.length);
1877
+ for (let idx = 0, idx_finish = items.length; idx < idx_finish; ++idx) {
1878
+ let item = items[idx];
1879
+ let reversed_schema = reverse(item.schema);
1880
+ let reversed_location = item.location;
1881
+ let reversed = {
1882
+ schema: reversed_schema,
1883
+ location: reversed_location
1884
+ };
1885
+ if (item.r) {
1886
+ reversed.r = item.r;
1887
+ }
1888
+ properties[item.location] = reversed_schema;
1889
+ newItems[idx] = reversed;
1890
+ }
1891
+ mut.items = newItems;
1892
+ let match = mut.properties;
1893
+ if (match !== void 0) {
1894
+ mut.properties = properties;
1895
+ }
1896
+ }
1897
+ if (typeof mut.additionalItems === "object") {
1898
+ mut.additionalItems = reverse(mut.additionalItems);
1899
+ }
1900
+ let anyOf = mut.anyOf;
1901
+ if (anyOf !== void 0) {
1902
+ let has2 = {};
1903
+ let newAnyOf = [];
1904
+ for (let idx$1 = 0, idx_finish$1 = anyOf.length; idx$1 < idx_finish$1; ++idx$1) {
1905
+ let s2 = anyOf[idx$1];
1906
+ let reversed$1 = reverse(s2);
1907
+ newAnyOf.push(reversed$1);
1908
+ setHas(has2, reversed$1.type);
1909
+ }
1910
+ mut.has = has2;
1911
+ mut.anyOf = newAnyOf;
1912
+ }
1913
+ let defs = mut.$defs;
1914
+ if (defs !== void 0) {
1915
+ let reversedDefs = {};
1916
+ for (let idx$2 = 0, idx_finish$2 = Object.keys(defs).length; idx$2 < idx_finish$2; ++idx$2) {
1917
+ let key = Object.keys(defs)[idx$2];
1918
+ reversedDefs[key] = reverse(defs[key]);
1919
+ }
1920
+ mut.$defs = reversedDefs;
1921
+ }
1922
+ reversedHead = mut;
1923
+ current = next;
1924
+ }
1925
+ return reversedHead;
1926
+ }
1927
+ function jsonableValidation(output, parent, path, flag) {
1928
+ let tagFlag = flags[output.type];
1929
+ if (tagFlag & 48129 || tagFlag & 16 && parent.type !== "object") {
1930
+ throw new SuryError({
1931
+ TAG: "InvalidJsonSchema",
1932
+ _0: parent
1933
+ }, flag, path);
1934
+ }
1935
+ if (tagFlag & 256) {
1936
+ output.anyOf.forEach((s2) => jsonableValidation(s2, parent, path, flag));
1937
+ return;
1938
+ }
1939
+ if (!(tagFlag & 192)) {
1940
+ return;
1941
+ }
1942
+ let additionalItems = output.additionalItems;
1943
+ if (additionalItems === "strip" || additionalItems === "strict") ; else {
1944
+ jsonableValidation(additionalItems, parent, path, flag);
1945
+ }
1946
+ let p2 = output.properties;
1947
+ if (p2 !== void 0) {
1948
+ let keys = Object.keys(p2);
1949
+ for (let idx = 0, idx_finish = keys.length; idx < idx_finish; ++idx) {
1950
+ let key = keys[idx];
1951
+ jsonableValidation(p2[key], parent, path, flag);
1952
+ }
1953
+ return;
1954
+ }
1955
+ output.items.forEach((item) => jsonableValidation(item.schema, output, path + (`[` + fromString(item.location) + `]`), flag));
1956
+ }
1957
+ function operationFn(s2, o) {
1958
+ if (o in s2) {
1959
+ return s2[o];
1960
+ }
1961
+ let f = internalCompile(s2, o, 0);
1962
+ s2[o] = f;
1963
+ return f;
1964
+ }
1965
+ d(sp, "~standard", {
1966
+ get: function() {
1967
+ let schema3 = this;
1968
+ return {
1969
+ version: 1,
1970
+ vendor,
1971
+ validate: (input) => {
1972
+ try {
1973
+ return {
1974
+ value: operationFn(schema3, 1)(input)
1975
+ };
1976
+ } catch (exn) {
1977
+ let error = getOrRethrow(exn);
1978
+ return {
1979
+ issues: [{
1980
+ message: reason(error, void 0),
1981
+ path: error.path === "" ? void 0 : toArray2(error.path)
1982
+ }]
1983
+ };
1984
+ }
1985
+ }
1986
+ };
1987
+ }
1988
+ });
1989
+ function parseOrThrow(any, schema3) {
1990
+ return operationFn(schema3, 1)(any);
1991
+ }
1992
+ function parseJsonStringOrThrow(jsonString2, schema3) {
1993
+ let tmp;
1994
+ try {
1995
+ tmp = JSON.parse(jsonString2);
1996
+ } catch (exn) {
1997
+ throw new SuryError({
1998
+ TAG: "OperationFailed",
1999
+ _0: exn.message
2000
+ }, 1, "");
2001
+ }
2002
+ return parseOrThrow(tmp, schema3);
2003
+ }
2004
+ var $$null = new Schema("null");
2005
+ $$null.const = null;
2006
+ function parse$1(value) {
2007
+ if (value === null) {
2008
+ return $$null;
2009
+ }
2010
+ let $$typeof = typeof value;
2011
+ let schema3;
2012
+ if ($$typeof === "object") {
2013
+ let i = new Schema("instance");
2014
+ i.class = value.constructor;
2015
+ schema3 = i;
2016
+ } else {
2017
+ schema3 = $$typeof === "undefined" ? unit : $$typeof === "number" ? Number.isNaN(value) ? new Schema("nan") : new Schema($$typeof) : new Schema($$typeof);
2018
+ }
2019
+ schema3.const = value;
2020
+ return schema3;
2021
+ }
2022
+ var nullAsUnit = new Schema("null");
2023
+ nullAsUnit.const = null;
2024
+ nullAsUnit.to = unit;
2025
+ function neverBuilder(b, input, selfSchema, path) {
2026
+ b.c = b.c + failWithArg(b, path, (input2) => ({
2027
+ TAG: "InvalidType",
2028
+ expected: selfSchema,
2029
+ received: input2
2030
+ }), input.i) + ";";
2031
+ return input;
2032
+ }
2033
+ var never = new Schema("never");
2034
+ never.compiler = neverBuilder;
2035
+ shaken("json");
2036
+ function objectStrictModeCheck(b, input, items, selfSchema, path) {
2037
+ if (!(selfSchema.type === "object" && selfSchema.additionalItems === "strict" && b.g.o & 1)) {
2038
+ return;
2039
+ }
2040
+ let key = allocateVal(b, unknown);
2041
+ let keyVar = key.i;
2042
+ b.c = b.c + (`for(` + keyVar + ` in ` + input.v(b) + `){if(`);
2043
+ if (items.length !== 0) {
2044
+ for (let idx = 0, idx_finish = items.length; idx < idx_finish; ++idx) {
2045
+ let match = items[idx];
2046
+ if (idx !== 0) {
2047
+ b.c = b.c + "&&";
2048
+ }
2049
+ b.c = b.c + (keyVar + `!==` + inlineLocation(b, match.location));
2050
+ }
2051
+ } else {
2052
+ b.c = b.c + "true";
2053
+ }
2054
+ b.c = b.c + (`){` + failWithArg(b, path, (exccessFieldName) => ({
2055
+ TAG: "ExcessField",
2056
+ _0: exccessFieldName
2057
+ }), keyVar) + `}}`);
2058
+ }
2059
+ function schemaCompiler(b, input, selfSchema, path) {
2060
+ let additionalItems = selfSchema.additionalItems;
2061
+ let items = selfSchema.items;
2062
+ let isArray = flags[selfSchema.type] & 128;
2063
+ if (b.g.o & 64) {
2064
+ let objectVal = make(b, isArray);
2065
+ for (let idx = 0, idx_finish = items.length; idx < idx_finish; ++idx) {
2066
+ let match = items[idx];
2067
+ let location = match.location;
2068
+ add(objectVal, location, input.properties[location]);
2069
+ }
2070
+ return complete(objectVal, isArray);
2071
+ }
2072
+ let objectVal$1 = make(b, isArray);
2073
+ for (let idx$1 = 0, idx_finish$1 = items.length; idx$1 < idx_finish$1; ++idx$1) {
2074
+ let match$1 = items[idx$1];
2075
+ let location$1 = match$1.location;
2076
+ let itemInput = get(b, input, location$1);
2077
+ let inlinedLocation = inlineLocation(b, location$1);
2078
+ let path$1 = path + (`[` + inlinedLocation + `]`);
2079
+ add(objectVal$1, location$1, parse(b, match$1.schema, itemInput, path$1));
2080
+ }
2081
+ objectStrictModeCheck(b, input, items, selfSchema, path);
2082
+ if ((additionalItems !== "strip" || b.g.o & 32) && items.every((item) => objectVal$1.properties[item.location] === input.properties[item.location])) {
2083
+ input.additionalItems = "strip";
2084
+ return input;
2085
+ } else {
2086
+ return complete(objectVal$1, isArray);
2087
+ }
2088
+ }
2089
+ function definitionToSchema(definition) {
2090
+ if (typeof definition !== "object" || definition === null) {
2091
+ return parse$1(definition);
2092
+ }
2093
+ if (definition["~standard"]) {
2094
+ return definition;
2095
+ }
2096
+ if (Array.isArray(definition)) {
2097
+ for (let idx = 0, idx_finish = definition.length; idx < idx_finish; ++idx) {
2098
+ let schema3 = definitionToSchema(definition[idx]);
2099
+ let location = idx.toString();
2100
+ definition[idx] = {
2101
+ schema: schema3,
2102
+ location
2103
+ };
2104
+ }
2105
+ let mut = new Schema("array");
2106
+ mut.items = definition;
2107
+ mut.additionalItems = "strict";
2108
+ mut.compiler = schemaCompiler;
2109
+ return mut;
2110
+ }
2111
+ let cnstr = definition.constructor;
2112
+ if (cnstr && cnstr !== Object) {
2113
+ return {
2114
+ type: "instance",
2115
+ const: definition,
2116
+ class: cnstr
2117
+ };
2118
+ }
2119
+ let fieldNames = Object.keys(definition);
2120
+ let length2 = fieldNames.length;
2121
+ let items = [];
2122
+ for (let idx$1 = 0; idx$1 < length2; ++idx$1) {
2123
+ let location$1 = fieldNames[idx$1];
2124
+ let schema$1 = definitionToSchema(definition[location$1]);
2125
+ let item = {
2126
+ schema: schema$1,
2127
+ location: location$1
2128
+ };
2129
+ definition[location$1] = schema$1;
2130
+ items[idx$1] = item;
2131
+ }
2132
+ let mut$1 = new Schema("object");
2133
+ mut$1.items = items;
2134
+ mut$1.properties = definition;
2135
+ mut$1.additionalItems = globalConfig.a;
2136
+ mut$1.compiler = schemaCompiler;
2137
+ return mut$1;
2138
+ }
2139
+ function matches(schema3) {
2140
+ return schema3;
2141
+ }
2142
+ var ctx = {
2143
+ m: matches
2144
+ };
2145
+ function factory$4(definer) {
2146
+ return definitionToSchema(definer(ctx));
2147
+ }
2148
+ var schema = factory$4;
2149
+
2150
+ // ../../node_modules/sury/src/S.res.mjs
2151
+ var string2 = string;
2152
+ var parseJsonStringOrThrow2 = parseJsonStringOrThrow;
2153
+ var schema2 = schema;
2154
+
2155
+ // ../../node_modules/@rescript/runtime/lib/es6/Stdlib_Int.js
2156
+ function fromString2(x, radix) {
2157
+ let maybeInt = parseInt(x);
2158
+ if (Number.isNaN(maybeInt) || maybeInt > 2147483647 || maybeInt < -2147483648) {
2159
+ return;
2160
+ } else {
2161
+ return maybeInt | 0;
2162
+ }
2163
+ }
2164
+
2165
+ // src/cli/FrontmanAstro__Cli__Detect.res.mjs
2166
+ async function fileExists(path) {
2167
+ try {
2168
+ await Fs2.promises.access(path);
2169
+ return true;
2170
+ } catch (exn) {
2171
+ return false;
2172
+ }
2173
+ }
2174
+ async function readFile2(path) {
2175
+ try {
2176
+ return await Fs2.promises.readFile(path, "utf8");
2177
+ } catch (exn) {
2178
+ return;
2179
+ }
2180
+ }
2181
+ var astroPkgJsonSchema = schema2((s2) => ({
2182
+ version: s2.m(string2)
2183
+ }));
2184
+ async function detectAstroVersion(projectDir) {
2185
+ let astroPkgPath = Nodepath2.join(projectDir, "node_modules", "astro", "package.json");
2186
+ let content = await readFile2(astroPkgPath);
2187
+ if (content === void 0) {
2188
+ return;
2189
+ }
2190
+ try {
2191
+ let pkg = parseJsonStringOrThrow2(content, astroPkgJsonSchema);
2192
+ let version = pkg.version;
2193
+ let parts = version.split(".");
2194
+ let match = parts[0];
2195
+ let match$1 = parts[1];
2196
+ if (match === void 0) {
2197
+ return;
2198
+ }
2199
+ if (match$1 === void 0) {
2200
+ return;
2201
+ }
2202
+ let major = getOrThrow(fromString2(match, void 0), void 0);
2203
+ let minorClean = match$1.split("-")[0];
2204
+ let minor = getOrThrow(fromString2(minorClean, void 0), void 0);
2205
+ return {
2206
+ major,
2207
+ minor,
2208
+ raw: version
2209
+ };
2210
+ } catch (exn) {
2211
+ return;
2212
+ }
2213
+ }
2214
+ async function detectConfigFile(projectDir) {
2215
+ let variants = [
2216
+ "astro.config.mjs",
2217
+ "astro.config.ts",
2218
+ "astro.config.mts",
2219
+ "astro.config.js"
2220
+ ];
2221
+ let check2 = async (remaining) => {
2222
+ let name = remaining[0];
2223
+ if (name === void 0) {
2224
+ return;
2225
+ }
2226
+ let path = Nodepath2.join(projectDir, name);
2227
+ if (await fileExists(path)) {
2228
+ return name;
2229
+ }
2230
+ let rest = remaining.slice(1, remaining.length);
2231
+ return await check2(rest);
2232
+ };
2233
+ return await check2(variants);
2234
+ }
2235
+ var frontmanImportPattern = /@frontman-ai\/astro|@frontman\/frontman-astro|frontman-astro\/integration/;
2236
+ var hostPattern2 = /host:\s*['\"]([^'\"]+)['\"]/;
2237
+ async function analyzeFile(filePath) {
2238
+ let content = await readFile2(filePath);
2239
+ if (content === void 0) {
2240
+ return "NotFound";
2241
+ }
2242
+ if (!frontmanImportPattern.test(content)) {
2243
+ return "NeedsManualEdit";
2244
+ }
2245
+ let result = hostPattern2.exec(content);
2246
+ if (result == null) {
2247
+ return {
2248
+ TAG: "HasFrontman",
2249
+ host: ""
2250
+ };
2251
+ }
2252
+ let maybeHost = flatMap(result.slice(1)[0], (x) => x);
2253
+ if (maybeHost !== void 0) {
2254
+ return {
2255
+ TAG: "HasFrontman",
2256
+ host: maybeHost
2257
+ };
2258
+ } else {
2259
+ return {
2260
+ TAG: "HasFrontman",
2261
+ host: ""
2262
+ };
2263
+ }
2264
+ }
2265
+ async function detectPackageManager(projectDir) {
2266
+ let checkDir = async (dir) => {
2267
+ let lockFiles = [
2268
+ [
2269
+ Nodepath2.join(dir, "bun.lockb"),
2270
+ "Bun"
2271
+ ],
2272
+ [
2273
+ Nodepath2.join(dir, "bun.lock"),
2274
+ "Bun"
2275
+ ],
2276
+ [
2277
+ Nodepath2.join(dir, "deno.lock"),
2278
+ "Deno"
2279
+ ],
2280
+ [
2281
+ Nodepath2.join(dir, "pnpm-lock.yaml"),
2282
+ "Pnpm"
2283
+ ],
2284
+ [
2285
+ Nodepath2.join(dir, "yarn.lock"),
2286
+ "Yarn"
2287
+ ],
2288
+ [
2289
+ Nodepath2.join(dir, "package-lock.json"),
2290
+ "Npm"
2291
+ ]
2292
+ ];
2293
+ let check2 = async (remaining) => {
2294
+ let match = remaining[0];
2295
+ if (match === void 0) {
2296
+ return;
2297
+ }
2298
+ if (await fileExists(match[0])) {
2299
+ return match[1];
2300
+ }
2301
+ let rest = remaining.slice(1, remaining.length);
2302
+ return await check2(rest);
2303
+ };
2304
+ return await check2(lockFiles);
2305
+ };
2306
+ let parentDir = Nodepath2.dirname(projectDir);
2307
+ let grandparentDir = Nodepath2.dirname(parentDir);
2308
+ let dirsToCheck = [
2309
+ projectDir,
2310
+ parentDir,
2311
+ grandparentDir
2312
+ ].filter((d2) => {
2313
+ if (d2 !== projectDir) {
2314
+ return true;
2315
+ } else {
2316
+ return d2 === projectDir;
2317
+ }
2318
+ });
2319
+ let seen = {};
2320
+ let uniqueDirs = dirsToCheck.filter((d2) => {
2321
+ let match = seen[d2];
2322
+ if (match !== void 0) {
2323
+ return false;
2324
+ } else {
2325
+ seen[d2] = true;
2326
+ return true;
2327
+ }
2328
+ });
2329
+ let tryDirs = async (remaining) => {
2330
+ let dir = remaining[0];
2331
+ if (dir === void 0) {
2332
+ return "Npm";
2333
+ }
2334
+ let pm = await checkDir(dir);
2335
+ if (pm !== void 0) {
2336
+ return pm;
2337
+ }
2338
+ let rest = remaining.slice(1, remaining.length);
2339
+ return await tryDirs(rest);
2340
+ };
2341
+ return await tryDirs(uniqueDirs);
2342
+ }
2343
+ async function hasPackageJson(projectDir) {
2344
+ return await fileExists(Nodepath2.join(projectDir, "package.json"));
2345
+ }
2346
+ async function detect(projectDir) {
2347
+ let hasPackage = await hasPackageJson(projectDir);
2348
+ if (!hasPackage) {
2349
+ return {
2350
+ TAG: "Error",
2351
+ _0: "No package.json found. Please run from your Astro project root."
2352
+ };
2353
+ }
2354
+ let astroVersion = await detectAstroVersion(projectDir);
2355
+ if (astroVersion === void 0) {
2356
+ return {
2357
+ TAG: "Error",
2358
+ _0: "Could not find Astro in node_modules. Please run 'npm install' first or verify this is an Astro project."
2359
+ };
2360
+ }
2361
+ let name = await detectConfigFile(projectDir);
2362
+ let configFileName = name !== void 0 ? name : "astro.config.mjs";
2363
+ let configPath = Nodepath2.join(projectDir, configFileName);
2364
+ let config2 = await analyzeFile(configPath);
2365
+ let middlewareTsPath = Nodepath2.join(projectDir, "src", "middleware.ts");
2366
+ let middlewareJsPath = Nodepath2.join(projectDir, "src", "middleware.js");
2367
+ let match = await fileExists(middlewareTsPath) ? [
2368
+ await analyzeFile(middlewareTsPath),
2369
+ "src/middleware.ts"
2370
+ ] : await fileExists(middlewareJsPath) ? [
2371
+ await analyzeFile(middlewareJsPath),
2372
+ "src/middleware.js"
2373
+ ] : [
2374
+ "NotFound",
2375
+ "src/middleware.ts"
2376
+ ];
2377
+ let packageManager = await detectPackageManager(projectDir);
2378
+ return {
2379
+ TAG: "Ok",
2380
+ _0: {
2381
+ astroVersion,
2382
+ config: config2,
2383
+ middleware: match[0],
2384
+ configFileName,
2385
+ middlewareFileName: match[1],
2386
+ packageManager
2387
+ }
2388
+ };
2389
+ }
2390
+ function getPackageManagerCommand(pm) {
2391
+ switch (pm) {
2392
+ case "Npm":
2393
+ return "npm";
2394
+ case "Yarn":
2395
+ return "npx yarn";
2396
+ case "Pnpm":
2397
+ return "npx pnpm";
2398
+ case "Bun":
2399
+ return "bun";
2400
+ case "Deno":
2401
+ return "deno";
2402
+ }
2403
+ }
2404
+ function getDevCommand(pm) {
2405
+ switch (pm) {
2406
+ case "Npm":
2407
+ return "npm run dev";
2408
+ case "Yarn":
2409
+ return "yarn dev";
2410
+ case "Pnpm":
2411
+ return "pnpm dev";
2412
+ case "Bun":
2413
+ return "bun dev";
2414
+ case "Deno":
2415
+ return "deno task dev";
2416
+ }
2417
+ }
2418
+ function getInstallArgs(pm, isDevOpt) {
2419
+ switch (pm) {
2420
+ case "Npm":
2421
+ {
2422
+ return ["install"];
2423
+ }
2424
+ case "Yarn":
2425
+ {
2426
+ return ["add"];
2427
+ }
2428
+ case "Pnpm":
2429
+ {
2430
+ return ["add"];
2431
+ }
2432
+ }
2433
+ {
2434
+ return ["add"];
2435
+ }
2436
+ }
2437
+
2438
+ // src/cli/FrontmanAstro__Cli__Install.res.mjs
2439
+ async function installDependencies(projectDir, packageManager, dryRun) {
2440
+ let pm = getPackageManagerCommand(packageManager);
2441
+ let args = getInstallArgs(packageManager);
2442
+ let packages = [
2443
+ "@frontman-ai/astro",
2444
+ "@astrojs/node"
2445
+ ];
2446
+ let packages$1;
2447
+ packages$1 = packageManager === "Deno" ? packages.map((p2) => "npm:" + p2) : packages;
2448
+ let cmd = pm + ` ` + args.join(" ") + ` ` + packages$1.join(" ");
2449
+ if (dryRun) {
2450
+ console.log(` ` + dim(`Would run: ` + cmd));
2451
+ return {
2452
+ TAG: "Ok",
2453
+ _0: void 0
2454
+ };
2455
+ }
2456
+ console.log(` ` + purple("Installing dependencies with " + pm + "..."));
2457
+ let err = await execWithOptions(cmd, {
2458
+ cwd: projectDir
2459
+ });
2460
+ if (err.TAG === "Ok") {
2461
+ console.log(` ` + check + ` Dependencies installed`);
2462
+ return {
2463
+ TAG: "Ok",
2464
+ _0: void 0
2465
+ };
2466
+ }
2467
+ let err$1 = err._0;
2468
+ let stderr = err$1.stderr === "" ? "Unknown error" : err$1.stderr;
2469
+ return {
2470
+ TAG: "Error",
2471
+ _0: `Failed to install dependencies: ` + stderr
2472
+ };
2473
+ }
2474
+ function processFileResult(result, manualSteps) {
2475
+ if (result.TAG === "Ok") {
2476
+ let fileResult = result._0;
2477
+ console.log(formatResult(fileResult));
2478
+ if (fileResult.TAG === "ManualEditRequired") {
2479
+ manualSteps.push(fileResult.details);
2480
+ }
2481
+ return {
2482
+ TAG: "Ok",
2483
+ _0: void 0
2484
+ };
2485
+ }
2486
+ let msg = result._0;
2487
+ console.error(` ` + warn + ` ` + bold("Error:") + ` ` + msg);
2488
+ return {
2489
+ TAG: "Error",
2490
+ _0: msg
2491
+ };
2492
+ }
2493
+ function collectPendingAutoEdits(projectDir, host, info) {
2494
+ let pending = [];
2495
+ let p2 = getPendingAutoEdit(info.config, Nodepath2.join(projectDir, info.configFileName), info.configFileName, "Config", ManualInstructions.config(info.configFileName, host));
2496
+ if (p2 !== void 0) {
2497
+ pending.push(p2);
2498
+ }
2499
+ let p$1 = getPendingAutoEdit(info.middleware, Nodepath2.join(projectDir, info.middlewareFileName), info.middlewareFileName, "Middleware", ManualInstructions.middleware(info.middlewareFileName, host));
2500
+ if (p$1 !== void 0) {
2501
+ pending.push(p$1);
2502
+ }
2503
+ return pending;
2504
+ }
2505
+ async function run(options) {
2506
+ let projectDir = getOr(options.prefix, process.cwd());
2507
+ let host = options.server;
2508
+ console.log(banner());
2509
+ console.log(` ` + bullet + ` ` + bold("Server:") + ` ` + host);
2510
+ if (options.dryRun) {
2511
+ console.log("");
2512
+ console.log(SuccessMessages.dryRunHeader);
2513
+ }
2514
+ let msg = await detect(projectDir);
2515
+ if (msg.TAG === "Ok") {
2516
+ let info = msg._0;
2517
+ let version = getOrThrow(info.astroVersion).raw;
2518
+ console.log(` ` + bullet + ` ` + bold("Detected:") + ` Astro ` + version);
2519
+ console.log("");
2520
+ if (!options.skipDeps) {
2521
+ let msg$1 = await installDependencies(projectDir, info.packageManager, options.dryRun);
2522
+ if (msg$1.TAG !== "Ok") {
2523
+ console.error(` ` + warn + ` ` + msg$1._0);
2524
+ }
2525
+ console.log("");
2526
+ }
2527
+ let pendingEdits = collectPendingAutoEdits(projectDir, host, info);
2528
+ let match = pendingEdits.length !== 0;
2529
+ let match$1 = options.dryRun;
2530
+ let shouldAutoEdit;
2531
+ if (match && !match$1) {
2532
+ let fileNames = pendingEdits.map((p2) => p2.fileName);
2533
+ shouldAutoEdit = await promptUserForAutoEdit(fileNames);
2534
+ } else {
2535
+ shouldAutoEdit = false;
2536
+ }
2537
+ let manualSteps = [];
2538
+ let configResult = await handleConfig(projectDir, host, info.configFileName, info.config, options.dryRun, shouldAutoEdit);
2539
+ let msg$2 = processFileResult(configResult, manualSteps);
2540
+ if (msg$2.TAG !== "Ok") {
2541
+ return {
2542
+ TAG: "Failure",
2543
+ _0: msg$2._0
2544
+ };
2545
+ }
2546
+ let middlewareResult = await handleMiddleware(projectDir, host, info.middlewareFileName, info.middleware, options.dryRun, shouldAutoEdit);
2547
+ let msg$3 = processFileResult(middlewareResult, manualSteps);
2548
+ if (msg$3.TAG !== "Ok") {
2549
+ return {
2550
+ TAG: "Failure",
2551
+ _0: msg$3._0
2552
+ };
2553
+ }
2554
+ if (manualSteps.length !== 0) {
2555
+ console.log("");
2556
+ console.log(` ` + divider);
2557
+ console.log("");
2558
+ console.log(` ` + yellowBold("Manual steps required:"));
2559
+ console.log("");
2560
+ manualSteps.forEach((step) => {
2561
+ console.log(step);
2562
+ });
2563
+ console.log("");
2564
+ return {
2565
+ TAG: "PartialSuccess",
2566
+ manualStepsRequired: manualSteps
2567
+ };
2568
+ }
2569
+ if (!options.dryRun) {
2570
+ let devCommand = getDevCommand(info.packageManager);
2571
+ console.log("");
2572
+ console.log(` ` + divider);
2573
+ console.log(SuccessMessages.installComplete(devCommand));
2574
+ }
2575
+ return "Success";
2576
+ }
2577
+ let msg$4 = msg._0;
2578
+ console.error(` ` + warn + ` ` + bold("Error:") + ` ` + msg$4);
2579
+ return {
2580
+ TAG: "Failure",
2581
+ _0: msg$4
2582
+ };
2583
+ }
2584
+
2585
+ // src/cli/FrontmanAstro__Cli.res.mjs
2586
+ var helpText = `
2587
+ Frontman Astro CLI
2588
+
2589
+ Usage:
2590
+ frontman-ai-astro <command> [options]
2591
+
2592
+ Commands:
2593
+ install Install Frontman in an Astro project
2594
+
2595
+ Options:
2596
+ --server <host> Frontman server host (default: api.frontman.sh)
2597
+ --prefix <path> Target directory (default: current directory)
2598
+ --dry-run Preview changes without writing files
2599
+ --skip-deps Skip dependency installation
2600
+ --help Show this help message
2601
+
2602
+ Examples:
2603
+ npx @frontman-ai/astro install
2604
+ npx @frontman-ai/astro install --server frontman.company.com
2605
+ npx @frontman-ai/astro install --dry-run
2606
+ `;
2607
+ function parseArgs(argv) {
2608
+ let args = argv.slice(2, argv.length);
2609
+ let _remaining = args;
2610
+ let _result = {
2611
+ command: void 0,
2612
+ server: void 0,
2613
+ prefix: void 0,
2614
+ dryRun: false,
2615
+ skipDeps: false,
2616
+ help: false
2617
+ };
2618
+ while (true) {
2619
+ let result = _result;
2620
+ let remaining = _remaining;
2621
+ let arg = remaining[0];
2622
+ if (arg === void 0) {
2623
+ return result;
2624
+ }
2625
+ let rest = remaining.slice(1, remaining.length);
2626
+ switch (arg) {
2627
+ case "--dry-run":
2628
+ _result = {
2629
+ command: result.command,
2630
+ server: result.server,
2631
+ prefix: result.prefix,
2632
+ dryRun: true,
2633
+ skipDeps: result.skipDeps,
2634
+ help: result.help
2635
+ };
2636
+ _remaining = rest;
2637
+ continue;
2638
+ case "--prefix":
2639
+ let value = rest[0];
2640
+ let nextRest = rest.slice(1, rest.length);
2641
+ _result = {
2642
+ command: result.command,
2643
+ server: result.server,
2644
+ prefix: value,
2645
+ dryRun: result.dryRun,
2646
+ skipDeps: result.skipDeps,
2647
+ help: result.help
2648
+ };
2649
+ _remaining = nextRest;
2650
+ continue;
2651
+ case "--server":
2652
+ let value$1 = rest[0];
2653
+ let nextRest$1 = rest.slice(1, rest.length);
2654
+ _result = {
2655
+ command: result.command,
2656
+ server: value$1,
2657
+ prefix: result.prefix,
2658
+ dryRun: result.dryRun,
2659
+ skipDeps: result.skipDeps,
2660
+ help: result.help
2661
+ };
2662
+ _remaining = nextRest$1;
2663
+ continue;
2664
+ case "--skip-deps":
2665
+ _result = {
2666
+ command: result.command,
2667
+ server: result.server,
2668
+ prefix: result.prefix,
2669
+ dryRun: result.dryRun,
2670
+ skipDeps: true,
2671
+ help: result.help
2672
+ };
2673
+ _remaining = rest;
2674
+ continue;
2675
+ case "--help":
2676
+ case "-h":
2677
+ break;
2678
+ case "install":
2679
+ _result = {
2680
+ command: "install",
2681
+ server: result.server,
2682
+ prefix: result.prefix,
2683
+ dryRun: result.dryRun,
2684
+ skipDeps: result.skipDeps,
2685
+ help: result.help
2686
+ };
2687
+ _remaining = rest;
2688
+ continue;
2689
+ default:
2690
+ _remaining = rest;
2691
+ continue;
2692
+ }
2693
+ _result = {
2694
+ command: result.command,
2695
+ server: result.server,
2696
+ prefix: result.prefix,
2697
+ dryRun: result.dryRun,
2698
+ skipDeps: result.skipDeps,
2699
+ help: true
2700
+ };
2701
+ _remaining = rest;
2702
+ continue;
2703
+ }
2704
+ }
2705
+ async function main() {
2706
+ let args = parseArgs(process.argv);
2707
+ if (args.help) {
2708
+ console.log(helpText);
2709
+ Process.exit(0);
2710
+ }
2711
+ let cmd = args.command;
2712
+ if (cmd !== void 0) {
2713
+ if (cmd === "install") {
2714
+ let s2 = args.server;
2715
+ let server = s2 !== void 0 ? s2 : "api.frontman.sh";
2716
+ let result = await run({
2717
+ server,
2718
+ prefix: args.prefix,
2719
+ dryRun: args.dryRun,
2720
+ skipDeps: args.skipDeps
2721
+ });
2722
+ if (typeof result !== "object") {
2723
+ Process.exit(0);
2724
+ return;
2725
+ }
2726
+ if (result.TAG === "PartialSuccess") {
2727
+ Process.exit(0);
2728
+ return;
2729
+ }
2730
+ Process.exit(1);
2731
+ return;
2732
+ } else {
2733
+ console.error(`Unknown command: ` + cmd);
2734
+ console.log(helpText);
2735
+ Process.exit(1);
2736
+ return;
2737
+ }
2738
+ } else {
2739
+ console.log(helpText);
2740
+ Process.exit(0);
2741
+ return;
2742
+ }
2743
+ }
2744
+ main();