veryfront 0.0.72 → 0.0.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -122,6 +122,47 @@ function resolveLogLevel(force = false) {
122
122
  }
123
123
  return cachedLogLevel;
124
124
  }
125
+ function resolveLogFormat(force = false) {
126
+ if (force || cachedLogFormat === void 0) {
127
+ cachedLogFormat = getDefaultFormat();
128
+ }
129
+ return cachedLogFormat;
130
+ }
131
+ function getDefaultFormat() {
132
+ const envFormat = getEnvironmentVariable("LOG_FORMAT");
133
+ if (envFormat === "json" || envFormat === "text") {
134
+ return envFormat;
135
+ }
136
+ return isProductionEnvironment() ? "json" : "text";
137
+ }
138
+ function serializeError(err) {
139
+ if (err instanceof Error) {
140
+ return {
141
+ name: err.name,
142
+ message: err.message,
143
+ stack: err.stack
144
+ };
145
+ }
146
+ if (err !== void 0 && err !== null) {
147
+ return {
148
+ name: "UnknownError",
149
+ message: String(err)
150
+ };
151
+ }
152
+ return void 0;
153
+ }
154
+ function extractContext(args) {
155
+ let context;
156
+ let error2;
157
+ for (const arg of args) {
158
+ if (arg instanceof Error) {
159
+ error2 = serializeError(arg);
160
+ } else if (typeof arg === "object" && arg !== null && !Array.isArray(arg)) {
161
+ context = { ...context, ...arg };
162
+ }
163
+ }
164
+ return { context, error: error2 };
165
+ }
125
166
  function parseLogLevel(levelString) {
126
167
  if (!levelString)
127
168
  return void 0;
@@ -146,8 +187,10 @@ function createLogger(prefix) {
146
187
  }
147
188
  function __loggerResetForTests(options = {}) {
148
189
  const updatedLevel = resolveLogLevel(true);
190
+ const updatedFormat = resolveLogFormat(true);
149
191
  for (const instance of trackedLoggers) {
150
192
  instance.setLevel(updatedLevel);
193
+ instance.setFormat(updatedFormat);
151
194
  }
152
195
  if (options.restoreConsole) {
153
196
  console.debug = originalConsole.debug;
@@ -156,7 +199,10 @@ function __loggerResetForTests(options = {}) {
156
199
  console.error = originalConsole.error;
157
200
  }
158
201
  }
159
- var LogLevel, originalConsole, cachedLogLevel, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, logger;
202
+ function createRequestLogger(baseLogger, requestContext) {
203
+ return baseLogger.child(requestContext);
204
+ }
205
+ var LogLevel, originalConsole, cachedLogLevel, cachedLogFormat, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, proxyLogger, logger;
160
206
  var init_logger = __esm({
161
207
  "src/core/utils/logger/logger.ts"() {
162
208
  init_deno_env();
@@ -174,47 +220,104 @@ var init_logger = __esm({
174
220
  warn: console.warn,
175
221
  error: console.error
176
222
  };
177
- ConsoleLogger = class {
178
- constructor(prefix, level = resolveLogLevel()) {
223
+ ConsoleLogger = class _ConsoleLogger {
224
+ constructor(prefix, level = resolveLogLevel(), format = resolveLogFormat(), boundContext) {
179
225
  this.prefix = prefix;
180
226
  this.level = level;
227
+ this.format = format;
228
+ if (boundContext) {
229
+ this.boundContext = boundContext;
230
+ }
181
231
  }
232
+ boundContext = {};
182
233
  setLevel(level) {
183
234
  this.level = level;
184
235
  }
185
236
  getLevel() {
186
237
  return this.level;
187
238
  }
188
- debug(message, ...args) {
189
- if (this.level <= 0 /* DEBUG */) {
190
- console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);
239
+ setFormat(format) {
240
+ this.format = format;
241
+ }
242
+ getFormat() {
243
+ return this.format;
244
+ }
245
+ /**
246
+ * Create a child logger with additional bound context.
247
+ */
248
+ child(context) {
249
+ return new _ConsoleLogger(this.prefix, this.level, this.format, {
250
+ ...this.boundContext,
251
+ ...context
252
+ });
253
+ }
254
+ formatJson(level, message, args) {
255
+ const { context, error: error2 } = extractContext(args);
256
+ const entry = {
257
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
258
+ level,
259
+ service: this.prefix.toLowerCase(),
260
+ message
261
+ };
262
+ const mergedContext = { ...this.boundContext, ...context };
263
+ if (Object.keys(mergedContext).length > 0) {
264
+ if ("requestId" in mergedContext) {
265
+ entry.requestId = String(mergedContext.requestId);
266
+ delete mergedContext.requestId;
267
+ }
268
+ if ("traceId" in mergedContext) {
269
+ entry.traceId = String(mergedContext.traceId);
270
+ delete mergedContext.traceId;
271
+ }
272
+ if ("projectSlug" in mergedContext) {
273
+ entry.projectSlug = String(mergedContext.projectSlug);
274
+ delete mergedContext.projectSlug;
275
+ }
276
+ if ("durationMs" in mergedContext) {
277
+ entry.durationMs = Number(mergedContext.durationMs);
278
+ delete mergedContext.durationMs;
279
+ }
280
+ if (Object.keys(mergedContext).length > 0) {
281
+ entry.context = mergedContext;
282
+ }
191
283
  }
284
+ if (error2) {
285
+ entry.error = error2;
286
+ }
287
+ return JSON.stringify(entry);
192
288
  }
193
- info(message, ...args) {
194
- if (this.level <= 1 /* INFO */) {
195
- console.log(`[${this.prefix}] ${message}`, ...args);
289
+ log(level, logLevel, consoleFn, message, args) {
290
+ if (this.level > logLevel)
291
+ return;
292
+ if (this.format === "json") {
293
+ consoleFn(this.formatJson(level, message, args));
294
+ } else {
295
+ const prefix = level === "info" ? "" : ` ${level.toUpperCase()}:`;
296
+ consoleFn(`[${this.prefix}]${prefix} ${message}`, ...args);
196
297
  }
197
298
  }
299
+ debug(message, ...args) {
300
+ this.log("debug", 0 /* DEBUG */, console.debug, message, args);
301
+ }
302
+ info(message, ...args) {
303
+ this.log("info", 1 /* INFO */, console.log, message, args);
304
+ }
198
305
  warn(message, ...args) {
199
- if (this.level <= 2 /* WARN */) {
200
- console.warn(`[${this.prefix}] WARN: ${message}`, ...args);
201
- }
306
+ this.log("warn", 2 /* WARN */, console.warn, message, args);
202
307
  }
203
308
  error(message, ...args) {
204
- if (this.level <= 3 /* ERROR */) {
205
- console.error(`[${this.prefix}] ERROR: ${message}`, ...args);
206
- }
309
+ this.log("error", 3 /* ERROR */, console.error, message, args);
207
310
  }
208
311
  async time(label, fn) {
209
312
  const start = performance.now();
210
313
  try {
211
314
  const result = await fn();
212
- const end = performance.now();
213
- this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);
315
+ const durationMs = performance.now() - start;
316
+ this.debug(`${label} completed`, { durationMs: Math.round(durationMs) });
214
317
  return result;
215
318
  } catch (error2) {
216
- const end = performance.now();
217
- this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error2);
319
+ const durationMs = performance.now() - start;
320
+ this.error(`${label} failed`, { durationMs: Math.round(durationMs) }, error2);
218
321
  throw error2;
219
322
  }
220
323
  }
@@ -235,6 +338,7 @@ var init_logger = __esm({
235
338
  rendererLogger = createLogger("RENDERER");
236
339
  bundlerLogger = createLogger("BUNDLER");
237
340
  agentLogger = createLogger("AGENT");
341
+ proxyLogger = createLogger("PROXY");
238
342
  logger = createLogger("VERYFRONT");
239
343
  }
240
344
  });
@@ -267,7 +371,6 @@ var init_build = __esm({
267
371
  var SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, MS_PER_SECOND, DEFAULT_LRU_MAX_ENTRIES, COMPONENT_LOADER_MAX_ENTRIES, COMPONENT_LOADER_TTL_MS, MDX_RENDERER_MAX_ENTRIES, MDX_RENDERER_TTL_MS, RENDERER_CORE_MAX_ENTRIES, RENDERER_CORE_TTL_MS, TSX_LAYOUT_MAX_ENTRIES, TSX_LAYOUT_TTL_MS, DATA_FETCHING_MAX_ENTRIES, DATA_FETCHING_TTL_MS, MDX_CACHE_TTL_PRODUCTION_MS, MDX_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_CACHE_TTL_PRODUCTION_MS, BUNDLE_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_MANIFEST_PROD_TTL_MS, BUNDLE_MANIFEST_DEV_TTL_MS, RSC_MANIFEST_CACHE_TTL_MS, SERVER_ACTION_DEFAULT_TTL_SEC, DENO_KV_SAFE_SIZE_LIMIT_BYTES, HTTP_CACHE_SHORT_MAX_AGE_SEC, HTTP_CACHE_MEDIUM_MAX_AGE_SEC, HTTP_CACHE_LONG_MAX_AGE_SEC, ONE_DAY_MS, CACHE_CLEANUP_INTERVAL_MS, LRU_DEFAULT_MAX_ENTRIES, LRU_DEFAULT_MAX_SIZE_BYTES, CLEANUP_INTERVAL_MULTIPLIER;
268
372
  var init_cache = __esm({
269
373
  "src/core/utils/constants/cache.ts"() {
270
- "use strict";
271
374
  init_deno_env();
272
375
  SECONDS_PER_MINUTE = 60;
273
376
  MINUTES_PER_HOUR = 60;
@@ -310,7 +413,7 @@ var init_deno = __esm({
310
413
  "deno.json"() {
311
414
  deno_default = {
312
415
  name: "veryfront",
313
- version: "0.0.71",
416
+ version: "0.0.74",
314
417
  nodeModulesDir: "auto",
315
418
  exclude: [
316
419
  "npm/",
@@ -395,12 +498,12 @@ var init_deno = __esm({
395
498
  csstype: "https://esm.sh/csstype@3.2.3",
396
499
  "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",
397
500
  "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",
398
- react: "https://esm.sh/react@18.3.1",
399
- "react-dom": "https://esm.sh/react-dom@18.3.1",
400
- "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",
401
- "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",
402
- "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",
403
- "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",
501
+ react: "npm:react@18.3.1",
502
+ "react-dom": "npm:react-dom@18.3.1",
503
+ "react-dom/server": "npm:react-dom@18.3.1/server.node",
504
+ "react-dom/client": "npm:react-dom@18.3.1/client",
505
+ "react/jsx-runtime": "npm:react@18.3.1/jsx-runtime",
506
+ "react/jsx-dev-runtime": "npm:react@18.3.1/jsx-dev-runtime",
404
507
  "@mdx-js/mdx": "npm:@mdx-js/mdx@3.0.0",
405
508
  "@mdx-js/react": "npm:@mdx-js/react@3.0.0",
406
509
  "unist-util-visit": "npm:unist-util-visit@5.0.0",
@@ -410,27 +513,36 @@ var init_deno = __esm({
410
513
  "remark-frontmatter": "npm:remark-frontmatter@5.0.0",
411
514
  "rehype-highlight": "npm:rehype-highlight@7.0.2",
412
515
  "rehype-slug": "npm:rehype-slug@6.0.0",
413
- esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",
414
- "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",
516
+ esbuild: "npm:esbuild@0.20.2",
517
+ "esbuild/mod.js": "npm:esbuild@0.20.2",
415
518
  "es-module-lexer": "npm:es-module-lexer@1.5.0",
416
- zod: "npm:zod@3.23.8",
519
+ zod: "npm:zod@3.25.76",
417
520
  "mime-types": "npm:mime-types@2.1.35",
418
521
  mdast: "npm:@types/mdast@4.0.3",
419
522
  hast: "npm:@types/hast@3.0.3",
420
523
  unist: "npm:@types/unist@3.0.2",
421
524
  unified: "npm:unified@11.0.5",
422
- ai: "https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1",
423
- "ai/react": "https://esm.sh/@ai-sdk/react@2.0.1?deps=react@18.3.1,react-dom@18.3.1",
424
- "@ai-sdk/react": "https://esm.sh/@ai-sdk/react@2.0.1?deps=react@18.3.1,react-dom@18.3.1",
525
+ ai: "npm:ai@5.0.76",
526
+ "ai/react": "npm:@ai-sdk/react@2.0.1",
527
+ "@ai-sdk/react": "npm:@ai-sdk/react@2.0.1",
425
528
  "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",
426
529
  "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.1",
427
530
  unocss: "https://esm.sh/unocss@0.59.0",
428
531
  "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",
429
532
  "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0",
533
+ "next-themes": "npm:next-themes@0.3.0",
430
534
  redis: "npm:redis",
431
535
  pg: "npm:pg",
432
536
  "@opentelemetry/api": "npm:@opentelemetry/api@1",
433
- "@opentelemetry/core": "npm:@opentelemetry/core@1"
537
+ "@opentelemetry/core": "npm:@opentelemetry/core@1",
538
+ "@opentelemetry/sdk-trace-base": "npm:@opentelemetry/sdk-trace-base@1",
539
+ "@opentelemetry/exporter-trace-otlp-http": "npm:@opentelemetry/exporter-trace-otlp-http@0.57",
540
+ "@opentelemetry/resources": "npm:@opentelemetry/resources@1",
541
+ "@opentelemetry/semantic-conventions": "npm:@opentelemetry/semantic-conventions@1",
542
+ "@babel/parser": "npm:@babel/parser@7.26.3",
543
+ "@babel/traverse": "npm:@babel/traverse@7.26.3",
544
+ "@babel/generator": "npm:@babel/generator@7.26.3",
545
+ "@babel/types": "npm:@babel/types@7.26.3"
434
546
  },
435
547
  compilerOptions: {
436
548
  jsx: "react-jsx",
@@ -438,7 +550,7 @@ var init_deno = __esm({
438
550
  strict: true,
439
551
  noImplicitAny: true,
440
552
  noUncheckedIndexedAccess: true,
441
- types: [],
553
+ types: ["npm:@types/react@18"],
442
554
  lib: [
443
555
  "deno.window",
444
556
  "dom",
@@ -453,9 +565,9 @@ var init_deno = __esm({
453
565
  build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",
454
566
  "build:npm": "deno run -A scripts/build-npm.ts",
455
567
  release: "deno run -A scripts/release.ts",
456
- test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",
457
- "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",
458
- "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",
568
+ test: "VF_DISABLE_LRU_INTERVAL=1 DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",
569
+ "test:unit": "VF_DISABLE_LRU_INTERVAL=1 DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests,src/ai/workflow/__tests__ --unstable-worker-options --unstable-net",
570
+ "test:integration": "VF_DISABLE_LRU_INTERVAL=1 DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",
459
571
  "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",
460
572
  "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",
461
573
  "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",
@@ -518,12 +630,17 @@ var init_deno = __esm({
518
630
  });
519
631
 
520
632
  // src/platform/compat/runtime.ts
633
+ function isNodeRuntime() {
634
+ const _global = globalThis;
635
+ const isRealDeno = typeof Deno !== "undefined" && typeof Deno.version === "object";
636
+ return !isRealDeno && typeof _global.process !== "undefined" && !!_global.process?.versions?.node;
637
+ }
521
638
  var isDeno, isNode, isBun, isCloudflare;
522
639
  var init_runtime = __esm({
523
640
  "src/platform/compat/runtime.ts"() {
524
641
  "use strict";
525
642
  init_deno_env();
526
- isDeno = typeof Deno !== "undefined";
643
+ isDeno = typeof Deno !== "undefined" && typeof Deno.version === "object";
527
644
  isNode = typeof globalThis.process !== "undefined" && globalThis.process?.versions?.node !== void 0;
528
645
  isBun = typeof globalThis.Bun !== "undefined";
529
646
  isCloudflare = typeof globalThis !== "undefined" && "caches" in globalThis && "WebSocketPair" in globalThis;
@@ -591,7 +708,7 @@ var init_process = __esm({
591
708
  });
592
709
 
593
710
  // src/core/utils/version.ts
594
- var VERSION;
711
+ var VERSION, SERVER_START_TIME;
595
712
  var init_version = __esm({
596
713
  "src/core/utils/version.ts"() {
597
714
  "use strict";
@@ -599,6 +716,7 @@ var init_version = __esm({
599
716
  init_deno();
600
717
  init_process();
601
718
  VERSION = getEnv("VERYFRONT_VERSION") || (typeof deno_default.version === "string" ? deno_default.version : "0.0.0");
719
+ SERVER_START_TIME = Date.now();
602
720
  }
603
721
  });
604
722
 
@@ -637,10 +755,9 @@ function getDenoStdNodeBase() {
637
755
  function getUnoCSSTailwindResetUrl() {
638
756
  return `${ESM_CDN_BASE}/@unocss/reset@${UNOCSS_VERSION}/tailwind.css`;
639
757
  }
640
- var ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, UNOCSS_VERSION;
758
+ var ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, TAILWIND_VERSION, UNOCSS_VERSION;
641
759
  var init_cdn = __esm({
642
760
  "src/core/utils/constants/cdn.ts"() {
643
- "use strict";
644
761
  init_deno_env();
645
762
  init_version();
646
763
  ESM_CDN_BASE = "https://esm.sh";
@@ -654,6 +771,7 @@ var init_cdn = __esm({
654
771
  REACT_DEFAULT_VERSION = REACT_VERSION_18_3;
655
772
  DEFAULT_ALLOWED_CDN_HOSTS = [ESM_CDN_BASE, DENO_STD_BASE];
656
773
  DENO_STD_VERSION = "0.220.0";
774
+ TAILWIND_VERSION = "4.1.8";
657
775
  UNOCSS_VERSION = "0.59.0";
658
776
  }
659
777
  });
@@ -912,7 +1030,6 @@ function normalizeChunkPath(filename, basePath = INTERNAL_PATH_PREFIXES.CHUNKS)
912
1030
  var DEFAULT_DASHBOARD_PORT, INTERNAL_PREFIX, INTERNAL_PATH_PREFIXES, INTERNAL_ENDPOINTS, BUILD_DIRS, PROJECT_DIRS, DEFAULT_CACHE_DIR, DEV_SERVER_ENDPOINTS;
913
1031
  var init_server = __esm({
914
1032
  "src/core/utils/constants/server.ts"() {
915
- "use strict";
916
1033
  init_deno_env();
917
1034
  init_defaults();
918
1035
  DEFAULT_DASHBOARD_PORT = 3002;
@@ -1421,8 +1538,8 @@ var init_bundle_manifest = __esm({
1421
1538
  // src/core/utils/bundle-manifest-init.ts
1422
1539
  async function initializeBundleManifest(config, mode, adapter) {
1423
1540
  const manifestConfig = config.cache?.bundleManifest;
1424
- const enabled = manifestConfig?.enabled ?? mode === "production";
1425
- if (!enabled) {
1541
+ const enabled2 = manifestConfig?.enabled ?? mode === "production";
1542
+ if (!enabled2) {
1426
1543
  serverLogger.info("[bundle-manifest] Bundle manifest disabled");
1427
1544
  setBundleManifestStore(new InMemoryBundleManifestStore());
1428
1545
  return;
@@ -1564,6 +1681,379 @@ var init_platform = __esm({
1564
1681
  }
1565
1682
  });
1566
1683
 
1684
+ // src/core/utils/import-lockfile.ts
1685
+ function createEmptyLockfile() {
1686
+ return {
1687
+ version: LOCKFILE_VERSION,
1688
+ imports: {}
1689
+ };
1690
+ }
1691
+ async function computeIntegrity(content) {
1692
+ const hash = await computeHash(content);
1693
+ return `sha256-${hash}`;
1694
+ }
1695
+ function verifyIntegrity(content, integrity) {
1696
+ return computeIntegrity(content).then((computed) => computed === integrity);
1697
+ }
1698
+ function createNodeFSAdapter() {
1699
+ const fs = globalThis.Deno ? null : __require2("fs/promises");
1700
+ return {
1701
+ readFile(path) {
1702
+ if (globalThis.Deno) {
1703
+ return Deno.readTextFile(path);
1704
+ }
1705
+ return fs.readFile(path, "utf-8");
1706
+ },
1707
+ async writeFile(path, content) {
1708
+ if (globalThis.Deno) {
1709
+ await Deno.writeTextFile(path, content);
1710
+ return;
1711
+ }
1712
+ await fs.writeFile(path, content, "utf-8");
1713
+ },
1714
+ async exists(path) {
1715
+ try {
1716
+ if (globalThis.Deno) {
1717
+ await Deno.stat(path);
1718
+ return true;
1719
+ }
1720
+ await fs.access(path);
1721
+ return true;
1722
+ } catch {
1723
+ return false;
1724
+ }
1725
+ },
1726
+ async remove(path) {
1727
+ if (globalThis.Deno) {
1728
+ await Deno.remove(path);
1729
+ return;
1730
+ }
1731
+ await fs.unlink(path);
1732
+ }
1733
+ };
1734
+ }
1735
+ function createLockfileManager(projectDir, fsAdapter) {
1736
+ const fs = fsAdapter || createNodeFSAdapter();
1737
+ const lockfilePath = `${projectDir}/${LOCKFILE_NAME}`;
1738
+ let cache = null;
1739
+ let dirty = false;
1740
+ const read = async () => {
1741
+ if (cache)
1742
+ return cache;
1743
+ try {
1744
+ if (await fs.exists(lockfilePath)) {
1745
+ const content = await fs.readFile(lockfilePath);
1746
+ cache = JSON.parse(content);
1747
+ if (cache.version !== LOCKFILE_VERSION) {
1748
+ serverLogger.warn(
1749
+ `[lockfile] Version mismatch, expected ${LOCKFILE_VERSION}, got ${cache.version}`
1750
+ );
1751
+ cache = createEmptyLockfile();
1752
+ }
1753
+ return cache;
1754
+ }
1755
+ } catch (e) {
1756
+ serverLogger.debug(`[lockfile] Could not read lockfile: ${e}`);
1757
+ }
1758
+ return null;
1759
+ };
1760
+ const write = async (data) => {
1761
+ cache = data;
1762
+ const sorted = {
1763
+ version: data.version,
1764
+ imports: Object.fromEntries(
1765
+ Object.entries(data.imports).sort(([a], [b]) => a.localeCompare(b))
1766
+ )
1767
+ };
1768
+ await fs.writeFile(lockfilePath, JSON.stringify(sorted, null, 2) + "\n");
1769
+ dirty = false;
1770
+ serverLogger.debug(`[lockfile] Written ${Object.keys(data.imports).length} entries`);
1771
+ };
1772
+ const get = async (url) => {
1773
+ const data = await read();
1774
+ return data?.imports[url] ?? null;
1775
+ };
1776
+ const set = async (url, entry) => {
1777
+ let data = await read();
1778
+ if (!data) {
1779
+ data = createEmptyLockfile();
1780
+ }
1781
+ data.imports[url] = entry;
1782
+ cache = data;
1783
+ dirty = true;
1784
+ };
1785
+ const has = async (url) => {
1786
+ const data = await read();
1787
+ return url in (data?.imports ?? {});
1788
+ };
1789
+ const clear = async () => {
1790
+ cache = createEmptyLockfile();
1791
+ if (fs.remove && await fs.exists(lockfilePath)) {
1792
+ await fs.remove(lockfilePath);
1793
+ }
1794
+ };
1795
+ const flush = async () => {
1796
+ if (dirty && cache) {
1797
+ await write(cache);
1798
+ }
1799
+ };
1800
+ return {
1801
+ read,
1802
+ write,
1803
+ get,
1804
+ set,
1805
+ has,
1806
+ clear,
1807
+ flush
1808
+ };
1809
+ }
1810
+ async function fetchWithLock(options) {
1811
+ const { lockfile, url, fetchFn = fetch, strict = false } = options;
1812
+ const entry = await lockfile.get(url);
1813
+ if (entry) {
1814
+ serverLogger.debug(`[lockfile] Cache hit for ${url}`);
1815
+ const res2 = await fetchFn(entry.resolved, {
1816
+ headers: { "user-agent": "Mozilla/5.0 Veryfront/1.0" }
1817
+ });
1818
+ if (!res2.ok) {
1819
+ if (strict) {
1820
+ throw new Error(
1821
+ `Lockfile entry stale: ${url} resolved to ${entry.resolved} returned ${res2.status}`
1822
+ );
1823
+ }
1824
+ serverLogger.warn(`[lockfile] Cached URL ${entry.resolved} returned ${res2.status}, refetching`);
1825
+ } else {
1826
+ const content2 = await res2.text();
1827
+ const currentIntegrity = await computeIntegrity(content2);
1828
+ if (currentIntegrity !== entry.integrity) {
1829
+ if (strict) {
1830
+ throw new Error(
1831
+ `Integrity mismatch for ${url}: expected ${entry.integrity}, got ${currentIntegrity}`
1832
+ );
1833
+ }
1834
+ serverLogger.warn(`[lockfile] Integrity mismatch for ${url}, updating lockfile`);
1835
+ } else {
1836
+ return {
1837
+ content: content2,
1838
+ resolvedUrl: entry.resolved,
1839
+ fromCache: true,
1840
+ integrity: entry.integrity
1841
+ };
1842
+ }
1843
+ }
1844
+ }
1845
+ serverLogger.debug(`[lockfile] Fetching fresh: ${url}`);
1846
+ const res = await fetchFn(url, {
1847
+ headers: { "user-agent": "Mozilla/5.0 Veryfront/1.0" },
1848
+ redirect: "follow"
1849
+ });
1850
+ if (!res.ok) {
1851
+ throw new Error(`Failed to fetch ${url}: ${res.status}`);
1852
+ }
1853
+ const content = await res.text();
1854
+ const resolvedUrl = res.url || url;
1855
+ const integrity = await computeIntegrity(content);
1856
+ await lockfile.set(url, {
1857
+ resolved: resolvedUrl,
1858
+ integrity,
1859
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
1860
+ });
1861
+ await lockfile.flush();
1862
+ return {
1863
+ content,
1864
+ resolvedUrl,
1865
+ fromCache: false,
1866
+ integrity
1867
+ };
1868
+ }
1869
+ function extractImports(content) {
1870
+ const imports = [];
1871
+ const seen = /* @__PURE__ */ new Set();
1872
+ for (const match of content.matchAll(IMPORT_REGEX)) {
1873
+ const specifier = match[1];
1874
+ if (specifier && !seen.has(specifier)) {
1875
+ seen.add(specifier);
1876
+ imports.push({ specifier, type: "static" });
1877
+ }
1878
+ }
1879
+ for (const match of content.matchAll(EXPORT_FROM_REGEX)) {
1880
+ const specifier = match[1];
1881
+ if (specifier && !seen.has(specifier)) {
1882
+ seen.add(specifier);
1883
+ imports.push({ specifier, type: "static" });
1884
+ }
1885
+ }
1886
+ for (const match of content.matchAll(DYNAMIC_IMPORT_REGEX)) {
1887
+ const specifier = match[1];
1888
+ if (specifier && !seen.has(specifier)) {
1889
+ seen.add(specifier);
1890
+ imports.push({ specifier, type: "dynamic" });
1891
+ }
1892
+ }
1893
+ return imports;
1894
+ }
1895
+ function resolveImportUrl(specifier, baseUrl) {
1896
+ if (specifier.startsWith("http://") || specifier.startsWith("https://")) {
1897
+ return specifier;
1898
+ }
1899
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
1900
+ try {
1901
+ return new URL(specifier, baseUrl).toString();
1902
+ } catch {
1903
+ return null;
1904
+ }
1905
+ }
1906
+ return null;
1907
+ }
1908
+ var LOCKFILE_NAME, LOCKFILE_VERSION, IMPORT_REGEX, DYNAMIC_IMPORT_REGEX, EXPORT_FROM_REGEX;
1909
+ var init_import_lockfile = __esm({
1910
+ "src/core/utils/import-lockfile.ts"() {
1911
+ "use strict";
1912
+ init_deno_env();
1913
+ init_hash_utils();
1914
+ init_logger2();
1915
+ LOCKFILE_NAME = "veryfront.lock";
1916
+ LOCKFILE_VERSION = 1;
1917
+ IMPORT_REGEX = /import\s+(?:(?:[\w*\s{},]*)\s+from\s+)?['"]([^'"]+)['"]/g;
1918
+ DYNAMIC_IMPORT_REGEX = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
1919
+ EXPORT_FROM_REGEX = /export\s+(?:[\w*\s{},]*)\s+from\s+['"]([^'"]+)['"]/g;
1920
+ }
1921
+ });
1922
+
1923
+ // src/core/utils/perf-timer.ts
1924
+ function startRequest(requestId) {
1925
+ if (!enabled)
1926
+ return;
1927
+ currentRequestId = requestId;
1928
+ timings.set(requestId, []);
1929
+ }
1930
+ function startTimer(label, parent) {
1931
+ if (!enabled || !currentRequestId)
1932
+ return () => {
1933
+ };
1934
+ const entry = {
1935
+ label,
1936
+ startMs: performance.now(),
1937
+ parent
1938
+ };
1939
+ const entries = timings.get(currentRequestId);
1940
+ if (entries) {
1941
+ entries.push(entry);
1942
+ }
1943
+ return () => {
1944
+ entry.endMs = performance.now();
1945
+ entry.durationMs = entry.endMs - entry.startMs;
1946
+ };
1947
+ }
1948
+ async function timeAsync(label, fn, parent) {
1949
+ if (!enabled)
1950
+ return fn();
1951
+ const stop = startTimer(label, parent);
1952
+ try {
1953
+ return await fn();
1954
+ } finally {
1955
+ stop();
1956
+ }
1957
+ }
1958
+ function endRequest(requestId) {
1959
+ if (!enabled)
1960
+ return;
1961
+ const entries = timings.get(requestId);
1962
+ if (!entries || entries.length === 0) {
1963
+ currentRequestId = null;
1964
+ return;
1965
+ }
1966
+ const sorted = entries.filter((e) => e.durationMs !== void 0).sort((a, b) => (b.durationMs || 0) - (a.durationMs || 0));
1967
+ const total = entries.find((e) => e.label === "total")?.durationMs || sorted.reduce((sum, e) => sum + (e.durationMs || 0), 0);
1968
+ console.log(`
1969
+ [PERF] Request ${requestId} - Total: ${total.toFixed(1)}ms`);
1970
+ console.log("\u2500".repeat(60));
1971
+ const roots = sorted.filter((e) => !e.parent);
1972
+ const children = /* @__PURE__ */ new Map();
1973
+ for (const entry of sorted) {
1974
+ if (entry.parent) {
1975
+ const list = children.get(entry.parent) || [];
1976
+ list.push(entry);
1977
+ children.set(entry.parent, list);
1978
+ }
1979
+ }
1980
+ for (const entry of roots) {
1981
+ const pct = ((entry.durationMs || 0) / total * 100).toFixed(1);
1982
+ console.log(` ${entry.label}: ${entry.durationMs?.toFixed(1)}ms (${pct}%)`);
1983
+ const childList = children.get(entry.label);
1984
+ if (childList) {
1985
+ for (const child of childList.slice(0, 5)) {
1986
+ const childPct = ((child.durationMs || 0) / total * 100).toFixed(1);
1987
+ console.log(` \u2514\u2500 ${child.label}: ${child.durationMs?.toFixed(1)}ms (${childPct}%)`);
1988
+ }
1989
+ if (childList.length > 5) {
1990
+ console.log(` \u2514\u2500 ... and ${childList.length - 5} more`);
1991
+ }
1992
+ }
1993
+ }
1994
+ console.log("\u2500".repeat(60));
1995
+ timings.delete(requestId);
1996
+ currentRequestId = null;
1997
+ }
1998
+ function isEnabled() {
1999
+ return enabled;
2000
+ }
2001
+ var enabled, timings, currentRequestId;
2002
+ var init_perf_timer = __esm({
2003
+ "src/core/utils/perf-timer.ts"() {
2004
+ "use strict";
2005
+ init_deno_env();
2006
+ enabled = typeof process !== "undefined" ? process.env?.VERYFRONT_PERF === "1" : typeof Deno !== "undefined" ? Deno.env.get("VERYFRONT_PERF") === "1" : false;
2007
+ timings = /* @__PURE__ */ new Map();
2008
+ currentRequestId = null;
2009
+ }
2010
+ });
2011
+
2012
+ // src/core/utils/cookie-utils.ts
2013
+ function parseCookies(cookieHeader) {
2014
+ const cookies = {};
2015
+ if (!cookieHeader)
2016
+ return cookies;
2017
+ cookieHeader.split(";").forEach((cookie) => {
2018
+ const trimmed = cookie.trim();
2019
+ if (!trimmed)
2020
+ return;
2021
+ const separatorIndex = trimmed.indexOf("=");
2022
+ if (separatorIndex <= 0)
2023
+ return;
2024
+ const name = trimmed.slice(0, separatorIndex).trim();
2025
+ const value = trimmed.slice(separatorIndex + 1);
2026
+ if (!name)
2027
+ return;
2028
+ cookies[name] = decodeURIComponent(value);
2029
+ });
2030
+ return cookies;
2031
+ }
2032
+ function parseCookiesFromHeaders(headers) {
2033
+ return parseCookies(headers.get("cookie") || "");
2034
+ }
2035
+ var init_cookie_utils = __esm({
2036
+ "src/core/utils/cookie-utils.ts"() {
2037
+ init_deno_env();
2038
+ }
2039
+ });
2040
+
2041
+ // src/core/utils/base64url.ts
2042
+ function base64urlEncode(input) {
2043
+ const b64 = btoa(input);
2044
+ return b64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
2045
+ }
2046
+ function base64urlEncodeBytes(bytes) {
2047
+ const b64 = btoa(String.fromCharCode(...bytes));
2048
+ return b64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
2049
+ }
2050
+ var init_base64url = __esm({
2051
+ "src/core/utils/base64url.ts"() {
2052
+ "use strict";
2053
+ init_deno_env();
2054
+ }
2055
+ });
2056
+
1567
2057
  // src/core/utils/index.ts
1568
2058
  var utils_exports = {};
1569
2059
  __export(utils_exports, {
@@ -1711,6 +2201,7 @@ __export(utils_exports, {
1711
2201
  SECONDS_PER_MINUTE: () => SECONDS_PER_MINUTE,
1712
2202
  SERVER_ACTION_DEFAULT_TTL_SEC: () => SERVER_ACTION_DEFAULT_TTL_SEC,
1713
2203
  SERVER_FUNCTION_DEFAULT_TIMEOUT_MS: () => SERVER_FUNCTION_DEFAULT_TIMEOUT_MS,
2204
+ TAILWIND_VERSION: () => TAILWIND_VERSION,
1714
2205
  TSX_LAYOUT_MAX_ENTRIES: () => TSX_LAYOUT_MAX_ENTRIES,
1715
2206
  TSX_LAYOUT_TTL_MS: () => TSX_LAYOUT_TTL_MS,
1716
2207
  UNOCSS_VERSION: () => UNOCSS_VERSION,
@@ -1721,13 +2212,22 @@ __export(utils_exports, {
1721
2212
  Z_INDEX_ERROR_OVERLAY: () => Z_INDEX_ERROR_OVERLAY,
1722
2213
  __loggerResetForTests: () => __loggerResetForTests,
1723
2214
  agentLogger: () => agentLogger,
2215
+ base64urlEncode: () => base64urlEncode,
2216
+ base64urlEncodeBytes: () => base64urlEncodeBytes,
1724
2217
  bundlerLogger: () => bundlerLogger,
1725
2218
  cliLogger: () => cliLogger,
1726
2219
  computeCodeHash: () => computeCodeHash,
1727
2220
  computeContentHash: () => computeContentHash,
1728
2221
  computeHash: () => computeHash,
2222
+ computeIntegrity: () => computeIntegrity,
2223
+ createEmptyLockfile: () => createEmptyLockfile,
2224
+ createLockfileManager: () => createLockfileManager,
2225
+ createRequestLogger: () => createRequestLogger,
2226
+ endRequest: () => endRequest,
1729
2227
  estimateSize: () => estimateSize,
1730
2228
  estimateSizeWithCircularHandling: () => estimateSizeWithCircularHandling,
2229
+ extractImports: () => extractImports,
2230
+ fetchWithLock: () => fetchWithLock,
1731
2231
  formatBytes: () => formatBytes,
1732
2232
  formatDuration: () => formatDuration,
1733
2233
  formatNumber: () => formatNumber,
@@ -1758,6 +2258,7 @@ __export(utils_exports, {
1758
2258
  isDebugEnabled: () => isDebugEnabled,
1759
2259
  isDeepInspectEnabled: () => isDeepInspectEnabled,
1760
2260
  isDevelopmentEnvironment: () => isDevelopmentEnvironment,
2261
+ isEnabled: () => isEnabled,
1761
2262
  isInternalEndpoint: () => isInternalEndpoint,
1762
2263
  isProductionEnvironment: () => isProductionEnvironment,
1763
2264
  isRSCEnabled: () => isRSCEnabled,
@@ -1774,13 +2275,21 @@ __export(utils_exports, {
1774
2275
  normalizeChunkPath: () => normalizeChunkPath,
1775
2276
  normalizePath: () => normalizePath,
1776
2277
  numericHash: () => simpleHash,
2278
+ parseCookies: () => parseCookies,
2279
+ parseCookiesFromHeaders: () => parseCookiesFromHeaders,
2280
+ proxyLogger: () => proxyLogger,
1777
2281
  rendererLogger: () => rendererLogger,
2282
+ resolveImportUrl: () => resolveImportUrl,
1778
2283
  serverLogger: () => serverLogger,
1779
2284
  setBundleManifestStore: () => setBundleManifestStore,
1780
2285
  shortHash: () => shortHash,
1781
2286
  simpleHash: () => simpleHash,
2287
+ startRequest: () => startRequest,
2288
+ startTimer: () => startTimer,
2289
+ timeAsync: () => timeAsync,
1782
2290
  toBase64Url: () => toBase64Url,
1783
2291
  truncateString: () => truncateString,
2292
+ verifyIntegrity: () => verifyIntegrity,
1784
2293
  warmupBundleManifest: () => warmupBundleManifest
1785
2294
  });
1786
2295
  var init_utils = __esm({
@@ -1799,6 +2308,10 @@ var init_utils = __esm({
1799
2308
  init_bundle_manifest_init();
1800
2309
  init_feature_flags();
1801
2310
  init_platform();
2311
+ init_import_lockfile();
2312
+ init_perf_timer();
2313
+ init_cookie_utils();
2314
+ init_base64url();
1802
2315
  }
1803
2316
  });
1804
2317
 
@@ -1825,6 +2338,56 @@ var init_veryfront_error = __esm({
1825
2338
 
1826
2339
  // src/core/config/schema.ts
1827
2340
  import { z } from "zod";
2341
+ function validateVeryfrontConfig(input) {
2342
+ const parsed = veryfrontConfigSchema.safeParse(input);
2343
+ if (!parsed.success) {
2344
+ const first = parsed.error.issues[0];
2345
+ const path = first?.path?.length ? first.path.join(".") : "<root>";
2346
+ const expected = first?.message || String(first);
2347
+ let hint = "";
2348
+ if (String(path).includes("security.cors")) {
2349
+ hint = " Expected boolean or { origin?: string }.";
2350
+ }
2351
+ const context = {
2352
+ field: path,
2353
+ expected: expected + hint,
2354
+ value: input
2355
+ };
2356
+ throw toError(
2357
+ createError({
2358
+ type: "config",
2359
+ message: `Invalid veryfront.config at ${path}: ${expected}.${hint}`,
2360
+ context
2361
+ })
2362
+ );
2363
+ }
2364
+ return parsed.data;
2365
+ }
2366
+ function findUnknownTopLevelKeys(input) {
2367
+ const known = /* @__PURE__ */ new Set([
2368
+ "title",
2369
+ "description",
2370
+ "experimental",
2371
+ "router",
2372
+ "defaultLayout",
2373
+ "layout",
2374
+ "provider",
2375
+ "app",
2376
+ "theme",
2377
+ "build",
2378
+ "cache",
2379
+ "dev",
2380
+ "resolve",
2381
+ "security",
2382
+ "middleware",
2383
+ "theming",
2384
+ "assetPipeline",
2385
+ "observability",
2386
+ "fs",
2387
+ "client"
2388
+ ]);
2389
+ return Object.keys(input).filter((k) => !known.has(k));
2390
+ }
1828
2391
  var corsSchema, veryfrontConfigSchema;
1829
2392
  var init_schema = __esm({
1830
2393
  "src/core/config/schema.ts"() {
@@ -1841,6 +2404,9 @@ var init_schema = __esm({
1841
2404
  }).partial().optional(),
1842
2405
  router: z.enum(["app", "pages"]).optional(),
1843
2406
  defaultLayout: z.string().optional(),
2407
+ layout: z.string().optional(),
2408
+ provider: z.string().optional(),
2409
+ app: z.string().optional(),
1844
2410
  theme: z.object({ colors: z.record(z.string()).optional() }).partial().optional(),
1845
2411
  build: z.object({
1846
2412
  outDir: z.string().optional(),
@@ -1936,6 +2502,8 @@ var init_schema = __esm({
1936
2502
  apiBaseUrl: z.string().url(),
1937
2503
  apiToken: z.string(),
1938
2504
  projectSlug: z.string(),
2505
+ proxyMode: z.boolean().optional(),
2506
+ productionMode: z.boolean().optional(),
1939
2507
  cache: z.object({
1940
2508
  enabled: z.boolean().optional(),
1941
2509
  ttl: z.number().int().positive().optional(),
@@ -1968,83 +2536,449 @@ var init_schema = __esm({
1968
2536
  }
1969
2537
  });
1970
2538
 
1971
- // src/core/config/loader.ts
1972
- import { join } from "node:path";
1973
- function getDefaultImportMapForConfig() {
1974
- return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };
1975
- }
1976
- var DEFAULT_CONFIG;
1977
- var init_loader = __esm({
1978
- "src/core/config/loader.ts"() {
1979
- "use strict";
1980
- init_deno_env();
1981
- init_schema();
1982
- init_logger();
1983
- init_cdn();
1984
- init_server();
1985
- init_defaults();
1986
- DEFAULT_CONFIG = {
1987
- title: "Veryfront App",
1988
- description: "Built with Veryfront",
1989
- experimental: {
1990
- esmLayouts: true
1991
- },
1992
- router: void 0,
1993
- defaultLayout: void 0,
1994
- theme: {
1995
- colors: {
1996
- primary: "#3B82F6"
1997
- }
1998
- },
1999
- build: {
2000
- outDir: "dist",
2001
- trailingSlash: false,
2002
- esbuild: {
2003
- wasmURL: "https://deno.land/x/esbuild@v0.20.1/esbuild.wasm",
2004
- worker: false
2005
- }
2006
- },
2007
- cache: {
2008
- dir: DEFAULT_CACHE_DIR,
2009
- render: {
2010
- type: "memory",
2011
- ttl: void 0,
2012
- maxEntries: 500,
2013
- kvPath: void 0,
2014
- redisUrl: void 0,
2015
- redisKeyPrefix: void 0
2016
- }
2017
- },
2018
- dev: {
2019
- port: DEFAULT_PORT,
2020
- host: "localhost",
2021
- open: false
2022
- },
2023
- resolve: {
2024
- importMap: getDefaultImportMapForConfig()
2025
- },
2026
- client: {
2027
- moduleResolution: "cdn",
2028
- cdn: {
2029
- provider: "esm.sh",
2030
- versions: "auto"
2031
- }
2032
- }
2033
- };
2539
+ // src/platform/compat/fs.ts
2540
+ function createFileSystem() {
2541
+ if (isDeno) {
2542
+ return new DenoFileSystem();
2543
+ } else {
2544
+ return new NodeFileSystem();
2034
2545
  }
2035
- });
2036
-
2037
- // src/core/config/define-config.ts
2038
- function defineConfig(config) {
2039
- return config;
2040
2546
  }
2041
- var init_define_config = __esm({
2042
- "src/core/config/define-config.ts"() {
2547
+ var NodeFileSystem, DenoFileSystem;
2548
+ var init_fs = __esm({
2549
+ "src/platform/compat/fs.ts"() {
2043
2550
  "use strict";
2044
2551
  init_deno_env();
2045
2552
  init_veryfront_error();
2046
- init_process();
2047
- }
2553
+ init_runtime();
2554
+ NodeFileSystem = class {
2555
+ constructor() {
2556
+ this.fs = null;
2557
+ this.os = null;
2558
+ this.path = null;
2559
+ this.initialized = false;
2560
+ }
2561
+ async ensureInitialized() {
2562
+ if (this.initialized)
2563
+ return;
2564
+ if (!isNode) {
2565
+ throw toError(createError({
2566
+ type: "not_supported",
2567
+ message: "Node.js fs modules not available",
2568
+ feature: "Node.js"
2569
+ }));
2570
+ }
2571
+ const [fsModule, osModule, pathModule] = await Promise.all([
2572
+ import("node:fs/promises"),
2573
+ import("node:os"),
2574
+ import("node:path")
2575
+ ]);
2576
+ this.fs = fsModule;
2577
+ this.os = osModule;
2578
+ this.path = pathModule;
2579
+ this.initialized = true;
2580
+ }
2581
+ async readTextFile(path) {
2582
+ await this.ensureInitialized();
2583
+ return await this.fs.readFile(path, { encoding: "utf8" });
2584
+ }
2585
+ async readFile(path) {
2586
+ await this.ensureInitialized();
2587
+ return await this.fs.readFile(path);
2588
+ }
2589
+ async writeTextFile(path, data) {
2590
+ await this.ensureInitialized();
2591
+ await this.fs.writeFile(path, data, { encoding: "utf8" });
2592
+ }
2593
+ async writeFile(path, data) {
2594
+ await this.ensureInitialized();
2595
+ await this.fs.writeFile(path, data);
2596
+ }
2597
+ async exists(path) {
2598
+ await this.ensureInitialized();
2599
+ try {
2600
+ await this.fs.access(path);
2601
+ return true;
2602
+ } catch (error2) {
2603
+ if (error2.code === "ENOENT") {
2604
+ return false;
2605
+ }
2606
+ throw error2;
2607
+ }
2608
+ }
2609
+ async stat(path) {
2610
+ await this.ensureInitialized();
2611
+ const stat = await this.fs.stat(path);
2612
+ return {
2613
+ isFile: stat.isFile(),
2614
+ isDirectory: stat.isDirectory(),
2615
+ isSymlink: stat.isSymbolicLink(),
2616
+ size: stat.size,
2617
+ mtime: stat.mtime
2618
+ };
2619
+ }
2620
+ async mkdir(path, options) {
2621
+ await this.ensureInitialized();
2622
+ await this.fs.mkdir(path, { recursive: options?.recursive ?? false });
2623
+ }
2624
+ async *readDir(path) {
2625
+ await this.ensureInitialized();
2626
+ const entries = await this.fs.readdir(path, { withFileTypes: true });
2627
+ for (const entry of entries) {
2628
+ yield {
2629
+ name: entry.name,
2630
+ isFile: entry.isFile(),
2631
+ isDirectory: entry.isDirectory()
2632
+ };
2633
+ }
2634
+ }
2635
+ async remove(path, options) {
2636
+ await this.ensureInitialized();
2637
+ await this.fs.rm(path, {
2638
+ recursive: options?.recursive ?? false,
2639
+ force: options?.recursive ?? false
2640
+ });
2641
+ }
2642
+ async makeTempDir(options) {
2643
+ await this.ensureInitialized();
2644
+ const tempDir = this.path.join(
2645
+ this.os.tmpdir(),
2646
+ `${options?.prefix ?? "tmp-"}${Math.random().toString(36).substring(2, 8)}`
2647
+ );
2648
+ await this.fs.mkdir(tempDir, { recursive: true });
2649
+ return tempDir;
2650
+ }
2651
+ };
2652
+ DenoFileSystem = class {
2653
+ async readTextFile(path) {
2654
+ return await Deno.readTextFile(path);
2655
+ }
2656
+ async readFile(path) {
2657
+ return await Deno.readFile(path);
2658
+ }
2659
+ async writeTextFile(path, data) {
2660
+ await Deno.writeTextFile(path, data);
2661
+ }
2662
+ async writeFile(path, data) {
2663
+ await Deno.writeFile(path, data);
2664
+ }
2665
+ async exists(path) {
2666
+ try {
2667
+ await Deno.stat(path);
2668
+ return true;
2669
+ } catch (error2) {
2670
+ if (error2 instanceof Deno.errors.NotFound) {
2671
+ return false;
2672
+ }
2673
+ throw error2;
2674
+ }
2675
+ }
2676
+ async stat(path) {
2677
+ const stat = await Deno.stat(path);
2678
+ return {
2679
+ isFile: stat.isFile,
2680
+ isDirectory: stat.isDirectory,
2681
+ isSymlink: stat.isSymlink,
2682
+ size: stat.size,
2683
+ mtime: stat.mtime
2684
+ };
2685
+ }
2686
+ async mkdir(path, options) {
2687
+ await Deno.mkdir(path, { recursive: options?.recursive ?? false });
2688
+ }
2689
+ async *readDir(path) {
2690
+ for await (const entry of Deno.readDir(path)) {
2691
+ yield {
2692
+ name: entry.name,
2693
+ isFile: entry.isFile,
2694
+ isDirectory: entry.isDirectory
2695
+ };
2696
+ }
2697
+ }
2698
+ async remove(path, options) {
2699
+ await Deno.remove(path, { recursive: options?.recursive ?? false });
2700
+ }
2701
+ async makeTempDir(options) {
2702
+ return await Deno.makeTempDir({ prefix: options?.prefix });
2703
+ }
2704
+ };
2705
+ }
2706
+ });
2707
+
2708
+ // src/core/config/loader.ts
2709
+ import { dirname, join } from "node:path";
2710
+ function getDefaultImportMapForConfig() {
2711
+ return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };
2712
+ }
2713
+ function validateCorsConfig(userConfig) {
2714
+ if (!userConfig || typeof userConfig !== "object") {
2715
+ return;
2716
+ }
2717
+ const config = userConfig;
2718
+ const security = config.security;
2719
+ const cors2 = security?.cors;
2720
+ if (!cors2 || typeof cors2 !== "object" || Array.isArray(cors2)) {
2721
+ return;
2722
+ }
2723
+ const corsObj = cors2;
2724
+ const origin = corsObj.origin;
2725
+ if (origin !== void 0 && typeof origin !== "string") {
2726
+ throw new ConfigValidationError(
2727
+ "security.cors.origin must be a string. Expected boolean or { origin?: string }"
2728
+ );
2729
+ }
2730
+ }
2731
+ function validateConfigShape(userConfig) {
2732
+ validateVeryfrontConfig(userConfig);
2733
+ const unknown = typeof userConfig === "object" && userConfig ? findUnknownTopLevelKeys(userConfig) : [];
2734
+ if (unknown.length > 0) {
2735
+ serverLogger.warn(`Unknown config keys: ${unknown.join(", ")}. These will be ignored.`);
2736
+ }
2737
+ }
2738
+ function mergeConfigs(userConfig) {
2739
+ const merged = {
2740
+ ...DEFAULT_CONFIG,
2741
+ ...userConfig,
2742
+ dev: {
2743
+ ...DEFAULT_CONFIG.dev,
2744
+ ...userConfig.dev
2745
+ },
2746
+ theme: {
2747
+ ...DEFAULT_CONFIG.theme,
2748
+ ...userConfig.theme
2749
+ },
2750
+ build: {
2751
+ ...DEFAULT_CONFIG.build,
2752
+ ...userConfig.build
2753
+ },
2754
+ cache: {
2755
+ ...DEFAULT_CONFIG.cache,
2756
+ ...userConfig.cache
2757
+ },
2758
+ resolve: {
2759
+ ...DEFAULT_CONFIG.resolve,
2760
+ ...userConfig.resolve
2761
+ },
2762
+ client: {
2763
+ ...DEFAULT_CONFIG.client,
2764
+ ...userConfig.client,
2765
+ cdn: {
2766
+ ...DEFAULT_CONFIG.client?.cdn,
2767
+ ...userConfig.client?.cdn
2768
+ }
2769
+ }
2770
+ };
2771
+ if (merged.resolve) {
2772
+ const defaultMap = DEFAULT_CONFIG.resolve?.importMap;
2773
+ const userMap = userConfig.resolve?.importMap;
2774
+ if (defaultMap || userMap) {
2775
+ merged.resolve.importMap = {
2776
+ imports: {
2777
+ ...defaultMap?.imports ?? {},
2778
+ ...userMap?.imports ?? {}
2779
+ },
2780
+ scopes: {
2781
+ ...defaultMap?.scopes ?? {},
2782
+ ...userMap?.scopes ?? {}
2783
+ }
2784
+ };
2785
+ }
2786
+ }
2787
+ return merged;
2788
+ }
2789
+ function isVirtualFilesystem(adapter) {
2790
+ const wrappedAdapter = adapter?.fs?.fsAdapter;
2791
+ const adapterName = wrappedAdapter?.constructor?.name;
2792
+ return adapterName === "VeryfrontFSAdapter";
2793
+ }
2794
+ async function loadConfigFromVirtualFS(configPath, projectDir, adapter) {
2795
+ const fs = createFileSystem();
2796
+ const content = await adapter.fs.readFile(configPath);
2797
+ const source = typeof content === "string" ? content : new TextDecoder().decode(content);
2798
+ serverLogger.debug(`[CONFIG] Loading config from virtual FS: ${configPath}`);
2799
+ const isTsx = configPath.endsWith(".tsx");
2800
+ const loader = isTsx ? "tsx" : configPath.endsWith(".ts") ? "ts" : "js";
2801
+ const { build: build2 } = await import("esbuild");
2802
+ const result = await build2({
2803
+ bundle: false,
2804
+ // Config files shouldn't need bundling
2805
+ write: false,
2806
+ format: "esm",
2807
+ platform: "neutral",
2808
+ target: "es2022",
2809
+ stdin: {
2810
+ contents: source,
2811
+ loader,
2812
+ resolveDir: dirname(configPath),
2813
+ sourcefile: configPath
2814
+ }
2815
+ });
2816
+ if (result.errors && result.errors.length > 0) {
2817
+ const first = result.errors[0]?.text || "unknown error";
2818
+ throw new ConfigValidationError(`Failed to transpile config: ${first}`);
2819
+ }
2820
+ const js = result.outputFiles?.[0]?.text ?? "export default {}";
2821
+ const tempDir = await fs.makeTempDir({ prefix: "vf-config-" });
2822
+ const tempFile = join(tempDir, "config.mjs");
2823
+ try {
2824
+ await fs.writeTextFile(tempFile, js);
2825
+ const configModule = await import(`file://${tempFile}?v=${Date.now()}`);
2826
+ const userConfig = configModule.default || configModule;
2827
+ if (userConfig === null || typeof userConfig !== "object" || Array.isArray(userConfig)) {
2828
+ throw new ConfigValidationError(
2829
+ `Expected object, received ${userConfig === null ? "null" : typeof userConfig}`
2830
+ );
2831
+ }
2832
+ validateCorsConfig(userConfig);
2833
+ validateConfigShape(userConfig);
2834
+ const merged = mergeConfigs(userConfig);
2835
+ configCacheByProject.set(projectDir, { revision: cacheRevision, config: merged });
2836
+ return merged;
2837
+ } finally {
2838
+ await fs.remove(tempDir, { recursive: true });
2839
+ }
2840
+ }
2841
+ async function loadAndMergeConfig(configPath, projectDir, adapter) {
2842
+ if (isVirtualFilesystem(adapter)) {
2843
+ return loadConfigFromVirtualFS(configPath, projectDir, adapter);
2844
+ }
2845
+ try {
2846
+ const configUrl = `file://${configPath}?t=${Date.now()}-${crypto.randomUUID()}`;
2847
+ const configModule = await import(configUrl);
2848
+ const userConfig = configModule.default || configModule;
2849
+ if (userConfig === null || typeof userConfig !== "object" || Array.isArray(userConfig)) {
2850
+ throw new ConfigValidationError(
2851
+ `Expected object, received ${userConfig === null ? "null" : typeof userConfig}`
2852
+ );
2853
+ }
2854
+ validateCorsConfig(userConfig);
2855
+ validateConfigShape(userConfig);
2856
+ const merged = mergeConfigs(userConfig);
2857
+ configCacheByProject.set(projectDir, { revision: cacheRevision, config: merged });
2858
+ return merged;
2859
+ } catch (error2) {
2860
+ if (error2 instanceof ConfigValidationError) {
2861
+ throw error2;
2862
+ }
2863
+ if (error2 instanceof Error && error2.message.startsWith("Invalid veryfront.config")) {
2864
+ throw error2;
2865
+ }
2866
+ throw error2;
2867
+ }
2868
+ }
2869
+ async function getConfig(projectDir, adapter) {
2870
+ const cached = configCacheByProject.get(projectDir);
2871
+ if (cached && cached.revision === cacheRevision)
2872
+ return cached.config;
2873
+ const configFiles = ["veryfront.config.js", "veryfront.config.ts", "veryfront.config.mjs"];
2874
+ for (const configFile of configFiles) {
2875
+ const configPath = join(projectDir, configFile);
2876
+ const exists = await adapter.fs.exists(configPath);
2877
+ if (!exists)
2878
+ continue;
2879
+ try {
2880
+ const merged = await loadAndMergeConfig(configPath, projectDir, adapter);
2881
+ if (merged)
2882
+ return merged;
2883
+ } catch (error2) {
2884
+ if (error2 instanceof ConfigValidationError) {
2885
+ throw error2;
2886
+ }
2887
+ if (error2 instanceof Error && error2.message.startsWith("Invalid veryfront.config")) {
2888
+ throw error2;
2889
+ }
2890
+ const errorMessage = error2 instanceof Error ? error2.message : String(error2);
2891
+ serverLogger.debug(`[CONFIG] Failed to load ${configFile}, trying next config file:`, {
2892
+ error: errorMessage
2893
+ });
2894
+ continue;
2895
+ }
2896
+ }
2897
+ const defaultConfig2 = DEFAULT_CONFIG;
2898
+ configCacheByProject.set(projectDir, { revision: cacheRevision, config: defaultConfig2 });
2899
+ return defaultConfig2;
2900
+ }
2901
+ var DEFAULT_CONFIG, configCacheByProject, cacheRevision, ConfigValidationError;
2902
+ var init_loader = __esm({
2903
+ "src/core/config/loader.ts"() {
2904
+ "use strict";
2905
+ init_deno_env();
2906
+ init_schema();
2907
+ init_logger();
2908
+ init_cdn();
2909
+ init_server();
2910
+ init_defaults();
2911
+ init_fs();
2912
+ DEFAULT_CONFIG = {
2913
+ title: "Veryfront App",
2914
+ description: "Built with Veryfront",
2915
+ experimental: {
2916
+ esmLayouts: true
2917
+ },
2918
+ router: void 0,
2919
+ defaultLayout: void 0,
2920
+ theme: {
2921
+ colors: {
2922
+ primary: "#3B82F6"
2923
+ }
2924
+ },
2925
+ build: {
2926
+ outDir: "dist",
2927
+ trailingSlash: false,
2928
+ esbuild: {
2929
+ wasmURL: "https://deno.land/x/esbuild@v0.20.1/esbuild.wasm",
2930
+ worker: false
2931
+ }
2932
+ },
2933
+ cache: {
2934
+ dir: DEFAULT_CACHE_DIR,
2935
+ render: {
2936
+ type: "memory",
2937
+ ttl: void 0,
2938
+ maxEntries: 500,
2939
+ kvPath: void 0,
2940
+ redisUrl: void 0,
2941
+ redisKeyPrefix: void 0
2942
+ }
2943
+ },
2944
+ dev: {
2945
+ port: DEFAULT_PORT,
2946
+ host: "localhost",
2947
+ open: false
2948
+ },
2949
+ resolve: {
2950
+ importMap: getDefaultImportMapForConfig()
2951
+ },
2952
+ client: {
2953
+ moduleResolution: "cdn",
2954
+ cdn: {
2955
+ provider: "esm.sh",
2956
+ versions: "auto"
2957
+ }
2958
+ }
2959
+ };
2960
+ configCacheByProject = /* @__PURE__ */ new Map();
2961
+ cacheRevision = 0;
2962
+ ConfigValidationError = class extends Error {
2963
+ constructor(message) {
2964
+ super(message);
2965
+ this.name = "ConfigValidationError";
2966
+ }
2967
+ };
2968
+ }
2969
+ });
2970
+
2971
+ // src/core/config/define-config.ts
2972
+ function defineConfig(config) {
2973
+ return config;
2974
+ }
2975
+ var init_define_config = __esm({
2976
+ "src/core/config/define-config.ts"() {
2977
+ "use strict";
2978
+ init_deno_env();
2979
+ init_veryfront_error();
2980
+ init_process();
2981
+ }
2048
2982
  });
2049
2983
 
2050
2984
  // src/core/config/network-defaults.ts
@@ -2327,7 +3261,7 @@ var init_deno2 = __esm({
2327
3261
  });
2328
3262
 
2329
3263
  // src/platform/adapters/shared-watcher.ts
2330
- import { join as join3 } from "node:path";
3264
+ import { join as join5 } from "node:path";
2331
3265
  async function setupNodeFsWatcher(path, options) {
2332
3266
  try {
2333
3267
  const fs = await import("node:fs");
@@ -2339,7 +3273,7 @@ async function setupNodeFsWatcher(path, options) {
2339
3273
  if (options.closed() || options.signal?.aborted)
2340
3274
  return;
2341
3275
  const kind = eventType === "change" ? "modify" : "any";
2342
- const fullPath = filename ? join3(path, filename) : path;
3276
+ const fullPath = filename ? join5(path, filename) : path;
2343
3277
  enqueueWatchEvent(
2344
3278
  { kind, paths: [fullPath] },
2345
3279
  options.eventQueue,
@@ -2469,9 +3403,9 @@ var init_filesystem_adapter = __esm({
2469
3403
  }
2470
3404
  async makeTempDir(prefix) {
2471
3405
  const { mkdtemp } = await import("node:fs/promises");
2472
- const { join: join8 } = await import("node:path");
3406
+ const { join: join10 } = await import("node:path");
2473
3407
  const { tmpdir } = await import("node:os");
2474
- return await mkdtemp(join8(tmpdir(), prefix));
3408
+ return await mkdtemp(join10(tmpdir(), prefix));
2475
3409
  }
2476
3410
  watch(paths, options) {
2477
3411
  const pathArray = Array.isArray(paths) ? paths : [paths];
@@ -2552,9 +3486,9 @@ var init_environment_adapter = __esm({
2552
3486
  }
2553
3487
  });
2554
3488
 
2555
- // ../node_modules/ws/lib/constants.js
3489
+ // ../../node_modules/ws/lib/constants.js
2556
3490
  var require_constants = __commonJS({
2557
- "../node_modules/ws/lib/constants.js"(exports, module) {
3491
+ "../../node_modules/ws/lib/constants.js"(exports, module) {
2558
3492
  "use strict";
2559
3493
  init_deno_env();
2560
3494
  var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
@@ -2576,9 +3510,9 @@ var require_constants = __commonJS({
2576
3510
  }
2577
3511
  });
2578
3512
 
2579
- // ../node_modules/ws/lib/buffer-util.js
3513
+ // ../../node_modules/ws/lib/buffer-util.js
2580
3514
  var require_buffer_util = __commonJS({
2581
- "../node_modules/ws/lib/buffer-util.js"(exports, module) {
3515
+ "../../node_modules/ws/lib/buffer-util.js"(exports, module) {
2582
3516
  "use strict";
2583
3517
  init_deno_env();
2584
3518
  var { EMPTY_BUFFER } = require_constants();
@@ -2659,9 +3593,9 @@ var require_buffer_util = __commonJS({
2659
3593
  }
2660
3594
  });
2661
3595
 
2662
- // ../node_modules/ws/lib/limiter.js
3596
+ // ../../node_modules/ws/lib/limiter.js
2663
3597
  var require_limiter = __commonJS({
2664
- "../node_modules/ws/lib/limiter.js"(exports, module) {
3598
+ "../../node_modules/ws/lib/limiter.js"(exports, module) {
2665
3599
  "use strict";
2666
3600
  init_deno_env();
2667
3601
  var kDone = Symbol("kDone");
@@ -2711,9 +3645,9 @@ var require_limiter = __commonJS({
2711
3645
  }
2712
3646
  });
2713
3647
 
2714
- // ../node_modules/ws/lib/permessage-deflate.js
3648
+ // ../../node_modules/ws/lib/permessage-deflate.js
2715
3649
  var require_permessage_deflate = __commonJS({
2716
- "../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
3650
+ "../../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
2717
3651
  "use strict";
2718
3652
  init_deno_env();
2719
3653
  var zlib = __require2("zlib");
@@ -3096,9 +4030,9 @@ var require_permessage_deflate = __commonJS({
3096
4030
  }
3097
4031
  });
3098
4032
 
3099
- // ../node_modules/ws/lib/validation.js
4033
+ // ../../node_modules/ws/lib/validation.js
3100
4034
  var require_validation = __commonJS({
3101
- "../node_modules/ws/lib/validation.js"(exports, module) {
4035
+ "../../node_modules/ws/lib/validation.js"(exports, module) {
3102
4036
  "use strict";
3103
4037
  init_deno_env();
3104
4038
  var { isUtf8 } = __require2("buffer");
@@ -3298,9 +4232,9 @@ var require_validation = __commonJS({
3298
4232
  }
3299
4233
  });
3300
4234
 
3301
- // ../node_modules/ws/lib/receiver.js
4235
+ // ../../node_modules/ws/lib/receiver.js
3302
4236
  var require_receiver = __commonJS({
3303
- "../node_modules/ws/lib/receiver.js"(exports, module) {
4237
+ "../../node_modules/ws/lib/receiver.js"(exports, module) {
3304
4238
  "use strict";
3305
4239
  init_deno_env();
3306
4240
  var { Writable } = __require2("stream");
@@ -3902,9 +4836,9 @@ var require_receiver = __commonJS({
3902
4836
  }
3903
4837
  });
3904
4838
 
3905
- // ../node_modules/ws/lib/sender.js
4839
+ // ../../node_modules/ws/lib/sender.js
3906
4840
  var require_sender = __commonJS({
3907
- "../node_modules/ws/lib/sender.js"(exports, module) {
4841
+ "../../node_modules/ws/lib/sender.js"(exports, module) {
3908
4842
  "use strict";
3909
4843
  init_deno_env();
3910
4844
  var { Duplex } = __require2("stream");
@@ -4397,9 +5331,9 @@ var require_sender = __commonJS({
4397
5331
  }
4398
5332
  });
4399
5333
 
4400
- // ../node_modules/ws/lib/event-target.js
5334
+ // ../../node_modules/ws/lib/event-target.js
4401
5335
  var require_event_target = __commonJS({
4402
- "../node_modules/ws/lib/event-target.js"(exports, module) {
5336
+ "../../node_modules/ws/lib/event-target.js"(exports, module) {
4403
5337
  "use strict";
4404
5338
  init_deno_env();
4405
5339
  var { kForOnEventAttribute, kListener } = require_constants();
@@ -4627,9 +5561,9 @@ var require_event_target = __commonJS({
4627
5561
  }
4628
5562
  });
4629
5563
 
4630
- // ../node_modules/ws/lib/extension.js
5564
+ // ../../node_modules/ws/lib/extension.js
4631
5565
  var require_extension = __commonJS({
4632
- "../node_modules/ws/lib/extension.js"(exports, module) {
5566
+ "../../node_modules/ws/lib/extension.js"(exports, module) {
4633
5567
  "use strict";
4634
5568
  init_deno_env();
4635
5569
  var { tokenChars } = require_validation();
@@ -4639,7 +5573,7 @@ var require_extension = __commonJS({
4639
5573
  else
4640
5574
  dest[name].push(elem);
4641
5575
  }
4642
- function parse(header) {
5576
+ function parse2(header) {
4643
5577
  const offers = /* @__PURE__ */ Object.create(null);
4644
5578
  let params = /* @__PURE__ */ Object.create(null);
4645
5579
  let mustUnescape = false;
@@ -4794,13 +5728,13 @@ var require_extension = __commonJS({
4794
5728
  }).join(", ");
4795
5729
  }).join(", ");
4796
5730
  }
4797
- module.exports = { format, parse };
5731
+ module.exports = { format, parse: parse2 };
4798
5732
  }
4799
5733
  });
4800
5734
 
4801
- // ../node_modules/ws/lib/websocket.js
5735
+ // ../../node_modules/ws/lib/websocket.js
4802
5736
  var require_websocket = __commonJS({
4803
- "../node_modules/ws/lib/websocket.js"(exports, module) {
5737
+ "../../node_modules/ws/lib/websocket.js"(exports, module) {
4804
5738
  "use strict";
4805
5739
  init_deno_env();
4806
5740
  var EventEmitter = __require2("events");
@@ -4828,7 +5762,7 @@ var require_websocket = __commonJS({
4828
5762
  var {
4829
5763
  EventTarget: { addEventListener, removeEventListener }
4830
5764
  } = require_event_target();
4831
- var { format, parse } = require_extension();
5765
+ var { format, parse: parse2 } = require_extension();
4832
5766
  var { toBuffer } = require_buffer_util();
4833
5767
  var closeTimeout = 30 * 1e3;
4834
5768
  var kAborted = Symbol("kAborted");
@@ -5516,7 +6450,7 @@ var require_websocket = __commonJS({
5516
6450
  }
5517
6451
  let extensions;
5518
6452
  try {
5519
- extensions = parse(secWebSocketExtensions);
6453
+ extensions = parse2(secWebSocketExtensions);
5520
6454
  } catch (err) {
5521
6455
  const message = "Invalid Sec-WebSocket-Extensions header";
5522
6456
  abortHandshake(websocket, socket, message);
@@ -5711,9 +6645,9 @@ var require_websocket = __commonJS({
5711
6645
  }
5712
6646
  });
5713
6647
 
5714
- // ../node_modules/ws/lib/stream.js
6648
+ // ../../node_modules/ws/lib/stream.js
5715
6649
  var require_stream = __commonJS({
5716
- "../node_modules/ws/lib/stream.js"(exports, module) {
6650
+ "../../node_modules/ws/lib/stream.js"(exports, module) {
5717
6651
  "use strict";
5718
6652
  init_deno_env();
5719
6653
  var WebSocket2 = require_websocket();
@@ -5818,13 +6752,13 @@ var require_stream = __commonJS({
5818
6752
  }
5819
6753
  });
5820
6754
 
5821
- // ../node_modules/ws/lib/subprotocol.js
6755
+ // ../../node_modules/ws/lib/subprotocol.js
5822
6756
  var require_subprotocol = __commonJS({
5823
- "../node_modules/ws/lib/subprotocol.js"(exports, module) {
6757
+ "../../node_modules/ws/lib/subprotocol.js"(exports, module) {
5824
6758
  "use strict";
5825
6759
  init_deno_env();
5826
6760
  var { tokenChars } = require_validation();
5827
- function parse(header) {
6761
+ function parse2(header) {
5828
6762
  const protocols = /* @__PURE__ */ new Set();
5829
6763
  let start = -1;
5830
6764
  let end = -1;
@@ -5863,13 +6797,13 @@ var require_subprotocol = __commonJS({
5863
6797
  protocols.add(protocol);
5864
6798
  return protocols;
5865
6799
  }
5866
- module.exports = { parse };
6800
+ module.exports = { parse: parse2 };
5867
6801
  }
5868
6802
  });
5869
6803
 
5870
- // ../node_modules/ws/lib/websocket-server.js
6804
+ // ../../node_modules/ws/lib/websocket-server.js
5871
6805
  var require_websocket_server = __commonJS({
5872
- "../node_modules/ws/lib/websocket-server.js"(exports, module) {
6806
+ "../../node_modules/ws/lib/websocket-server.js"(exports, module) {
5873
6807
  "use strict";
5874
6808
  init_deno_env();
5875
6809
  var EventEmitter = __require2("events");
@@ -6266,7 +7200,7 @@ var require_websocket_server = __commonJS({
6266
7200
  }
6267
7201
  });
6268
7202
 
6269
- // ../node_modules/ws/wrapper.mjs
7203
+ // ../../node_modules/ws/wrapper.mjs
6270
7204
  var wrapper_exports = {};
6271
7205
  __export(wrapper_exports, {
6272
7206
  Receiver: () => import_receiver.default,
@@ -6278,7 +7212,7 @@ __export(wrapper_exports, {
6278
7212
  });
6279
7213
  var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
6280
7214
  var init_wrapper = __esm({
6281
- "../node_modules/ws/wrapper.mjs"() {
7215
+ "../../node_modules/ws/wrapper.mjs"() {
6282
7216
  init_deno_env();
6283
7217
  import_stream = __toESM(require_stream(), 1);
6284
7218
  import_receiver = __toESM(require_receiver(), 1);
@@ -6732,6 +7666,15 @@ var init_error_handlers = __esm({
6732
7666
  }
6733
7667
  });
6734
7668
 
7669
+ // src/core/errors/error-context.ts
7670
+ var init_error_context = __esm({
7671
+ "src/core/errors/error-context.ts"() {
7672
+ "use strict";
7673
+ init_deno_env();
7674
+ init_logger();
7675
+ }
7676
+ });
7677
+
6735
7678
  // src/core/errors/error-codes.ts
6736
7679
  function getErrorDocsUrl(code) {
6737
7680
  return `https://veryfront.com/docs/errors/${code}`;
@@ -7894,6 +8837,7 @@ var init_errors = __esm({
7894
8837
  init_runtime_errors();
7895
8838
  init_system_errors();
7896
8839
  init_error_handlers();
8840
+ init_error_context();
7897
8841
  init_catalog();
7898
8842
  init_user_friendly();
7899
8843
  }
@@ -7964,9 +8908,9 @@ var init_filesystem_adapter2 = __esm({
7964
8908
  }
7965
8909
  async makeTempDir(prefix) {
7966
8910
  const { mkdtemp } = await import("node:fs/promises");
7967
- const { join: join8 } = await import("node:path");
8911
+ const { join: join10 } = await import("node:path");
7968
8912
  const { tmpdir } = await import("node:os");
7969
- return await mkdtemp(join8(tmpdir(), prefix));
8913
+ return await mkdtemp(join10(tmpdir(), prefix));
7970
8914
  }
7971
8915
  watch(paths, options) {
7972
8916
  const pathArray = Array.isArray(paths) ? paths : [paths];
@@ -8557,7 +9501,7 @@ __export(detect_exports, {
8557
9501
  runtime: () => runtime
8558
9502
  });
8559
9503
  function isDeno2(global) {
8560
- return "Deno" in global && typeof global.Deno === "object";
9504
+ return "Deno" in global && typeof global.Deno === "object" && typeof global.Deno.version === "object";
8561
9505
  }
8562
9506
  function isBun2(global) {
8563
9507
  return "Bun" in global && typeof global.Bun === "object";
@@ -9057,6 +10001,9 @@ var LRUCache = class {
9057
10001
  this.adapter.cleanupExpired();
9058
10002
  }, this.cleanupIntervalMs);
9059
10003
  this.cleanupTimer = timer;
10004
+ if (typeof Deno !== "undefined" && "unrefTimer" in Deno) {
10005
+ Deno.unrefTimer(timer);
10006
+ }
9060
10007
  }
9061
10008
  toStringKey(key) {
9062
10009
  if (typeof key === "string") {
@@ -9134,87 +10081,1748 @@ init_deno_env();
9134
10081
  init_deno_env();
9135
10082
  init_utils();
9136
10083
  init_config();
9137
- import { dirname, join as join2 } from "node:path";
10084
+ import { dirname as dirname2, join as join2 } from "node:path";
9138
10085
 
9139
10086
  // src/module-system/import-map/default-import-map.ts
9140
10087
  init_deno_env();
9141
10088
  init_utils();
10089
+ init_runtime();
10090
+ var IS_TRUE_NODE = isNode && !isDeno;
10091
+ function getNpmReactImportMap(version) {
10092
+ return {
10093
+ react: `npm:react@${version}`,
10094
+ "react-dom": `npm:react-dom@${version}`,
10095
+ "react-dom/client": `npm:react-dom@${version}/client`,
10096
+ "react-dom/server": `npm:react-dom@${version}/server`,
10097
+ "react/jsx-runtime": `npm:react@${version}/jsx-runtime`,
10098
+ "react/jsx-dev-runtime": `npm:react@${version}/jsx-dev-runtime`,
10099
+ "react/": `npm:react@${version}/`
10100
+ };
10101
+ }
9142
10102
  function getDefaultImportMap() {
9143
10103
  const reactVersion = REACT_DEFAULT_VERSION;
10104
+ if (!IS_TRUE_NODE) {
10105
+ return { imports: getNpmReactImportMap(reactVersion) };
10106
+ }
9144
10107
  const importMap = getReactImportMap(reactVersion);
9145
10108
  importMap["react/"] = `https://esm.sh/react@${reactVersion}/`;
9146
10109
  return { imports: importMap };
9147
10110
  }
9148
-
9149
- // src/module-system/import-map/resolver.ts
9150
- init_deno_env();
9151
- function resolveImport(specifier, importMap, scope) {
9152
- if (scope && importMap.scopes?.[scope]?.[specifier]) {
9153
- return importMap.scopes[scope][specifier];
10111
+
10112
+ // src/module-system/import-map/resolver.ts
10113
+ init_deno_env();
10114
+ function resolveImport(specifier, importMap, scope) {
10115
+ if (scope && importMap.scopes?.[scope]?.[specifier]) {
10116
+ return importMap.scopes[scope][specifier];
10117
+ }
10118
+ if (importMap.imports?.[specifier]) {
10119
+ return importMap.imports[specifier];
10120
+ }
10121
+ if (specifier.endsWith(".js") || specifier.endsWith(".mjs") || specifier.endsWith(".cjs")) {
10122
+ const base = specifier.replace(/\.(m|c)?js$/, "");
10123
+ if (importMap.imports?.[base]) {
10124
+ return importMap.imports[base];
10125
+ }
10126
+ }
10127
+ if (importMap.imports) {
10128
+ for (const [key, value] of Object.entries(importMap.imports)) {
10129
+ if (key.endsWith("/") && specifier.startsWith(key)) {
10130
+ return value + specifier.slice(key.length);
10131
+ }
10132
+ }
10133
+ }
10134
+ return specifier;
10135
+ }
10136
+
10137
+ // src/module-system/import-map/transformer.ts
10138
+ init_deno_env();
10139
+ function transformImportsWithMap(code, importMap, scope, options) {
10140
+ let transformedCode = code;
10141
+ transformedCode = transformedCode.replace(
10142
+ /((?:import|export)\s+(?:[\w,{}\s*]+\s+from\s+)?|export\s+(?:\*|\{[^}]+\})\s+from\s+)["']([^"']+)["']/g,
10143
+ (_match, prefix, specifier) => {
10144
+ const isBare = !specifier.startsWith("http") && !specifier.startsWith("/") && !specifier.startsWith(".");
10145
+ if (isBare && !options?.resolveBare) {
10146
+ return `${prefix}"${specifier}"`;
10147
+ }
10148
+ const resolved = resolveImport(specifier, importMap, scope);
10149
+ return `${prefix}"${resolved}"`;
10150
+ }
10151
+ );
10152
+ transformedCode = transformedCode.replace(
10153
+ /from\s+["']([^"']+)["']/g,
10154
+ (match, specifier) => {
10155
+ const isBare = !specifier.startsWith("http") && !specifier.startsWith("/") && !specifier.startsWith(".");
10156
+ if (isBare && !options?.resolveBare) {
10157
+ return match;
10158
+ }
10159
+ const resolved = resolveImport(specifier, importMap, scope);
10160
+ return `from "${resolved}"`;
10161
+ }
10162
+ );
10163
+ transformedCode = transformedCode.replace(
10164
+ /import\s*\(\s*["']([^"']+)["']\s*\)/g,
10165
+ (_match, specifier) => {
10166
+ const resolved = resolveImport(specifier, importMap, scope);
10167
+ return `import("${resolved}")`;
10168
+ }
10169
+ );
10170
+ return transformedCode;
10171
+ }
10172
+
10173
+ // src/module-system/import-map/merger.ts
10174
+ init_deno_env();
10175
+
10176
+ // src/build/transforms/mdx/esm-module-loader.ts
10177
+ init_runtime();
10178
+ init_process();
10179
+ import { join as join6, posix } from "node:path";
10180
+
10181
+ // src/build/transforms/esm-transform.ts
10182
+ init_deno_env();
10183
+
10184
+ // src/build/transforms/esm/index.ts
10185
+ init_deno_env();
10186
+
10187
+ // src/build/transforms/esm/transform-core.ts
10188
+ init_deno_env();
10189
+ import * as esbuild from "esbuild/mod.js";
10190
+
10191
+ // src/build/transforms/esm/transform-cache.ts
10192
+ init_deno_env();
10193
+
10194
+ // src/core/memory/index.ts
10195
+ init_deno_env();
10196
+
10197
+ // src/core/memory/profiler.ts
10198
+ init_deno_env();
10199
+ init_utils();
10200
+ var cacheRegistry = /* @__PURE__ */ new Map();
10201
+ function registerCache(name, getStats) {
10202
+ cacheRegistry.set(name, getStats);
10203
+ rendererLogger.debug(`[MemoryProfiler] Registered cache: ${name}`);
10204
+ }
10205
+
10206
+ // src/build/transforms/esm/transform-cache.ts
10207
+ init_logger();
10208
+
10209
+ // src/core/utils/redis-client.ts
10210
+ init_deno_env();
10211
+ init_logger();
10212
+
10213
+ // src/build/transforms/esm/transform-cache.ts
10214
+ var DEFAULT_TTL_MS = 5 * 60 * 1e3;
10215
+ var DEFAULT_TTL_SECONDS = 300;
10216
+ var MAX_ENTRIES = 2e3;
10217
+ var CLEANUP_INTERVAL_MS = 6e4;
10218
+ var REDIS_KEY_PREFIX = "veryfront:transform:";
10219
+ var memoryCache = /* @__PURE__ */ new Map();
10220
+ var redisEnabled = false;
10221
+ var redisClient = null;
10222
+ registerCache("transform-cache", () => ({
10223
+ name: "transform-cache",
10224
+ entries: memoryCache.size,
10225
+ maxEntries: MAX_ENTRIES,
10226
+ redisEnabled
10227
+ }));
10228
+ var cleanupInterval;
10229
+ function shouldDisableInterval2() {
10230
+ if (globalThis.__vfDisableLruInterval === true) {
10231
+ return true;
10232
+ }
10233
+ try {
10234
+ if (typeof Deno !== "undefined" && Deno.env) {
10235
+ return Deno.env.get("VF_DISABLE_LRU_INTERVAL") === "1";
10236
+ }
10237
+ } catch {
10238
+ }
10239
+ return false;
10240
+ }
10241
+ function startPeriodicCleanup() {
10242
+ if (shouldDisableInterval2()) {
10243
+ return;
10244
+ }
10245
+ if (cleanupInterval)
10246
+ return;
10247
+ cleanupInterval = setInterval(() => {
10248
+ const now = Date.now();
10249
+ for (const [key, entry] of memoryCache) {
10250
+ if (entry.expiresAt <= now) {
10251
+ memoryCache.delete(key);
10252
+ }
10253
+ }
10254
+ }, CLEANUP_INTERVAL_MS);
10255
+ if (typeof Deno !== "undefined" && "unrefTimer" in Deno) {
10256
+ Deno.unrefTimer(cleanupInterval);
10257
+ }
10258
+ }
10259
+ startPeriodicCleanup();
10260
+ function generateCacheKey(projectId, filePath, contentHash, ssr = false) {
10261
+ const projectKey = projectId?.trim() || "default";
10262
+ const ssrKey = ssr ? "ssr" : "browser";
10263
+ return `${projectKey}:${filePath}:${contentHash}:${ssrKey}`;
10264
+ }
10265
+ function redisKey(key) {
10266
+ return `${REDIS_KEY_PREFIX}${key}`;
10267
+ }
10268
+ function getCachedTransform(key) {
10269
+ const entry = memoryCache.get(key);
10270
+ if (!entry) {
10271
+ return void 0;
10272
+ }
10273
+ if (entry.expiresAt <= Date.now()) {
10274
+ memoryCache.delete(key);
10275
+ return void 0;
10276
+ }
10277
+ return entry;
10278
+ }
10279
+ function setCachedTransform(key, code, hash, ttl = DEFAULT_TTL_MS) {
10280
+ const now = Date.now();
10281
+ memoryCache.set(key, {
10282
+ code,
10283
+ hash,
10284
+ timestamp: now,
10285
+ expiresAt: now + Math.max(1, ttl)
10286
+ });
10287
+ if (memoryCache.size > MAX_ENTRIES) {
10288
+ pruneMemoryCache();
10289
+ }
10290
+ if (redisEnabled && redisClient) {
10291
+ const entry = {
10292
+ code,
10293
+ hash,
10294
+ timestamp: now,
10295
+ expiresAt: now + Math.max(1, ttl)
10296
+ };
10297
+ const ttlSeconds = Math.ceil(ttl / 1e3);
10298
+ redisClient.set(redisKey(key), JSON.stringify(entry), {
10299
+ EX: ttlSeconds > 0 ? ttlSeconds : DEFAULT_TTL_SECONDS
10300
+ }).catch((error2) => {
10301
+ logger.debug("[TransformCache] Redis set failed", { key, error: error2 });
10302
+ });
10303
+ }
10304
+ }
10305
+ function pruneMemoryCache() {
10306
+ const entries = Array.from(memoryCache.entries()).sort(
10307
+ ([, a], [, b]) => a.timestamp - b.timestamp
10308
+ );
10309
+ const excess = memoryCache.size - MAX_ENTRIES;
10310
+ for (let i = 0; i < excess; i++) {
10311
+ const [key] = entries[i];
10312
+ memoryCache.delete(key);
10313
+ }
10314
+ }
10315
+
10316
+ // src/build/transforms/esm/transform-utils.ts
10317
+ init_deno_env();
10318
+ init_hash_utils();
10319
+ function computeContentHash2(content) {
10320
+ return shortHash(content);
10321
+ }
10322
+ function getLoaderFromPath(filePath) {
10323
+ if (filePath.endsWith(".tsx"))
10324
+ return "tsx";
10325
+ if (filePath.endsWith(".ts"))
10326
+ return "ts";
10327
+ if (filePath.endsWith(".jsx"))
10328
+ return "jsx";
10329
+ if (filePath.endsWith(".js"))
10330
+ return "js";
10331
+ if (filePath.endsWith(".mdx"))
10332
+ return "jsx";
10333
+ return "tsx";
10334
+ }
10335
+
10336
+ // src/build/transforms/esm/react-imports.ts
10337
+ init_deno_env();
10338
+
10339
+ // src/build/transforms/esm/lexer.ts
10340
+ init_deno_env();
10341
+
10342
+ // node_modules/.deno/es-module-lexer@1.5.0/node_modules/es-module-lexer/dist/lexer.js
10343
+ init_deno_env();
10344
+ var ImportType;
10345
+ !function(A2) {
10346
+ A2[A2.Static = 1] = "Static", A2[A2.Dynamic = 2] = "Dynamic", A2[A2.ImportMeta = 3] = "ImportMeta", A2[A2.StaticSourcePhase = 4] = "StaticSourcePhase", A2[A2.DynamicSourcePhase = 5] = "DynamicSourcePhase";
10347
+ }(ImportType || (ImportType = {}));
10348
+ var A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0];
10349
+ function parse(E2, g = "@") {
10350
+ if (!C)
10351
+ return init.then(() => parse(E2));
10352
+ const I = E2.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength;
10353
+ w > 0 && C.memory.grow(Math.ceil(w / 65536));
10354
+ const D = C.sa(I - 1);
10355
+ if ((A ? B : Q)(E2, new Uint16Array(C.memory.buffer, D, I)), !C.parse())
10356
+ throw Object.assign(new Error(`Parse error ${g}:${E2.slice(0, C.e()).split("\n").length}:${C.e() - E2.lastIndexOf("\n", C.e() - 1)}`), { idx: C.e() });
10357
+ const o = [], K = [];
10358
+ for (; C.ri(); ) {
10359
+ const A2 = C.is(), Q2 = C.ie(), B2 = C.it(), g2 = C.ai(), I2 = C.id(), w2 = C.ss(), D2 = C.se();
10360
+ let K2;
10361
+ C.ip() && (K2 = k(E2.slice(-1 === I2 ? A2 - 1 : A2, -1 === I2 ? Q2 + 1 : Q2))), o.push({ n: K2, t: B2, s: A2, e: Q2, ss: w2, se: D2, d: I2, a: g2 });
10362
+ }
10363
+ for (; C.re(); ) {
10364
+ const A2 = C.es(), Q2 = C.ee(), B2 = C.els(), g2 = C.ele(), I2 = E2.slice(A2, Q2), w2 = I2[0], D2 = B2 < 0 ? void 0 : E2.slice(B2, g2), o2 = D2 ? D2[0] : "";
10365
+ K.push({ s: A2, e: Q2, ls: B2, le: g2, n: '"' === w2 || "'" === w2 ? k(I2) : I2, ln: '"' === o2 || "'" === o2 ? k(D2) : D2 });
10366
+ }
10367
+ function k(A2) {
10368
+ try {
10369
+ return (0, eval)(A2);
10370
+ } catch (A3) {
10371
+ }
10372
+ }
10373
+ return [o, K, !!C.f(), !!C.ms()];
10374
+ }
10375
+ function Q(A2, Q2) {
10376
+ const B2 = A2.length;
10377
+ let C2 = 0;
10378
+ for (; C2 < B2; ) {
10379
+ const B3 = A2.charCodeAt(C2);
10380
+ Q2[C2++] = (255 & B3) << 8 | B3 >>> 8;
10381
+ }
10382
+ }
10383
+ function B(A2, Q2) {
10384
+ const B2 = A2.length;
10385
+ let C2 = 0;
10386
+ for (; C2 < B2; )
10387
+ Q2[C2] = A2.charCodeAt(C2++);
10388
+ }
10389
+ var C;
10390
+ var init = WebAssembly.compile((E = "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", "undefined" != typeof Buffer ? Buffer.from(E, "base64") : Uint8Array.from(atob(E), (A2) => A2.charCodeAt(0)))).then(WebAssembly.instantiate).then(({ exports: A2 }) => {
10391
+ C = A2;
10392
+ });
10393
+ var E;
10394
+
10395
+ // src/build/transforms/esm/lexer.ts
10396
+ var initPromise = null;
10397
+ async function initLexer() {
10398
+ if (!initPromise) {
10399
+ const anyInit = init;
10400
+ initPromise = typeof anyInit === "function" ? anyInit() : anyInit;
10401
+ }
10402
+ await initPromise;
10403
+ }
10404
+ async function parseImports(code) {
10405
+ await initLexer();
10406
+ return parse(code)[0];
10407
+ }
10408
+ async function replaceSpecifiers(code, replacer) {
10409
+ const imports = await parseImports(code);
10410
+ let result = code;
10411
+ for (let i = imports.length - 1; i >= 0; i--) {
10412
+ const imp = imports[i];
10413
+ if (!imp)
10414
+ continue;
10415
+ if (imp.n === void 0)
10416
+ continue;
10417
+ const replacement = replacer(imp.n, imp.d > -1);
10418
+ if (replacement && replacement !== imp.n) {
10419
+ const before = result.substring(0, imp.s);
10420
+ const after = result.substring(imp.e);
10421
+ result = before + replacement + after;
10422
+ }
10423
+ }
10424
+ return result;
10425
+ }
10426
+ async function rewriteImports(code, rewriter) {
10427
+ const imports = await parseImports(code);
10428
+ let result = code;
10429
+ for (let i = imports.length - 1; i >= 0; i--) {
10430
+ const imp = imports[i];
10431
+ if (!imp)
10432
+ continue;
10433
+ const statement = code.substring(imp.ss, imp.se);
10434
+ const replacement = rewriter(imp, statement);
10435
+ if (replacement !== null) {
10436
+ const before = result.substring(0, imp.ss);
10437
+ const after = result.substring(imp.se);
10438
+ result = before + replacement + after;
10439
+ }
10440
+ }
10441
+ return result;
10442
+ }
10443
+
10444
+ // src/build/transforms/esm/react-imports.ts
10445
+ init_cdn();
10446
+ init_runtime();
10447
+ init_process();
10448
+ function getVeryfrontAIReactPath(subpath = "") {
10449
+ const currentDir = new URL(".", import.meta.url).pathname;
10450
+ const srcDir = currentDir.replace(/\/build\/transforms\/esm\/?$/, "");
10451
+ const modulePath = subpath || "index.ts";
10452
+ return `file://${srcDir}/ai/react/${modulePath}`;
10453
+ }
10454
+ var projectHasReactDom = null;
10455
+ async function checkProjectHasReactDom() {
10456
+ if (projectHasReactDom !== null) {
10457
+ return projectHasReactDom;
10458
+ }
10459
+ if (!isNodeRuntime()) {
10460
+ projectHasReactDom = false;
10461
+ return false;
10462
+ }
10463
+ try {
10464
+ const { createRequire } = await import("node:module");
10465
+ const { pathToFileURL } = await import("node:url");
10466
+ const projectRequire = createRequire(pathToFileURL(cwd() + "/").href);
10467
+ projectRequire.resolve("react");
10468
+ projectRequire.resolve("react-dom/server");
10469
+ projectHasReactDom = true;
10470
+ return true;
10471
+ } catch {
10472
+ projectHasReactDom = false;
10473
+ return false;
10474
+ }
10475
+ }
10476
+ async function getBundledReactPath(subpath = "") {
10477
+ if (!isNodeRuntime()) {
10478
+ return null;
10479
+ }
10480
+ try {
10481
+ const { createRequire } = await import("node:module");
10482
+ const cliRequire = createRequire(import.meta.url);
10483
+ const moduleName = subpath ? `react${subpath}` : "react";
10484
+ return cliRequire.resolve(moduleName);
10485
+ } catch {
10486
+ return null;
10487
+ }
10488
+ }
10489
+ async function resolveReactImports(code, forSSR = false) {
10490
+ const isNode2 = isNodeRuntime();
10491
+ if (isNode2 && forSSR) {
10492
+ const hasReactDom = await checkProjectHasReactDom();
10493
+ const { pathToFileURL } = await import("node:url");
10494
+ if (hasReactDom) {
10495
+ try {
10496
+ const { createRequire } = await import("node:module");
10497
+ const projectRequire = createRequire(pathToFileURL(cwd() + "/").href);
10498
+ const projectImports = {
10499
+ "react/jsx-runtime": pathToFileURL(projectRequire.resolve("react/jsx-runtime")).href,
10500
+ "react/jsx-dev-runtime": pathToFileURL(projectRequire.resolve("react/jsx-dev-runtime")).href,
10501
+ "react": pathToFileURL(projectRequire.resolve("react")).href
10502
+ };
10503
+ return replaceSpecifiers(code, (specifier) => {
10504
+ return projectImports[specifier] || null;
10505
+ });
10506
+ } catch {
10507
+ }
10508
+ }
10509
+ const bundledReact = await getBundledReactPath();
10510
+ const bundledJsxRuntime = await getBundledReactPath("/jsx-runtime");
10511
+ const bundledJsxDevRuntime = await getBundledReactPath("/jsx-dev-runtime");
10512
+ if (bundledReact && bundledJsxRuntime && bundledJsxDevRuntime) {
10513
+ const bundledImports = {
10514
+ "react/jsx-runtime": pathToFileURL(bundledJsxRuntime).href,
10515
+ "react/jsx-dev-runtime": pathToFileURL(bundledJsxDevRuntime).href,
10516
+ "react": pathToFileURL(bundledReact).href
10517
+ };
10518
+ return replaceSpecifiers(code, (specifier) => {
10519
+ return bundledImports[specifier] || null;
10520
+ });
10521
+ }
10522
+ return code;
10523
+ }
10524
+ if (isNode2) {
10525
+ return code;
10526
+ }
10527
+ if (forSSR) {
10528
+ const denoSSRImports = {
10529
+ "veryfront/ai/react": getVeryfrontAIReactPath(),
10530
+ "veryfront/ai/components": getVeryfrontAIReactPath("components/index.ts"),
10531
+ "veryfront/ai/primitives": getVeryfrontAIReactPath("primitives/index.ts")
10532
+ };
10533
+ return replaceSpecifiers(code, (specifier) => {
10534
+ return denoSSRImports[specifier] || null;
10535
+ });
10536
+ }
10537
+ const reactImports = {
10538
+ "react/jsx-runtime": `https://esm.sh/react@${REACT_DEFAULT_VERSION}/jsx-runtime`,
10539
+ "react/jsx-dev-runtime": `https://esm.sh/react@${REACT_DEFAULT_VERSION}/jsx-dev-runtime`,
10540
+ "react-dom/server": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}/server`,
10541
+ "react-dom/client": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}/client`,
10542
+ "react-dom": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}`,
10543
+ "react": `https://esm.sh/react@${REACT_DEFAULT_VERSION}`
10544
+ };
10545
+ return replaceSpecifiers(code, (specifier) => {
10546
+ return reactImports[specifier] || null;
10547
+ });
10548
+ }
10549
+ function addDepsToEsmShUrls(code, forSSR = false) {
10550
+ if (isNodeRuntime()) {
10551
+ return Promise.resolve(code);
10552
+ }
10553
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
10554
+ if (specifier.startsWith("https://esm.sh/") && !specifier.includes(`react@${REACT_DEFAULT_VERSION}`)) {
10555
+ const hasQuery = specifier.includes("?");
10556
+ const hasExternal = specifier.includes("external=");
10557
+ if (forSSR) {
10558
+ if (hasExternal) {
10559
+ return null;
10560
+ }
10561
+ const separator = hasQuery ? "&" : "?";
10562
+ return `${specifier}${separator}external=react,react-dom`;
10563
+ } else {
10564
+ if (hasQuery) {
10565
+ return null;
10566
+ }
10567
+ return `${specifier}?deps=react@${REACT_DEFAULT_VERSION},react-dom@${REACT_DEFAULT_VERSION}`;
10568
+ }
10569
+ }
10570
+ return null;
10571
+ }));
10572
+ }
10573
+
10574
+ // src/build/transforms/esm/path-resolver.ts
10575
+ init_deno_env();
10576
+ init_cdn();
10577
+ init_utils();
10578
+ import { join as join3 } from "node:path";
10579
+ import { ensureDir } from "node:fs";
10580
+ var SSR_STUBS_DIR = join3(
10581
+ Deno.env.get("HOME") || "/tmp",
10582
+ ".cache",
10583
+ "veryfront-ssr-stubs"
10584
+ );
10585
+ var stubFileCache = /* @__PURE__ */ new Map();
10586
+ function extractNamedImports(statement) {
10587
+ const namedImports = [];
10588
+ const braceMatch = statement.match(/\{([^}]+)\}/);
10589
+ if (braceMatch) {
10590
+ const inside = braceMatch[1];
10591
+ const parts = inside.split(",");
10592
+ for (const part of parts) {
10593
+ const trimmed = part.trim();
10594
+ if (!trimmed)
10595
+ continue;
10596
+ const asMatch = trimmed.match(/^(\w+)\s+as\s+\w+$/);
10597
+ if (asMatch) {
10598
+ namedImports.push(asMatch[1]);
10599
+ } else {
10600
+ namedImports.push(trimmed);
10601
+ }
10602
+ }
10603
+ }
10604
+ return namedImports;
10605
+ }
10606
+ var CROSS_PROJECT_VERSIONED_PATTERN = /^([a-z0-9-]+)@([\d^~x][\d.x^~-]*)\/@\/(.+)$/;
10607
+ var CROSS_PROJECT_LATEST_PATTERN = /^([a-z0-9-]+)\/@\/(.+)$/;
10608
+ function parseCrossProjectImport(specifier) {
10609
+ const versionedMatch = specifier.match(CROSS_PROJECT_VERSIONED_PATTERN);
10610
+ if (versionedMatch) {
10611
+ return {
10612
+ projectSlug: versionedMatch[1],
10613
+ version: versionedMatch[2],
10614
+ path: versionedMatch[3]
10615
+ };
10616
+ }
10617
+ const latestMatch = specifier.match(CROSS_PROJECT_LATEST_PATTERN);
10618
+ if (latestMatch) {
10619
+ return {
10620
+ projectSlug: latestMatch[1],
10621
+ version: "latest",
10622
+ path: latestMatch[2]
10623
+ };
10624
+ }
10625
+ return null;
10626
+ }
10627
+ function resolveCrossProjectImports(code, options) {
10628
+ const { ssr = false } = options;
10629
+ if (ssr) {
10630
+ return Promise.resolve(code);
10631
+ }
10632
+ return Promise.resolve(
10633
+ replaceSpecifiers(code, (specifier) => {
10634
+ const parsed = parseCrossProjectImport(specifier);
10635
+ if (!parsed)
10636
+ return null;
10637
+ const { projectSlug, version, path } = parsed;
10638
+ let modulePath = path;
10639
+ if (!/\.(js|mjs|jsx|ts|tsx|mdx)$/.test(modulePath)) {
10640
+ modulePath = `${modulePath}.tsx`;
10641
+ }
10642
+ const projectRef = version === "latest" ? projectSlug : `${projectSlug}@${version}`;
10643
+ const moduleServerUrl = `/_vf_modules/_cross/${projectRef}/@/${modulePath}`;
10644
+ rendererLogger.debug("[CrossProjectImport] Rewriting", { from: specifier, to: moduleServerUrl });
10645
+ return moduleServerUrl;
10646
+ })
10647
+ );
10648
+ }
10649
+ async function hashUrl(url) {
10650
+ const encoder = new TextEncoder();
10651
+ const data = encoder.encode(url);
10652
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
10653
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
10654
+ return hashArray.slice(0, 8).map((b) => b.toString(16).padStart(2, "0")).join("");
10655
+ }
10656
+ async function getOrCreateStubFile(specifier, namedExports = []) {
10657
+ const sortedExports = [...namedExports].sort();
10658
+ const cacheKey = `${specifier}::${sortedExports.join(",")}`;
10659
+ const cached = stubFileCache.get(cacheKey);
10660
+ if (cached) {
10661
+ return cached;
10662
+ }
10663
+ const namedExportDeclarations = namedExports.map((name) => {
10664
+ if (/^[A-Z]/.test(name) || name.endsWith("Provider") || name.endsWith("Consumer")) {
10665
+ return `export const ${name} = noopComponent;`;
10666
+ }
10667
+ if (name.startsWith("use")) {
10668
+ return `export const ${name} = () => ({});`;
10669
+ }
10670
+ if (["clsx", "cn", "twMerge", "twJoin", "cx", "classNames", "classnames"].includes(name)) {
10671
+ return `export const ${name} = (...args) => args.filter(Boolean).join(" ");`;
10672
+ }
10673
+ if (name === "cva") {
10674
+ return `export const ${name} = (base, _config) => (_props) => base || "";`;
10675
+ }
10676
+ if (name === "motion" || name === "m") {
10677
+ return `export const ${name} = motionProxy;`;
10678
+ }
10679
+ if (name === "AnimatePresence") {
10680
+ return `export const ${name} = noopComponent;`;
10681
+ }
10682
+ return `export const ${name} = noop;`;
10683
+ }).join("\n");
10684
+ const stubModule = `// SSR stub for ${specifier}
10685
+ // Named exports: ${namedExports.join(", ") || "(none)"}
10686
+ const noop = () => {};
10687
+ const noopComponent = (props) => props?.children || null;
10688
+
10689
+ // Proxy for motion-like APIs (motion.div, motion.span, etc.)
10690
+ const motionProxy = new Proxy(noopComponent, {
10691
+ get(_, prop) {
10692
+ if (prop === 'default' || prop === '__esModule') return motionProxy;
10693
+ // motion.div, motion.span, etc. should return a component
10694
+ return noopComponent;
10695
+ }
10696
+ });
10697
+
10698
+ const noopProxy = new Proxy(function(){}, {
10699
+ get(_, prop) {
10700
+ if (prop === 'default' || prop === '__esModule') return noopProxy;
10701
+ if (prop === 'Provider' || prop === 'Consumer') return noopComponent;
10702
+ if (typeof prop === 'string' && prop.startsWith('use')) return () => ({});
10703
+ return noop;
10704
+ },
10705
+ apply() { return null; }
10706
+ });
10707
+
10708
+ // Named exports
10709
+ ${namedExportDeclarations}
10710
+
10711
+ // Default export and metadata
10712
+ export default noopProxy;
10713
+ export const __ssr_stub__ = true;
10714
+ export const __original_url__ = ${JSON.stringify(specifier)};
10715
+ `;
10716
+ const hash = await hashUrl(cacheKey);
10717
+ const stubPath = join3(SSR_STUBS_DIR, `stub-${hash}.js`);
10718
+ await ensureDir(SSR_STUBS_DIR);
10719
+ await Deno.writeTextFile(stubPath, stubModule);
10720
+ try {
10721
+ await import(`file://${stubPath}`);
10722
+ } catch {
10723
+ }
10724
+ stubFileCache.set(cacheKey, stubPath);
10725
+ return stubPath;
10726
+ }
10727
+ async function blockExternalUrlImports(code, _filePath) {
10728
+ const blockedUrls = [];
10729
+ const imports = await parseImports(code);
10730
+ const urlToNamedExports = /* @__PURE__ */ new Map();
10731
+ for (const imp of imports) {
10732
+ if (imp.n && (imp.n.startsWith("https://") || imp.n.startsWith("http://"))) {
10733
+ blockedUrls.push(imp.n);
10734
+ const statement = code.substring(imp.ss, imp.se);
10735
+ const namedExports = extractNamedImports(statement);
10736
+ const existing = urlToNamedExports.get(imp.n) || [];
10737
+ urlToNamedExports.set(imp.n, [.../* @__PURE__ */ new Set([...existing, ...namedExports])]);
10738
+ }
10739
+ }
10740
+ if (blockedUrls.length === 0) {
10741
+ return { code, blockedUrls };
10742
+ }
10743
+ const stubPaths = /* @__PURE__ */ new Map();
10744
+ for (const [url, namedExports] of urlToNamedExports) {
10745
+ const stubPath = await getOrCreateStubFile(url, namedExports);
10746
+ stubPaths.set(url, stubPath);
10747
+ }
10748
+ const transformedCode = await replaceSpecifiers(code, (specifier) => {
10749
+ if (specifier.startsWith("https://") || specifier.startsWith("http://")) {
10750
+ const stubPath = stubPaths.get(specifier);
10751
+ if (stubPath) {
10752
+ return `file://${stubPath}`;
10753
+ }
10754
+ }
10755
+ return null;
10756
+ });
10757
+ return { code: transformedCode, blockedUrls };
10758
+ }
10759
+ function resolveVeryfrontImports(code) {
10760
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
10761
+ if (specifier.startsWith("@veryfront/")) {
10762
+ return specifier.replace("@veryfront/", "veryfront/");
10763
+ }
10764
+ if (specifier === "@veryfront") {
10765
+ return "veryfront";
10766
+ }
10767
+ return null;
10768
+ }));
10769
+ }
10770
+ function resolvePathAliases(code, filePath, projectDir, ssr = false) {
10771
+ const _normalizedProjectDir = projectDir.replace(/\\/g, "/").replace(/\/$/, "");
10772
+ let relativeFilePath = filePath;
10773
+ if (filePath.startsWith(_normalizedProjectDir)) {
10774
+ relativeFilePath = filePath.substring(_normalizedProjectDir.length + 1);
10775
+ } else if (filePath.startsWith("/")) {
10776
+ const pathParts = filePath.split("/");
10777
+ const projectParts = _normalizedProjectDir.split("/");
10778
+ const lastProjectPart = projectParts[projectParts.length - 1];
10779
+ const projectIndex = pathParts.indexOf(lastProjectPart);
10780
+ if (projectIndex >= 0) {
10781
+ relativeFilePath = pathParts.slice(projectIndex + 1).join("/");
10782
+ }
10783
+ }
10784
+ const fileDir = relativeFilePath.substring(0, relativeFilePath.lastIndexOf("/"));
10785
+ const depth = fileDir.split("/").filter(Boolean).length;
10786
+ const relativeToRoot = depth === 0 ? "." : "../".repeat(depth).slice(0, -1);
10787
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
10788
+ if (specifier.startsWith("@/")) {
10789
+ const path = specifier.substring(2);
10790
+ const relativePath = depth === 0 ? `./${path}` : `${relativeToRoot}/${path}`;
10791
+ if (!/\.(tsx?|jsx?|mjs|cjs|mdx)$/.test(relativePath)) {
10792
+ return relativePath + ".js";
10793
+ }
10794
+ if (ssr) {
10795
+ return relativePath.replace(/\.(tsx?|jsx|mdx)$/, ".js");
10796
+ }
10797
+ return relativePath;
10798
+ }
10799
+ return null;
10800
+ }));
10801
+ }
10802
+ function resolveRelativeImports(code, filePath, projectDir, moduleServerUrl) {
10803
+ const _normalizedProjectDir = projectDir.replace(/\\/g, "/").replace(/\/$/, "");
10804
+ let relativeFilePath = filePath;
10805
+ if (filePath.startsWith(_normalizedProjectDir)) {
10806
+ relativeFilePath = filePath.substring(_normalizedProjectDir.length + 1);
10807
+ } else if (filePath.startsWith("/")) {
10808
+ const pathParts = filePath.split("/");
10809
+ const projectParts = _normalizedProjectDir.split("/");
10810
+ const lastProjectPart = projectParts[projectParts.length - 1];
10811
+ const projectIndex = pathParts.indexOf(lastProjectPart);
10812
+ if (projectIndex >= 0) {
10813
+ relativeFilePath = pathParts.slice(projectIndex + 1).join("/");
10814
+ }
10815
+ }
10816
+ const fileDir = relativeFilePath.substring(0, relativeFilePath.lastIndexOf("/"));
10817
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
10818
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
10819
+ let rewrittenSpecifier = specifier;
10820
+ if (/\.(tsx?|jsx)$/.test(specifier)) {
10821
+ rewrittenSpecifier = specifier.replace(/\.(tsx?|jsx)$/, ".js");
10822
+ }
10823
+ if (moduleServerUrl) {
10824
+ const resolvedPath = resolveRelativePath(fileDir, rewrittenSpecifier);
10825
+ return `${moduleServerUrl}/${resolvedPath}`;
10826
+ }
10827
+ return rewrittenSpecifier;
10828
+ }
10829
+ return null;
10830
+ }));
10831
+ }
10832
+ function resolveRelativePath(currentDir, importPath) {
10833
+ const currentParts = currentDir.split("/").filter(Boolean);
10834
+ const importParts = importPath.split("/").filter(Boolean);
10835
+ const resolvedParts = [...currentParts];
10836
+ for (const part of importParts) {
10837
+ if (part === "..") {
10838
+ resolvedParts.pop();
10839
+ } else if (part !== ".") {
10840
+ resolvedParts.push(part);
10841
+ }
10842
+ }
10843
+ return resolvedParts.join("/");
10844
+ }
10845
+ function resolveRelativeImportsForSSR(code) {
10846
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
10847
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
10848
+ if (/\.(js|mjs|cjs)$/.test(specifier)) {
10849
+ return null;
10850
+ }
10851
+ const withoutExt = specifier.replace(/\.(tsx?|jsx|mdx)$/, "");
10852
+ return withoutExt + ".js";
10853
+ }
10854
+ return null;
10855
+ }));
10856
+ }
10857
+
10858
+ // src/build/transforms/esm/import-rewriter.ts
10859
+ init_deno_env();
10860
+ init_cdn();
10861
+ init_utils();
10862
+ var unversionedImportsWarned = /* @__PURE__ */ new Set();
10863
+ function hasVersionSpecifier(specifier) {
10864
+ return /@[\d^~x][\d.x^~-]*(?=\/|$)/.test(specifier);
10865
+ }
10866
+ function warnUnversionedImport(specifier) {
10867
+ if (unversionedImportsWarned.has(specifier)) {
10868
+ return;
10869
+ }
10870
+ unversionedImportsWarned.add(specifier);
10871
+ const suggestedVersion = "x.y.z";
10872
+ const packageName = specifier.split("/")[0];
10873
+ const isScoped = specifier.startsWith("@");
10874
+ const scopedPackage = isScoped ? specifier.split("/").slice(0, 2).join("/") : packageName;
10875
+ const subpath = isScoped ? specifier.split("/").slice(2).join("/") : specifier.split("/").slice(1).join("/");
10876
+ const versionedSpecifier = subpath ? `${scopedPackage}@${suggestedVersion}/${subpath}` : `${scopedPackage}@${suggestedVersion}`;
10877
+ rendererLogger.warn("[ESM] Unversioned import may cause reproducibility issues", {
10878
+ import: specifier,
10879
+ suggestion: `Pin version: import '${versionedSpecifier}'`,
10880
+ help: "Run 'npm info " + (isScoped ? scopedPackage : packageName) + " version' to find current version"
10881
+ });
10882
+ }
10883
+ function normalizeVersionedSpecifier(specifier) {
10884
+ return specifier.replace(/@[\d^~x][\d.x^~-]*(?=\/|$)/, "");
10885
+ }
10886
+ function rewriteBareImports(code, _moduleServerUrl) {
10887
+ const importMap = {
10888
+ "react": `https://esm.sh/react@${REACT_DEFAULT_VERSION}`,
10889
+ "react-dom": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}`,
10890
+ "react-dom/client": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}/client`,
10891
+ "react-dom/server": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}/server`,
10892
+ "react/jsx-runtime": `https://esm.sh/react@${REACT_DEFAULT_VERSION}/jsx-runtime`,
10893
+ "react/jsx-dev-runtime": `https://esm.sh/react@${REACT_DEFAULT_VERSION}/jsx-dev-runtime`,
10894
+ // React Query must use same URL as HTML import map to avoid multiple module instances
10895
+ "@tanstack/react-query": `https://esm.sh/@tanstack/react-query@5?external=react`
10896
+ // NOTE: veryfront/ai/react is NOT rewritten here - it's handled by the HTML import map
10897
+ // which points to /_veryfront/lib/ai/react.js served from the local package
10898
+ };
10899
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
10900
+ if (importMap[specifier]) {
10901
+ return importMap[specifier];
10902
+ }
10903
+ if (specifier.startsWith("http://") || specifier.startsWith("https://") || specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/") || specifier.startsWith("@/") || // Project alias
10904
+ specifier.startsWith("veryfront")) {
10905
+ return null;
10906
+ }
10907
+ const normalized = normalizeVersionedSpecifier(specifier);
10908
+ let finalSpecifier = normalized;
10909
+ if (normalized === "tailwindcss" || normalized.startsWith("tailwindcss/")) {
10910
+ finalSpecifier = normalized.replace(/^tailwindcss/, `tailwindcss@${TAILWIND_VERSION}`);
10911
+ } else if (!hasVersionSpecifier(specifier)) {
10912
+ warnUnversionedImport(specifier);
10913
+ }
10914
+ return `https://esm.sh/${finalSpecifier}?deps=react@${REACT_DEFAULT_VERSION},react-dom@${REACT_DEFAULT_VERSION}`;
10915
+ }));
10916
+ }
10917
+ async function rewriteVendorImports(code, moduleServerUrl, vendorBundleHash) {
10918
+ const vendorUrl = `${moduleServerUrl}/_vendor.js?v=${vendorBundleHash}`;
10919
+ const reactPackages = /* @__PURE__ */ new Set([
10920
+ "react",
10921
+ "react-dom",
10922
+ "react-dom/client",
10923
+ "react-dom/server",
10924
+ "react/jsx-runtime",
10925
+ "react/jsx-dev-runtime"
10926
+ ]);
10927
+ let result = await rewriteImports(code, (imp, statement) => {
10928
+ if (!imp.n || !reactPackages.has(imp.n))
10929
+ return null;
10930
+ const trimmed = statement.trimStart();
10931
+ if (!trimmed.startsWith("export"))
10932
+ return null;
10933
+ const specStart = imp.s - imp.ss;
10934
+ const specEnd = imp.e - imp.ss;
10935
+ const before = statement.slice(0, specStart);
10936
+ const after = statement.slice(specEnd);
10937
+ return `${before}${vendorUrl}${after}`;
10938
+ });
10939
+ const baseSource = result;
10940
+ const imports = await parseImports(baseSource);
10941
+ for (let i = imports.length - 1; i >= 0; i--) {
10942
+ const imp = imports[i];
10943
+ if (!imp)
10944
+ continue;
10945
+ if (!imp.n || !reactPackages.has(imp.n))
10946
+ continue;
10947
+ const exportName = sanitizeVendorExportName(imp.n);
10948
+ if (imp.d > -1) {
10949
+ const afterSpecifier = baseSource.substring(imp.e);
10950
+ const match = afterSpecifier.match(/^['"]\s*\)/);
10951
+ if (!match)
10952
+ continue;
10953
+ const endOfCall = imp.e + match[0].length;
10954
+ const before = result.substring(0, imp.d);
10955
+ const after = result.substring(endOfCall);
10956
+ const replacement = `import('${vendorUrl}').then(m => m.${exportName})`;
10957
+ result = before + replacement + after;
10958
+ } else {
10959
+ const beforeSpecifier = baseSource.substring(imp.ss, imp.s);
10960
+ const fromIndex = beforeSpecifier.lastIndexOf("from");
10961
+ if (fromIndex === -1) {
10962
+ const before2 = result.substring(0, imp.ss);
10963
+ const after2 = result.substring(imp.se);
10964
+ result = before2 + `import '${vendorUrl}'` + after2;
10965
+ continue;
10966
+ }
10967
+ const clause = beforeSpecifier.substring(6, fromIndex).trim();
10968
+ let replacement = "";
10969
+ if (clause.startsWith("*")) {
10970
+ replacement = `import ${clause} from '${vendorUrl}'`;
10971
+ } else if (clause.startsWith("{")) {
10972
+ replacement = `import { ${exportName} } from '${vendorUrl}'; const ${clause} = ${exportName}`;
10973
+ } else {
10974
+ replacement = `import { ${exportName} as ${clause} } from '${vendorUrl}'`;
10975
+ }
10976
+ const before = result.substring(0, imp.ss);
10977
+ const after = result.substring(imp.se);
10978
+ result = before + replacement + after;
10979
+ }
10980
+ }
10981
+ return result;
10982
+ }
10983
+ function sanitizeVendorExportName(pkg) {
10984
+ return pkg.replace(/^@/, "").replace(/[\/\-]/g, "_").replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/^_/, "");
10985
+ }
10986
+
10987
+ // src/build/transforms/mdx/compiler/mdx-compiler.ts
10988
+ init_deno_env();
10989
+ init_utils();
10990
+
10991
+ // src/build/transforms/plugins/plugin-loader.ts
10992
+ init_deno_env();
10993
+ init_config();
10994
+ init_utils();
10995
+
10996
+ // src/build/transforms/plugins/rehype-utils.ts
10997
+ init_deno_env();
10998
+ import { visit } from "unist-util-visit";
10999
+ function rehypePreserveNodeIds() {
11000
+ return (tree) => {
11001
+ visit(tree, "element", (node) => {
11002
+ if (!node.properties) {
11003
+ node.properties = {};
11004
+ }
11005
+ if (node.data && node.data.hProperties) {
11006
+ Object.entries(
11007
+ node.data.hProperties
11008
+ ).forEach(([key, value]) => {
11009
+ if (key.startsWith("data-node-")) {
11010
+ node.properties[key] = value;
11011
+ }
11012
+ });
11013
+ }
11014
+ });
11015
+ };
11016
+ }
11017
+ function rehypeAddClasses() {
11018
+ return (tree) => {
11019
+ visit(tree, "element", (node) => {
11020
+ if (!node.properties) {
11021
+ node.properties = {};
11022
+ }
11023
+ switch (node.tagName) {
11024
+ case "p":
11025
+ addClassName(node, "mb-4");
11026
+ break;
11027
+ case "h1":
11028
+ addClassName(node, "text-4xl font-bold mb-8 mt-12");
11029
+ break;
11030
+ case "h2":
11031
+ addClassName(node, "text-3xl font-bold mb-6 mt-10");
11032
+ break;
11033
+ case "h3":
11034
+ addClassName(node, "text-2xl font-bold mb-4 mt-8");
11035
+ break;
11036
+ case "a":
11037
+ addClassName(node, "text-blue-600 hover:text-blue-800 underline");
11038
+ break;
11039
+ case "code":
11040
+ if (Array.isArray(node.properties.className) && node.properties.className.some((cls) => String(cls).includes("language-"))) {
11041
+ addClassName(node, "block p-4 bg-gray-900 text-gray-100 rounded-lg overflow-x-auto");
11042
+ } else {
11043
+ addClassName(node, "px-1 py-0.5 bg-gray-100 text-gray-900 rounded text-sm");
11044
+ }
11045
+ break;
11046
+ case "blockquote":
11047
+ addClassName(node, "border-l-4 border-gray-300 pl-4 italic");
11048
+ break;
11049
+ case "ul":
11050
+ addClassName(node, "list-disc list-inside mb-4");
11051
+ break;
11052
+ case "ol":
11053
+ addClassName(node, "list-decimal list-inside mb-4");
11054
+ break;
11055
+ case "li":
11056
+ addClassName(node, "mb-2");
11057
+ break;
11058
+ }
11059
+ });
11060
+ };
11061
+ }
11062
+ function rehypeMdxComponents() {
11063
+ return (tree) => {
11064
+ visit(tree, "mdxJsxFlowElement", (node) => {
11065
+ if (!node.data) {
11066
+ node.data = {};
11067
+ }
11068
+ if (!node.data.hProperties) {
11069
+ node.data.hProperties = {};
11070
+ }
11071
+ node.data.hProperties["data-mdx-component"] = node.name;
11072
+ });
11073
+ };
11074
+ }
11075
+ function addClassName(node, className) {
11076
+ if (!node.properties) {
11077
+ node.properties = {};
11078
+ }
11079
+ if (!node.properties.className) {
11080
+ node.properties.className = [];
11081
+ } else if (typeof node.properties.className === "string") {
11082
+ node.properties.className = node.properties.className.split(" ");
11083
+ }
11084
+ node.properties.className.push(className);
11085
+ }
11086
+
11087
+ // src/build/transforms/plugins/remark-headings.ts
11088
+ init_deno_env();
11089
+ import GithubSlugger from "github-slugger";
11090
+ import { toString } from "mdast-util-to-string";
11091
+ import { visit as visit2 } from "unist-util-visit";
11092
+ function remarkMdxHeadings() {
11093
+ const slugger = new GithubSlugger();
11094
+ return (tree, file) => {
11095
+ const headings = [];
11096
+ slugger.reset();
11097
+ visit2(tree, "heading", (node) => {
11098
+ const text2 = toString(node);
11099
+ const id = slugger.slug(text2);
11100
+ if (!node.data) {
11101
+ node.data = {};
11102
+ }
11103
+ if (!node.data.hProperties) {
11104
+ node.data.hProperties = {};
11105
+ }
11106
+ node.data.hProperties.id = id;
11107
+ headings.push({
11108
+ text: text2,
11109
+ id,
11110
+ level: node.depth
11111
+ });
11112
+ });
11113
+ if (!file.data) {
11114
+ file.data = {};
11115
+ }
11116
+ file.data.headings = headings;
11117
+ const headingsExport = {
11118
+ type: "mdxjsEsm",
11119
+ value: "",
11120
+ data: {
11121
+ estree: {
11122
+ type: "Program",
11123
+ sourceType: "module",
11124
+ body: [
11125
+ {
11126
+ type: "ExportNamedDeclaration",
11127
+ specifiers: [],
11128
+ source: null,
11129
+ declaration: {
11130
+ type: "VariableDeclaration",
11131
+ kind: "const",
11132
+ declarations: [
11133
+ {
11134
+ type: "VariableDeclarator",
11135
+ id: { type: "Identifier", name: "headings" },
11136
+ init: {
11137
+ type: "ArrayExpression",
11138
+ elements: headings.map((h) => ({
11139
+ type: "ObjectExpression",
11140
+ properties: [
11141
+ {
11142
+ type: "Property",
11143
+ key: { type: "Identifier", name: "text" },
11144
+ value: { type: "Literal", value: h.text },
11145
+ kind: "init",
11146
+ method: false,
11147
+ shorthand: false,
11148
+ computed: false
11149
+ },
11150
+ {
11151
+ type: "Property",
11152
+ key: { type: "Identifier", name: "id" },
11153
+ value: { type: "Literal", value: h.id },
11154
+ kind: "init",
11155
+ method: false,
11156
+ shorthand: false,
11157
+ computed: false
11158
+ },
11159
+ {
11160
+ type: "Property",
11161
+ key: { type: "Identifier", name: "level" },
11162
+ value: { type: "Literal", value: h.level },
11163
+ kind: "init",
11164
+ method: false,
11165
+ shorthand: false,
11166
+ computed: false
11167
+ }
11168
+ ]
11169
+ }))
11170
+ }
11171
+ }
11172
+ ]
11173
+ }
11174
+ }
11175
+ ]
11176
+ }
11177
+ }
11178
+ };
11179
+ tree.children.unshift(headingsExport);
11180
+ };
11181
+ }
11182
+
11183
+ // src/build/transforms/plugins/plugin-loader.ts
11184
+ init_veryfront_error();
11185
+
11186
+ // src/build/transforms/plugins/remark-mdx-utils.ts
11187
+ init_deno_env();
11188
+ import { visit as visit3 } from "unist-util-visit";
11189
+ function remarkMdxRemoveParagraphs() {
11190
+ return (tree) => {
11191
+ visit3(
11192
+ tree,
11193
+ "paragraph",
11194
+ (node, index, parent) => {
11195
+ const children = Array.isArray(node?.children) ? node.children : [];
11196
+ if (children.length === 1 && (children[0]?.type === "mdxJsxTextElement" || children[0]?.type === "mdxJsxFlowElement")) {
11197
+ if (parent && Array.isArray(parent.children) && typeof index === "number") {
11198
+ parent.children.splice(index, 1, children[0]);
11199
+ }
11200
+ }
11201
+ }
11202
+ );
11203
+ };
11204
+ }
11205
+ function remarkCodeBlocks() {
11206
+ return (tree) => {
11207
+ visit3(tree, "code", (node) => {
11208
+ if (!node.data) {
11209
+ node.data = {};
11210
+ }
11211
+ if (!node.data.hProperties) {
11212
+ node.data.hProperties = {};
11213
+ }
11214
+ if (node.lang) {
11215
+ node.data.hProperties.className = [`language-${node.lang}`];
11216
+ }
11217
+ if (node.meta) {
11218
+ const highlightMatch = node.meta.match(/\{([\d,-]+)\}/);
11219
+ if (highlightMatch) {
11220
+ node.data.hProperties["data-line-numbers"] = highlightMatch[1];
11221
+ }
11222
+ }
11223
+ });
11224
+ };
11225
+ }
11226
+ function remarkMdxImports() {
11227
+ return (tree, file) => {
11228
+ const imports = [];
11229
+ visit3(tree, "mdxjsEsm", (node) => {
11230
+ if (node.value?.includes("import")) {
11231
+ const importMatches = node.value.matchAll(
11232
+ /import\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s+from\s+)?['"]([^'"]+)['"]/g
11233
+ );
11234
+ for (const match of importMatches) {
11235
+ const path = match[1];
11236
+ if (typeof path === "string")
11237
+ imports.push(path);
11238
+ }
11239
+ }
11240
+ });
11241
+ if (!file.data) {
11242
+ file.data = {};
11243
+ }
11244
+ file.data.imports = imports;
11245
+ };
11246
+ }
11247
+
11248
+ // src/build/transforms/plugins/remark-node-id.ts
11249
+ init_deno_env();
11250
+ import { visit as visit4 } from "unist-util-visit";
11251
+ function remarkAddNodeId(options = {}) {
11252
+ const { prefix = "node", includePosition = true } = options;
11253
+ return (tree, file) => {
11254
+ let nodeId = 0;
11255
+ const nodeMap = /* @__PURE__ */ new Map();
11256
+ visit4(tree, (node) => {
11257
+ if (["yaml", "toml", "mdxjsEsm", "mdxjsFlow"].includes(String(node.type))) {
11258
+ return;
11259
+ }
11260
+ if (!node.data) {
11261
+ node.data = {};
11262
+ }
11263
+ if (!node.data.hProperties) {
11264
+ node.data.hProperties = {};
11265
+ }
11266
+ const id = `${prefix}-${nodeId}`;
11267
+ node.data.hProperties["data-node-id"] = id;
11268
+ if (includePosition && node.position) {
11269
+ const pos = node.position;
11270
+ node.data.hProperties["data-node-start"] = pos.start.offset;
11271
+ node.data.hProperties["data-node-end"] = pos.end.offset;
11272
+ node.data.hProperties["data-node-line"] = pos.start.line;
11273
+ node.data.hProperties["data-node-column"] = pos.start.column;
11274
+ node.data.hProperties["data-node-end-line"] = pos.end.line;
11275
+ node.data.hProperties["data-node-end-column"] = pos.end.column;
11276
+ }
11277
+ nodeMap.set(nodeId, {
11278
+ id,
11279
+ type: node.type,
11280
+ position: node.position,
11281
+ value: node.value
11282
+ });
11283
+ nodeId++;
11284
+ });
11285
+ if (!file.data) {
11286
+ file.data = {};
11287
+ }
11288
+ file.data.nodeMap = nodeMap;
11289
+ file.data.nodeCount = nodeId;
11290
+ };
11291
+ }
11292
+
11293
+ // src/build/transforms/plugins/rehype-mermaid.ts
11294
+ init_deno_env();
11295
+ import { visit as visit5 } from "unist-util-visit";
11296
+ function rehypeMermaid() {
11297
+ return (tree) => {
11298
+ visit5(tree, "element", (node, index, parent) => {
11299
+ const firstChild = node.children[0];
11300
+ if (node.tagName === "pre" && node.children.length === 1 && firstChild && firstChild.type === "element" && firstChild.tagName === "code") {
11301
+ const codeNode = node.children[0];
11302
+ const className = codeNode.properties?.className;
11303
+ const isMermaid = Array.isArray(className) ? className.some(
11304
+ (c) => String(c).includes("mermaid") || String(c).includes("language-mermaid")
11305
+ ) : String(className || "").includes("mermaid");
11306
+ if (isMermaid && parent && typeof index === "number") {
11307
+ const textContent = extractText(codeNode);
11308
+ const mermaidDiv = {
11309
+ type: "element",
11310
+ tagName: "div",
11311
+ properties: {
11312
+ className: ["mermaid"]
11313
+ },
11314
+ children: [{ type: "text", value: textContent }]
11315
+ };
11316
+ parent.children[index] = mermaidDiv;
11317
+ }
11318
+ }
11319
+ });
11320
+ };
11321
+ }
11322
+ function extractText(node) {
11323
+ let text2 = "";
11324
+ for (const child of node.children) {
11325
+ if (child.type === "text") {
11326
+ text2 += child.value;
11327
+ } else if (child.type === "element") {
11328
+ text2 += extractText(child);
11329
+ }
11330
+ }
11331
+ return text2.trim();
11332
+ }
11333
+
11334
+ // src/build/transforms/plugins/plugin-loader.ts
11335
+ import remarkGfm from "remark-gfm";
11336
+ import remarkFrontmatter from "remark-frontmatter";
11337
+ import rehypeHighlight from "rehype-highlight";
11338
+ import rehypeSlug from "rehype-slug";
11339
+ async function loadUserPlugins(projectDir, adapter, pluginType) {
11340
+ try {
11341
+ const _config = await getConfig(projectDir, adapter);
11342
+ return [];
11343
+ } catch (error2) {
11344
+ serverLogger.warn(
11345
+ `Failed to load ${pluginType} plugins from config`,
11346
+ { error: error2 instanceof Error ? error2.message : String(error2) }
11347
+ );
11348
+ return [];
11349
+ }
11350
+ }
11351
+ async function getRemarkPlugins(projectDir, adapter) {
11352
+ const defaultPlugins = [
11353
+ remarkGfm,
11354
+ remarkFrontmatter,
11355
+ remarkAddNodeId,
11356
+ remarkMdxHeadings,
11357
+ remarkMdxRemoveParagraphs,
11358
+ remarkCodeBlocks,
11359
+ remarkMdxImports
11360
+ ];
11361
+ if (adapter) {
11362
+ try {
11363
+ const userPlugins = await loadUserPlugins(projectDir, adapter, "remark");
11364
+ return [...defaultPlugins, ...userPlugins];
11365
+ } catch (error2) {
11366
+ serverLogger.error(
11367
+ "Error loading user remark plugins",
11368
+ { error: error2 instanceof Error ? error2.message : String(error2) }
11369
+ );
11370
+ }
11371
+ }
11372
+ return defaultPlugins;
11373
+ }
11374
+ async function getRehypePlugins(projectDir, adapter) {
11375
+ const defaultPlugins = [
11376
+ rehypeMermaid,
11377
+ // Must run before rehypeHighlight
11378
+ rehypeHighlight,
11379
+ rehypeSlug,
11380
+ rehypePreserveNodeIds,
11381
+ rehypeAddClasses,
11382
+ rehypeMdxComponents
11383
+ ];
11384
+ if (adapter) {
11385
+ try {
11386
+ const userPlugins = await loadUserPlugins(projectDir, adapter, "rehype");
11387
+ return [...defaultPlugins, ...userPlugins];
11388
+ } catch (error2) {
11389
+ serverLogger.error(
11390
+ "Error loading user rehype plugins",
11391
+ { error: error2 instanceof Error ? error2.message : String(error2) }
11392
+ );
11393
+ }
11394
+ }
11395
+ return defaultPlugins;
11396
+ }
11397
+
11398
+ // src/build/transforms/mdx/compiler/frontmatter-extractor.ts
11399
+ init_deno_env();
11400
+ init_utils();
11401
+ async function extractYamlFrontmatter(content) {
11402
+ if (!content.trim().startsWith("---")) {
11403
+ return { body: content, frontmatter: {} };
11404
+ }
11405
+ const { extract } = await import("gray-matter");
11406
+ const extracted = extract(content);
11407
+ return {
11408
+ body: extracted.body,
11409
+ frontmatter: extracted.attrs
11410
+ };
11411
+ }
11412
+ function extractExportConstants(body) {
11413
+ const exportRegex = /^export\s+const\s+(\w+)\s*=\s*(['"`][^'"`\n]*['"`]|\d+(?:\.\d+)?|true|false|null)\s*;?\s*$/gm;
11414
+ const exports = {};
11415
+ const linesToRemove = [];
11416
+ let match;
11417
+ while ((match = exportRegex.exec(body)) !== null) {
11418
+ const key = match[1];
11419
+ const rawValue = match[2];
11420
+ if (key && key.length > 0 && rawValue) {
11421
+ linesToRemove.push(match[0]);
11422
+ if (rawValue === "true") {
11423
+ exports[key] = true;
11424
+ } else if (rawValue === "false") {
11425
+ exports[key] = false;
11426
+ } else if (rawValue === "null") {
11427
+ exports[key] = null;
11428
+ } else if (/^\d+(?:\.\d+)?$/.test(rawValue)) {
11429
+ exports[key] = parseFloat(rawValue);
11430
+ } else {
11431
+ exports[key] = rawValue.replace(/^['"`]|['"`]$/g, "");
11432
+ }
11433
+ }
11434
+ }
11435
+ let cleanedBody = body;
11436
+ for (const line of linesToRemove) {
11437
+ cleanedBody = cleanedBody.replace(line, "");
11438
+ }
11439
+ return { body: cleanedBody, exports };
11440
+ }
11441
+ async function extractFrontmatter(content, providedFrontmatter) {
11442
+ let body = content;
11443
+ let frontmatter = {};
11444
+ if (content.trim().startsWith("---")) {
11445
+ const yamlResult = await extractYamlFrontmatter(content);
11446
+ body = yamlResult.body;
11447
+ frontmatter = yamlResult.frontmatter;
11448
+ }
11449
+ if (providedFrontmatter) {
11450
+ frontmatter = { ...frontmatter, ...providedFrontmatter };
11451
+ }
11452
+ const exportResult = extractExportConstants(body);
11453
+ body = exportResult.body;
11454
+ frontmatter = { ...frontmatter, ...exportResult.exports };
11455
+ rendererLogger.info("Extracted frontmatter:", frontmatter);
11456
+ return { body, frontmatter };
11457
+ }
11458
+
11459
+ // src/build/transforms/mdx/compiler/import-rewriter.ts
11460
+ init_deno_env();
11461
+ import { dirname as dirname3, join as join4, resolve as pathResolve } from "node:path";
11462
+ function toAbsPath(spec, basedir) {
11463
+ try {
11464
+ if (spec.startsWith("file://"))
11465
+ return new URL(spec).pathname;
11466
+ if (spec.startsWith("/"))
11467
+ return pathResolve(spec);
11468
+ if (spec.startsWith("http://") || spec.startsWith("https://"))
11469
+ return spec;
11470
+ if (!spec.startsWith(".") && !spec.startsWith("/")) {
11471
+ return spec;
11472
+ }
11473
+ return pathResolve(join4(basedir, spec));
11474
+ } catch {
11475
+ return spec;
11476
+ }
11477
+ }
11478
+ function toBrowserFs(abs, baseUrl) {
11479
+ if (abs.startsWith("http://") || abs.startsWith("https://"))
11480
+ return abs;
11481
+ const b64 = btoa(abs).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
11482
+ const path = `/_veryfront/fs/${b64}.js`;
11483
+ return baseUrl ? `${baseUrl}${path}` : path;
11484
+ }
11485
+ function mapSpec(spec, basedir, target, baseUrl, _projectDir) {
11486
+ if (spec.startsWith("@/")) {
11487
+ const relativePath = spec.slice(2);
11488
+ if (target === "browser") {
11489
+ const path = `/_vf_modules/${relativePath}.js`;
11490
+ return baseUrl ? `${baseUrl}${path}` : path;
11491
+ } else {
11492
+ return spec;
11493
+ }
11494
+ }
11495
+ const abs = toAbsPath(spec, basedir);
11496
+ if (typeof abs !== "string")
11497
+ return spec;
11498
+ if (abs === spec && !spec.startsWith(".") && !spec.startsWith("/") && !spec.startsWith("file://") && !spec.startsWith("http")) {
11499
+ return spec;
11500
+ }
11501
+ if (target === "browser")
11502
+ return toBrowserFs(abs, baseUrl);
11503
+ return abs.startsWith("http") ? abs : `file://${abs}`;
11504
+ }
11505
+ function rewriteLine(line, basedir, target, baseUrl, projectDir) {
11506
+ const mapper = (spec) => mapSpec(spec, basedir, target, baseUrl, projectDir);
11507
+ line = line.replace(
11508
+ /^(\s*import\s+[^'";]+?from\s+)(["'])([^"']+)(\2)/,
11509
+ (_m, p1, q, s, q2) => `${p1}${q}${mapper(s)}${q2}`
11510
+ );
11511
+ line = line.replace(
11512
+ /^(\s*import\s+)(["'])([^"']+)(\2)/,
11513
+ (_m, p1, q, s, q2) => `${p1}${q}${mapper(s)}${q2}`
11514
+ );
11515
+ line = line.replace(
11516
+ /^(\s*export\s+[^'";]+?from\s+)(["'])([^"']+)(\2)/,
11517
+ (_m, p1, q, s, q2) => `${p1}${q}${mapper(s)}${q2}`
11518
+ );
11519
+ return line;
11520
+ }
11521
+ function rewriteBodyImports(body, config) {
11522
+ const basedir = dirname3(config.filePath);
11523
+ return body.split(/\r?\n/).map((ln) => {
11524
+ const trimmed = ln.trimStart();
11525
+ if (trimmed.startsWith("import") || trimmed.startsWith("export")) {
11526
+ return rewriteLine(ln, basedir, config.target, config.baseUrl, config.projectDir);
11527
+ }
11528
+ return ln;
11529
+ }).join("\n");
11530
+ }
11531
+ function rewriteCompiledImports(compiledCode, config) {
11532
+ const basedir = dirname3(config.filePath);
11533
+ const mapper = (spec) => mapSpec(spec, basedir, config.target, config.baseUrl, config.projectDir);
11534
+ let code = compiledCode;
11535
+ code = code.replace(
11536
+ /(from\s+["'])(@\/[^"']+)(["'])/g,
11537
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
11538
+ );
11539
+ code = code.replace(
11540
+ /(import\(\s*["'])(@\/[^"']+)(["']\s*\))/g,
11541
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
11542
+ );
11543
+ code = code.replace(
11544
+ /(from\s+["'])(\.{1,2}\/[^"']+)(["'])/g,
11545
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
11546
+ );
11547
+ code = code.replace(
11548
+ /(from\s+["'])(file:\/\/[^"']+)(["'])/g,
11549
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
11550
+ );
11551
+ code = code.replace(
11552
+ /(import\(\s*["'])(\.{1,2}\/[^"']+)(["']\s*\))/g,
11553
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
11554
+ );
11555
+ code = code.replace(
11556
+ /(import\(\s*["'])(file:\/\/[^"']+)(["']\s*\))/g,
11557
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
11558
+ );
11559
+ code = code.replace(/file:\/\/[A-Za-z0-9_\-./%]+/g, (match) => mapper(match));
11560
+ return code;
11561
+ }
11562
+
11563
+ // src/build/transforms/mdx/compiler/mdx-compiler.ts
11564
+ init_veryfront_error();
11565
+
11566
+ // src/build/transforms/plugins/rehype-node-positions.ts
11567
+ init_deno_env();
11568
+ import { visit as visit6 } from "unist-util-visit";
11569
+ function rehypeNodePositions(options = {}) {
11570
+ console.log("[rehypeNodePositions] Plugin called with options:", options);
11571
+ return (tree) => {
11572
+ console.log(
11573
+ "[rehypeNodePositions] Processing tree, root type:",
11574
+ tree.type,
11575
+ "children:",
11576
+ tree.children?.length
11577
+ );
11578
+ tree.children?.slice(0, 5).forEach((child, i) => {
11579
+ console.log(
11580
+ `[rehypeNodePositions] Child ${i}: type=${child.type}, name=${child.name || child.tagName || "N/A"}`
11581
+ );
11582
+ });
11583
+ let elementCount = 0;
11584
+ let positionCount = 0;
11585
+ visit6(tree, (node) => {
11586
+ if (node.type === "element") {
11587
+ elementCount++;
11588
+ if (node.position) {
11589
+ positionCount++;
11590
+ addPositionAttributes(node, node.properties || (node.properties = {}), options.filePath);
11591
+ }
11592
+ return;
11593
+ }
11594
+ if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") {
11595
+ elementCount++;
11596
+ console.log(
11597
+ "[rehypeNodePositions] Found MDX JSX element:",
11598
+ node.name,
11599
+ "position:",
11600
+ node.position ? "yes" : "no"
11601
+ );
11602
+ if (node.position) {
11603
+ positionCount++;
11604
+ if (!node.attributes) {
11605
+ node.attributes = [];
11606
+ }
11607
+ const { start, end } = node.position;
11608
+ if (start) {
11609
+ node.attributes.push(
11610
+ { type: "mdxJsxAttribute", name: "data-node-line", value: String(start.line) },
11611
+ {
11612
+ type: "mdxJsxAttribute",
11613
+ name: "data-node-column",
11614
+ value: String(start.column - 1)
11615
+ }
11616
+ );
11617
+ }
11618
+ if (end) {
11619
+ node.attributes.push(
11620
+ { type: "mdxJsxAttribute", name: "data-node-end-line", value: String(end.line) },
11621
+ {
11622
+ type: "mdxJsxAttribute",
11623
+ name: "data-node-end-column",
11624
+ value: String(end.column - 1)
11625
+ }
11626
+ );
11627
+ }
11628
+ if (options.filePath) {
11629
+ node.attributes.push(
11630
+ { type: "mdxJsxAttribute", name: "data-node-file", value: options.filePath }
11631
+ );
11632
+ }
11633
+ }
11634
+ }
11635
+ });
11636
+ console.log("[rehypeNodePositions] Processed", { elementCount, positionCount });
11637
+ };
11638
+ }
11639
+ function addPositionAttributes(node, properties, filePath) {
11640
+ if (!node.position)
11641
+ return;
11642
+ const { start, end } = node.position;
11643
+ if (start) {
11644
+ properties["data-node-line"] = start.line;
11645
+ properties["data-node-column"] = start.column - 1;
9154
11646
  }
9155
- if (importMap.imports?.[specifier]) {
9156
- return importMap.imports[specifier];
11647
+ if (end) {
11648
+ properties["data-node-end-line"] = end.line;
11649
+ properties["data-node-end-column"] = end.column - 1;
9157
11650
  }
9158
- if (specifier.endsWith(".js") || specifier.endsWith(".mjs") || specifier.endsWith(".cjs")) {
9159
- const base = specifier.replace(/\.(m|c)?js$/, "");
9160
- if (importMap.imports?.[base]) {
9161
- return importMap.imports[base];
9162
- }
11651
+ if (filePath) {
11652
+ properties["data-node-file"] = filePath;
9163
11653
  }
9164
- if (importMap.imports) {
9165
- for (const [key, value] of Object.entries(importMap.imports)) {
9166
- if (key.endsWith("/") && specifier.startsWith(key)) {
9167
- return value + specifier.slice(key.length);
9168
- }
11654
+ }
11655
+
11656
+ // src/build/transforms/mdx/compiler/mdx-compiler.ts
11657
+ async function compileMDXRuntime(mode, projectDir, content, frontmatter, filePath, target = "server", baseUrl) {
11658
+ try {
11659
+ const { compile } = await import("@mdx-js/mdx");
11660
+ const remarkPlugins = await getRemarkPlugins(projectDir);
11661
+ const rehypePlugins = await getRehypePlugins(projectDir);
11662
+ const extracted = await extractFrontmatter(content, frontmatter);
11663
+ let { body } = extracted;
11664
+ const { frontmatter: extractedFrontmatter } = extracted;
11665
+ if (filePath && (target === "browser" || target === "server")) {
11666
+ body = rewriteBodyImports(body, { filePath, target, baseUrl, projectDir });
11667
+ }
11668
+ const allRehypePlugins = [
11669
+ ...rehypePlugins,
11670
+ [rehypeNodePositions, { filePath }]
11671
+ ];
11672
+ const compiled = await compile(body, {
11673
+ outputFormat: "program",
11674
+ development: mode === "development",
11675
+ remarkPlugins,
11676
+ rehypePlugins: allRehypePlugins,
11677
+ providerImportSource: void 0,
11678
+ jsxImportSource: "react"
11679
+ });
11680
+ rendererLogger.info("MDX compiled output preview:", String(compiled).substring(0, 200));
11681
+ rendererLogger.info("Extracted frontmatter:", extractedFrontmatter);
11682
+ let compiledCode = String(compiled);
11683
+ if (filePath && (target === "browser" || target === "server")) {
11684
+ compiledCode = rewriteCompiledImports(compiledCode, {
11685
+ filePath,
11686
+ target,
11687
+ baseUrl,
11688
+ projectDir
11689
+ });
9169
11690
  }
11691
+ return {
11692
+ compiledCode,
11693
+ frontmatter: extractedFrontmatter,
11694
+ globals: {},
11695
+ headings: [],
11696
+ nodeMap: /* @__PURE__ */ new Map()
11697
+ };
11698
+ } catch (error2) {
11699
+ rendererLogger.error("[MDX Compiler] Compilation failed:", {
11700
+ filePath,
11701
+ error: error2 instanceof Error ? error2.message : String(error2),
11702
+ stack: error2 instanceof Error ? error2.stack : void 0
11703
+ });
11704
+ throw toError(createError({
11705
+ type: "build",
11706
+ message: `MDX compilation error: ${error2 instanceof Error ? error2.message : String(error2)} | file: ${filePath || "<memory>"}`
11707
+ }));
9170
11708
  }
9171
- return specifier;
9172
11709
  }
9173
11710
 
9174
- // src/module-system/import-map/transformer.ts
9175
- init_deno_env();
9176
- function transformImportsWithMap(code, importMap, scope, options) {
9177
- let transformedCode = code;
9178
- transformedCode = transformedCode.replace(
9179
- /((?:import|export)\s+(?:[\w,{}\s*]+\s+from\s+)?|export\s+(?:\*|\{[^}]+\})\s+from\s+)["']([^"']+)["']/g,
9180
- (_match, prefix, specifier) => {
9181
- const isBare = !specifier.startsWith("http") && !specifier.startsWith("/") && !specifier.startsWith(".");
9182
- if (isBare && !options?.resolveBare) {
9183
- return `${prefix}"${specifier}"`;
9184
- }
9185
- const resolved = resolveImport(specifier, importMap, scope);
9186
- return `${prefix}"${resolved}"`;
9187
- }
9188
- );
9189
- transformedCode = transformedCode.replace(
9190
- /from\s+["']([^"']+)["']/g,
9191
- (match, specifier) => {
9192
- const isBare = !specifier.startsWith("http") && !specifier.startsWith("/") && !specifier.startsWith(".");
9193
- if (isBare && !options?.resolveBare) {
9194
- return match;
9195
- }
9196
- const resolved = resolveImport(specifier, importMap, scope);
9197
- return `from "${resolved}"`;
9198
- }
9199
- );
9200
- transformedCode = transformedCode.replace(
9201
- /import\s*\(\s*["']([^"']+)["']\s*\)/g,
9202
- (_match, specifier) => {
9203
- const resolved = resolveImport(specifier, importMap, scope);
9204
- return `import("${resolved}")`;
11711
+ // src/build/transforms/esm/transform-core.ts
11712
+ init_utils();
11713
+ async function transformToESM(source, filePath, projectDir, _adapter, options) {
11714
+ const transformStart = performance.now();
11715
+ const timings2 = {};
11716
+ const {
11717
+ dev = true,
11718
+ projectId,
11719
+ jsxImportSource = "react",
11720
+ moduleServerUrl,
11721
+ vendorBundleHash,
11722
+ ssr = false
11723
+ } = options;
11724
+ const hashStart = performance.now();
11725
+ const contentHash = await computeContentHash2(source);
11726
+ timings2.hash = performance.now() - hashStart;
11727
+ const cacheKey = generateCacheKey(projectId, filePath, contentHash, ssr);
11728
+ const cached = getCachedTransform(cacheKey);
11729
+ if (cached) {
11730
+ return cached.code;
11731
+ }
11732
+ let transformSource = source;
11733
+ if (filePath.endsWith(".mdx")) {
11734
+ const mdxStart = performance.now();
11735
+ const mdxTarget = ssr ? "server" : "browser";
11736
+ const mdxBaseUrl = ssr ? void 0 : moduleServerUrl;
11737
+ const mdxResult = await compileMDXRuntime(
11738
+ dev ? "development" : "production",
11739
+ projectDir,
11740
+ source,
11741
+ void 0,
11742
+ filePath,
11743
+ mdxTarget,
11744
+ mdxBaseUrl
11745
+ );
11746
+ transformSource = mdxResult.compiledCode;
11747
+ timings2.mdx = performance.now() - mdxStart;
11748
+ }
11749
+ const esbuildStart = performance.now();
11750
+ const loader = getLoaderFromPath(filePath);
11751
+ let result;
11752
+ try {
11753
+ result = await esbuild.transform(transformSource, {
11754
+ loader,
11755
+ format: "esm",
11756
+ target: "es2020",
11757
+ jsx: "automatic",
11758
+ jsxImportSource,
11759
+ minify: !dev,
11760
+ sourcemap: dev ? "inline" : false,
11761
+ treeShaking: !dev,
11762
+ // Disable in dev mode to preserve import errors
11763
+ keepNames: true
11764
+ });
11765
+ } catch (transformError) {
11766
+ const sourcePreview = transformSource.split("\n").slice(0, 10).map(
11767
+ (line, i) => `${String(i + 1).padStart(3, " ")}| ${line}`
11768
+ ).join("\n");
11769
+ rendererLogger.error("[ESM-TRANSFORM] Transform failed", {
11770
+ filePath,
11771
+ loader,
11772
+ sourceLength: transformSource.length,
11773
+ isMdx: filePath.endsWith(".mdx"),
11774
+ error: transformError instanceof Error ? transformError.message : String(transformError)
11775
+ });
11776
+ rendererLogger.error("[ESM-TRANSFORM] Source preview (first 10 lines):\n" + sourcePreview);
11777
+ const errorMsg = transformError instanceof Error ? transformError.message : String(transformError);
11778
+ throw new Error(`ESM transform failed for ${filePath} (loader: ${loader}): ${errorMsg}`);
11779
+ }
11780
+ timings2.esbuild = performance.now() - esbuildStart;
11781
+ const rewriteStart = performance.now();
11782
+ let code = result.code;
11783
+ code = await resolveReactImports(code, ssr);
11784
+ code = await addDepsToEsmShUrls(code, ssr);
11785
+ code = await resolvePathAliases(code, filePath, projectDir, ssr);
11786
+ const apiBaseUrl = options.apiBaseUrl || Deno.env.get("VERYFRONT_API_BASE_URL") || Deno.env.get("VERYFRONT_API_URL")?.replace("/graphql", "/api") || "http://api.lvh.me:4000/api";
11787
+ code = await resolveCrossProjectImports(code, {
11788
+ apiBaseUrl,
11789
+ ssr
11790
+ });
11791
+ if (ssr) {
11792
+ const urlBlockResult = await blockExternalUrlImports(code, filePath);
11793
+ code = urlBlockResult.code;
11794
+ if (urlBlockResult.blockedUrls.length > 0) {
11795
+ rendererLogger.warn("[ESM-TRANSFORM] Blocked external URL imports in SSR mode", {
11796
+ file: filePath.slice(-60),
11797
+ blockedUrls: urlBlockResult.blockedUrls
11798
+ });
9205
11799
  }
9206
- );
9207
- return transformedCode;
11800
+ code = await resolveRelativeImportsForSSR(code);
11801
+ code = await resolveVeryfrontImports(code);
11802
+ } else {
11803
+ code = await resolveRelativeImports(code, filePath, projectDir, moduleServerUrl);
11804
+ if (moduleServerUrl && vendorBundleHash) {
11805
+ code = await rewriteVendorImports(code, moduleServerUrl, vendorBundleHash);
11806
+ } else {
11807
+ code = await rewriteBareImports(code, moduleServerUrl);
11808
+ }
11809
+ }
11810
+ timings2.rewrite = performance.now() - rewriteStart;
11811
+ setCachedTransform(cacheKey, code, contentHash);
11812
+ const totalMs = performance.now() - transformStart;
11813
+ rendererLogger.debug("[ESM-TRANSFORM] Timing breakdown", {
11814
+ file: filePath.slice(-40),
11815
+ totalMs: totalMs.toFixed(1),
11816
+ hashMs: timings2.hash?.toFixed(1),
11817
+ mdxMs: timings2.mdx?.toFixed(1),
11818
+ esbuildMs: timings2.esbuild?.toFixed(1),
11819
+ rewriteMs: timings2.rewrite?.toFixed(1)
11820
+ });
11821
+ return code;
9208
11822
  }
9209
11823
 
9210
- // src/module-system/import-map/merger.ts
9211
- init_deno_env();
9212
-
9213
11824
  // src/build/transforms/mdx/esm-module-loader.ts
9214
- init_runtime();
9215
- init_process();
9216
- import { join as join4 } from "node:path";
9217
- var IS_TRUE_NODE = isNode && !isDeno;
11825
+ var IS_TRUE_NODE2 = isNode && !isDeno;
9218
11826
  var LOG_PREFIX_MDX_LOADER = "[mdx-loader]";
9219
11827
  var LOG_PREFIX_MDX_RENDERER = "[mdx-renderer]";
9220
11828
  var JSX_IMPORT_PATTERN = /import\s+([^'"]+)\s+from\s+['"]file:\/\/([^'"]+\.(jsx|tsx))['"];?/g;
@@ -9224,8 +11832,42 @@ var ESBUILD_JSX_FACTORY = "React.createElement";
9224
11832
  var ESBUILD_JSX_FRAGMENT = "React.Fragment";
9225
11833
  var HTTP_MODULE_FETCH_TIMEOUT_MS2 = 3e4;
9226
11834
  var _resolvedPaths = {};
11835
+ var _modulePathCache = null;
11836
+ var _modulePathCacheLoaded = false;
11837
+ async function getModulePathCache(cacheDir) {
11838
+ if (_modulePathCache && _modulePathCacheLoaded) {
11839
+ return _modulePathCache;
11840
+ }
11841
+ _modulePathCache = /* @__PURE__ */ new Map();
11842
+ const indexPath = join6(cacheDir, "_index.json");
11843
+ try {
11844
+ const content = await Deno.readTextFile(indexPath);
11845
+ const index = JSON.parse(content);
11846
+ for (const [path, cachePath] of Object.entries(index)) {
11847
+ _modulePathCache.set(path, cachePath);
11848
+ }
11849
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Loaded module index: ${_modulePathCache.size} entries`);
11850
+ } catch {
11851
+ }
11852
+ _modulePathCacheLoaded = true;
11853
+ return _modulePathCache;
11854
+ }
11855
+ async function saveModulePathCache(cacheDir) {
11856
+ if (!_modulePathCache)
11857
+ return;
11858
+ const indexPath = join6(cacheDir, "_index.json");
11859
+ const index = {};
11860
+ for (const [path, cachePath] of _modulePathCache.entries()) {
11861
+ index[path] = cachePath;
11862
+ }
11863
+ try {
11864
+ await Deno.writeTextFile(indexPath, JSON.stringify(index));
11865
+ } catch (error2) {
11866
+ rendererLogger.warn(`${LOG_PREFIX_MDX_LOADER} Failed to save module index`, error2);
11867
+ }
11868
+ }
9227
11869
  async function resolveNodePackage(packageSpec) {
9228
- if (!IS_TRUE_NODE)
11870
+ if (!IS_TRUE_NODE2)
9229
11871
  return null;
9230
11872
  if (packageSpec in _resolvedPaths)
9231
11873
  return _resolvedPaths[packageSpec];
@@ -9241,7 +11883,7 @@ async function resolveNodePackage(packageSpec) {
9241
11883
  }
9242
11884
  }
9243
11885
  async function transformReactImportsToAbsolute(code) {
9244
- if (!IS_TRUE_NODE)
11886
+ if (!IS_TRUE_NODE2)
9245
11887
  return code;
9246
11888
  const reactPath = await resolveNodePackage("react");
9247
11889
  const reactJsxPath = await resolveNodePackage("react/jsx-runtime");
@@ -9274,6 +11916,94 @@ async function transformReactImportsToAbsolute(code) {
9274
11916
  }
9275
11917
  return result;
9276
11918
  }
11919
+ function addExternalToEsmShUrls(code) {
11920
+ if (IS_TRUE_NODE2)
11921
+ return code;
11922
+ return code.replace(
11923
+ /from\s+["'](https:\/\/esm\.sh\/[^"']+)["']/g,
11924
+ (match, url) => {
11925
+ if (url.includes("external=")) {
11926
+ return match;
11927
+ }
11928
+ if (url.includes("/react@") || url.includes("/react-dom@")) {
11929
+ return match;
11930
+ }
11931
+ const separator = url.includes("?") ? "&" : "?";
11932
+ return `from "${url}${separator}external=react,react-dom"`;
11933
+ }
11934
+ );
11935
+ }
11936
+ function normalizeReactToNpm(code) {
11937
+ if (IS_TRUE_NODE2)
11938
+ return code;
11939
+ const REACT_VERSION = "18.3.1";
11940
+ let result = code;
11941
+ result = result.replace(
11942
+ /import\s*\{([^}]*)\bjsxDEV\s+as\s+(\w+)([^}]*)\}\s*from\s*["']([^"']*\/?)jsx-dev-runtime["']/g,
11943
+ (_match, before, alias, after, prefix) => {
11944
+ return `import {${before}jsx as ${alias}${after}} from "${prefix}jsx-runtime"`;
11945
+ }
11946
+ );
11947
+ result = result.replace(
11948
+ /import\s*\{([^}]*)\bjsxDEV\b([^}]*)\}\s*from\s*["']([^"']*\/?)jsx-dev-runtime["']/g,
11949
+ (_match, before, after, prefix) => {
11950
+ return `import {${before}jsx${after}} from "${prefix}jsx-runtime"`;
11951
+ }
11952
+ );
11953
+ result = result.replace(
11954
+ /from\s+['"]https:\/\/esm\.sh\/react@[^'"\/]+\/jsx-dev-runtime[^'"]*['"]/g,
11955
+ `from "npm:react@${REACT_VERSION}/jsx-runtime"`
11956
+ );
11957
+ result = result.replace(
11958
+ /from\s+['"]https:\/\/esm\.sh\/react@[^'"\/]+\/jsx-runtime[^'"]*['"]/g,
11959
+ `from "npm:react@${REACT_VERSION}/jsx-runtime"`
11960
+ );
11961
+ result = result.replace(
11962
+ /from\s+['"]https:\/\/esm\.sh\/react-dom@[^'"\/]+\/server[^'"]*['"]/g,
11963
+ `from "npm:react-dom@${REACT_VERSION}/server"`
11964
+ );
11965
+ result = result.replace(
11966
+ /from\s+['"]npm:react\/jsx-dev-runtime['"]/g,
11967
+ `from "npm:react@${REACT_VERSION}/jsx-runtime"`
11968
+ );
11969
+ result = result.replace(
11970
+ /from\s+['"]npm:react\/jsx-runtime['"]/g,
11971
+ `from "npm:react@${REACT_VERSION}/jsx-runtime"`
11972
+ );
11973
+ result = result.replace(
11974
+ /from\s+['"]npm:react-dom\/server['"]/g,
11975
+ `from "npm:react-dom@${REACT_VERSION}/server"`
11976
+ );
11977
+ result = result.replace(
11978
+ /from\s+['"]react\/jsx-dev-runtime['"]/g,
11979
+ `from "npm:react@${REACT_VERSION}/jsx-runtime"`
11980
+ );
11981
+ result = result.replace(
11982
+ /from\s+['"]react\/jsx-runtime['"]/g,
11983
+ `from "npm:react@${REACT_VERSION}/jsx-runtime"`
11984
+ );
11985
+ result = result.replace(
11986
+ /from\s+['"]https:\/\/esm\.sh\/react@[^'"\/]+['"]/g,
11987
+ `from "npm:react@${REACT_VERSION}"`
11988
+ );
11989
+ result = result.replace(
11990
+ /from\s+['"]https:\/\/esm\.sh\/react-dom@[^'"\/]+['"]/g,
11991
+ `from "npm:react-dom@${REACT_VERSION}"`
11992
+ );
11993
+ result = result.replace(
11994
+ /from\s+['"]npm:react['"]/g,
11995
+ `from "npm:react@${REACT_VERSION}"`
11996
+ );
11997
+ result = result.replace(
11998
+ /from\s+['"]npm:react-dom['"]/g,
11999
+ `from "npm:react-dom@${REACT_VERSION}"`
12000
+ );
12001
+ result = result.replace(
12002
+ /from\s+['"]npm:@tanstack\/react-query(?:@[^'"\/]+)?['"]/g,
12003
+ `from "https://esm.sh/@tanstack/react-query?external=react,react-dom"`
12004
+ );
12005
+ return result;
12006
+ }
9277
12007
  function hashString(input) {
9278
12008
  const HASH_SEED_FNV1A2 = 2166136261;
9279
12009
  let hash = HASH_SEED_FNV1A2 >>> 0;
@@ -9344,37 +12074,436 @@ function createHTTPPluginForMDX() {
9344
12074
  };
9345
12075
  }
9346
12076
  async function loadModuleESM(compiledProgramCode, context) {
12077
+ const loadStart = performance.now();
9347
12078
  try {
9348
12079
  const { getAdapter: getAdapter2 } = await Promise.resolve().then(() => (init_detect(), detect_exports));
9349
12080
  const adapter = await getAdapter2();
9350
12081
  if (!context.esmCacheDir) {
9351
- if (IS_TRUE_NODE) {
9352
- const projectCacheDir = join4(
9353
- cwd(),
9354
- "node_modules",
9355
- ".cache",
9356
- "veryfront-mdx"
9357
- );
9358
- await adapter.fs.mkdir(projectCacheDir, { recursive: true });
9359
- context.esmCacheDir = projectCacheDir;
9360
- } else {
9361
- context.esmCacheDir = await adapter.fs.makeTempDir("veryfront-mdx-esm-");
12082
+ const persistentCacheDir = join6(cwd(), ".cache", "veryfront-mdx-esm");
12083
+ try {
12084
+ await Deno.mkdir(persistentCacheDir, { recursive: true });
12085
+ context.esmCacheDir = persistentCacheDir;
12086
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Using persistent cache dir: ${persistentCacheDir}`);
12087
+ } catch {
12088
+ if (IS_TRUE_NODE2) {
12089
+ const projectCacheDir = join6(cwd(), "node_modules", ".cache", "veryfront-mdx");
12090
+ await adapter.fs.mkdir(projectCacheDir, { recursive: true });
12091
+ context.esmCacheDir = projectCacheDir;
12092
+ } else {
12093
+ context.esmCacheDir = await adapter.fs.makeTempDir("veryfront-mdx-esm-");
12094
+ }
9362
12095
  }
9363
12096
  }
9364
- let rewritten;
9365
- if (IS_TRUE_NODE) {
9366
- rewritten = await transformReactImportsToAbsolute(compiledProgramCode);
12097
+ let rewritten = compiledProgramCode.replace(
12098
+ /from\s+["']@\/([^"']+)["']/g,
12099
+ (_match, path) => {
12100
+ const jsPath = path.endsWith(".js") ? path : `${path}.js`;
12101
+ return `from "/_vf_modules/${jsPath}"`;
12102
+ }
12103
+ );
12104
+ if (IS_TRUE_NODE2) {
12105
+ rewritten = await transformReactImportsToAbsolute(rewritten);
9367
12106
  } else {
9368
12107
  rewritten = transformImportsWithMap(
9369
- compiledProgramCode,
12108
+ rewritten,
9370
12109
  getDefaultImportMap(),
9371
12110
  void 0,
9372
12111
  { resolveBare: true }
9373
12112
  );
9374
12113
  }
12114
+ const vfModulePattern = /from\s+["'](\/?)(_vf_modules\/[^"']+)["']/g;
12115
+ const vfModuleImports = [];
12116
+ let vfMatch;
12117
+ while ((vfMatch = vfModulePattern.exec(rewritten)) !== null) {
12118
+ const [original, , path] = vfMatch;
12119
+ if (path) {
12120
+ vfModuleImports.push({ original, path });
12121
+ }
12122
+ }
12123
+ const projectDir = cwd();
12124
+ const projectId = "default";
12125
+ const inFlight = /* @__PURE__ */ new Map();
12126
+ async function fetchAndCacheModule(modulePath, parentModulePath) {
12127
+ let normalizedPath = modulePath.replace(/^\//, "");
12128
+ if (parentModulePath && (modulePath.startsWith("./") || modulePath.startsWith("../"))) {
12129
+ const parentDir = parentModulePath.replace(/\/[^/]+$/, "");
12130
+ const joinedPath = posix.join(parentDir, modulePath);
12131
+ normalizedPath = posix.normalize(joinedPath);
12132
+ if (!normalizedPath.startsWith("_vf_modules/")) {
12133
+ normalizedPath = `_vf_modules/${normalizedPath}`;
12134
+ }
12135
+ }
12136
+ const existingFetch = inFlight.get(normalizedPath);
12137
+ if (existingFetch) {
12138
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Waiting for in-flight fetch: ${normalizedPath}`);
12139
+ return existingFetch;
12140
+ }
12141
+ let resolveDeferred;
12142
+ const fetchPromise = new Promise((resolve2) => {
12143
+ resolveDeferred = resolve2;
12144
+ });
12145
+ inFlight.set(normalizedPath, fetchPromise);
12146
+ const result2 = await (async () => {
12147
+ const pathCache = await getModulePathCache(context.esmCacheDir);
12148
+ const cachedPath = pathCache.get(normalizedPath);
12149
+ if (cachedPath) {
12150
+ try {
12151
+ const stat = await adapter.fs.stat(cachedPath);
12152
+ if (stat?.isFile) {
12153
+ return cachedPath;
12154
+ }
12155
+ } catch {
12156
+ pathCache.delete(normalizedPath);
12157
+ }
12158
+ }
12159
+ try {
12160
+ const filePathWithoutJs = normalizedPath.replace(/^_vf_modules\//, "").replace(/\.js$/, "");
12161
+ const extensions = [".tsx", ".ts", ".jsx", ".js", ".mdx"];
12162
+ const prefixes = ["", "src/"];
12163
+ const prefixesToStrip = ["components/", "pages/", "lib/", "app/"];
12164
+ let sourceCode = null;
12165
+ let actualFilePath = null;
12166
+ const hasKnownExt = extensions.some((ext) => filePathWithoutJs.endsWith(ext));
12167
+ if (hasKnownExt) {
12168
+ for (const prefix of prefixes) {
12169
+ const tryPath = prefix + filePathWithoutJs;
12170
+ try {
12171
+ const content = await adapter.fs.readFile(tryPath);
12172
+ sourceCode = typeof content === "string" ? content : new TextDecoder().decode(content);
12173
+ actualFilePath = tryPath;
12174
+ break;
12175
+ } catch {
12176
+ }
12177
+ }
12178
+ }
12179
+ if (!sourceCode) {
12180
+ const filePathWithoutExt = hasKnownExt ? filePathWithoutJs.replace(/\.(tsx|ts|jsx|js|mdx)$/, "") : filePathWithoutJs;
12181
+ const triedPaths = [];
12182
+ outer:
12183
+ for (const prefix of prefixes) {
12184
+ for (const ext of extensions) {
12185
+ const tryPath = prefix + filePathWithoutExt + ext;
12186
+ triedPaths.push(tryPath);
12187
+ try {
12188
+ const content = await adapter.fs.readFile(tryPath);
12189
+ sourceCode = typeof content === "string" ? content : new TextDecoder().decode(content);
12190
+ actualFilePath = tryPath;
12191
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Found file with extension`, {
12192
+ normalizedPath,
12193
+ tryPath
12194
+ });
12195
+ break outer;
12196
+ } catch {
12197
+ }
12198
+ }
12199
+ }
12200
+ if (!sourceCode) {
12201
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Extension resolution failed`, {
12202
+ normalizedPath,
12203
+ filePathWithoutExt,
12204
+ triedPaths
12205
+ });
12206
+ }
12207
+ }
12208
+ if (!sourceCode) {
12209
+ const filePathWithoutExt = hasKnownExt ? filePathWithoutJs.replace(/\.(tsx|ts|jsx|js|mdx)$/, "") : filePathWithoutJs;
12210
+ stripLoop:
12211
+ for (const stripPrefix of prefixesToStrip) {
12212
+ if (filePathWithoutExt.startsWith(stripPrefix)) {
12213
+ const strippedPath = filePathWithoutExt.slice(stripPrefix.length);
12214
+ for (const ext of extensions) {
12215
+ const tryPath = strippedPath + ext;
12216
+ try {
12217
+ const content = await adapter.fs.readFile(tryPath);
12218
+ sourceCode = typeof content === "string" ? content : new TextDecoder().decode(content);
12219
+ actualFilePath = tryPath;
12220
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Found file after stripping prefix`, {
12221
+ originalPath: filePathWithoutJs,
12222
+ strippedPath: tryPath
12223
+ });
12224
+ break stripLoop;
12225
+ } catch {
12226
+ }
12227
+ }
12228
+ }
12229
+ }
12230
+ }
12231
+ if (!sourceCode) {
12232
+ const basePath = hasKnownExt ? filePathWithoutJs.replace(/\.(tsx|ts|jsx|js|mdx)$/, "") : filePathWithoutJs;
12233
+ outer:
12234
+ for (const prefix of prefixes) {
12235
+ for (const ext of extensions) {
12236
+ const tryPath = `${prefix}${basePath}/index${ext}`;
12237
+ try {
12238
+ const content = await adapter.fs.readFile(tryPath);
12239
+ sourceCode = typeof content === "string" ? content : new TextDecoder().decode(content);
12240
+ actualFilePath = tryPath;
12241
+ break outer;
12242
+ } catch {
12243
+ }
12244
+ }
12245
+ }
12246
+ }
12247
+ if (!sourceCode || !actualFilePath) {
12248
+ rendererLogger.debug(
12249
+ `${LOG_PREFIX_MDX_LOADER} Direct read failed, falling back to HTTP: ${filePathWithoutJs}`
12250
+ );
12251
+ const envGet = (key) => globalThis.Deno?.env?.get(key);
12252
+ const port = envGet("VERYFRONT_DEV_PORT") || envGet("PORT") || "3001";
12253
+ const moduleUrl = `http://localhost:${port}/${normalizedPath}?ssr=true`;
12254
+ const response = await fetch(moduleUrl);
12255
+ if (!response.ok) {
12256
+ rendererLogger.warn(
12257
+ `${LOG_PREFIX_MDX_LOADER} HTTP fetch also failed: ${moduleUrl} (${response.status})`
12258
+ );
12259
+ return null;
12260
+ }
12261
+ let moduleCode2 = await response.text();
12262
+ moduleCode2 = addExternalToEsmShUrls(moduleCode2);
12263
+ moduleCode2 = normalizeReactToNpm(moduleCode2);
12264
+ const vfModuleImportPattern2 = /from\s+["'](\/?_vf_modules\/[^"'?]+)(?:\?[^"']*)?["']/g;
12265
+ const nestedImports2 = [];
12266
+ let match2;
12267
+ while ((match2 = vfModuleImportPattern2.exec(moduleCode2)) !== null) {
12268
+ if (match2[1]) {
12269
+ nestedImports2.push({ original: match2[0], path: match2[1].replace(/^\//, "") });
12270
+ }
12271
+ }
12272
+ const relativeImportPattern2 = /from\s+["'](\.\.?\/[^"'?]+)(?:\?[^"']*)?["']/g;
12273
+ const relativeImports2 = [];
12274
+ let relMatch2;
12275
+ while ((relMatch2 = relativeImportPattern2.exec(moduleCode2)) !== null) {
12276
+ if (relMatch2[1]) {
12277
+ relativeImports2.push({ original: relMatch2[0], path: relMatch2[1] });
12278
+ }
12279
+ }
12280
+ const nestedResults2 = await Promise.all(
12281
+ nestedImports2.map(async ({ original, path: nestedPath }) => {
12282
+ const nestedFilePath = await fetchAndCacheModule(nestedPath, normalizedPath);
12283
+ return { original, nestedFilePath };
12284
+ })
12285
+ );
12286
+ for (const { original, nestedFilePath } of nestedResults2) {
12287
+ if (nestedFilePath) {
12288
+ moduleCode2 = moduleCode2.replace(original, `from "file://${nestedFilePath}"`);
12289
+ }
12290
+ }
12291
+ const relativeResults2 = await Promise.all(
12292
+ relativeImports2.map(async ({ original, path: relativePath }) => {
12293
+ const nestedFilePath = await fetchAndCacheModule(relativePath, normalizedPath);
12294
+ return { original, nestedFilePath };
12295
+ })
12296
+ );
12297
+ for (const { original, nestedFilePath } of relativeResults2) {
12298
+ if (nestedFilePath) {
12299
+ moduleCode2 = moduleCode2.replace(original, `from "file://${nestedFilePath}"`);
12300
+ }
12301
+ }
12302
+ const unresolvedPattern3 = /from\s+["'](\/?_vf_modules\/[^"']+)["']/g;
12303
+ const unresolvedMatches3 = [...moduleCode2.matchAll(unresolvedPattern3)];
12304
+ if (unresolvedMatches3.length > 0) {
12305
+ const unresolvedPaths = unresolvedMatches3.map((m) => m[1]).slice(0, 3);
12306
+ rendererLogger.warn(
12307
+ `${LOG_PREFIX_MDX_LOADER} Module has ${unresolvedMatches3.length} unresolved imports, skipping cache`,
12308
+ { path: normalizedPath, unresolved: unresolvedPaths }
12309
+ );
12310
+ return null;
12311
+ }
12312
+ const contentHash2 = hashString(normalizedPath + moduleCode2);
12313
+ const cachePath2 = join6(context.esmCacheDir, `vfmod-${contentHash2}.mjs`);
12314
+ try {
12315
+ const stat = await adapter.fs.stat(cachePath2);
12316
+ if (stat?.isFile) {
12317
+ pathCache.set(normalizedPath, cachePath2);
12318
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Content cache hit: ${normalizedPath}`);
12319
+ return cachePath2;
12320
+ }
12321
+ } catch {
12322
+ }
12323
+ await Deno.mkdir(context.esmCacheDir, { recursive: true });
12324
+ await adapter.fs.writeFile(cachePath2, moduleCode2);
12325
+ pathCache.set(normalizedPath, cachePath2);
12326
+ await saveModulePathCache(context.esmCacheDir);
12327
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Cached: ${normalizedPath} -> ${cachePath2}`);
12328
+ return cachePath2;
12329
+ }
12330
+ let moduleCode;
12331
+ try {
12332
+ moduleCode = await transformToESM(
12333
+ sourceCode,
12334
+ actualFilePath,
12335
+ projectDir,
12336
+ adapter,
12337
+ { projectId, dev: true, ssr: true }
12338
+ );
12339
+ } catch (transformError) {
12340
+ rendererLogger.error(`${LOG_PREFIX_MDX_LOADER} Transform failed for module`, {
12341
+ normalizedPath,
12342
+ actualFilePath,
12343
+ sourceLength: sourceCode.length,
12344
+ sourcePreview: sourceCode.slice(0, 200),
12345
+ error: transformError instanceof Error ? transformError.message : String(transformError)
12346
+ });
12347
+ throw transformError;
12348
+ }
12349
+ moduleCode = addExternalToEsmShUrls(moduleCode);
12350
+ moduleCode = normalizeReactToNpm(moduleCode);
12351
+ const vfModuleImportPattern = /from\s+["'](\/?_vf_modules\/[^"'?]+)(?:\?[^"']*)?["']/g;
12352
+ const nestedImports = [];
12353
+ let match;
12354
+ while ((match = vfModuleImportPattern.exec(moduleCode)) !== null) {
12355
+ if (match[1]) {
12356
+ nestedImports.push({ original: match[0], path: match[1].replace(/^\//, "") });
12357
+ }
12358
+ }
12359
+ const relativeImportPattern = /from\s+["'](\.\.?\/[^"'?]+)(?:\?[^"']*)?["']/g;
12360
+ const relativeImports = [];
12361
+ let relMatch;
12362
+ while ((relMatch = relativeImportPattern.exec(moduleCode)) !== null) {
12363
+ if (relMatch[1]) {
12364
+ relativeImports.push({ original: relMatch[0], path: relMatch[1] });
12365
+ }
12366
+ }
12367
+ const nestedResults = await Promise.all(
12368
+ nestedImports.map(async ({ original, path: nestedPath }) => {
12369
+ const nestedFilePath = await fetchAndCacheModule(nestedPath, normalizedPath);
12370
+ return { original, nestedFilePath, nestedPath };
12371
+ })
12372
+ );
12373
+ for (const { original, nestedFilePath, nestedPath } of nestedResults) {
12374
+ if (nestedFilePath) {
12375
+ moduleCode = moduleCode.replace(original, `from "file://${nestedFilePath}"`);
12376
+ } else {
12377
+ const stubCode = `
12378
+ // Stub module for missing file: ${nestedPath}
12379
+ // This file was not found in the project's published release.
12380
+ const handler = {
12381
+ get(_, prop) {
12382
+ if (prop === 'default' || prop === '__esModule' || typeof prop === 'symbol') {
12383
+ return new Proxy({}, handler);
12384
+ }
12385
+ console.warn('[Veryfront] Missing module: ${nestedPath}. Component "' + prop + '" was not found.');
12386
+ return () => null;
12387
+ },
12388
+ apply() { return null; }
12389
+ };
12390
+ export default new Proxy(function(){}, handler);
12391
+ `;
12392
+ const stubHash = hashString(`stub:${nestedPath}`);
12393
+ const stubPath = join6(context.esmCacheDir, `stub-${stubHash}.mjs`);
12394
+ try {
12395
+ await adapter.fs.writeFile(stubPath, stubCode);
12396
+ moduleCode = moduleCode.replace(original, `from "file://${stubPath}"`);
12397
+ rendererLogger.warn(
12398
+ `${LOG_PREFIX_MDX_LOADER} Created stub for missing module: ${nestedPath}`
12399
+ );
12400
+ } catch (e) {
12401
+ rendererLogger.error(
12402
+ `${LOG_PREFIX_MDX_LOADER} Failed to create stub for: ${nestedPath}`,
12403
+ e
12404
+ );
12405
+ }
12406
+ }
12407
+ }
12408
+ const relativeResults = await Promise.all(
12409
+ relativeImports.map(async ({ original, path: relativePath }) => {
12410
+ const nestedFilePath = await fetchAndCacheModule(relativePath, normalizedPath);
12411
+ return { original, nestedFilePath, relativePath };
12412
+ })
12413
+ );
12414
+ for (const { original, nestedFilePath, relativePath } of relativeResults) {
12415
+ if (nestedFilePath) {
12416
+ moduleCode = moduleCode.replace(original, `from "file://${nestedFilePath}"`);
12417
+ } else {
12418
+ const stubCode = `
12419
+ // Stub module for missing file: ${relativePath}
12420
+ // This file was not found in the project's published release.
12421
+ const handler = {
12422
+ get(_, prop) {
12423
+ if (prop === 'default' || prop === '__esModule' || typeof prop === 'symbol') {
12424
+ return new Proxy({}, handler);
12425
+ }
12426
+ console.warn('[Veryfront] Missing module: ${relativePath}. Component "' + prop + '" was not found.');
12427
+ return () => null;
12428
+ },
12429
+ apply() { return null; }
12430
+ };
12431
+ export default new Proxy(function(){}, handler);
12432
+ `;
12433
+ const stubHash = hashString(`stub:${relativePath}`);
12434
+ const stubPath = join6(context.esmCacheDir, `stub-${stubHash}.mjs`);
12435
+ try {
12436
+ await adapter.fs.writeFile(stubPath, stubCode);
12437
+ moduleCode = moduleCode.replace(original, `from "file://${stubPath}"`);
12438
+ rendererLogger.warn(
12439
+ `${LOG_PREFIX_MDX_LOADER} Created stub for missing module: ${relativePath}`
12440
+ );
12441
+ } catch (e) {
12442
+ rendererLogger.error(
12443
+ `${LOG_PREFIX_MDX_LOADER} Failed to create stub for: ${relativePath}`,
12444
+ e
12445
+ );
12446
+ }
12447
+ }
12448
+ }
12449
+ const unresolvedPattern2 = /from\s+["'](\/?_vf_modules\/[^"']+)["']/g;
12450
+ const unresolvedMatches2 = [...moduleCode.matchAll(unresolvedPattern2)];
12451
+ if (unresolvedMatches2.length > 0) {
12452
+ const unresolvedPaths = unresolvedMatches2.map((m) => m[1]).slice(0, 3);
12453
+ rendererLogger.warn(
12454
+ `${LOG_PREFIX_MDX_LOADER} Module has ${unresolvedMatches2.length} unresolved imports, skipping cache`,
12455
+ { path: normalizedPath, unresolved: unresolvedPaths }
12456
+ );
12457
+ return null;
12458
+ }
12459
+ const contentHash = hashString(normalizedPath + moduleCode);
12460
+ const cachePath = join6(context.esmCacheDir, `vfmod-${contentHash}.mjs`);
12461
+ try {
12462
+ const stat = await adapter.fs.stat(cachePath);
12463
+ if (stat?.isFile) {
12464
+ pathCache.set(normalizedPath, cachePath);
12465
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Content cache hit: ${normalizedPath}`);
12466
+ return cachePath;
12467
+ }
12468
+ } catch {
12469
+ }
12470
+ await Deno.mkdir(context.esmCacheDir, { recursive: true });
12471
+ await adapter.fs.writeFile(cachePath, moduleCode);
12472
+ pathCache.set(normalizedPath, cachePath);
12473
+ await saveModulePathCache(context.esmCacheDir);
12474
+ rendererLogger.debug(
12475
+ `${LOG_PREFIX_MDX_LOADER} Cached vf_module: ${normalizedPath} -> ${cachePath}`
12476
+ );
12477
+ return cachePath;
12478
+ } catch (error2) {
12479
+ rendererLogger.warn(`${LOG_PREFIX_MDX_LOADER} Failed to process ${normalizedPath}`, error2);
12480
+ return null;
12481
+ }
12482
+ })();
12483
+ resolveDeferred(result2);
12484
+ inFlight.delete(normalizedPath);
12485
+ return result2;
12486
+ }
12487
+ const fetchStart = performance.now();
12488
+ const vfModuleResults = await Promise.all(
12489
+ vfModuleImports.map(async ({ original, path }) => {
12490
+ const filePath2 = await fetchAndCacheModule(path);
12491
+ return { original, filePath: filePath2 };
12492
+ })
12493
+ );
12494
+ const fetchEnd = performance.now();
12495
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Module fetch phase completed`, {
12496
+ moduleCount: vfModuleImports.length,
12497
+ durationMs: (fetchEnd - fetchStart).toFixed(1)
12498
+ });
12499
+ for (const { original, filePath: filePath2 } of vfModuleResults) {
12500
+ if (filePath2) {
12501
+ rewritten = rewritten.replace(original, `from "file://${filePath2}"`);
12502
+ }
12503
+ }
9375
12504
  let jsxMatch;
9376
12505
  const jsxTransforms = [];
9377
- const { transform } = await import("esbuild/mod.js");
12506
+ const { transform: transform2 } = await import("esbuild/mod.js");
9378
12507
  while ((jsxMatch = JSX_IMPORT_PATTERN.exec(rewritten)) !== null) {
9379
12508
  const [fullMatch, importClause, filePath2, ext] = jsxMatch;
9380
12509
  if (!filePath2) {
@@ -9385,7 +12514,7 @@ async function loadModuleESM(compiledProgramCode, context) {
9385
12514
  }
9386
12515
  try {
9387
12516
  const jsxCode = await adapter.fs.readFile(filePath2);
9388
- const result2 = await transform(jsxCode, {
12517
+ const result2 = await transform2(jsxCode, {
9389
12518
  loader: ext === "tsx" ? "tsx" : "jsx",
9390
12519
  jsx: "transform",
9391
12520
  jsxFactory: ESBUILD_JSX_FACTORY,
@@ -9398,7 +12527,7 @@ async function loadModuleESM(compiledProgramCode, context) {
9398
12527
  ${transformed}`;
9399
12528
  }
9400
12529
  const transformedFileName = `jsx-${hashString(filePath2)}.mjs`;
9401
- const transformedPath = join4(context.esmCacheDir, transformedFileName);
12530
+ const transformedPath = join6(context.esmCacheDir, transformedFileName);
9402
12531
  await adapter.fs.writeFile(transformedPath, transformed);
9403
12532
  jsxTransforms.push({
9404
12533
  original: fullMatch,
@@ -9417,10 +12546,10 @@ ${transformed}`;
9417
12546
  if (/\bconst\s+MDXLayout\b/.test(rewritten) && !/export\s+\{[^}]*MDXLayout/.test(rewritten)) {
9418
12547
  rewritten += "\nexport { MDXLayout as __vfLayout };\n";
9419
12548
  }
9420
- if (IS_TRUE_NODE && HTTP_IMPORT_PATTERN.test(rewritten)) {
9421
- rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Bundling HTTP imports via esbuild for Node.js`);
12549
+ if (HTTP_IMPORT_PATTERN.test(rewritten)) {
12550
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Bundling HTTP imports via esbuild`);
9422
12551
  const { build: build2 } = await import("esbuild/mod.js");
9423
- const tempSourcePath = join4(context.esmCacheDir, `temp-${hashString(rewritten)}.mjs`);
12552
+ const tempSourcePath = join6(context.esmCacheDir, `temp-${hashString(rewritten)}.mjs`);
9424
12553
  await adapter.fs.writeFile(tempSourcePath, rewritten);
9425
12554
  try {
9426
12555
  const result2 = await build2({
@@ -9440,8 +12569,8 @@ ${transformed}`;
9440
12569
  rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Successfully bundled HTTP imports`);
9441
12570
  }
9442
12571
  } catch (bundleError) {
9443
- rendererLogger.warn(
9444
- `${LOG_PREFIX_MDX_LOADER} Failed to bundle HTTP imports, falling back to original code`,
12572
+ rendererLogger.error(
12573
+ `${LOG_PREFIX_MDX_LOADER} Failed to bundle HTTP imports`,
9445
12574
  bundleError
9446
12575
  );
9447
12576
  } finally {
@@ -9456,13 +12585,23 @@ ${transformed}`;
9456
12585
  }
9457
12586
  }
9458
12587
  }
12588
+ rewritten = addExternalToEsmShUrls(rewritten);
12589
+ rewritten = normalizeReactToNpm(rewritten);
9459
12590
  const codeHash = hashString(rewritten);
9460
12591
  const namespace = getCacheNamespace() || "default";
9461
12592
  const compositeKey = `${namespace}:${codeHash}`;
9462
12593
  const cached = context.moduleCache.get(compositeKey);
9463
12594
  if (cached)
9464
12595
  return cached;
9465
- const nsDir = join4(context.esmCacheDir, namespace);
12596
+ const unresolvedPattern = /from\s+["'](\/?_vf_modules\/[^"']+)["']/g;
12597
+ const unresolvedMatches = [...rewritten.matchAll(unresolvedPattern)];
12598
+ if (unresolvedMatches.length > 0) {
12599
+ const unresolvedPaths = unresolvedMatches.map((m) => m[1]).slice(0, 5);
12600
+ const errorMsg = `MDX has ${unresolvedMatches.length} unresolved module imports: ${unresolvedPaths.join(", ")}`;
12601
+ rendererLogger.error(`${LOG_PREFIX_MDX_RENDERER} ${errorMsg}`);
12602
+ throw new Error(errorMsg);
12603
+ }
12604
+ const nsDir = join6(context.esmCacheDir, namespace);
9466
12605
  try {
9467
12606
  await adapter.fs.mkdir(nsDir, { recursive: true });
9468
12607
  } catch (e) {
@@ -9471,7 +12610,7 @@ ${transformed}`;
9471
12610
  e instanceof Error ? e : String(e)
9472
12611
  );
9473
12612
  }
9474
- const filePath = join4(nsDir, `${codeHash}.mjs`);
12613
+ const filePath = join6(nsDir, `${codeHash}.mjs`);
9475
12614
  try {
9476
12615
  const stat = await adapter.fs.stat(filePath);
9477
12616
  if (!stat?.isFile) {
@@ -9499,6 +12638,10 @@ ${transformed}`;
9499
12638
  MainLayout: mod?.MainLayout
9500
12639
  };
9501
12640
  context.moduleCache.set(compositeKey, result);
12641
+ const loadEnd = performance.now();
12642
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} loadModuleESM completed`, {
12643
+ durationMs: (loadEnd - loadStart).toFixed(1)
12644
+ });
9502
12645
  return result;
9503
12646
  } catch (error2) {
9504
12647
  rendererLogger.error(`${LOG_PREFIX_MDX_RENDERER} MDX ESM load failed:`, error2);
@@ -9557,7 +12700,7 @@ function parseJsonish(value) {
9557
12700
  }
9558
12701
 
9559
12702
  // src/build/transforms/mdx/module-loader/metadata-extractor.ts
9560
- function extractFrontmatter(moduleCode) {
12703
+ function extractFrontmatter2(moduleCode) {
9561
12704
  try {
9562
12705
  const fmIndex = moduleCode.search(/(?:export\s+)?const\s+frontmatter\s*=\s*/);
9563
12706
  if (fmIndex < 0)
@@ -9656,7 +12799,7 @@ function parseMDXCode(compiledCode) {
9656
12799
  rendererLogger.debug("Code snippet:", cleanedCode.substring(0, 200));
9657
12800
  }
9658
12801
  const exports = {};
9659
- const frontmatter = extractFrontmatter(cleanedCode);
12802
+ const frontmatter = extractFrontmatter2(cleanedCode);
9660
12803
  if (frontmatter) {
9661
12804
  exports.frontmatter = frontmatter;
9662
12805
  }
@@ -10077,6 +13220,9 @@ init_config();
10077
13220
  // src/security/client/html-sanitizer.ts
10078
13221
  init_deno_env();
10079
13222
 
13223
+ // src/html/html-escape.ts
13224
+ init_deno_env();
13225
+
10080
13226
  // src/routing/client/viewport-prefetch.ts
10081
13227
  init_deno_env();
10082
13228
  init_utils();
@@ -10088,7 +13234,7 @@ init_deno_env();
10088
13234
  init_deno_env();
10089
13235
  init_utils();
10090
13236
  init_config();
10091
- import { join as join7 } from "node:path";
13237
+ import { join as join9 } from "node:path";
10092
13238
  init_veryfront_error();
10093
13239
 
10094
13240
  // src/http/responses.ts
@@ -10760,11 +13906,21 @@ function createHttpInstruments(meter, config) {
10760
13906
 
10761
13907
  // src/observability/instruments/memory-instruments.ts
10762
13908
  init_deno_env();
13909
+ var V8_HEAP_LIMIT_MB = (() => {
13910
+ try {
13911
+ const flags = Deno.env.get("DENO_V8_FLAGS") ?? "";
13912
+ const match = flags.match(/--max-old-space-size=(\d+)/);
13913
+ if (match?.[1])
13914
+ return parseInt(match[1], 10);
13915
+ } catch {
13916
+ }
13917
+ return 5120;
13918
+ })();
10763
13919
  function createMemoryInstruments(meter, config) {
10764
13920
  const memoryUsageGauge = meter.createObservableGauge(
10765
13921
  `${config.prefix}.memory.usage`,
10766
13922
  {
10767
- description: "Memory usage",
13923
+ description: "Memory usage (RSS)",
10768
13924
  unit: "bytes"
10769
13925
  }
10770
13926
  );
@@ -10777,7 +13933,7 @@ function createMemoryInstruments(meter, config) {
10777
13933
  const heapUsageGauge = meter.createObservableGauge(
10778
13934
  `${config.prefix}.memory.heap`,
10779
13935
  {
10780
- description: "Heap memory usage",
13936
+ description: "V8 heap memory used",
10781
13937
  unit: "bytes"
10782
13938
  }
10783
13939
  );
@@ -10787,9 +13943,39 @@ function createMemoryInstruments(meter, config) {
10787
13943
  result.observe(memoryUsage2.heapUsed);
10788
13944
  }
10789
13945
  });
13946
+ const heapTotalGauge = meter.createObservableGauge(
13947
+ `${config.prefix}.memory.heap_total`,
13948
+ {
13949
+ description: "V8 heap memory allocated",
13950
+ unit: "bytes"
13951
+ }
13952
+ );
13953
+ heapTotalGauge.addCallback((result) => {
13954
+ const memoryUsage2 = getMemoryUsage();
13955
+ if (memoryUsage2) {
13956
+ result.observe(memoryUsage2.heapTotal);
13957
+ }
13958
+ });
13959
+ const heapPercentGauge = meter.createObservableGauge(
13960
+ `${config.prefix}.memory.heap_percent`,
13961
+ {
13962
+ description: "V8 heap usage as percentage of configured limit",
13963
+ unit: "percent"
13964
+ }
13965
+ );
13966
+ heapPercentGauge.addCallback((result) => {
13967
+ const memoryUsage2 = getMemoryUsage();
13968
+ if (memoryUsage2) {
13969
+ const heapUsedMB = memoryUsage2.heapUsed / (1024 * 1024);
13970
+ const percent = heapUsedMB / V8_HEAP_LIMIT_MB * 100;
13971
+ result.observe(Math.round(percent * 100) / 100);
13972
+ }
13973
+ });
10790
13974
  return {
10791
13975
  memoryUsageGauge,
10792
- heapUsageGauge
13976
+ heapUsageGauge,
13977
+ heapTotalGauge,
13978
+ heapPercentGauge
10793
13979
  };
10794
13980
  }
10795
13981
 
@@ -10923,7 +14109,9 @@ function initializeInstruments(meter, config, runtimeState) {
10923
14109
  corsRejectionCounter: null,
10924
14110
  securityHeadersCounter: null,
10925
14111
  memoryUsageGauge: null,
10926
- heapUsageGauge: null
14112
+ heapUsageGauge: null,
14113
+ heapTotalGauge: null,
14114
+ heapPercentGauge: null
10927
14115
  };
10928
14116
  try {
10929
14117
  const httpInstruments = createHttpInstruments(meter, config);
@@ -11088,7 +14276,9 @@ var MetricsManager = class {
11088
14276
  corsRejectionCounter: null,
11089
14277
  securityHeadersCounter: null,
11090
14278
  memoryUsageGauge: null,
11091
- heapUsageGauge: null
14279
+ heapUsageGauge: null,
14280
+ heapTotalGauge: null,
14281
+ heapPercentGauge: null
11092
14282
  };
11093
14283
  }
11094
14284
  async initialize(config = {}, adapter) {
@@ -11186,6 +14376,10 @@ init_deno_env();
11186
14376
  // src/observability/auto-instrument/wrappers.ts
11187
14377
  init_deno_env();
11188
14378
 
14379
+ // src/observability/tracing/otlp-setup.ts
14380
+ init_deno_env();
14381
+ init_utils();
14382
+
11189
14383
  // src/security/http/cors/validators.ts
11190
14384
  async function validateOrigin(requestOrigin, config) {
11191
14385
  if (!config) {
@@ -11464,26 +14658,13 @@ function generateNonce() {
11464
14658
  crypto.getRandomValues(array);
11465
14659
  return btoa(String.fromCharCode(...array));
11466
14660
  }
11467
- function buildCSP(isDev, nonce, cspUserHeader, config, adapter) {
14661
+ function buildCSP(_isDev, nonce, cspUserHeader, config, adapter) {
11468
14662
  const envCsp = adapter?.env?.get?.("VERYFRONT_CSP");
11469
14663
  if (envCsp?.trim())
11470
14664
  return envCsp.replace(/{NONCE}/g, nonce);
11471
- const defaultCsp = isDev ? [
11472
- "default-src 'self'",
11473
- `style-src 'self' 'unsafe-inline' https://esm.sh https://cdnjs.cloudflare.com https://cdn.veryfront.com https://cdn.jsdelivr.net https://cdn.tailwindcss.com`,
11474
- "img-src 'self' data: https://cdn.veryfront.com https://cdnjs.cloudflare.com",
11475
- `script-src 'self' 'nonce-${nonce}' 'unsafe-eval' https://esm.sh https://cdn.tailwindcss.com`,
11476
- "connect-src 'self' https://esm.sh ws://localhost:* wss://localhost:*",
11477
- "font-src 'self' data: https://cdnjs.cloudflare.com"
11478
- ].join("; ") : [
11479
- "default-src 'self'",
11480
- `style-src 'self' 'nonce-${nonce}'`,
11481
- "img-src 'self' data:",
11482
- `script-src 'self' 'nonce-${nonce}'`,
11483
- "connect-src 'self'"
11484
- ].join("; ");
14665
+ const defaultCsp = "";
11485
14666
  if (cspUserHeader?.trim()) {
11486
- return `${cspUserHeader.replace(/{NONCE}/g, nonce)}; ${defaultCsp}`;
14667
+ return cspUserHeader.replace(/{NONCE}/g, nonce);
11487
14668
  }
11488
14669
  const cfgCsp = config?.csp;
11489
14670
  if (cfgCsp && typeof cfgCsp === "object") {
@@ -11496,7 +14677,7 @@ function buildCSP(isDev, nonce, cspUserHeader, config, adapter) {
11496
14677
  pieces.push(`${key} ${val}`.replace(/{NONCE}/g, nonce));
11497
14678
  }
11498
14679
  if (pieces.length > 0) {
11499
- return `${pieces.join("; ")}; ${defaultCsp}`;
14680
+ return pieces.join("; ");
11500
14681
  }
11501
14682
  }
11502
14683
  return defaultCsp;
@@ -11507,7 +14688,7 @@ function getSecurityHeader(headerName, defaultValue, config, adapter) {
11507
14688
  const envValue = adapter?.env?.get?.(`VERYFRONT_${headerName}`);
11508
14689
  return (typeof configValue === "string" ? configValue : void 0) || envValue || defaultValue;
11509
14690
  }
11510
- function applySecurityHeaders(headers, isDev, nonce, cspUserHeader, config, adapter) {
14691
+ function applySecurityHeaders(headers, isDev, nonce, cspUserHeader, config, adapter, studioEmbed) {
11511
14692
  const getHeaderOverride = (name) => {
11512
14693
  const overrides = config?.headers;
11513
14694
  if (!overrides)
@@ -11522,8 +14703,10 @@ function applySecurityHeaders(headers, isDev, nonce, cspUserHeader, config, adap
11522
14703
  };
11523
14704
  const contentTypeOptions = getHeaderOverride("x-content-type-options") ?? "nosniff";
11524
14705
  headers.set("X-Content-Type-Options", contentTypeOptions);
11525
- const frameOptions = getHeaderOverride("x-frame-options") ?? "DENY";
11526
- headers.set("X-Frame-Options", frameOptions);
14706
+ if (!isDev && !studioEmbed) {
14707
+ const frameOptions = getHeaderOverride("x-frame-options") ?? "DENY";
14708
+ headers.set("X-Frame-Options", frameOptions);
14709
+ }
11527
14710
  const xssProtection = getHeaderOverride("x-xss-protection") ?? "1; mode=block";
11528
14711
  headers.set("X-XSS-Protection", xssProtection);
11529
14712
  const csp = buildCSP(isDev, nonce, cspUserHeader, config, adapter);
@@ -11630,7 +14813,8 @@ function withSecurity(config) {
11630
14813
  this.nonce,
11631
14814
  this.cspUserHeader,
11632
14815
  cfg,
11633
- this.adapter
14816
+ this.adapter,
14817
+ this.studioEmbed
11634
14818
  );
11635
14819
  return this;
11636
14820
  }
@@ -11855,6 +15039,7 @@ var ResponseBuilder = class {
11855
15039
  this.nonce = config?.nonce ?? generateNonce();
11856
15040
  this.cspUserHeader = config?.cspUserHeader ?? null;
11857
15041
  this.adapter = config?.adapter;
15042
+ this.studioEmbed = config?.studioEmbed ?? false;
11858
15043
  }
11859
15044
  static {
11860
15045
  this.error = error;
@@ -12275,6 +15460,7 @@ init_deno_env();
12275
15460
  init_utils();
12276
15461
  init_utils();
12277
15462
  init_utils();
15463
+ init_utils();
12278
15464
 
12279
15465
  // src/routing/api/module-loader/http-validator.ts
12280
15466
  init_deno_env();
@@ -12287,13 +15473,7 @@ init_utils();
12287
15473
 
12288
15474
  // src/routing/api/module-loader/loader.ts
12289
15475
  init_veryfront_error();
12290
-
12291
- // src/platform/compat/fs.ts
12292
- init_deno_env();
12293
- init_veryfront_error();
12294
- init_runtime();
12295
-
12296
- // src/routing/api/module-loader/loader.ts
15476
+ init_fs();
12297
15477
  init_runtime();
12298
15478
 
12299
15479
  // src/routing/api/route-discovery.ts
@@ -12303,13 +15483,14 @@ import { relative } from "node:path";
12303
15483
  // src/core/utils/file-discovery.ts
12304
15484
  init_deno_env();
12305
15485
  init_deno2();
12306
- import { join as join6 } from "node:path";
15486
+ import { join as join8 } from "node:path";
12307
15487
 
12308
15488
  // src/routing/api/route-executor.ts
12309
15489
  init_deno_env();
12310
15490
 
12311
15491
  // src/routing/api/context-builder.ts
12312
15492
  init_deno_env();
15493
+ init_cookie_utils();
12313
15494
 
12314
15495
  // src/routing/api/route-executor.ts
12315
15496
  init_veryfront_error();