veryfront 0.1.991 → 0.1.993

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/esm/deno.js +3 -3
  2. package/esm/extensions/ext-llm-openai/src/openai-provider.d.ts +3 -0
  3. package/esm/extensions/ext-llm-openai/src/openai-provider.d.ts.map +1 -1
  4. package/esm/extensions/ext-llm-openai/src/openai-provider.js +46 -15
  5. package/esm/extensions/ext-llm-openai/src/openai-reasoning-models.d.ts +1 -0
  6. package/esm/extensions/ext-llm-openai/src/openai-reasoning-models.d.ts.map +1 -1
  7. package/esm/extensions/ext-llm-openai/src/openai-reasoning-models.js +5 -5
  8. package/esm/src/build/production-build/templates.d.ts.map +1 -1
  9. package/esm/src/build/production-build/templates.js +1 -1
  10. package/esm/src/provider/model-registry.d.ts.map +1 -1
  11. package/esm/src/provider/model-registry.js +1 -0
  12. package/esm/src/provider/veryfront-cloud/openai.d.ts.map +1 -1
  13. package/esm/src/provider/veryfront-cloud/openai.js +2 -0
  14. package/esm/src/provider/veryfront-cloud/provider.d.ts.map +1 -1
  15. package/esm/src/provider/veryfront-cloud/provider.js +3 -0
  16. package/esm/src/react/runtime/core.d.ts +57 -5
  17. package/esm/src/react/runtime/core.d.ts.map +1 -1
  18. package/esm/src/react/runtime/core.js +168 -6
  19. package/esm/src/rendering/rsc/client-boot.ts +5 -1
  20. package/esm/src/rendering/rsc/client-module-strategy.d.ts +14 -0
  21. package/esm/src/rendering/rsc/client-module-strategy.d.ts.map +1 -1
  22. package/esm/src/rendering/rsc/client-module-strategy.js +11 -0
  23. package/esm/src/rendering/rsc/hydrate-client.ts +9 -2
  24. package/esm/src/server/services/rsc/endpoints/rsc-bundles.generated.d.ts.map +1 -1
  25. package/esm/src/server/services/rsc/endpoints/rsc-bundles.generated.js +1 -1
  26. package/esm/src/utils/version-constant.d.ts +1 -1
  27. package/esm/src/utils/version-constant.js +1 -1
  28. package/package.json +1 -1
package/esm/deno.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export default {
2
2
  "name": "veryfront",
3
- "version": "0.1.991",
3
+ "version": "0.1.993",
4
4
  "license": "Apache-2.0",
5
5
  "nodeModulesDir": "auto",
6
6
  "minimumDependencyAge": {
@@ -393,12 +393,12 @@ export default {
393
393
  "build:npm": "deno run -A scripts/build/generate-integrations-module.ts && deno task generate && deno run -A scripts/build/build-npm-dnt.ts",
394
394
  "release": "deno run -A scripts/release.ts",
395
395
  "test": "deno task generate && VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --preload=src/schemas/_test-setup.ts --no-check --parallel --allow-all '--ignore=tests/e2e,tests/integration/compiled-binary-e2e.test.ts' --unstable-worker-options --unstable-net",
396
- "test:unit": "deno task generate && VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --preload=src/schemas/_test-setup.ts --no-check --parallel --allow-all --v8-flags=--max-old-space-size=8192 '--ignore=tests,src/workflow/__tests__' --unstable-worker-options --unstable-net $(find src cli -name '*.test.ts' ! -name '*.integration.test.ts')",
396
+ "test:unit": "deno task generate && VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --preload=src/schemas/_test-setup.ts --no-check --parallel --allow-all --v8-flags=--max-old-space-size=8192 '--ignore=tests,src/workflow/__tests__' --unstable-worker-options --unstable-net $(find src cli -name '*.test.ts*' ! -name '*.integration.test.ts*')",
397
397
  "test:integration": "deno task generate && VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --preload=src/schemas/_test-setup.ts --no-check --parallel --allow-all '--ignore=tests/e2e,tests/integration/compiled-binary-e2e.test.ts' tests --unstable-worker-options --unstable-net",
398
398
  "test:integration:cli": "VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --no-check --parallel --allow-all --unstable-worker-options --unstable-net $(find cli -name '*.integration.test.ts')",
399
399
  "test:record": "VCR=record deno test --no-check --allow-all $(find cli -name '*.integration.test.ts' -path '*/commands/*')",
400
400
  "test:coverage": "rm -rf coverage && deno task generate && VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --preload=src/schemas/_test-setup.ts --no-check --parallel --fail-fast --allow-all --v8-flags=--max-old-space-size=8192 --coverage=coverage '--ignore=tests/integration/compiled-binary-e2e.test.ts' --unstable-worker-options --unstable-net || exit 1",
401
- "test:coverage:unit": "rm -rf coverage && deno task generate && VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --preload=src/schemas/_test-setup.ts --no-check --parallel --fail-fast --allow-all --v8-flags=--max-old-space-size=8192 --coverage=coverage '--ignore=tests,src/workflow/__tests__' --unstable-worker-options --unstable-net $(find src cli -name '*.test.ts' ! -name '*.integration.test.ts') || exit 1",
401
+ "test:coverage:unit": "rm -rf coverage && deno task generate && VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --preload=src/schemas/_test-setup.ts --no-check --parallel --fail-fast --allow-all --v8-flags=--max-old-space-size=8192 --coverage=coverage '--ignore=tests,src/workflow/__tests__' --unstable-worker-options --unstable-net $(find src cli -name '*.test.ts*' ! -name '*.integration.test.ts*') || exit 1",
402
402
  "test:coverage:integration": "rm -rf coverage && deno task generate && VF_DISABLE_LRU_INTERVAL=1 SSR_TRANSFORM_PER_PROJECT_LIMIT=0 REVALIDATION_PER_PROJECT_LIMIT=0 NODE_ENV=production LOG_FORMAT=text deno test --preload=src/schemas/_test-setup.ts --no-check --parallel --fail-fast --allow-all --v8-flags=--max-old-space-size=8192 --coverage=coverage '--ignore=tests/e2e,tests/integration/compiled-binary-e2e.test.ts' tests --unstable-worker-options --unstable-net || exit 1",
403
403
  "coverage:report": "deno coverage coverage --include=src/ --exclude=tests '--exclude=src/**/*_test.ts' '--exclude=src/**/*_test.tsx' '--exclude=src/**/*.test.ts' '--exclude=src/**/*.test.tsx' --lcov > coverage/lcov.info && deno run --allow-read scripts/lint/check-coverage.ts 80",
404
404
  "coverage:gate": "deno coverage coverage --include=src/ --exclude=tests '--exclude=src/**/*_test.ts' '--exclude=src/**/*_test.tsx' '--exclude=src/**/*.test.ts' '--exclude=src/**/*.test.tsx' --lcov > coverage/lcov.info && deno run --allow-read scripts/lint/check-coverage.ts 68",
@@ -14,7 +14,10 @@ export { buildProviderError, isNumberArray, mergeUsage, parseRetryAfterMs, Provi
14
14
  export interface OpenAIRuntimeConfig {
15
15
  apiKey: string;
16
16
  baseURL?: string;
17
+ /** Display/telemetry label. */
17
18
  name?: string;
19
+ /** Provider identity for OpenAI request defaults. Defaults to `name` in low-level factories. */
20
+ providerName?: string;
18
21
  fetch?: typeof globalThis.fetch;
19
22
  }
20
23
  export declare function createOpenAIModelRuntime(config: OpenAIRuntimeConfig, modelId: string): ModelRuntime;
@@ -1 +1 @@
1
- {"version":3,"file":"openai-provider.d.ts","sourceRoot":"","sources":["../../../../src/extensions/ext-llm-openai/src/openai-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AAC3F,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACrF,OAAO,EACL,kBAAkB,EAMlB,aAAa,EACb,UAAU,EACV,iBAAiB,EACjB,aAAa,EACb,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EAMpB,+BAA+B,EAC/B,8BAA8B,EAC/B,MAAM,uCAAuC,CAAC;AAc/C,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,UAAU,EACV,iBAAiB,EACjB,aAAa,EACb,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EACpB,+BAA+B,EAC/B,8BAA8B,GAC/B,CAAC;AAEF,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACjC;AAkVD,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,GACd,YAAY,CAsEd;AAED,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,GACd,YAAY,CAsEd;AAED,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,GACd,gBAAgB,CAuClB;AAED,qBAAa,cAAe,YAAW,WAAW;IAChD,QAAQ,CAAC,EAAE,YAAY;IAEvB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAG,YAAY;IAYrE,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAG,gBAAgB;IAY7E,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAG,YAAY;CAW1E"}
1
+ {"version":3,"file":"openai-provider.d.ts","sourceRoot":"","sources":["../../../../src/extensions/ext-llm-openai/src/openai-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AAC3F,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACrF,OAAO,EACL,kBAAkB,EAMlB,aAAa,EACb,UAAU,EACV,iBAAiB,EACjB,aAAa,EACb,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EAMpB,+BAA+B,EAC/B,8BAA8B,EAC/B,MAAM,uCAAuC,CAAC;AAe/C,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,UAAU,EACV,iBAAiB,EACjB,aAAa,EACb,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EACpB,+BAA+B,EAC/B,8BAA8B,GAC/B,CAAC;AAEF,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,+BAA+B;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gGAAgG;IAChG,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACjC;AAkWD,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,GACd,YAAY,CAwEd;AAED,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,GACd,YAAY,CAwEd;AAED,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,GACd,gBAAgB,CAwClB;AAED,qBAAa,cAAe,YAAW,WAAW;IAChD,QAAQ,CAAC,EAAE,YAAY;IAEvB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAG,YAAY;IA4BrE,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAG,gBAAgB;IAY7E,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAG,YAAY;CAY1E"}
@@ -11,9 +11,22 @@ import { buildProviderError, createOpenAIRequestInit, createWarningCollector, ge
11
11
  import { buildOpenAIChatRequest, } from "./openai-chat-request-builder.js";
12
12
  import { streamOpenAICompatibleParts } from "./openai-chat-stream.js";
13
13
  import { buildOpenAIResponsesRequest } from "./openai-responses-request-builder.js";
14
+ import { isOpenAIReasoningModel } from "./openai-reasoning-models.js";
14
15
  import { extractOpenAIResponsesUsage, normalizeOpenAIResponsesFinishReason, streamOpenAIResponsesParts, } from "./openai-responses-stream.js";
15
16
  // Re-export error classes so extension tests can import from this module.
16
17
  export { buildProviderError, isNumberArray, mergeUsage, parseRetryAfterMs, ProviderError, ProviderOverloadedError, ProviderQuotaError, ProviderRateLimitError, ProviderRequestError, TOOL_INPUT_PENDING_THRESHOLD_MS, withToolInputStatusTransitions, };
18
+ function readNonEmptyString(value) {
19
+ return typeof value === "string" && value.length > 0 ? value : undefined;
20
+ }
21
+ function getOpenAIProviderLabel(config) {
22
+ return readNonEmptyString(config.name) ?? "openai";
23
+ }
24
+ function getRuntimeOpenAIProviderName(config) {
25
+ return readNonEmptyString(config.providerName) ?? getOpenAIProviderLabel(config);
26
+ }
27
+ function getLLMOpenAIProviderName(config) {
28
+ return readNonEmptyString(config.providerName) ?? "openai";
29
+ }
17
30
  // ---------------------------------------------------------------------------
18
31
  // Embedding helpers
19
32
  // ---------------------------------------------------------------------------
@@ -256,8 +269,10 @@ function buildOpenAIResponsesGenerateResult(payload) {
256
269
  // ---------------------------------------------------------------------------
257
270
  export function createOpenAIModelRuntime(config, modelId) {
258
271
  const fetchImpl = config.fetch ?? globalThis.fetch;
272
+ const providerLabel = getOpenAIProviderLabel(config);
273
+ const providerName = getRuntimeOpenAIProviderName(config);
259
274
  return {
260
- provider: config.name ?? "openai",
275
+ provider: providerLabel,
261
276
  modelId,
262
277
  specificationVersion: "v3",
263
278
  supportedUrls: {},
@@ -265,11 +280,11 @@ export function createOpenAIModelRuntime(config, modelId) {
265
280
  const options = optionsForRuntime;
266
281
  const url = getOpenAIChatCompletionsUrl(config.baseURL);
267
282
  const warnings = createWarningCollector();
268
- const body = buildOpenAIChatRequest(modelId, config.name ?? "openai", options, false, warnings);
283
+ const body = buildOpenAIChatRequest(modelId, providerName, options, false, warnings);
269
284
  return requestJson({
270
285
  url,
271
286
  fetchImpl,
272
- providerLabel: config.name ?? "openai",
287
+ providerLabel,
273
288
  providerKind: "openai",
274
289
  init: createOpenAIRequestInit({
275
290
  apiKey: config.apiKey,
@@ -289,11 +304,11 @@ export function createOpenAIModelRuntime(config, modelId) {
289
304
  const options = optionsForRuntime;
290
305
  const url = getOpenAIChatCompletionsUrl(config.baseURL);
291
306
  const warnings = createWarningCollector();
292
- const body = buildOpenAIChatRequest(modelId, config.name ?? "openai", options, true, warnings);
307
+ const body = buildOpenAIChatRequest(modelId, providerName, options, true, warnings);
293
308
  return requestStream({
294
309
  url,
295
310
  fetchImpl,
296
- providerLabel: config.name ?? "openai",
311
+ providerLabel,
297
312
  providerKind: "openai",
298
313
  init: createOpenAIRequestInit({
299
314
  apiKey: config.apiKey,
@@ -313,8 +328,10 @@ export function createOpenAIModelRuntime(config, modelId) {
313
328
  }
314
329
  export function createOpenAIResponsesRuntime(config, modelId) {
315
330
  const fetchImpl = config.fetch ?? globalThis.fetch;
331
+ const providerLabel = getOpenAIProviderLabel(config);
332
+ const providerName = getRuntimeOpenAIProviderName(config);
316
333
  return {
317
- provider: config.name ?? "openai",
334
+ provider: providerLabel,
318
335
  modelId,
319
336
  specificationVersion: "v3",
320
337
  supportedUrls: {},
@@ -322,11 +339,11 @@ export function createOpenAIResponsesRuntime(config, modelId) {
322
339
  const options = optionsForRuntime;
323
340
  const url = getOpenAIResponsesUrl(config.baseURL);
324
341
  const warnings = createWarningCollector();
325
- const body = buildOpenAIResponsesRequest(modelId, config.name ?? "openai", options, false, warnings);
342
+ const body = buildOpenAIResponsesRequest(modelId, providerName, options, false, warnings);
326
343
  return requestJson({
327
344
  url,
328
345
  fetchImpl,
329
- providerLabel: config.name ?? "openai",
346
+ providerLabel,
330
347
  providerKind: "openai",
331
348
  init: createOpenAIRequestInit({
332
349
  apiKey: config.apiKey,
@@ -346,11 +363,11 @@ export function createOpenAIResponsesRuntime(config, modelId) {
346
363
  const options = optionsForRuntime;
347
364
  const url = getOpenAIResponsesUrl(config.baseURL);
348
365
  const warnings = createWarningCollector();
349
- const body = buildOpenAIResponsesRequest(modelId, config.name ?? "openai", options, true, warnings);
366
+ const body = buildOpenAIResponsesRequest(modelId, providerName, options, true, warnings);
350
367
  return requestStream({
351
368
  url,
352
369
  fetchImpl,
353
- providerLabel: config.name ?? "openai",
370
+ providerLabel,
354
371
  providerKind: "openai",
355
372
  init: createOpenAIRequestInit({
356
373
  apiKey: config.apiKey,
@@ -370,8 +387,9 @@ export function createOpenAIResponsesRuntime(config, modelId) {
370
387
  }
371
388
  export function createOpenAIEmbeddingRuntime(config, modelId) {
372
389
  const fetchImpl = config.fetch ?? globalThis.fetch;
390
+ const providerLabel = getOpenAIProviderLabel(config);
373
391
  return {
374
- provider: config.name ?? "openai",
392
+ provider: providerLabel,
375
393
  modelId,
376
394
  supportsParallelCalls: true,
377
395
  doEmbed({ values, abortSignal }) {
@@ -386,7 +404,7 @@ export function createOpenAIEmbeddingRuntime(config, modelId) {
386
404
  return requestJson({
387
405
  url,
388
406
  fetchImpl,
389
- providerLabel: config.name ?? "openai",
407
+ providerLabel,
390
408
  providerKind: "openai",
391
409
  init: createOpenAIRequestInit({
392
410
  apiKey: config.apiKey,
@@ -410,10 +428,22 @@ export function createOpenAIEmbeddingRuntime(config, modelId) {
410
428
  export class OpenAIProvider {
411
429
  id = "openai";
412
430
  createModel(modelId, config) {
431
+ const providerLabel = getOpenAIProviderLabel(config);
432
+ const providerName = getLLMOpenAIProviderName(config);
433
+ if (isOpenAIReasoningModel(modelId, providerName)) {
434
+ return createOpenAIResponsesRuntime({
435
+ apiKey: config.credential,
436
+ baseURL: config.baseURL,
437
+ name: providerLabel,
438
+ providerName,
439
+ fetch: config.fetch,
440
+ }, modelId);
441
+ }
413
442
  return createOpenAIModelRuntime({
414
443
  apiKey: config.credential,
415
444
  baseURL: config.baseURL,
416
- name: config.name ?? "openai",
445
+ name: providerLabel,
446
+ providerName,
417
447
  fetch: config.fetch,
418
448
  }, modelId);
419
449
  }
@@ -421,7 +451,7 @@ export class OpenAIProvider {
421
451
  return createOpenAIEmbeddingRuntime({
422
452
  apiKey: config.credential,
423
453
  baseURL: config.baseURL,
424
- name: config.name ?? "openai",
454
+ name: getOpenAIProviderLabel(config),
425
455
  fetch: config.fetch,
426
456
  }, modelId);
427
457
  }
@@ -429,7 +459,8 @@ export class OpenAIProvider {
429
459
  return createOpenAIResponsesRuntime({
430
460
  apiKey: config.credential,
431
461
  baseURL: config.baseURL,
432
- name: config.name ?? "openai",
462
+ name: getOpenAIProviderLabel(config),
463
+ providerName: getLLMOpenAIProviderName(config),
433
464
  fetch: config.fetch,
434
465
  }, modelId);
435
466
  }
@@ -9,6 +9,7 @@ export type ResolvedOpenAIReasoning = {
9
9
  effort: OpenAIReasoningEffort;
10
10
  source: "default" | "explicit";
11
11
  };
12
+ export declare function supportsDefaultReasoningParams(providerName: string): boolean;
12
13
  export declare function getDefaultOpenAIReasoningEffort(modelId: string, providerName?: string): OpenAIReasoningEffort | undefined;
13
14
  export declare function resolveOpenAIReasoningConfig(modelId: string, providerName: string, option: OpenAIProviderReasoningOption | undefined): ResolvedOpenAIReasoning | undefined;
14
15
  export declare function shouldRequestOpenAIReasoningSummary(providerName: string, reasoning: ResolvedOpenAIReasoning): boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"openai-reasoning-models.d.ts","sourceRoot":"","sources":["../../../../src/extensions/ext-llm-openai/src/openai-reasoning-models.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAE9D,MAAM,MAAM,6BAA6B,GAAG,qBAAqB,GAAG,KAAK,CAAC;AAE1E,MAAM,MAAM,6BAA6B,GAAG;IAC1C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,6BAA6B,CAAC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,MAAM,EAAE,qBAAqB,CAAC;IAC9B,MAAM,EAAE,SAAS,GAAG,UAAU,CAAC;CAChC,CAAC;AA6BF,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,MAAM,EACf,YAAY,SAAW,GACtB,qBAAqB,GAAG,SAAS,CA0BnC;AAED,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,6BAA6B,GAAG,SAAS,GAChD,uBAAuB,GAAG,SAAS,CAoBrC;AAED,wBAAgB,mCAAmC,CACjD,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,uBAAuB,GACjC,OAAO,CAET;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,SAAW,GAAG,OAAO,CAExF;AAED,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAIpE"}
1
+ {"version":3,"file":"openai-reasoning-models.d.ts","sourceRoot":"","sources":["../../../../src/extensions/ext-llm-openai/src/openai-reasoning-models.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAE9D,MAAM,MAAM,6BAA6B,GAAG,qBAAqB,GAAG,KAAK,CAAC;AAE1E,MAAM,MAAM,6BAA6B,GAAG;IAC1C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,6BAA6B,CAAC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,MAAM,EAAE,qBAAqB,CAAC;IAC9B,MAAM,EAAE,SAAS,GAAG,UAAU,CAAC;CAChC,CAAC;AAIF,wBAAgB,8BAA8B,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAG5E;AAuBD,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,MAAM,EACf,YAAY,SAAW,GACtB,qBAAqB,GAAG,SAAS,CAwBnC;AAED,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,6BAA6B,GAAG,SAAS,GAChD,uBAAuB,GAAG,SAAS,CAoBrC;AAED,wBAAgB,mCAAmC,CACjD,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,uBAAuB,GACjC,OAAO,CAET;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,SAAW,GAAG,OAAO,CAExF;AAED,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAIpE"}
@@ -1,6 +1,7 @@
1
1
  const DEFAULT_REASONING_EFFORT = "medium";
2
- function supportsDefaultReasoningParams(providerName) {
3
- return providerName === "openai" || providerName === "veryfront-cloud";
2
+ export function supportsDefaultReasoningParams(providerName) {
3
+ const normalizedProvider = providerName.toLowerCase();
4
+ return normalizedProvider === "openai" || normalizedProvider === "veryfront-cloud";
4
5
  }
5
6
  function isGpt5ChatSnapshot(modelId) {
6
7
  return /^gpt-5-chat($|-)/.test(modelId);
@@ -20,8 +21,7 @@ function isReasoningCapableGpt5(modelId) {
20
21
  }
21
22
  export function getDefaultOpenAIReasoningEffort(modelId, providerName = "openai") {
22
23
  const normalized = modelId.toLowerCase();
23
- const normalizedProvider = providerName.toLowerCase();
24
- if (!supportsDefaultReasoningParams(normalizedProvider)) {
24
+ if (!supportsDefaultReasoningParams(providerName)) {
25
25
  return undefined;
26
26
  }
27
27
  if (isGpt5ChatSnapshot(normalized)) {
@@ -59,7 +59,7 @@ export function resolveOpenAIReasoningConfig(modelId, providerName, option) {
59
59
  }
60
60
  }
61
61
  export function shouldRequestOpenAIReasoningSummary(providerName, reasoning) {
62
- return reasoning.source === "explicit" || providerName.toLowerCase() === "veryfront-cloud";
62
+ return reasoning.source === "explicit" || supportsDefaultReasoningParams(providerName);
63
63
  }
64
64
  export function isOpenAIReasoningModel(modelId, providerName = "openai") {
65
65
  return getDefaultOpenAIReasoningEffort(modelId, providerName) !== undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../../../src/src/build/production-build/templates.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,eAAO,MAAM,aAAa,8KACmJ,CAAC;AAE9K,eAAO,MAAM,oBAAoB,EAAE,MAAM,GAAG,SACky2B,CAAC;AAE/02B,eAAO,MAAM,sBAAsB,EAAE,MAAM,GAAG,SAC630B,CAAC"}
1
+ {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../../../src/src/build/production-build/templates.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,eAAO,MAAM,aAAa,8KACmJ,CAAC;AAE9K,eAAO,MAAM,oBAAoB,EAAE,MAAM,GAAG,SAC8z8B,CAAC;AAE328B,eAAO,MAAM,sBAAsB,EAAE,MAAM,GAAG,SAC630B,CAAC"}
@@ -7,5 +7,5 @@
7
7
  * @module
8
8
  */
9
9
  export const CLIENT_STYLES = ".error-container {\n max-width: 600px;\n margin: 2rem auto;\n padding: 2rem;\n background: #fee;\n border: 1px solid #fcc;\n border-radius: 8px;\n color: #c00;\n}";
10
- export const CLIENT_ROUTER_BUNDLE = 'var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);\n\n// src/rendering/client/browser-stubs/logger.ts\nfunction noop() {\n}\nvar logger = {\n debug: noop,\n info: console.log.bind(console),\n warn: console.warn.bind(console),\n error: console.error.bind(console),\n component: () => logger\n};\nvar rendererLogger = logger;\nvar PREFETCH_MAX_SIZE_BYTES = 200 * 1024;\n\n// src/rendering/client/router.ts\nimport ReactDOM from "react-dom/client";\n\n// src/routing/client/dom-utils.ts\nvar logger2 = rendererLogger.component("veryfront");\nfunction isInternalLink(target) {\n const href = target.getAttribute("href");\n if (!href) return false;\n if (href.startsWith("http") || href.startsWith("mailto:") || href.startsWith("#")) return false;\n const linkTarget = target.getAttribute("target");\n if (linkTarget === "_blank" || target.hasAttribute("download")) return false;\n return true;\n}\nfunction findAnchorElement(element) {\n let current = element;\n while (current && current.tagName !== "A") {\n current = current.parentElement;\n }\n return current instanceof HTMLAnchorElement ? current : null;\n}\nfunction updateMetaTags(frontmatter) {\n if (frontmatter.description) {\n updateMetaTag(\'meta[name="description"]\', "name", "description", frontmatter.description);\n }\n if (frontmatter.ogTitle) {\n updateMetaTag(\'meta[property="og:title"]\', "property", "og:title", frontmatter.ogTitle);\n }\n}\nfunction updateMetaTag(selector, attributeName, attributeValue, content) {\n let metaTag = document.querySelector(selector);\n if (!metaTag) {\n metaTag = document.createElement("meta");\n metaTag.setAttribute(attributeName, attributeValue);\n document.head.appendChild(metaTag);\n }\n metaTag.setAttribute("content", content);\n}\nfunction executeScripts(container) {\n for (const oldScript of container.querySelectorAll("script")) {\n const newScript = document.createElement("script");\n for (const { name, value } of oldScript.attributes) {\n newScript.setAttribute(name, value);\n }\n newScript.textContent = oldScript.textContent;\n oldScript.parentNode?.replaceChild(newScript, oldScript);\n }\n}\nfunction applyHeadDirectives(container) {\n const nodes = container.querySelectorAll(\'[data-veryfront-head="1"], vf-head\');\n if (!nodes.length) return;\n cleanManagedHeadTags();\n for (const wrapper of nodes) {\n const contentSource = typeof HTMLTemplateElement !== "undefined" && wrapper instanceof HTMLTemplateElement ? wrapper.content : wrapper;\n processHeadWrapper(contentSource);\n wrapper.parentElement?.removeChild(wrapper);\n }\n}\nfunction cleanManagedHeadTags() {\n for (const element of document.head.querySelectorAll(\'[data-veryfront-managed="1"]\')) {\n element.parentElement?.removeChild(element);\n }\n}\nfunction processHeadWrapper(wrapper) {\n for (const node of wrapper.childNodes) {\n if (!(node instanceof Element)) continue;\n const tagName = node.tagName.toLowerCase();\n if (tagName === "title") {\n document.title = node.textContent || document.title;\n continue;\n }\n const clone = document.createElement(tagName);\n for (const { name, value } of node.attributes) {\n clone.setAttribute(name, value);\n }\n if (node.textContent && !clone.hasAttribute("src")) {\n clone.textContent = node.textContent;\n }\n clone.setAttribute("data-veryfront-managed", "1");\n document.head.appendChild(clone);\n }\n}\nfunction manageFocus(container) {\n try {\n const focusElement = container.querySelector("[data-router-focus]") || container.querySelector("main") || container.querySelector("h1");\n focusElement?.focus?.({ preventScroll: true });\n } catch (error) {\n logger2.warn("focus management failed", error);\n }\n}\nfunction extractPageDataFromScript() {\n const pageDataScript = document.querySelector("script[data-veryfront-page]");\n if (!pageDataScript) return null;\n try {\n const content = pageDataScript.textContent;\n if (!content) {\n logger2.warn("Page data script has no content");\n return {};\n }\n return JSON.parse(content);\n } catch (error) {\n logger2.error("Failed to parse page data:", error);\n return null;\n }\n}\nfunction parsePageDataFromHTML(html) {\n const doc = new DOMParser().parseFromString(html, "text/html");\n const root = doc.getElementById("root");\n if (!root) logger2.warn("[Veryfront] No root element found in HTML");\n const content = root?.innerHTML ?? "";\n const pageDataScript = doc.querySelector("script[data-veryfront-page]");\n let pageData = {};\n if (pageDataScript) {\n try {\n const scriptContent = pageDataScript.textContent;\n if (!scriptContent) {\n logger2.warn("Page data script in HTML has no content");\n } else {\n pageData = JSON.parse(scriptContent);\n }\n } catch (error) {\n logger2.error("Failed to parse page data from HTML:", error);\n }\n }\n return { content, pageData };\n}\n\n// src/rendering/client/browser-stubs/config.ts\nvar DEFAULT_PREFETCH_DELAY_MS = 100;\nvar PAGE_TRANSITION_DELAY_MS = 150;\n\n// src/routing/client/navigation-handlers.ts\nvar logger3 = rendererLogger.component("veryfront");\nvar MAX_SCROLL_POSITIONS = 100;\nvar NavigationHandlers = class {\n constructor(prefetchDelay = DEFAULT_PREFETCH_DELAY_MS, prefetchOptions = {}) {\n __publicField(this, "prefetchQueue", /* @__PURE__ */ new Set());\n __publicField(this, "pendingTimeouts", /* @__PURE__ */ new Map());\n __publicField(this, "scrollPositions", /* @__PURE__ */ new Map());\n __publicField(this, "isPopStateNav", false);\n __publicField(this, "prefetchDelay");\n __publicField(this, "prefetchOptions");\n this.prefetchDelay = prefetchDelay;\n this.prefetchOptions = prefetchOptions;\n }\n createClickHandler(callbacks) {\n return (event) => {\n if (!(event.target instanceof HTMLElement)) return;\n const anchor = findAnchorElement(event.target);\n if (!anchor || !isInternalLink(anchor)) return;\n const href = anchor.getAttribute("href");\n if (!href) return;\n event.preventDefault();\n callbacks.onNavigate(href);\n };\n }\n createPopStateHandler(callbacks) {\n return (_event) => {\n this.isPopStateNav = true;\n callbacks.onNavigate(globalThis.location.pathname);\n };\n }\n createMouseOverHandler(callbacks) {\n return (event) => {\n if (!(event.target instanceof HTMLElement)) return;\n if (event.target.tagName !== "A") return;\n const href = event.target.getAttribute("href");\n if (!href || href.startsWith("http") || href.startsWith("#")) return;\n if (!this.shouldPrefetchOnHover(event.target)) return;\n if (this.prefetchQueue.has(href)) return;\n this.prefetchQueue.add(href);\n const timeoutId = setTimeout(() => {\n callbacks.onPrefetch(href);\n this.prefetchQueue.delete(href);\n this.pendingTimeouts.delete(href);\n }, this.prefetchDelay);\n this.pendingTimeouts.set(href, timeoutId);\n };\n }\n shouldPrefetchOnHover(target) {\n const prefetchAttribute = target.getAttribute("data-prefetch");\n if (prefetchAttribute === "false") return false;\n if (prefetchAttribute === "true") return true;\n return Boolean(this.prefetchOptions.hover);\n }\n saveScrollPosition(path) {\n try {\n if (this.scrollPositions.size >= MAX_SCROLL_POSITIONS) {\n const oldest = this.scrollPositions.keys().next().value;\n if (oldest) this.scrollPositions.delete(oldest);\n }\n const scrollY = globalThis.scrollY;\n if (typeof scrollY !== "number") {\n logger3.debug("No valid scrollY value available");\n this.scrollPositions.set(path, 0);\n return;\n }\n this.scrollPositions.set(path, scrollY);\n } catch (error) {\n logger3.warn("failed to record scroll position", error);\n }\n }\n getScrollPosition(path) {\n const position = this.scrollPositions.get(path);\n if (position === void 0) {\n logger3.debug(`No scroll position stored for ${path}`);\n return 0;\n }\n return position;\n }\n isPopState() {\n return this.isPopStateNav;\n }\n clearPopStateFlag() {\n this.isPopStateNav = false;\n }\n clear() {\n for (const timeoutId of this.pendingTimeouts.values()) clearTimeout(timeoutId);\n this.pendingTimeouts.clear();\n this.prefetchQueue.clear();\n this.scrollPositions.clear();\n this.isPopStateNav = false;\n }\n};\n\n// src/rendering/client/browser-stubs/error-registry.ts\nfunction createBrowserError(name, fallbackMessage) {\n return {\n create(options = {}) {\n const error = new Error(options.detail ?? fallbackMessage);\n error.name = name;\n Object.assign(error, {\n status: options.status,\n context: options.context\n });\n return error;\n }\n };\n}\nvar NETWORK_ERROR = createBrowserError("NetworkError", "Network request failed");\nvar SECURITY_VIOLATION = createBrowserError("SecurityViolation", "Security violation");\n\n// src/routing/client/page-loader.ts\nvar logger4 = rendererLogger.component("veryfront");\nvar MAX_CACHE_SIZE = 50;\nvar PageLoader = class {\n constructor() {\n __publicField(this, "cache", /* @__PURE__ */ new Map());\n __publicField(this, "spaCache", /* @__PURE__ */ new Map());\n __publicField(this, "pendingRequests", /* @__PURE__ */ new Map());\n __publicField(this, "pendingSpaRequests", /* @__PURE__ */ new Map());\n }\n evictIfFull(map) {\n if (map.size < MAX_CACHE_SIZE) return;\n const oldest = map.keys().next().value;\n if (oldest) map.delete(oldest);\n }\n getCached(path) {\n return this.cache.get(path);\n }\n isCached(path) {\n return this.cache.has(path);\n }\n setCache(path, data) {\n this.evictIfFull(this.cache);\n this.cache.set(path, data);\n }\n clearCache() {\n this.cache.clear();\n this.spaCache.clear();\n this.pendingRequests.clear();\n this.pendingSpaRequests.clear();\n }\n getSpaCached(path) {\n return this.spaCache.get(path);\n }\n isSpaDataCached(path) {\n return this.spaCache.has(path);\n }\n setSpaCache(path, data) {\n this.evictIfFull(this.spaCache);\n this.spaCache.set(path, data);\n }\n async fetchPageData(path) {\n return await this.tryFetchJSON(path) ?? this.fetchAndParseHTML(path);\n }\n async tryFetchJSON(path) {\n try {\n const response = await fetch(`/_veryfront/data${path}.json`, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (!response.ok) return null;\n return await response.json();\n } catch (error) {\n logger4.debug(`JSON fetch failed for ${path}, falling back to HTML:`, error);\n return null;\n }\n }\n async fetchAndParseHTML(path) {\n const response = await fetch(path, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (!response.ok) {\n throw NETWORK_ERROR.create({\n detail: `Failed to fetch ${path}`,\n status: response.status,\n context: { path }\n });\n }\n const html = await response.text();\n const { content, pageData } = parsePageDataFromHTML(html);\n return { html: content, ...pageData };\n }\n loadPage(path) {\n const cachedData = this.getCached(path);\n if (cachedData) {\n logger4.debug(`Loading ${path} from cache`);\n return Promise.resolve(cachedData);\n }\n const pending = this.pendingRequests.get(path);\n if (pending) {\n logger4.debug(`Reusing pending request for ${path}`);\n return pending;\n }\n logger4.debug(`Creating pending request for ${path}`);\n return this.createPendingRequest(path, this.pendingRequests, async () => {\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n return data;\n });\n }\n async prefetch(path) {\n if (this.isCached(path)) return;\n logger4.debug(`Prefetching ${path}`);\n try {\n await this.loadPage(path);\n } catch (error) {\n logger4.warn(\n `[Veryfront] Failed to prefetch ${path}`,\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n async fetchSpaPageData(path) {\n const normalizedPath = path === "/" ? "" : path.replace(/^\\//, "");\n const endpoint = `/_veryfront/page-data/${normalizedPath}.json`;\n logger4.debug(`Fetching SPA page data from ${endpoint}`);\n const response = await fetch(endpoint, {\n headers: { "X-Veryfront-Navigation": "spa" }\n });\n if (!response.ok) {\n throw NETWORK_ERROR.create({\n detail: `Failed to fetch SPA page data for ${path}`,\n status: response.status,\n context: { path }\n });\n }\n return response.json();\n }\n loadSpaPageData(path) {\n const cachedData = this.getSpaCached(path);\n if (cachedData) {\n logger4.debug(`Loading SPA data for ${path} from cache`);\n return Promise.resolve(cachedData);\n }\n const pending = this.pendingSpaRequests.get(path);\n if (pending) {\n logger4.debug(`Reusing pending SPA request for ${path}`);\n return pending;\n }\n logger4.debug(`Creating pending SPA request for ${path}`);\n return this.createPendingRequest(path, this.pendingSpaRequests, async () => {\n const data = await this.fetchSpaPageData(path);\n this.setSpaCache(path, data);\n return data;\n });\n }\n async prefetchSpaPageData(path) {\n if (this.isSpaDataCached(path)) return;\n logger4.debug(`Prefetching SPA page data for ${path}`);\n try {\n await this.loadSpaPageData(path);\n } catch (error) {\n logger4.warn(\n `[Veryfront] Failed to prefetch SPA data for ${path}`,\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n createPendingRequest(path, pendingMap, fetcher) {\n const request = (async () => {\n try {\n return await fetcher();\n } finally {\n pendingMap.delete(path);\n }\n })();\n pendingMap.set(path, request);\n return request;\n }\n};\n\n// src/security/client/html-sanitizer.ts\nvar SUSPICIOUS_PATTERN_SPECS = [\n { source: String.raw`<script[^>]*>[\\s\\S]*?<\\/script>`, flags: "gi", name: "inline script" },\n { source: String.raw`javascript:`, flags: "gi", name: "javascript: URL" },\n { source: String.raw`\\bon\\w+\\s*=`, flags: "gi", name: "event handler attribute" },\n { source: String.raw`data:\\s*text\\/html`, flags: "gi", name: "data: HTML URL" }\n];\nfunction createSuspiciousPatterns() {\n return SUSPICIOUS_PATTERN_SPECS.map(({ source, flags, name }) => ({\n pattern: new RegExp(source, flags),\n name\n }));\n}\nfunction isDevMode() {\n const g = globalThis;\n return g.__VERYFRONT_DEV__ === true || g.Deno?.env?.get?.("VERYFRONT_ENV") === "development";\n}\nfunction validateTrustedHtml(html, options = {}) {\n const { allowInlineScripts = false, strict = false, warn = true } = options;\n for (const { pattern, name } of createSuspiciousPatterns()) {\n if (allowInlineScripts && name === "inline script") continue;\n pattern.lastIndex = 0;\n if (!pattern.test(html)) continue;\n if (warn) console.warn(`[Security] Suspicious ${name} detected in server HTML`);\n if (strict || !isDevMode()) {\n throw SECURITY_VIOLATION.create({ detail: `Potentially unsafe HTML: ${name} detected` });\n }\n }\n return html;\n}\n\n// src/routing/client/page-transition.ts\nvar logger5 = rendererLogger.component("veryfront");\nvar PageTransition = class {\n constructor(setupViewportPrefetch) {\n __publicField(this, "setupViewportPrefetch", setupViewportPrefetch);\n __publicField(this, "pendingTransitionTimeout");\n }\n destroy() {\n if (this.pendingTransitionTimeout === void 0) return;\n clearTimeout(this.pendingTransitionTimeout);\n this.pendingTransitionTimeout = void 0;\n }\n updatePage(data, isPopState, scrollY) {\n const title = data.frontmatter?.title;\n if (title) document.title = title;\n updateMetaTags(data.frontmatter ?? {});\n const rootElement = document.getElementById("root");\n if (!rootElement || !data.html) return;\n this.performTransition(rootElement, data, isPopState, scrollY);\n }\n performTransition(rootElement, data, isPopState, scrollY) {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n this.pendingTransitionTimeout = void 0;\n }\n rootElement.style.opacity = "0";\n this.pendingTransitionTimeout = setTimeout(() => {\n this.pendingTransitionTimeout = void 0;\n rootElement.innerHTML = validateTrustedHtml(String(data.html), { allowInlineScripts: true });\n rootElement.style.opacity = "1";\n executeScripts(rootElement);\n applyHeadDirectives(rootElement);\n this.setupViewportPrefetch(rootElement);\n manageFocus(rootElement);\n this.handleScroll(isPopState, scrollY);\n }, PAGE_TRANSITION_DELAY_MS);\n }\n handleScroll(isPopState, scrollY) {\n try {\n globalThis.scrollTo(0, isPopState ? scrollY : 0);\n } catch (error) {\n logger5.warn("scroll handling failed", error);\n }\n }\n showError(error) {\n const rootElement = document.getElementById("root");\n if (!rootElement) return;\n const errorDiv = document.createElement("div");\n errorDiv.className = "veryfront-error-page";\n const heading = document.createElement("h1");\n heading.textContent = "Oops! Something went wrong";\n const message = document.createElement("p");\n message.textContent = error.message;\n const button = document.createElement("button");\n button.type = "button";\n button.textContent = "Reload Page";\n button.onclick = () => globalThis.location.reload();\n errorDiv.append(heading, message, button);\n rootElement.innerHTML = "";\n rootElement.appendChild(errorDiv);\n }\n setLoadingState(loading) {\n const indicator = document.getElementById("veryfront-loading");\n if (indicator) indicator.style.display = loading ? "block" : "none";\n document.body.classList.toggle("veryfront-loading", loading);\n }\n};\n\n// src/routing/client/viewport-prefetch.ts\nvar logger6 = rendererLogger.component("veryfront");\nvar ViewportPrefetch = class {\n constructor(prefetchCallback, prefetchOptions = {}) {\n __publicField(this, "observer", null);\n __publicField(this, "prefetchCallback");\n __publicField(this, "prefetchOptions");\n this.prefetchCallback = prefetchCallback;\n this.prefetchOptions = prefetchOptions;\n }\n setup(root) {\n try {\n if (!("IntersectionObserver" in globalThis)) return;\n this.observer?.disconnect();\n this.createObserver();\n this.observeLinks(root);\n } catch (error) {\n logger6.debug("setupViewportPrefetch failed", error);\n }\n }\n createObserver() {\n this.observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n if (!(entry.target instanceof HTMLAnchorElement)) continue;\n const href = entry.target.getAttribute("href");\n if (href) this.prefetchCallback(href);\n this.observer?.unobserve(entry.target);\n }\n },\n { rootMargin: "200px" }\n );\n }\n observeLinks(root) {\n const anchors = root.querySelectorAll(\'a[href]:not([target="_blank"])\');\n const isViewportEnabled = Boolean(this.prefetchOptions.viewport);\n for (const anchor of anchors) {\n if (!this.shouldObserveAnchor(anchor, isViewportEnabled)) continue;\n this.observer?.observe(anchor);\n }\n }\n shouldObserveAnchor(anchor, isViewportEnabled) {\n const href = anchor.getAttribute("href");\n if (!href) return false;\n if (href.startsWith("http") || href.startsWith("#")) return false;\n if (anchor.getAttribute("download")) return false;\n const prefetchAttribute = anchor.getAttribute("data-prefetch");\n if (prefetchAttribute === "false") return false;\n return prefetchAttribute === "viewport" || isViewportEnabled;\n }\n disconnect() {\n if (!this.observer) return;\n try {\n this.observer.disconnect();\n } catch (error) {\n logger6.warn("prefetchObserver.disconnect failed", error);\n } finally {\n this.observer = null;\n }\n }\n};\n\n// src/rendering/client/router.ts\nvar logger7 = rendererLogger.component("veryfront");\nvar VeryfrontRouter = class {\n constructor(options = {}) {\n __publicField(this, "baseUrl");\n __publicField(this, "currentPath");\n __publicField(this, "root", null);\n __publicField(this, "options");\n __publicField(this, "spaMode");\n __publicField(this, "spaNavigationHandler", null);\n __publicField(this, "pageLoader");\n __publicField(this, "navigationHandlers");\n __publicField(this, "pageTransition");\n __publicField(this, "viewportPrefetch");\n __publicField(this, "handleClick");\n __publicField(this, "handlePopState");\n __publicField(this, "handleMouseOver");\n const globalOptions = this.loadGlobalOptions();\n this.options = { ...globalOptions, ...options };\n this.baseUrl = this.options.baseUrl || globalThis.location.origin;\n this.currentPath = globalThis.location.pathname;\n this.spaMode = this.options.spaMode ?? globalThis.__VERYFRONT_SPA_MODE__ ?? false;\n this.pageLoader = new PageLoader();\n this.navigationHandlers = new NavigationHandlers(\n this.options.prefetchDelay,\n this.options.prefetch\n );\n this.pageTransition = new PageTransition((root) => this.viewportPrefetch.setup(root));\n this.viewportPrefetch = new ViewportPrefetch(\n (path) => this.prefetch(path),\n this.options.prefetch\n );\n this.handleClick = this.navigationHandlers.createClickHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handlePopState = this.navigationHandlers.createPopStateHandler({\n onNavigate: (url) => this.navigate(url, false),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handleMouseOver = this.navigationHandlers.createMouseOverHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n }\n registerNavigationHandler(handler) {\n logger7.debug("Registering SPA navigation handler");\n this.spaNavigationHandler = handler;\n this.spaMode = true;\n }\n loadGlobalOptions() {\n try {\n const options = globalThis.__VERYFRONT_ROUTER_OPTS__;\n if (!options) {\n logger7.debug("No global options configured");\n return {};\n }\n return options;\n } catch (error) {\n logger7.error("Failed to read global options:", error);\n return {};\n }\n }\n init() {\n logger7.debug("Initializing client-side router");\n const rootElement = document.getElementById("root");\n if (!rootElement) {\n logger7.error("Root element not found");\n return;\n }\n const ReactDOMToUse = globalThis.ReactDOM ?? ReactDOM;\n this.root = ReactDOMToUse.createRoot(rootElement);\n document.addEventListener("click", this.handleClick);\n globalThis.addEventListener("popstate", this.handlePopState);\n document.addEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.setup(document);\n this.cacheCurrentPage();\n }\n cacheCurrentPage() {\n const pageData = extractPageDataFromScript();\n if (pageData) this.pageLoader.setCache(this.currentPath, pageData);\n }\n async navigate(url, pushState = true) {\n logger7.debug(`Navigating to ${url} (SPA mode: ${this.spaMode})`);\n this.navigationHandlers.saveScrollPosition(this.currentPath);\n this.options.onStart?.(url);\n if (pushState) globalThis.history.pushState({}, "", url);\n if (this.spaMode && this.spaNavigationHandler) {\n await this.loadSpaPage(url);\n } else {\n await this.loadPage(url);\n }\n this.options.onNavigate?.(url);\n }\n async loadSpaPage(path) {\n logger7.debug(`Loading SPA page: ${path}`);\n try {\n const spaData = await this.pageLoader.loadSpaPageData(path);\n await this.spaNavigationHandler?.(spaData);\n this.currentPath = path;\n this.handleScrollAfterNavigation();\n this.options.onComplete?.(path);\n } catch (error) {\n const normalizedError = error instanceof Error ? error : new Error(String(error));\n logger7.error(`Failed to load SPA page ${path}`, normalizedError);\n this.options.onError?.(normalizedError);\n this.pageTransition.showError(normalizedError);\n }\n }\n handleScrollAfterNavigation() {\n const isPopState = this.navigationHandlers.isPopState();\n const scrollY = this.navigationHandlers.getScrollPosition(this.currentPath);\n try {\n globalThis.scrollTo(0, isPopState ? scrollY : 0);\n } catch (error) {\n logger7.warn("scroll handling failed", error);\n }\n this.navigationHandlers.clearPopStateFlag();\n }\n async loadPage(path, updateUI = true) {\n if (this.pageLoader.isCached(path)) {\n logger7.debug(`Loading ${path} from cache`);\n const data = this.pageLoader.getCached(path);\n if (data) {\n if (updateUI) this.updatePage(data);\n return;\n }\n logger7.warn(`Cache entry for ${path} was unexpectedly null, fetching fresh data`);\n }\n this.pageTransition.setLoadingState(true);\n try {\n const data = await this.pageLoader.loadPage(path);\n if (updateUI) this.updatePage(data);\n this.currentPath = path;\n this.options.onComplete?.(path);\n } catch (error) {\n const normalizedError = error instanceof Error ? error : new Error(String(error));\n logger7.error(`Failed to load ${path}`, normalizedError);\n this.options.onError?.(normalizedError);\n this.pageTransition.showError(normalizedError);\n } finally {\n this.pageTransition.setLoadingState(false);\n }\n }\n async prefetch(path) {\n if (this.spaMode) {\n await this.pageLoader.prefetchSpaPageData(path);\n return;\n }\n await this.pageLoader.prefetch(path);\n }\n updatePage(data) {\n if (!this.root) return;\n const isPopState = this.navigationHandlers.isPopState();\n const scrollY = this.navigationHandlers.getScrollPosition(this.currentPath);\n this.pageTransition.updatePage(data, isPopState, scrollY);\n this.navigationHandlers.clearPopStateFlag();\n }\n destroy() {\n document.removeEventListener("click", this.handleClick);\n globalThis.removeEventListener("popstate", this.handlePopState);\n document.removeEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.disconnect();\n this.pageLoader.clearCache();\n this.navigationHandlers.clear();\n this.pageTransition.destroy();\n }\n};\nfunction boot(options = {}) {\n if (typeof window === "undefined" || !globalThis.document) return null;\n const globalWithRouter = globalThis;\n if (globalWithRouter.veryFrontRouter) return globalWithRouter.veryFrontRouter;\n const { slug: _slug, ...routerOptions } = options;\n const router = new VeryfrontRouter(routerOptions);\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => router.init(), { once: true });\n } else {\n router.init();\n }\n globalWithRouter.veryFrontRouter = router;\n return router;\n}\nif (typeof window !== "undefined" && globalThis.document) {\n boot();\n}\nexport {\n VeryfrontRouter,\n boot\n};\n';
10
+ export const CLIENT_ROUTER_BUNDLE = 'var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);\n\n// src/rendering/client/browser-stubs/logger.ts\nfunction noop() {\n}\nvar logger = {\n debug: noop,\n info: console.log.bind(console),\n warn: console.warn.bind(console),\n error: console.error.bind(console),\n component: () => logger\n};\nvar rendererLogger = logger;\nvar PREFETCH_MAX_SIZE_BYTES = 200 * 1024;\n\n// src/rendering/client/navigation-store.ts\nvar STORE_KEY = /* @__PURE__ */ Symbol.for("veryfront.navigation.store.v1");\nfunction getNavigationStore() {\n const holder = globalThis;\n const existing = holder[STORE_KEY];\n if (existing) return existing;\n const listeners = /* @__PURE__ */ new Set();\n let navigator = null;\n const store = {\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n getHref() {\n const loc = globalThis.location;\n return loc ? `${loc.pathname}${loc.search}${loc.hash}` : "/";\n },\n notify() {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n }\n }\n },\n navigate(href, options) {\n if (navigator) return navigator(href, options);\n globalThis.location?.assign(href);\n return Promise.resolve();\n },\n setNavigator(next) {\n navigator = next;\n }\n };\n holder[STORE_KEY] = store;\n return store;\n}\n\n// src/rendering/client/router.ts\nimport ReactDOM from "react-dom/client";\n\n// src/routing/client/dom-utils.ts\nvar logger2 = rendererLogger.component("veryfront");\nfunction isInternalLink(target) {\n const href = target.getAttribute("href");\n if (!href) return false;\n if (href.startsWith("http") || href.startsWith("mailto:") || href.startsWith("#")) return false;\n const linkTarget = target.getAttribute("target");\n if (linkTarget === "_blank" || target.hasAttribute("download")) return false;\n return true;\n}\nfunction findAnchorElement(element) {\n let current = element;\n while (current && current.tagName !== "A") {\n current = current.parentElement;\n }\n return current instanceof HTMLAnchorElement ? current : null;\n}\nfunction updateMetaTags(frontmatter) {\n if (frontmatter.description) {\n updateMetaTag(\'meta[name="description"]\', "name", "description", frontmatter.description);\n }\n if (frontmatter.ogTitle) {\n updateMetaTag(\'meta[property="og:title"]\', "property", "og:title", frontmatter.ogTitle);\n }\n}\nfunction updateMetaTag(selector, attributeName, attributeValue, content) {\n let metaTag = document.querySelector(selector);\n if (!metaTag) {\n metaTag = document.createElement("meta");\n metaTag.setAttribute(attributeName, attributeValue);\n document.head.appendChild(metaTag);\n }\n metaTag.setAttribute("content", content);\n}\nfunction executeScripts(container) {\n for (const oldScript of container.querySelectorAll("script")) {\n const newScript = document.createElement("script");\n for (const { name, value } of oldScript.attributes) {\n newScript.setAttribute(name, value);\n }\n newScript.textContent = oldScript.textContent;\n oldScript.parentNode?.replaceChild(newScript, oldScript);\n }\n}\nfunction applyHeadDirectives(container) {\n const nodes = container.querySelectorAll(\'[data-veryfront-head="1"], vf-head\');\n if (!nodes.length) return;\n cleanManagedHeadTags();\n for (const wrapper of nodes) {\n const contentSource = typeof HTMLTemplateElement !== "undefined" && wrapper instanceof HTMLTemplateElement ? wrapper.content : wrapper;\n processHeadWrapper(contentSource);\n wrapper.parentElement?.removeChild(wrapper);\n }\n}\nfunction cleanManagedHeadTags() {\n for (const element of document.head.querySelectorAll(\'[data-veryfront-managed="1"]\')) {\n element.parentElement?.removeChild(element);\n }\n}\nfunction processHeadWrapper(wrapper) {\n for (const node of wrapper.childNodes) {\n if (!(node instanceof Element)) continue;\n const tagName = node.tagName.toLowerCase();\n if (tagName === "title") {\n document.title = node.textContent || document.title;\n continue;\n }\n const clone = document.createElement(tagName);\n for (const { name, value } of node.attributes) {\n clone.setAttribute(name, value);\n }\n if (node.textContent && !clone.hasAttribute("src")) {\n clone.textContent = node.textContent;\n }\n clone.setAttribute("data-veryfront-managed", "1");\n document.head.appendChild(clone);\n }\n}\nfunction manageFocus(container) {\n try {\n const focusElement = container.querySelector("[data-router-focus]") || container.querySelector("main") || container.querySelector("h1");\n focusElement?.focus?.({ preventScroll: true });\n } catch (error) {\n logger2.warn("focus management failed", error);\n }\n}\nfunction extractPageDataFromScript() {\n const pageDataScript = document.querySelector("script[data-veryfront-page]");\n if (!pageDataScript) return null;\n try {\n const content = pageDataScript.textContent;\n if (!content) {\n logger2.warn("Page data script has no content");\n return {};\n }\n return JSON.parse(content);\n } catch (error) {\n logger2.error("Failed to parse page data:", error);\n return null;\n }\n}\nfunction parsePageDataFromHTML(html) {\n const doc = new DOMParser().parseFromString(html, "text/html");\n const root = doc.getElementById("root");\n if (!root) logger2.warn("[Veryfront] No root element found in HTML");\n const content = root?.innerHTML ?? "";\n const pageDataScript = doc.querySelector("script[data-veryfront-page]");\n let pageData = {};\n if (pageDataScript) {\n try {\n const scriptContent = pageDataScript.textContent;\n if (!scriptContent) {\n logger2.warn("Page data script in HTML has no content");\n } else {\n pageData = JSON.parse(scriptContent);\n }\n } catch (error) {\n logger2.error("Failed to parse page data from HTML:", error);\n }\n }\n return { content, pageData };\n}\n\n// src/rendering/client/browser-stubs/config.ts\nvar DEFAULT_PREFETCH_DELAY_MS = 100;\nvar PAGE_TRANSITION_DELAY_MS = 150;\n\n// src/routing/client/navigation-handlers.ts\nvar logger3 = rendererLogger.component("veryfront");\nvar MAX_SCROLL_POSITIONS = 100;\nvar NavigationHandlers = class {\n constructor(prefetchDelay = DEFAULT_PREFETCH_DELAY_MS, prefetchOptions = {}) {\n __publicField(this, "prefetchQueue", /* @__PURE__ */ new Set());\n __publicField(this, "pendingTimeouts", /* @__PURE__ */ new Map());\n __publicField(this, "scrollPositions", /* @__PURE__ */ new Map());\n __publicField(this, "isPopStateNav", false);\n __publicField(this, "prefetchDelay");\n __publicField(this, "prefetchOptions");\n this.prefetchDelay = prefetchDelay;\n this.prefetchOptions = prefetchOptions;\n }\n createClickHandler(callbacks) {\n return (event) => {\n if (!(event.target instanceof HTMLElement)) return;\n const anchor = findAnchorElement(event.target);\n if (!anchor || !isInternalLink(anchor)) return;\n const href = anchor.getAttribute("href");\n if (!href) return;\n event.preventDefault();\n callbacks.onNavigate(href);\n };\n }\n createPopStateHandler(callbacks) {\n return (_event) => {\n this.isPopStateNav = true;\n callbacks.onNavigate(globalThis.location.pathname);\n };\n }\n createMouseOverHandler(callbacks) {\n return (event) => {\n if (!(event.target instanceof HTMLElement)) return;\n if (event.target.tagName !== "A") return;\n const href = event.target.getAttribute("href");\n if (!href || href.startsWith("http") || href.startsWith("#")) return;\n if (!this.shouldPrefetchOnHover(event.target)) return;\n if (this.prefetchQueue.has(href)) return;\n this.prefetchQueue.add(href);\n const timeoutId = setTimeout(() => {\n callbacks.onPrefetch(href);\n this.prefetchQueue.delete(href);\n this.pendingTimeouts.delete(href);\n }, this.prefetchDelay);\n this.pendingTimeouts.set(href, timeoutId);\n };\n }\n shouldPrefetchOnHover(target) {\n const prefetchAttribute = target.getAttribute("data-prefetch");\n if (prefetchAttribute === "false") return false;\n if (prefetchAttribute === "true") return true;\n return Boolean(this.prefetchOptions.hover);\n }\n saveScrollPosition(path) {\n try {\n if (this.scrollPositions.size >= MAX_SCROLL_POSITIONS) {\n const oldest = this.scrollPositions.keys().next().value;\n if (oldest) this.scrollPositions.delete(oldest);\n }\n const scrollY = globalThis.scrollY;\n if (typeof scrollY !== "number") {\n logger3.debug("No valid scrollY value available");\n this.scrollPositions.set(path, 0);\n return;\n }\n this.scrollPositions.set(path, scrollY);\n } catch (error) {\n logger3.warn("failed to record scroll position", error);\n }\n }\n getScrollPosition(path) {\n const position = this.scrollPositions.get(path);\n if (position === void 0) {\n logger3.debug(`No scroll position stored for ${path}`);\n return 0;\n }\n return position;\n }\n isPopState() {\n return this.isPopStateNav;\n }\n clearPopStateFlag() {\n this.isPopStateNav = false;\n }\n clear() {\n for (const timeoutId of this.pendingTimeouts.values()) clearTimeout(timeoutId);\n this.pendingTimeouts.clear();\n this.prefetchQueue.clear();\n this.scrollPositions.clear();\n this.isPopStateNav = false;\n }\n};\n\n// src/rendering/client/browser-stubs/error-registry.ts\nfunction createBrowserError(name, fallbackMessage) {\n return {\n create(options = {}) {\n const error = new Error(options.detail ?? fallbackMessage);\n error.name = name;\n Object.assign(error, {\n status: options.status,\n context: options.context\n });\n return error;\n }\n };\n}\nvar NETWORK_ERROR = createBrowserError("NetworkError", "Network request failed");\nvar SECURITY_VIOLATION = createBrowserError("SecurityViolation", "Security violation");\n\n// src/routing/client/page-loader.ts\nvar logger4 = rendererLogger.component("veryfront");\nvar MAX_CACHE_SIZE = 50;\nvar PageLoader = class {\n constructor() {\n __publicField(this, "cache", /* @__PURE__ */ new Map());\n __publicField(this, "spaCache", /* @__PURE__ */ new Map());\n __publicField(this, "pendingRequests", /* @__PURE__ */ new Map());\n __publicField(this, "pendingSpaRequests", /* @__PURE__ */ new Map());\n }\n evictIfFull(map) {\n if (map.size < MAX_CACHE_SIZE) return;\n const oldest = map.keys().next().value;\n if (oldest) map.delete(oldest);\n }\n getCached(path) {\n return this.cache.get(path);\n }\n isCached(path) {\n return this.cache.has(path);\n }\n setCache(path, data) {\n this.evictIfFull(this.cache);\n this.cache.set(path, data);\n }\n clearCache() {\n this.cache.clear();\n this.spaCache.clear();\n this.pendingRequests.clear();\n this.pendingSpaRequests.clear();\n }\n getSpaCached(path) {\n return this.spaCache.get(path);\n }\n isSpaDataCached(path) {\n return this.spaCache.has(path);\n }\n setSpaCache(path, data) {\n this.evictIfFull(this.spaCache);\n this.spaCache.set(path, data);\n }\n async fetchPageData(path) {\n return await this.tryFetchJSON(path) ?? this.fetchAndParseHTML(path);\n }\n async tryFetchJSON(path) {\n try {\n const response = await fetch(`/_veryfront/data${path}.json`, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (!response.ok) return null;\n return await response.json();\n } catch (error) {\n logger4.debug(`JSON fetch failed for ${path}, falling back to HTML:`, error);\n return null;\n }\n }\n async fetchAndParseHTML(path) {\n const response = await fetch(path, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (!response.ok) {\n throw NETWORK_ERROR.create({\n detail: `Failed to fetch ${path}`,\n status: response.status,\n context: { path }\n });\n }\n const html = await response.text();\n const { content, pageData } = parsePageDataFromHTML(html);\n return { html: content, ...pageData };\n }\n loadPage(path) {\n const cachedData = this.getCached(path);\n if (cachedData) {\n logger4.debug(`Loading ${path} from cache`);\n return Promise.resolve(cachedData);\n }\n const pending = this.pendingRequests.get(path);\n if (pending) {\n logger4.debug(`Reusing pending request for ${path}`);\n return pending;\n }\n logger4.debug(`Creating pending request for ${path}`);\n return this.createPendingRequest(path, this.pendingRequests, async () => {\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n return data;\n });\n }\n async prefetch(path) {\n if (this.isCached(path)) return;\n logger4.debug(`Prefetching ${path}`);\n try {\n await this.loadPage(path);\n } catch (error) {\n logger4.warn(\n `[Veryfront] Failed to prefetch ${path}`,\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n async fetchSpaPageData(path) {\n const normalizedPath = path === "/" ? "" : path.replace(/^\\//, "");\n const endpoint = `/_veryfront/page-data/${normalizedPath}.json`;\n logger4.debug(`Fetching SPA page data from ${endpoint}`);\n const response = await fetch(endpoint, {\n headers: { "X-Veryfront-Navigation": "spa" }\n });\n if (!response.ok) {\n throw NETWORK_ERROR.create({\n detail: `Failed to fetch SPA page data for ${path}`,\n status: response.status,\n context: { path }\n });\n }\n return response.json();\n }\n loadSpaPageData(path) {\n const cachedData = this.getSpaCached(path);\n if (cachedData) {\n logger4.debug(`Loading SPA data for ${path} from cache`);\n return Promise.resolve(cachedData);\n }\n const pending = this.pendingSpaRequests.get(path);\n if (pending) {\n logger4.debug(`Reusing pending SPA request for ${path}`);\n return pending;\n }\n logger4.debug(`Creating pending SPA request for ${path}`);\n return this.createPendingRequest(path, this.pendingSpaRequests, async () => {\n const data = await this.fetchSpaPageData(path);\n this.setSpaCache(path, data);\n return data;\n });\n }\n async prefetchSpaPageData(path) {\n if (this.isSpaDataCached(path)) return;\n logger4.debug(`Prefetching SPA page data for ${path}`);\n try {\n await this.loadSpaPageData(path);\n } catch (error) {\n logger4.warn(\n `[Veryfront] Failed to prefetch SPA data for ${path}`,\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n createPendingRequest(path, pendingMap, fetcher) {\n const request = (async () => {\n try {\n return await fetcher();\n } finally {\n pendingMap.delete(path);\n }\n })();\n pendingMap.set(path, request);\n return request;\n }\n};\n\n// src/security/client/html-sanitizer.ts\nvar SUSPICIOUS_PATTERN_SPECS = [\n { source: String.raw`<script[^>]*>[\\s\\S]*?<\\/script>`, flags: "gi", name: "inline script" },\n { source: String.raw`javascript:`, flags: "gi", name: "javascript: URL" },\n { source: String.raw`\\bon\\w+\\s*=`, flags: "gi", name: "event handler attribute" },\n { source: String.raw`data:\\s*text\\/html`, flags: "gi", name: "data: HTML URL" }\n];\nfunction createSuspiciousPatterns() {\n return SUSPICIOUS_PATTERN_SPECS.map(({ source, flags, name }) => ({\n pattern: new RegExp(source, flags),\n name\n }));\n}\nfunction isDevMode() {\n const g = globalThis;\n return g.__VERYFRONT_DEV__ === true || g.Deno?.env?.get?.("VERYFRONT_ENV") === "development";\n}\nfunction validateTrustedHtml(html, options = {}) {\n const { allowInlineScripts = false, strict = false, warn = true } = options;\n for (const { pattern, name } of createSuspiciousPatterns()) {\n if (allowInlineScripts && name === "inline script") continue;\n pattern.lastIndex = 0;\n if (!pattern.test(html)) continue;\n if (warn) console.warn(`[Security] Suspicious ${name} detected in server HTML`);\n if (strict || !isDevMode()) {\n throw SECURITY_VIOLATION.create({ detail: `Potentially unsafe HTML: ${name} detected` });\n }\n }\n return html;\n}\n\n// src/routing/client/page-transition.ts\nvar logger5 = rendererLogger.component("veryfront");\nvar PageTransition = class {\n constructor(setupViewportPrefetch) {\n __publicField(this, "setupViewportPrefetch", setupViewportPrefetch);\n __publicField(this, "pendingTransitionTimeout");\n }\n destroy() {\n if (this.pendingTransitionTimeout === void 0) return;\n clearTimeout(this.pendingTransitionTimeout);\n this.pendingTransitionTimeout = void 0;\n }\n updatePage(data, isPopState, scrollY) {\n const title = data.frontmatter?.title;\n if (title) document.title = title;\n updateMetaTags(data.frontmatter ?? {});\n const rootElement = document.getElementById("root");\n if (!rootElement || !data.html) return;\n this.performTransition(rootElement, data, isPopState, scrollY);\n }\n performTransition(rootElement, data, isPopState, scrollY) {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n this.pendingTransitionTimeout = void 0;\n }\n rootElement.style.opacity = "0";\n this.pendingTransitionTimeout = setTimeout(() => {\n this.pendingTransitionTimeout = void 0;\n rootElement.innerHTML = validateTrustedHtml(String(data.html), { allowInlineScripts: true });\n rootElement.style.opacity = "1";\n executeScripts(rootElement);\n applyHeadDirectives(rootElement);\n this.setupViewportPrefetch(rootElement);\n manageFocus(rootElement);\n this.handleScroll(isPopState, scrollY);\n }, PAGE_TRANSITION_DELAY_MS);\n }\n handleScroll(isPopState, scrollY) {\n try {\n globalThis.scrollTo(0, isPopState ? scrollY : 0);\n } catch (error) {\n logger5.warn("scroll handling failed", error);\n }\n }\n showError(error) {\n const rootElement = document.getElementById("root");\n if (!rootElement) return;\n const errorDiv = document.createElement("div");\n errorDiv.className = "veryfront-error-page";\n const heading = document.createElement("h1");\n heading.textContent = "Oops! Something went wrong";\n const message = document.createElement("p");\n message.textContent = error.message;\n const button = document.createElement("button");\n button.type = "button";\n button.textContent = "Reload Page";\n button.onclick = () => globalThis.location.reload();\n errorDiv.append(heading, message, button);\n rootElement.innerHTML = "";\n rootElement.appendChild(errorDiv);\n }\n setLoadingState(loading) {\n const indicator = document.getElementById("veryfront-loading");\n if (indicator) indicator.style.display = loading ? "block" : "none";\n document.body.classList.toggle("veryfront-loading", loading);\n }\n};\n\n// src/routing/client/viewport-prefetch.ts\nvar logger6 = rendererLogger.component("veryfront");\nvar ViewportPrefetch = class {\n constructor(prefetchCallback, prefetchOptions = {}) {\n __publicField(this, "observer", null);\n __publicField(this, "prefetchCallback");\n __publicField(this, "prefetchOptions");\n this.prefetchCallback = prefetchCallback;\n this.prefetchOptions = prefetchOptions;\n }\n setup(root) {\n try {\n if (!("IntersectionObserver" in globalThis)) return;\n this.observer?.disconnect();\n this.createObserver();\n this.observeLinks(root);\n } catch (error) {\n logger6.debug("setupViewportPrefetch failed", error);\n }\n }\n createObserver() {\n this.observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n if (!(entry.target instanceof HTMLAnchorElement)) continue;\n const href = entry.target.getAttribute("href");\n if (href) this.prefetchCallback(href);\n this.observer?.unobserve(entry.target);\n }\n },\n { rootMargin: "200px" }\n );\n }\n observeLinks(root) {\n const anchors = root.querySelectorAll(\'a[href]:not([target="_blank"])\');\n const isViewportEnabled = Boolean(this.prefetchOptions.viewport);\n for (const anchor of anchors) {\n if (!this.shouldObserveAnchor(anchor, isViewportEnabled)) continue;\n this.observer?.observe(anchor);\n }\n }\n shouldObserveAnchor(anchor, isViewportEnabled) {\n const href = anchor.getAttribute("href");\n if (!href) return false;\n if (href.startsWith("http") || href.startsWith("#")) return false;\n if (anchor.getAttribute("download")) return false;\n const prefetchAttribute = anchor.getAttribute("data-prefetch");\n if (prefetchAttribute === "false") return false;\n return prefetchAttribute === "viewport" || isViewportEnabled;\n }\n disconnect() {\n if (!this.observer) return;\n try {\n this.observer.disconnect();\n } catch (error) {\n logger6.warn("prefetchObserver.disconnect failed", error);\n } finally {\n this.observer = null;\n }\n }\n};\n\n// src/rendering/client/router.ts\nvar logger7 = rendererLogger.component("veryfront");\nfunction toHistoryMode(options) {\n if (typeof options === "boolean") return options ? "push" : "none";\n return options?.history ?? "push";\n}\nvar VeryfrontRouter = class {\n constructor(options = {}) {\n __publicField(this, "baseUrl");\n __publicField(this, "currentPath");\n __publicField(this, "root", null);\n __publicField(this, "options");\n __publicField(this, "spaMode");\n __publicField(this, "spaNavigationHandler", null);\n __publicField(this, "pageLoader");\n __publicField(this, "navigationHandlers");\n __publicField(this, "pageTransition");\n __publicField(this, "viewportPrefetch");\n __publicField(this, "handleClick");\n __publicField(this, "handlePopState");\n __publicField(this, "handleMouseOver");\n const globalOptions = this.loadGlobalOptions();\n this.options = { ...globalOptions, ...options };\n this.baseUrl = this.options.baseUrl || globalThis.location.origin;\n this.currentPath = globalThis.location.pathname;\n this.spaMode = this.options.spaMode ?? globalThis.__VERYFRONT_SPA_MODE__ ?? false;\n this.pageLoader = new PageLoader();\n this.navigationHandlers = new NavigationHandlers(\n this.options.prefetchDelay,\n this.options.prefetch\n );\n this.pageTransition = new PageTransition((root) => this.viewportPrefetch.setup(root));\n this.viewportPrefetch = new ViewportPrefetch(\n (path) => this.prefetch(path),\n this.options.prefetch\n );\n this.handleClick = this.navigationHandlers.createClickHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handlePopState = this.navigationHandlers.createPopStateHandler({\n // The browser already updated the URL for a popstate, so don\'t touch history.\n onNavigate: (url) => this.navigate(url, { history: "none" }),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handleMouseOver = this.navigationHandlers.createMouseOverHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n getNavigationStore().setNavigator((href, options2) => this.navigate(href, options2));\n }\n registerNavigationHandler(handler) {\n logger7.debug("Registering SPA navigation handler");\n this.spaNavigationHandler = handler;\n this.spaMode = true;\n }\n /**\n * Notify React (and any other) subscribers that a navigation completed —\n * after full page loads, soft same-route changes, and popstate. Delegates to\n * the shared navigation store, the single subscription surface both bundles\n * share.\n */\n notify() {\n getNavigationStore().notify();\n }\n pathnameOf(url) {\n try {\n return new URL(url, this.baseUrl).pathname;\n } catch {\n return url.split("?")[0]?.split("#")[0] || this.currentPath;\n }\n }\n loadGlobalOptions() {\n try {\n const options = globalThis.__VERYFRONT_ROUTER_OPTS__;\n if (!options) {\n logger7.debug("No global options configured");\n return {};\n }\n return options;\n } catch (error) {\n logger7.error("Failed to read global options:", error);\n return {};\n }\n }\n init() {\n logger7.debug("Initializing client-side router");\n const rootElement = document.getElementById("root");\n if (!rootElement) {\n logger7.error("Root element not found");\n return;\n }\n const ReactDOMToUse = globalThis.ReactDOM ?? ReactDOM;\n this.root = ReactDOMToUse.createRoot(rootElement);\n document.addEventListener("click", this.handleClick);\n globalThis.addEventListener("popstate", this.handlePopState);\n document.addEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.setup(document);\n this.cacheCurrentPage();\n }\n cacheCurrentPage() {\n const pageData = extractPageDataFromScript();\n if (pageData) this.pageLoader.setCache(this.currentPath, pageData);\n }\n /**\n * Navigate to a URL. `options` selects the history behaviour: `{ history:\n * "push" }` (default), `"replace"`, or `"none"` (the URL already reflects the\n * target, as after popstate). A boolean is accepted for backward\n * compatibility — `true` pushes, `false` maps to `"none"`.\n */\n async navigate(url, options) {\n logger7.debug(`Navigating to ${url} (SPA mode: ${this.spaMode})`);\n const history = toHistoryMode(options);\n const sameRoute = this.pathnameOf(url) === this.pathnameOf(this.currentPath);\n this.navigationHandlers.saveScrollPosition(this.currentPath);\n this.options.onStart?.(url);\n if (history === "replace") globalThis.history.replaceState({}, "", url);\n else if (history === "push") globalThis.history.pushState({}, "", url);\n if (sameRoute && !this.shouldRevalidate(url, sameRoute)) {\n this.currentPath = url;\n this.notify();\n this.options.onComplete?.(url);\n this.options.onNavigate?.(url);\n return;\n }\n if (this.spaMode && this.spaNavigationHandler) {\n await this.loadSpaPage(url);\n } else {\n await this.loadPage(url);\n }\n this.notify();\n this.options.onNavigate?.(url);\n }\n /**\n * Whether a navigation should refetch page data. A route change always does;\n * a same-route (query/hash-only) change consults `options.shouldRevalidate`,\n * defaulting to `true` so server data is never shown stale.\n */\n shouldRevalidate(nextUrl, sameRoute) {\n const policy = this.options.shouldRevalidate;\n if (!policy) return true;\n return policy({ currentHref: this.currentPath, nextHref: nextUrl, sameRoute });\n }\n async loadSpaPage(path) {\n logger7.debug(`Loading SPA page: ${path}`);\n try {\n const spaData = await this.pageLoader.loadSpaPageData(path);\n await this.spaNavigationHandler?.(spaData);\n this.currentPath = path;\n this.handleScrollAfterNavigation();\n this.options.onComplete?.(path);\n } catch (error) {\n const normalizedError = error instanceof Error ? error : new Error(String(error));\n logger7.error(`Failed to load SPA page ${path}`, normalizedError);\n this.options.onError?.(normalizedError);\n this.pageTransition.showError(normalizedError);\n }\n }\n handleScrollAfterNavigation() {\n const isPopState = this.navigationHandlers.isPopState();\n const scrollY = this.navigationHandlers.getScrollPosition(this.currentPath);\n try {\n globalThis.scrollTo(0, isPopState ? scrollY : 0);\n } catch (error) {\n logger7.warn("scroll handling failed", error);\n }\n this.navigationHandlers.clearPopStateFlag();\n }\n async loadPage(path, updateUI = true) {\n if (this.pageLoader.isCached(path)) {\n logger7.debug(`Loading ${path} from cache`);\n const data = this.pageLoader.getCached(path);\n if (data) {\n if (updateUI) this.updatePage(data);\n return;\n }\n logger7.warn(`Cache entry for ${path} was unexpectedly null, fetching fresh data`);\n }\n this.pageTransition.setLoadingState(true);\n try {\n const data = await this.pageLoader.loadPage(path);\n if (updateUI) this.updatePage(data);\n this.currentPath = path;\n this.options.onComplete?.(path);\n } catch (error) {\n const normalizedError = error instanceof Error ? error : new Error(String(error));\n logger7.error(`Failed to load ${path}`, normalizedError);\n this.options.onError?.(normalizedError);\n this.pageTransition.showError(normalizedError);\n } finally {\n this.pageTransition.setLoadingState(false);\n }\n }\n async prefetch(path) {\n if (this.spaMode) {\n await this.pageLoader.prefetchSpaPageData(path);\n return;\n }\n await this.pageLoader.prefetch(path);\n }\n updatePage(data) {\n if (!this.root) return;\n const isPopState = this.navigationHandlers.isPopState();\n const scrollY = this.navigationHandlers.getScrollPosition(this.currentPath);\n this.pageTransition.updatePage(data, isPopState, scrollY);\n this.navigationHandlers.clearPopStateFlag();\n }\n destroy() {\n document.removeEventListener("click", this.handleClick);\n globalThis.removeEventListener("popstate", this.handlePopState);\n document.removeEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.disconnect();\n this.pageLoader.clearCache();\n this.navigationHandlers.clear();\n this.pageTransition.destroy();\n }\n};\nfunction boot(options = {}) {\n if (typeof window === "undefined" || !globalThis.document) return null;\n const globalWithRouter = globalThis;\n if (globalWithRouter.veryFrontRouter) return globalWithRouter.veryFrontRouter;\n const { slug: _slug, ...routerOptions } = options;\n const router = new VeryfrontRouter(routerOptions);\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => router.init(), { once: true });\n } else {\n router.init();\n }\n globalWithRouter.veryFrontRouter = router;\n return router;\n}\nif (typeof window !== "undefined" && globalThis.document) {\n boot();\n}\nexport {\n VeryfrontRouter,\n boot\n};\n';
11
11
  export const CLIENT_PREFETCH_BUNDLE = 'var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);\n\n// src/rendering/client/browser-logger.ts\nvar ConditionalBrowserLogger = class {\n constructor(prefix, level) {\n __publicField(this, "prefix", prefix);\n __publicField(this, "level", level);\n }\n log(minLevel, fn, message, ...args) {\n if (this.level > minLevel) return;\n fn?.(message, ...args);\n }\n debug(message, ...args) {\n this.log(\n 0 /* DEBUG */,\n console.debug,\n `[${this.prefix}] DEBUG: ${message}`,\n ...args\n );\n }\n info(message, ...args) {\n this.log(1 /* INFO */, console.log, `[${this.prefix}] ${message}`, ...args);\n }\n warn(message, ...args) {\n this.log(\n 2 /* WARN */,\n console.warn,\n `[${this.prefix}] WARN: ${message}`,\n ...args\n );\n }\n error(message, ...args) {\n this.log(\n 3 /* ERROR */,\n console.error,\n `[${this.prefix}] ERROR: ${message}`,\n ...args\n );\n }\n};\nfunction getBrowserLogLevel() {\n if (typeof window === "undefined") return 2 /* WARN */;\n const g = globalThis;\n const isDevelopment = g.__VERYFRONT_DEV__ || g.__RSC_DEV__;\n if (!isDevelopment) return 2 /* WARN */;\n const isDebugEnabled2 = g.__VERYFRONT_DEBUG__ || g.__RSC_DEBUG__;\n return isDebugEnabled2 ? 0 /* DEBUG */ : 1 /* INFO */;\n}\nvar defaultLevel = getBrowserLogLevel();\nvar rscLogger = new ConditionalBrowserLogger("RSC", defaultLevel);\nvar prefetchLogger = new ConditionalBrowserLogger("PREFETCH", defaultLevel);\nvar hydrateLogger = new ConditionalBrowserLogger("HYDRATE", defaultLevel);\nvar browserLogger = new ConditionalBrowserLogger("VERYFRONT", defaultLevel);\n\n// src/rendering/client/prefetch/link-observer.ts\nfunction isAnchorElement(element) {\n return typeof HTMLAnchorElement !== "undefined" ? element instanceof HTMLAnchorElement : element.tagName === "A";\n}\nvar LinkObserver = class {\n constructor(options, prefetchedUrls) {\n __publicField(this, "options");\n __publicField(this, "intersectionObserver", null);\n __publicField(this, "mutationObserver", null);\n __publicField(this, "prefetchedUrls");\n __publicField(this, "pendingTimeouts", /* @__PURE__ */ new Map());\n __publicField(this, "elementTimeoutMap", /* @__PURE__ */ new WeakMap());\n __publicField(this, "timeoutCounter", 0);\n this.options = options;\n this.prefetchedUrls = prefetchedUrls;\n }\n init() {\n this.createIntersectionObserver();\n this.observeLinks();\n this.setupMutationObserver();\n }\n createIntersectionObserver() {\n this.intersectionObserver = new IntersectionObserver(\n (entries) => this.handleIntersection(entries),\n { rootMargin: this.options.rootMargin }\n );\n }\n handleIntersection(entries) {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n if (!isAnchorElement(entry.target)) continue;\n const link = entry.target;\n if (this.timeoutCounter > 1e6) this.timeoutCounter = 0;\n const timeoutKey = this.timeoutCounter++;\n const timeoutId = setTimeout(() => {\n this.pendingTimeouts.delete(timeoutKey);\n this.elementTimeoutMap.delete(link);\n this.options.onLinkVisible(link);\n }, this.options.delay);\n this.pendingTimeouts.set(timeoutKey, timeoutId);\n this.elementTimeoutMap.set(link, timeoutKey);\n }\n }\n observeLinks() {\n this.observeAnchors(document.querySelectorAll(\'a[href^="/"], a[href^="./"]\'));\n }\n setupMutationObserver() {\n this.mutationObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type !== "childList") continue;\n for (const node of mutation.addedNodes) {\n if (node.nodeType !== Node.ELEMENT_NODE) continue;\n this.observeElement(node);\n }\n for (const node of mutation.removedNodes) {\n if (node.nodeType !== Node.ELEMENT_NODE) continue;\n this.clearElementTimeouts(node);\n }\n }\n });\n this.mutationObserver.observe(document.body, { childList: true, subtree: true });\n }\n clearTimeoutForElement(element) {\n const timeoutKey = this.elementTimeoutMap.get(element);\n if (timeoutKey === void 0) return;\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId !== void 0) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(element);\n }\n clearElementTimeouts(element) {\n if (isAnchorElement(element)) this.clearTimeoutForElement(element);\n for (const link of element.querySelectorAll("a")) {\n this.clearTimeoutForElement(link);\n }\n }\n observeElement(element) {\n if (isAnchorElement(element) && this.isValidLink(element)) {\n this.intersectionObserver?.observe(element);\n }\n this.observeAnchors(element.querySelectorAll(\'a[href^="/"], a[href^="./"]\'));\n }\n observeAnchors(links) {\n for (const link of links) {\n if (!isAnchorElement(link)) continue;\n if (!this.isValidLink(link)) continue;\n this.intersectionObserver?.observe(link);\n }\n }\n isValidLink(link) {\n if (link.hostname !== globalThis.location.hostname) return false;\n if (link.hasAttribute("download")) return false;\n if (link.target === "_blank") return false;\n const url = link.href;\n if (this.prefetchedUrls.has(url)) return false;\n if (url === globalThis.location.href) return false;\n if (link.hash && link.pathname === globalThis.location.pathname) return false;\n if (link.dataset.noPrefetch) return false;\n return true;\n }\n destroy() {\n for (const timeoutId of this.pendingTimeouts.values()) {\n clearTimeout(timeoutId);\n }\n this.pendingTimeouts.clear();\n this.timeoutCounter = 0;\n this.intersectionObserver?.disconnect();\n this.intersectionObserver = null;\n this.mutationObserver?.disconnect();\n this.mutationObserver = null;\n }\n};\n\n// src/rendering/client/prefetch/network-utils.ts\nvar NetworkUtils = class {\n constructor(allowedNetworks = ["4g", "wifi", "ethernet"]) {\n __publicField(this, "networkInfo");\n __publicField(this, "allowedNetworks");\n this.allowedNetworks = allowedNetworks;\n this.networkInfo = this.getNetworkConnection();\n }\n getNavigatorWithConnection() {\n if (typeof globalThis.navigator === "undefined") return null;\n return globalThis.navigator;\n }\n getNetworkConnection() {\n const nav = this.getNavigatorWithConnection();\n return nav?.connection ?? nav?.mozConnection ?? nav?.webkitConnection ?? null;\n }\n shouldPrefetch() {\n if (this.networkInfo?.saveData) return false;\n const effectiveType = this.networkInfo?.effectiveType;\n if (effectiveType != null && !this.allowedNetworks.includes(effectiveType)) return false;\n return true;\n }\n onNetworkChange(callback) {\n this.networkInfo?.addEventListener?.("change", callback);\n }\n getNetworkInfo() {\n return this.networkInfo;\n }\n};\n\n// src/utils/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = DEFAULT_MAX_BODY_SIZE_BYTES;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE = 60;\nvar MINUTES_PER_HOUR = 60;\nvar HOURS_PER_DAY = 24;\nvar MS_PER_SECOND = 1e3;\nvar MS_PER_MINUTE = SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MS_PER_HOUR = MINUTES_PER_HOUR * MS_PER_MINUTE;\nvar ONE_DAY_MS = HOURS_PER_DAY * MS_PER_HOUR;\nfunction getEnvString(key) {\n const g = globalThis;\n try {\n return g.Deno?.env?.get?.(key) ?? g.process?.env?.[key];\n } catch (_) {\n return void 0;\n }\n}\nfunction getEnvNumber(key, fallback) {\n const value = getEnvString(key);\n if (value == null) return fallback;\n const parsed = Number.parseInt(value, 10);\n if (Number.isNaN(parsed)) return fallback;\n return parsed;\n}\nvar DEFAULT_LRU_MAX_ENTRIES = getEnvNumber("LRU_DEFAULT_MAX_ENTRIES", 100);\nvar COMPONENT_LOADER_MAX_ENTRIES = getEnvNumber("COMPONENT_LOADER_MAX_ENTRIES", 200);\nvar COMPONENT_LOADER_TTL_MS = 10 * MS_PER_MINUTE;\nvar MDX_RENDERER_MAX_ENTRIES = getEnvNumber("MDX_RENDERER_MAX_ENTRIES", 500);\nvar MDX_RENDERER_TTL_MS = 10 * MS_PER_MINUTE;\nvar RENDERER_CORE_MAX_ENTRIES = getEnvNumber("RENDERER_CORE_MAX_ENTRIES", 200);\nvar RENDERER_CORE_TTL_MS = 5 * MS_PER_MINUTE;\nvar TSX_LAYOUT_MAX_ENTRIES = getEnvNumber("TSX_LAYOUT_MAX_ENTRIES", 100);\nvar TSX_LAYOUT_TTL_MS = 10 * MS_PER_MINUTE;\nvar TSX_LAYOUT_PER_PROJECT_MAX_ENTRIES = getEnvNumber(\n "TSX_LAYOUT_PER_PROJECT_MAX_ENTRIES",\n Math.ceil(TSX_LAYOUT_MAX_ENTRIES / 10)\n);\nvar DATA_FETCHING_MAX_ENTRIES = getEnvNumber("DATA_FETCHING_MAX_ENTRIES", 500);\nvar DATA_FETCHING_TTL_MS = 10 * MS_PER_MINUTE;\nvar MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * MS_PER_MINUTE;\nvar BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * MS_PER_MINUTE;\nvar BUNDLE_MANIFEST_PROD_TTL_MS = 7 * ONE_DAY_MS;\nvar SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\nvar DISTRIBUTED_SSR_MODULE_TTL_PRODUCTION_SEC = getEnvNumber(\n "DISTRIBUTED_SSR_MODULE_TTL_SEC",\n 6 * MINUTES_PER_HOUR * SECONDS_PER_MINUTE\n);\nvar DISTRIBUTED_SSR_MODULE_TTL_PREVIEW_SEC = getEnvNumber(\n "DISTRIBUTED_SSR_MODULE_TTL_PREVIEW_SEC",\n 10 * SECONDS_PER_MINUTE\n);\nvar DISTRIBUTED_TRANSFORM_TTL_PRODUCTION_SEC = getEnvNumber(\n "DISTRIBUTED_TRANSFORM_TTL_SEC",\n 6 * MINUTES_PER_HOUR * SECONDS_PER_MINUTE\n);\nvar DISTRIBUTED_TRANSFORM_TTL_PREVIEW_SEC = getEnvNumber(\n "DISTRIBUTED_TRANSFORM_TTL_PREVIEW_SEC",\n 10 * SECONDS_PER_MINUTE\n);\nvar DISTRIBUTED_FILE_TTL_PRODUCTION_SEC = getEnvNumber(\n "DISTRIBUTED_FILE_TTL_SEC",\n MINUTES_PER_HOUR * SECONDS_PER_MINUTE\n);\nvar DISTRIBUTED_FILE_TTL_PREVIEW_SEC = getEnvNumber(\n "DISTRIBUTED_FILE_TTL_PREVIEW_SEC",\n 5 * SECONDS_PER_MINUTE\n);\nvar DISTRIBUTED_CSS_TTL_PRODUCTION_SEC = getEnvNumber(\n "DISTRIBUTED_CSS_TTL_SEC",\n 6 * MINUTES_PER_HOUR * SECONDS_PER_MINUTE\n);\nvar DISTRIBUTED_CSS_TTL_PREVIEW_SEC = getEnvNumber(\n "DISTRIBUTED_CSS_TTL_PREVIEW_SEC",\n 10 * SECONDS_PER_MINUTE\n);\nvar LRU_DEFAULT_MAX_ENTRIES_V2 = getEnvNumber("LRU_MAX_ENTRIES", 2e3);\nvar LRU_DEFAULT_MAX_SIZE_BYTES = getEnvNumber("LRU_MAX_SIZE_MB", 200) * 1024 * 1024;\nvar MEMORY_CACHE_MAX_ENTRIES = getEnvNumber("MEMORY_CACHE_MAX_ENTRIES", 2e3);\nvar MEMORY_CACHE_MAX_SIZE_BYTES = getEnvNumber("MEMORY_CACHE_MAX_SIZE_MB", 50) * 1024 * 1024;\nvar FILE_CACHE_MAX_ENTRIES = getEnvNumber("FILE_CACHE_MAX_ENTRIES", 1e3);\nvar FILE_CACHE_MAX_SIZE_MB = getEnvNumber("FILE_CACHE_MAX_SIZE_MB", 100);\nvar MAX_CONCURRENT_REVALIDATIONS = getEnvNumber("MAX_CONCURRENT_REVALIDATIONS", 32);\nvar MAX_CONCURRENT_HTTP_FETCHES = getEnvNumber("MAX_CONCURRENT_HTTP_FETCHES", 50);\nvar REVALIDATION_TIMEOUT_MS = getEnvNumber("REVALIDATION_TIMEOUT_MS", 15e3);\nvar REVALIDATION_PER_PROJECT_LIMIT = getEnvNumber(\n "REVALIDATION_PER_PROJECT_LIMIT",\n Math.ceil(MAX_CONCURRENT_REVALIDATIONS / 3)\n);\nvar BUNDLE_MANIFEST_DISTRIBUTED_TTL_SEC = getEnvNumber(\n "BUNDLE_MANIFEST_DISTRIBUTED_TTL_SEC",\n HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE\n // 24 hours (86400)\n);\nvar BUNDLE_MANIFEST_LRU_MAX_ENTRIES = getEnvNumber(\n "BUNDLE_MANIFEST_LRU_MAX_ENTRIES",\n 5e3\n);\nvar HTTP_MODULE_CACHE_MAX_ENTRIES = getEnvNumber("HTTP_MODULE_CACHE_MAX_ENTRIES", 2e3);\nvar HTTP_MODULE_DISTRIBUTED_TTL_SEC = getEnvNumber(\n "HTTP_MODULE_DISTRIBUTED_TTL_SEC",\n HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE\n // 24 hours (86400)\n);\nvar TRANSFORM_DISTRIBUTED_TTL_SEC = getEnvNumber(\n "TRANSFORM_DISTRIBUTED_TTL_SEC",\n 6 * MINUTES_PER_HOUR * SECONDS_PER_MINUTE\n // 6 hours (21600)\n);\nvar MODULE_CACHE_MAX_ENTRIES = getEnvNumber("MODULE_CACHE_MAX_ENTRIES", 1e4);\nvar MODULE_CACHE_TTL_MS = getEnvNumber(\n "MODULE_CACHE_TTL_MS",\n 5 * MS_PER_MINUTE\n // 5 minutes - short enough to pick up changes, long enough to cache\n);\nvar ESM_CACHE_MAX_ENTRIES = getEnvNumber("ESM_CACHE_MAX_ENTRIES", 5e3);\nvar ESM_CACHE_TTL_MS = getEnvNumber(\n "ESM_CACHE_TTL_MS",\n 10 * MS_PER_MINUTE\n // 10 minutes - external modules change less frequently\n);\n\n// src/utils/constants/http.ts\nvar KB_IN_BYTES = 1024;\nvar PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\n\n// src/utils/constants/hmr.ts\nvar HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n\n// src/utils/constants/network.ts\nvar BYTES_PER_KB = 1024;\nvar BYTES_PER_MB = BYTES_PER_KB * BYTES_PER_KB;\n\n// src/utils/constants/server.ts\nvar INTERNAL_PREFIX = "/_veryfront";\nvar INTERNAL_PATH_PREFIXES = {\n /** React Server Components endpoints */\n RSC: `${INTERNAL_PREFIX}/rsc/`,\n /** File system access endpoints (base64 encoded paths) */\n FS: `${INTERNAL_PREFIX}/fs/`,\n /** Virtual module system */\n MODULES: `${INTERNAL_PREFIX}/modules/`,\n /** Generated page modules */\n PAGES: `${INTERNAL_PREFIX}/pages/`,\n /** Data JSON endpoints */\n DATA: `${INTERNAL_PREFIX}/data/`,\n /** Library modules and large vendor surfaces */\n LIB: `${INTERNAL_PREFIX}/lib/`,\n /** Chunk assets */\n CHUNKS: `${INTERNAL_PREFIX}/chunks/`,\n /** Client component modules */\n CLIENT: `${INTERNAL_PREFIX}/client/`\n};\nvar INTERNAL_ENDPOINTS = {\n // Development endpoints\n HMR_RUNTIME: `${INTERNAL_PREFIX}/hmr-runtime.js`,\n HMR: `${INTERNAL_PREFIX}/hmr.js`,\n ERROR_OVERLAY: `${INTERNAL_PREFIX}/error-overlay.js`,\n // Legacy endpoint retained for backward compatibility (no active handler).\n DEV_LOADER: `${INTERNAL_PREFIX}/dev-loader.js`,\n CLIENT_LOG: `${INTERNAL_PREFIX}/log`,\n // Production endpoints\n CLIENT_JS: `${INTERNAL_PREFIX}/client.js`,\n ROUTER_JS: `${INTERNAL_PREFIX}/router.js`,\n PREFETCH_JS: `${INTERNAL_PREFIX}/prefetch.js`,\n MANIFEST_JSON: `${INTERNAL_PREFIX}/manifest.json`,\n APP_JS: `${INTERNAL_PREFIX}/app.js`,\n // RSC endpoints\n RSC_CLIENT: `${INTERNAL_PREFIX}/rsc/client.js`,\n RSC_MANIFEST: `${INTERNAL_PREFIX}/rsc/manifest`,\n RSC_STREAM: `${INTERNAL_PREFIX}/rsc/stream`,\n RSC_PAYLOAD: `${INTERNAL_PREFIX}/rsc/payload`,\n RSC_RENDER: `${INTERNAL_PREFIX}/rsc/render`,\n RSC_PAGE: `${INTERNAL_PREFIX}/rsc/page`,\n RSC_MODULE: `${INTERNAL_PREFIX}/rsc/module`,\n RSC_DOM: `${INTERNAL_PREFIX}/rsc/dom.js`,\n // Library module endpoints\n LIB_CHAT_REACT: `${INTERNAL_PREFIX}/lib/chat/react.js`,\n LIB_CHAT_COMPONENTS: `${INTERNAL_PREFIX}/lib/chat/components.js`,\n LIB_CHAT_PRIMITIVES: `${INTERNAL_PREFIX}/lib/chat/primitives.js`\n};\nvar PROJECT_DIRS = {\n /** Base veryfront internal directory */\n ROOT: ".veryfront",\n /** Cache directory for build artifacts, transforms, etc. */\n CACHE: ".veryfront/cache",\n /** KV store directory */\n KV: ".veryfront/kv",\n /** Log files directory */\n LOGS: ".veryfront/logs",\n /** Temporary files directory */\n TMP: ".veryfront/tmp"\n};\nvar DEFAULT_CACHE_DIR = PROJECT_DIRS.CACHE;\nvar DEV_SERVER_ENDPOINTS = {\n HMR_RUNTIME: INTERNAL_ENDPOINTS.HMR_RUNTIME,\n ERROR_OVERLAY: INTERNAL_ENDPOINTS.ERROR_OVERLAY\n};\n\n// src/rendering/client/prefetch/prefetch-queue.ts\nvar DEFAULT_OPTIONS = {\n maxConcurrent: 4,\n maxSize: PREFETCH_QUEUE_MAX_SIZE_BYTES,\n timeout: 5e3\n};\nfunction isAbortError(error) {\n if (typeof error !== "object" || error === null) return false;\n if (!("name" in error)) return false;\n return error.name === "AbortError";\n}\nvar PrefetchQueue = class {\n constructor(options = {}, prefetchedUrls) {\n __publicField(this, "options");\n __publicField(this, "controllers", /* @__PURE__ */ new Map());\n __publicField(this, "prefetchedUrls");\n __publicField(this, "concurrent", 0);\n __publicField(this, "stopped", false);\n __publicField(this, "onResourcesFetched");\n this.options = { ...DEFAULT_OPTIONS, ...options };\n this.prefetchedUrls = prefetchedUrls ?? /* @__PURE__ */ new Set();\n }\n setResourceCallback(callback) {\n this.onResourcesFetched = callback;\n }\n enqueue(url) {\n void this.prefetch(url);\n }\n has(url) {\n return this.prefetchedUrls.has(url) || this.controllers.has(url);\n }\n get size() {\n return this.controllers.size;\n }\n clear() {\n this.stopAll();\n this.prefetchedUrls.clear();\n }\n start() {\n this.stopped = false;\n }\n stop() {\n this.stopped = true;\n this.stopAll();\n }\n getQueueSize() {\n return this.controllers.size;\n }\n getConcurrentCount() {\n return this.concurrent;\n }\n async prefetchLink(link) {\n if (this.stopped) return;\n const url = link.href;\n if (!url || this.controllers.has(url) || this.prefetchedUrls.has(url)) return;\n if (this.concurrent >= this.options.maxConcurrent) {\n prefetchLogger.debug?.(`Prefetch queue full, skipping ${url}`);\n return;\n }\n let parsedUrl;\n try {\n parsedUrl = new URL(url);\n } catch (_) {\n prefetchLogger.debug?.(`Invalid prefetch URL ${url}`);\n return;\n }\n const controller = new AbortController();\n this.controllers.set(url, controller);\n this.concurrent += 1;\n const timeoutId = this.options.timeout > 0 ? setTimeout(() => controller.abort(), this.options.timeout) : void 0;\n try {\n const response = await fetch(parsedUrl.toString(), {\n method: "GET",\n signal: controller.signal,\n headers: { "X-Veryfront-Prefetch": "1" }\n });\n if (!response.ok) return;\n if (this.isResponseTooLarge(response)) {\n prefetchLogger.debug?.(`Prefetch too large, skipping ${url}`);\n return;\n }\n this.prefetchedUrls.add(url);\n if (!this.onResourcesFetched) return;\n try {\n await this.onResourcesFetched(response, url);\n } catch (callbackError) {\n prefetchLogger.error?.(`Prefetch callback failed for ${url}`, callbackError);\n }\n } catch (error) {\n if (!isAbortError(error)) {\n prefetchLogger.error?.(`Failed to prefetch ${url}`, error);\n }\n } finally {\n if (timeoutId !== void 0) clearTimeout(timeoutId);\n this.controllers.delete(url);\n this.concurrent = Math.max(0, this.concurrent - 1);\n }\n }\n async prefetch(url) {\n const link = typeof document !== "undefined" ? document.createElement("a") : { href: url };\n link.href = url;\n await this.prefetchLink(link);\n }\n stopAll() {\n for (const controller of this.controllers.values()) {\n controller.abort();\n }\n this.controllers.clear();\n this.concurrent = 0;\n }\n isResponseTooLarge(response) {\n const rawLength = response.headers.get("content-length");\n if (rawLength === null) return false;\n const size = Number.parseInt(rawLength, 10);\n if (!Number.isFinite(size)) return false;\n return size > this.options.maxSize;\n }\n};\nvar prefetchQueue = new PrefetchQueue();\n\n// src/rendering/client/prefetch/resource-hints.ts\nvar ResourceHintsManager = class {\n constructor() {\n __publicField(this, "appliedHints", /* @__PURE__ */ new Set());\n }\n applyResourceHints(hints) {\n for (const hint of hints) {\n const key = `${hint.type}:${hint.href}`;\n if (this.appliedHints.has(key)) continue;\n const existing = document.querySelector(\n `link[rel="${hint.type}"][href="${hint.href}"]`\n );\n if (existing) {\n this.appliedHints.add(key);\n continue;\n }\n this.createAndAppendHint(hint);\n this.appliedHints.add(key);\n prefetchLogger.debug(`Added resource hint: ${hint.type} ${hint.href}`);\n }\n }\n createAndAppendHint(hint) {\n if (!document.head) {\n prefetchLogger.warn("document.head is not available, skipping resource hint");\n return;\n }\n const link = document.createElement("link");\n link.rel = hint.type;\n link.href = hint.href;\n if (hint.as) link.setAttribute("as", hint.as);\n if (hint.crossOrigin) link.setAttribute("crossorigin", hint.crossOrigin);\n if (hint.media) link.setAttribute("media", hint.media);\n document.head.appendChild(link);\n }\n extractResourceHints(html, prefetchedUrls) {\n try {\n const doc = new DOMParser().parseFromString(html, "text/html");\n const hints = [];\n this.extractPreloadLinks(doc, prefetchedUrls, hints);\n this.extractScripts(doc, prefetchedUrls, hints);\n this.extractStylesheets(doc, prefetchedUrls, hints);\n return hints;\n } catch (error) {\n prefetchLogger.error("Failed to parse prefetched page", error);\n return [];\n }\n }\n isValidResourceHintType(rel) {\n switch (rel) {\n case "prefetch":\n case "preload":\n case "preconnect":\n case "dns-prefetch":\n return true;\n default:\n return false;\n }\n }\n extractPreloadLinks(doc, prefetchedUrls, hints) {\n const links = doc.querySelectorAll(\n \'link[rel="preload"], link[rel="prefetch"]\'\n );\n for (const link of links) {\n const href = link.href;\n if (!href) continue;\n if (prefetchedUrls.has(href)) continue;\n if (!this.isValidResourceHintType(link.rel)) continue;\n hints.push({\n type: link.rel,\n href,\n as: link.getAttribute("as") ?? void 0\n });\n }\n }\n extractScripts(doc, prefetchedUrls, hints) {\n for (const script of doc.querySelectorAll("script[src]")) {\n const src = script.src;\n if (!src || prefetchedUrls.has(src)) continue;\n hints.push({ type: "prefetch", href: src, as: "script" });\n }\n }\n extractStylesheets(doc, prefetchedUrls, hints) {\n for (const link of doc.querySelectorAll(\'link[rel="stylesheet"]\')) {\n const href = link.href;\n if (!href || prefetchedUrls.has(href)) continue;\n hints.push({ type: "prefetch", href, as: "style" });\n }\n }\n static generateResourceHints(_route, assets) {\n const hints = [\n \'<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">\',\n \'<link rel="dns-prefetch" href="https://esm.sh">\',\n \'<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>\'\n ];\n for (const asset of assets) {\n if (asset.endsWith(".js")) {\n hints.push(`<link rel="modulepreload" href="${asset}">`);\n continue;\n }\n if (asset.endsWith(".css")) {\n hints.push(`<link rel="preload" as="style" href="${asset}">`);\n continue;\n }\n if (/\\.(woff2?|ttf|otf)$/.test(asset)) {\n hints.push(`<link rel="preload" as="font" href="${asset}" crossorigin>`);\n }\n }\n return hints.join("\\n");\n }\n};\n\n// src/rendering/client/browser-stubs/logger.ts\nfunction noop() {\n}\nvar logger = {\n debug: noop,\n info: console.log.bind(console),\n warn: console.warn.bind(console),\n error: console.error.bind(console),\n component: () => logger\n};\nvar PREFETCH_MAX_SIZE_BYTES2 = 200 * 1024;\nvar PREFETCH_DEFAULT_TIMEOUT_MS2 = 1e4;\nvar PREFETCH_DEFAULT_DELAY_MS2 = 200;\n\n// src/rendering/client/prefetch.ts\nvar PrefetchManager = class {\n constructor(options = {}) {\n __publicField(this, "options");\n __publicField(this, "prefetchedUrls", /* @__PURE__ */ new Set());\n __publicField(this, "networkUtils");\n __publicField(this, "linkObserver", null);\n __publicField(this, "resourceHintsManager");\n __publicField(this, "prefetchQueue");\n this.options = {\n rootMargin: options.rootMargin ?? "50px",\n delay: options.delay ?? PREFETCH_DEFAULT_DELAY_MS2,\n maxConcurrent: options.maxConcurrent ?? 2,\n allowedNetworks: options.allowedNetworks ?? ["4g", "wifi", "ethernet"],\n maxSize: options.maxSize ?? PREFETCH_MAX_SIZE_BYTES2,\n timeout: options.timeout ?? PREFETCH_DEFAULT_TIMEOUT_MS2\n };\n this.networkUtils = new NetworkUtils(this.options.allowedNetworks);\n this.resourceHintsManager = new ResourceHintsManager();\n this.prefetchQueue = new PrefetchQueue(\n {\n maxConcurrent: this.options.maxConcurrent,\n maxSize: this.options.maxSize,\n timeout: this.options.timeout\n },\n this.prefetchedUrls\n );\n this.prefetchQueue.setResourceCallback(\n (response, url) => this.prefetchPageResources(response, url)\n );\n }\n init() {\n prefetchLogger.info("Initializing prefetch manager");\n if (!this.networkUtils.shouldPrefetch()) {\n prefetchLogger.info("Prefetching disabled due to network conditions");\n return;\n }\n this.linkObserver = new LinkObserver(\n {\n rootMargin: this.options.rootMargin,\n delay: this.options.delay,\n onLinkVisible: (link) => this.prefetchQueue.prefetchLink(link)\n },\n this.prefetchedUrls\n );\n this.linkObserver.init();\n this.networkUtils.onNetworkChange(() => {\n if (!this.networkUtils.shouldPrefetch()) this.prefetchQueue.stopAll();\n });\n }\n async prefetchPageResources(response, _pageUrl) {\n const html = await response.text();\n const hints = this.resourceHintsManager.extractResourceHints(html, this.prefetchedUrls);\n this.resourceHintsManager.applyResourceHints(hints);\n }\n applyResourceHints(hints) {\n this.resourceHintsManager.applyResourceHints(hints);\n }\n async prefetch(url) {\n await this.prefetchQueue.prefetch(url);\n }\n static generateResourceHints(route, assets) {\n return ResourceHintsManager.generateResourceHints(route, assets);\n }\n destroy() {\n this.linkObserver?.destroy();\n this.prefetchQueue.stopAll();\n this.prefetchedUrls.clear();\n }\n};\nfunction initPrefetch(options) {\n const prefetchManager = new PrefetchManager(options);\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => prefetchManager.init(), { once: true });\n } else {\n prefetchManager.init();\n }\n globalThis.veryFrontPrefetch = prefetchManager;\n return prefetchManager;\n}\nfunction resolveAutoInitOptions() {\n const setting = globalThis.__VERYFRONT_PREFETCH__;\n if (!setting) return null;\n if (setting === true) return {};\n if (typeof setting === "object") return setting;\n return null;\n}\nfunction shouldAutoInitPrefetch(options) {\n if (!options) return false;\n if (typeof window === "undefined" || typeof document === "undefined") return false;\n const win = window;\n const doc = document;\n if (win.__veryfrontSSRStub || doc.__veryfrontSSRStub) return false;\n if (typeof IntersectionObserver === "undefined") return false;\n if (typeof MutationObserver === "undefined") return false;\n return true;\n}\nvar autoInitOptions = resolveAutoInitOptions();\nif (shouldAutoInitPrefetch(autoInitOptions)) initPrefetch(autoInitOptions);\nexport {\n PrefetchManager,\n initPrefetch\n};\n';
@@ -1 +1 @@
1
- {"version":3,"file":"model-registry.d.ts","sourceRoot":"","sources":["../../../src/src/provider/model-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAeH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,sDAAsD;AACtD,MAAM,MAAM,oBAAoB,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,YAAY,CAAC;AAOrE;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,oBAAoB,GAC5B,IAAI,CAEN;AAsJD;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,WAAW,EAAE,MAAM,GAAG,YAAY,CAuC9D;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAGtD;AAED;;GAEG;AACH,wBAAgB,2BAA2B,IAAI,MAAM,EAAE,CAGtD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,YAAY,GAClB,OAAO,CAAC,IAAI,CAAC,CAKf;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,IAAI,CAG1C"}
1
+ {"version":3,"file":"model-registry.d.ts","sourceRoot":"","sources":["../../../src/src/provider/model-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAeH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,sDAAsD;AACtD,MAAM,MAAM,oBAAoB,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,YAAY,CAAC;AAOrE;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,oBAAoB,GAC5B,IAAI,CAEN;AAuJD;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,WAAW,EAAE,MAAM,GAAG,YAAY,CAuC9D;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAGtD;AAED;;GAEG;AACH,wBAAgB,2BAA2B,IAAI,MAAM,EAAE,CAGtD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,YAAY,GAClB,OAAO,CAAC,IAAI,CAAC,CAKf;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,IAAI,CAG1C"}
@@ -65,6 +65,7 @@ function autoInitializeFromEnv() {
65
65
  return provider.createModel(id, {
66
66
  credential: config.apiKey,
67
67
  baseURL: config.baseURL,
68
+ providerName: "openai-compatible",
68
69
  });
69
70
  }
70
71
  throw toError(createError({
@@ -1 +1 @@
1
- {"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../../../src/src/provider/veryfront-cloud/openai.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAKlE,UAAU,0BAA0B;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CAChC;AAED,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,0BAA0B,GACjC,YAAY,CAOd;AAED,wBAAgB,wCAAwC,CACtD,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,0BAA0B,GACjC,YAAY,CAOd;AAED,wBAAgB,wCAAwC,CACtD,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,0BAA0B,GACjC,gBAAgB,CAOlB"}
1
+ {"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../../../src/src/provider/veryfront-cloud/openai.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAKlE,UAAU,0BAA0B;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CAChC;AAED,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,0BAA0B,GACjC,YAAY,CAQd;AAED,wBAAgB,wCAAwC,CACtD,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,0BAA0B,GACjC,YAAY,CAQd;AAED,wBAAgB,wCAAwC,CACtD,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,0BAA0B,GACjC,gBAAgB,CAOlB"}
@@ -5,6 +5,7 @@ export function createVeryfrontCloudOpenAIModel(modelId, config) {
5
5
  credential: config.apiToken,
6
6
  baseURL: config.baseURL,
7
7
  name: "veryfront-cloud",
8
+ providerName: "veryfront-cloud",
8
9
  fetch: config.fetch,
9
10
  });
10
11
  }
@@ -13,6 +14,7 @@ export function createVeryfrontCloudOpenAIResponsesModel(modelId, config) {
13
14
  credential: config.apiToken,
14
15
  baseURL: config.baseURL,
15
16
  name: "veryfront-cloud",
17
+ providerName: "veryfront-cloud",
16
18
  fetch: config.fetch,
17
19
  });
18
20
  }
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../../src/src/provider/veryfront-cloud/provider.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAqBhD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,GAAG,YAAY,CAuGvE"}
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../../src/src/provider/veryfront-cloud/provider.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAqBhD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,GAAG,YAAY,CA0GvE"}
@@ -49,6 +49,7 @@ export function createVeryfrontCloudModel(modelId) {
49
49
  credential: apiToken,
50
50
  baseURL,
51
51
  name: "veryfront-cloud",
52
+ providerName: "veryfront-cloud",
52
53
  fetch,
53
54
  }));
54
55
  }
@@ -63,6 +64,7 @@ export function createVeryfrontCloudModel(modelId) {
63
64
  credential: apiToken,
64
65
  baseURL,
65
66
  name: "veryfront-cloud",
67
+ providerName: "veryfront-cloud",
66
68
  fetch,
67
69
  }));
68
70
  }
@@ -80,6 +82,7 @@ export function createVeryfrontCloudModel(modelId) {
80
82
  credential: apiToken,
81
83
  baseURL,
82
84
  name: "veryfront-cloud",
85
+ providerName: "openai-compatible",
83
86
  fetch,
84
87
  }));
85
88
  }
@@ -33,7 +33,15 @@ export type LinkProps = React.AnchorHTMLAttributes<HTMLAnchorElement> & {
33
33
  export interface RouterProviderProps {
34
34
  /** React children rendered within the router context. */
35
35
  children: React.ReactNode;
36
- /** Router value to expose to descendants. */
36
+ /**
37
+ * The router snapshot. On the server it is exposed verbatim. On the client it
38
+ * seeds `params`/`domain`/`isPreview` and the initial `pathname`/`query` — the
39
+ * server-render snapshot the first client render must match — after which
40
+ * `pathname`/`query` track the live URL through the navigation store.
41
+ *
42
+ * This is the single source for everything the URL and route match know;
43
+ * callers hand over one `RouterValue` rather than loose href/param fields.
44
+ */
37
45
  router?: RouterValue;
38
46
  }
39
47
  /** Heading metadata extracted from MDX content. */
@@ -69,13 +77,57 @@ export interface PageContextProviderProps {
69
77
  /** Page context value to expose to descendants. */
70
78
  pageContext?: PageContextValue;
71
79
  }
72
- /** Provides the router context value used by `useRouter()`. */
73
- export declare function RouterProvider({ children, router, }: RouterProviderProps): React.ReactElement;
74
- /** Reads the current router context. */
80
+ /**
81
+ * Provides the router context. `pathname`/`query` track the live URL through the
82
+ * shared navigation store's `useSyncExternalStore` surface; `params`/`domain`
83
+ * are seeded from the `router` prop. One component serves both sides: React uses
84
+ * `getServerSnapshot` (the seed href) during SSR and the live store on the
85
+ * client, so there is no environment branch — the server render and the first
86
+ * client render match by construction.
87
+ *
88
+ * The store is a stable singleton that exists on first access, so there is no
89
+ * "is the router mounted yet?" race: the subscription is live from the first
90
+ * render, and the router's navigations notify through the same object. Page
91
+ * context (frontmatter/slug/headings) is a separate concern, provided by
92
+ * `PageContextProvider`, which derives its live location from this router.
93
+ */
94
+ export declare function RouterProvider({ router, children }: RouterProviderProps): React.ReactElement;
95
+ /** Options for {@link wrapForHydration}. */
96
+ export interface HydrationWrapOptions {
97
+ /** Route params from the initial match. */
98
+ params?: Record<string, string>;
99
+ /** Page frontmatter, exposed reactively through `usePageContext()`. */
100
+ frontmatter?: Record<string, unknown>;
101
+ }
102
+ /**
103
+ * Wraps a hydrated client component in `RouterProvider` (router state) nested
104
+ * with `PageContextProvider` (frontmatter), seeded from the live location plus
105
+ * the initial route match — mirroring how SSR wraps the tree.
106
+ *
107
+ * The RSC hydration path calls this through a runtime import of
108
+ * `veryfront/router`, so it runs under the app's React instance — the same one
109
+ * the hydrated component uses, and the same providers and `React` this module
110
+ * already reference. That is why the caller does not (and must not) pass a
111
+ * `React` across the module boundary: the wrapping happens here, inside the
112
+ * module that owns React.
113
+ */
114
+ export declare function wrapForHydration(child: React.ReactNode, options?: HydrationWrapOptions): React.ReactElement;
115
+ /**
116
+ * Reads the router context: `pathname`, `query`, `params`, and the navigation
117
+ * actions. Reactive across client-side navigation — this is the single hook for
118
+ * location and navigation state.
119
+ */
75
120
  export declare function useRouter(): RouterValue;
76
121
  /** Renders an anchor element annotated for Veryfront prefetch handling. */
77
122
  export declare function Link({ prefetch, children, ...rest }: LinkProps): React.ReactElement;
78
- /** Provides page context to route and MDX descendants. */
123
+ /**
124
+ * Provides page context to route and MDX descendants. Page-authored fields
125
+ * (`frontmatter`, `slug`, `headings`) come from the `pageContext` prop; the
126
+ * location fields (`path`, `query`, `params`) are derived from the router so
127
+ * they stay reactive and there is a single source of truth — `usePageContext()`
128
+ * exposes the same `query`/`pathname` as `useRouter()`. When rendered outside a
129
+ * `RouterProvider` (no live router) it falls back to the seed's own location.
130
+ */
79
131
  export declare function PageContextProvider({ children, pageContext, }: PageContextProviderProps): React.ReactElement;
80
132
  /** Reads the current page context. */
81
133
  export declare function usePageContext(): PageContextValue;
@@ -1 +1 @@
1
- {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../../../src/src/react/runtime/core.ts"],"names":[],"mappings":"AACA,OAAO,KAAoB,MAAM,yBAAyB,CAAC;AAE3D,kDAAkD;AAClD,MAAM,WAAW,WAAW;IAC1B,2CAA2C;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,4BAA4B;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,uDAAuD;IACvD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,4CAA4C;IAC5C,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,qDAAqD;IACrD,SAAS,EAAE,OAAO,CAAC;IACnB,4CAA4C;IAC5C,SAAS,EAAE,OAAO,CAAC;IACnB,iDAAiD;IACjD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,6CAA6C;IAC7C,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrC,oDAAoD;IACpD,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,gCAAgC;IAChC,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AAED,kCAAkC;AAClC,MAAM,MAAM,SAAS,GAAG,KAAK,CAAC,oBAAoB,CAAC,iBAAiB,CAAC,GAAG;IACtE,wDAAwD;IACxD,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,4CAA4C;AAC5C,MAAM,WAAW,mBAAmB;IAClC,yDAAyD;IACzD,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,6CAA6C;IAC7C,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,mDAAmD;AACnD,MAAM,WAAW,UAAU;IACzB,4BAA4B;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,iCAAiC;IACjC,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wDAAwD;AACxD,MAAM,WAAW,gBAAgB;IAC/B,uCAAuC;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,0BAA0B;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,4CAA4C;IAC5C,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,+BAA+B;IAC/B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,+CAA+C;IAC/C,QAAQ,EAAE,UAAU,EAAE,CAAC;IACvB,mDAAmD;IACnD,WAAW,EAAE,UAAU,EAAE,CAAC;CAC3B;AAED,iDAAiD;AACjD,MAAM,WAAW,wBAAwB;IACvC,uDAAuD;IACvD,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,mDAAmD;IACnD,WAAW,CAAC,EAAE,gBAAgB,CAAC;CAChC;AA6ED,+DAA+D;AAC/D,wBAAgB,cAAc,CAAC,EAC7B,QAAQ,EACR,MAAM,GACP,EAAE,mBAAmB,GAAG,KAAK,CAAC,YAAY,CAM1C;AAED,wCAAwC;AACxC,wBAAgB,SAAS,IAAI,WAAW,CAEvC;AAED,2EAA2E;AAC3E,wBAAgB,IAAI,CAAC,EACnB,QAAe,EACf,QAAQ,EACR,GAAG,IAAI,EACR,EAAE,SAAS,GAAG,KAAK,CAAC,YAAY,CAMhC;AAED,0DAA0D;AAC1D,wBAAgB,mBAAmB,CAAC,EAClC,QAAQ,EACR,WAAW,GACZ,EAAE,wBAAwB,GAAG,KAAK,CAAC,YAAY,CAM/C;AAED,sCAAsC;AACtC,wBAAgB,cAAc,IAAI,gBAAgB,CAEjD;AAED,sEAAsE;AACtE,wBAAgB,IAAI,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;CAAE,GAAG,KAAK,CAAC,YAAY,CAwIpF;AAED,OAAO,EAAE,cAAc,IAAI,MAAM,EAAE,CAAC"}
1
+ {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../../../src/src/react/runtime/core.ts"],"names":[],"mappings":"AACA,OAAO,KAAoB,MAAM,yBAAyB,CAAC;AAE3D,kDAAkD;AAClD,MAAM,WAAW,WAAW;IAC1B,2CAA2C;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,4BAA4B;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,uDAAuD;IACvD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,4CAA4C;IAC5C,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,qDAAqD;IACrD,SAAS,EAAE,OAAO,CAAC;IACnB,4CAA4C;IAC5C,SAAS,EAAE,OAAO,CAAC;IACnB,iDAAiD;IACjD,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,6CAA6C;IAC7C,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrC,oDAAoD;IACpD,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,gCAAgC;IAChC,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AAED,kCAAkC;AAClC,MAAM,MAAM,SAAS,GAAG,KAAK,CAAC,oBAAoB,CAAC,iBAAiB,CAAC,GAAG;IACtE,wDAAwD;IACxD,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,4CAA4C;AAC5C,MAAM,WAAW,mBAAmB;IAClC,yDAAyD;IACzD,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,mDAAmD;AACnD,MAAM,WAAW,UAAU;IACzB,4BAA4B;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,iCAAiC;IACjC,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wDAAwD;AACxD,MAAM,WAAW,gBAAgB;IAC/B,uCAAuC;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,0BAA0B;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,4CAA4C;IAC5C,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,+BAA+B;IAC/B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,+CAA+C;IAC/C,QAAQ,EAAE,UAAU,EAAE,CAAC;IACvB,mDAAmD;IACnD,WAAW,EAAE,UAAU,EAAE,CAAC;CAC3B;AAED,iDAAiD;AACjD,MAAM,WAAW,wBAAwB;IACvC,uDAAuD;IACvD,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B,mDAAmD;IACnD,WAAW,CAAC,EAAE,gBAAgB,CAAC;CAChC;AAqKD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,cAAc,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,mBAAmB,GAAG,KAAK,CAAC,YAAY,CA0C5F;AAED,4CAA4C;AAC5C,MAAM,WAAW,oBAAoB;IACnC,2CAA2C;IAC3C,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,uEAAuE;IACvE,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,KAAK,CAAC,SAAS,EACtB,OAAO,GAAE,oBAAyB,GACjC,KAAK,CAAC,YAAY,CA6BpB;AAED;;;;GAIG;AACH,wBAAgB,SAAS,IAAI,WAAW,CAEvC;AAED,2EAA2E;AAC3E,wBAAgB,IAAI,CAAC,EACnB,QAAe,EACf,QAAQ,EACR,GAAG,IAAI,EACR,EAAE,SAAS,GAAG,KAAK,CAAC,YAAY,CAMhC;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,QAAQ,EACR,WAAW,GACZ,EAAE,wBAAwB,GAAG,KAAK,CAAC,YAAY,CAc/C;AAED,sCAAsC;AACtC,wBAAgB,cAAc,IAAI,gBAAgB,CAEjD;AAED,sEAAsE;AACtE,wBAAgB,IAAI,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;CAAE,GAAG,KAAK,CAAC,YAAY,CAwIpF;AAED,OAAO,EAAE,cAAc,IAAI,MAAM,EAAE,CAAC"}
@@ -50,11 +50,160 @@ function collectHead(data) {
50
50
  const collector = dntShim.dntGlobalThis[HEAD_COLLECTOR_SYMBOL];
51
51
  collector?.(data);
52
52
  }
53
- /** Provides the router context value used by `useRouter()`. */
54
- export function RouterProvider({ children, router, }) {
55
- return React.createElement(RouterContext.Provider, { value: router ?? defaultRouter }, children);
53
+ const NAVIGATION_STORE_KEY = Symbol.for("veryfront.navigation.store.v1");
54
+ function getNavigationStore() {
55
+ const holder = dntShim.dntGlobalThis;
56
+ const existing = holder[NAVIGATION_STORE_KEY];
57
+ if (existing)
58
+ return existing;
59
+ const listeners = new Set();
60
+ let navigator = null;
61
+ const store = {
62
+ subscribe(listener) {
63
+ listeners.add(listener);
64
+ return () => {
65
+ listeners.delete(listener);
66
+ };
67
+ },
68
+ getHref() {
69
+ const loc = globalThis.location;
70
+ return loc ? `${loc.pathname}${loc.search}${loc.hash}` : "/";
71
+ },
72
+ notify() {
73
+ for (const listener of [...listeners]) {
74
+ try {
75
+ listener();
76
+ }
77
+ catch {
78
+ // A subscriber threw; ignore it and continue notifying the others.
79
+ }
80
+ }
81
+ },
82
+ navigate(href, options) {
83
+ if (navigator)
84
+ return navigator(href, options);
85
+ globalThis.location?.assign(href);
86
+ return Promise.resolve();
87
+ },
88
+ setNavigator(next) {
89
+ navigator = next;
90
+ },
91
+ };
92
+ holder[NAVIGATION_STORE_KEY] = store;
93
+ return store;
94
+ }
95
+ function hrefFromRouter(router) {
96
+ if (!router)
97
+ return undefined;
98
+ const search = new URLSearchParams(router.query ?? {}).toString();
99
+ return search ? `${router.pathname}?${search}` : router.pathname;
100
+ }
101
+ function splitHref(href) {
102
+ const queryIndex = href.indexOf("?");
103
+ if (queryIndex === -1) {
104
+ const hashIndex = href.indexOf("#");
105
+ return { pathname: hashIndex === -1 ? href : href.slice(0, hashIndex), search: "" };
106
+ }
107
+ const afterQuery = href.slice(queryIndex + 1);
108
+ const hashIndex = afterQuery.indexOf("#");
109
+ return {
110
+ pathname: href.slice(0, queryIndex),
111
+ search: hashIndex === -1 ? afterQuery : afterQuery.slice(0, hashIndex),
112
+ };
113
+ }
114
+ /**
115
+ * Provides the router context. `pathname`/`query` track the live URL through the
116
+ * shared navigation store's `useSyncExternalStore` surface; `params`/`domain`
117
+ * are seeded from the `router` prop. One component serves both sides: React uses
118
+ * `getServerSnapshot` (the seed href) during SSR and the live store on the
119
+ * client, so there is no environment branch — the server render and the first
120
+ * client render match by construction.
121
+ *
122
+ * The store is a stable singleton that exists on first access, so there is no
123
+ * "is the router mounted yet?" race: the subscription is live from the first
124
+ * render, and the router's navigations notify through the same object. Page
125
+ * context (frontmatter/slug/headings) is a separate concern, provided by
126
+ * `PageContextProvider`, which derives its live location from this router.
127
+ */
128
+ export function RouterProvider({ router, children }) {
129
+ const store = getNavigationStore();
130
+ const seed = router ?? defaultRouter;
131
+ // The server snapshot is derived from the router itself, so the first client
132
+ // render matches the server exactly (both come from one `RouterValue`).
133
+ const seedHref = hrefFromRouter(router) ?? "/";
134
+ const getServerSnapshot = React.useCallback(() => seedHref, [seedHref]);
135
+ const href = React.useSyncExternalStore(store.subscribe, store.getHref, getServerSnapshot);
136
+ const { pathname, search } = splitHref(href);
137
+ const query = React.useMemo(() => Object.fromEntries(new URLSearchParams(search)), [search]);
138
+ // `isMounted` is `false` on the server and the first client render (so they
139
+ // agree — hydration-safe), then flips `true` after mount. Consumers guard on
140
+ // this (e.g. `if (!router.isMounted) return null`).
141
+ const [isMounted, setIsMounted] = React.useState(false);
142
+ React.useEffect(() => setIsMounted(true), []);
143
+ const routerValue = React.useMemo(() => ({
144
+ domain: seed.domain || (globalThis.location?.hostname ?? ""),
145
+ path: pathname,
146
+ pathname,
147
+ params: seed.params,
148
+ query,
149
+ isPreview: seed.isPreview,
150
+ isMounted,
151
+ navigate: (url) => store.navigate(url, { history: "push" }),
152
+ push: (url) => store.navigate(url, { history: "push" }),
153
+ replace: (url) => store.navigate(url, { history: "replace" }),
154
+ reload: async () => {
155
+ globalThis.location?.reload();
156
+ },
157
+ }), [pathname, query, seed.params, seed.domain, seed.isPreview, isMounted, store]);
158
+ return React.createElement(RouterContext.Provider, { value: routerValue }, children);
159
+ }
160
+ /**
161
+ * Wraps a hydrated client component in `RouterProvider` (router state) nested
162
+ * with `PageContextProvider` (frontmatter), seeded from the live location plus
163
+ * the initial route match — mirroring how SSR wraps the tree.
164
+ *
165
+ * The RSC hydration path calls this through a runtime import of
166
+ * `veryfront/router`, so it runs under the app's React instance — the same one
167
+ * the hydrated component uses, and the same providers and `React` this module
168
+ * already reference. That is why the caller does not (and must not) pass a
169
+ * `React` across the module boundary: the wrapping happens here, inside the
170
+ * module that owns React.
171
+ */
172
+ export function wrapForHydration(child, options = {}) {
173
+ const loc = globalThis.location;
174
+ const pathname = loc?.pathname ?? "/";
175
+ const params = options.params ?? {};
176
+ const query = loc
177
+ ? Object.fromEntries(new URLSearchParams(loc.search))
178
+ : {};
179
+ const router = {
180
+ ...defaultRouter,
181
+ domain: loc?.hostname ?? "",
182
+ path: pathname,
183
+ pathname,
184
+ params,
185
+ query,
186
+ };
187
+ // `PageContextProvider` derives its live location from the router above; only
188
+ // the page-authored bits (frontmatter/slug) are seeded here.
189
+ const pageContext = {
190
+ ...defaultPageContext,
191
+ slug: pathname,
192
+ path: pathname,
193
+ params,
194
+ query,
195
+ frontmatter: options.frontmatter ?? {},
196
+ };
197
+ return React.createElement(RouterProvider, {
198
+ router,
199
+ children: React.createElement(PageContextProvider, { pageContext, children: child }),
200
+ });
56
201
  }
57
- /** Reads the current router context. */
202
+ /**
203
+ * Reads the router context: `pathname`, `query`, `params`, and the navigation
204
+ * actions. Reactive across client-side navigation — this is the single hook for
205
+ * location and navigation state.
206
+ */
58
207
  export function useRouter() {
59
208
  return React.useContext(RouterContext);
60
209
  }
@@ -62,9 +211,22 @@ export function useRouter() {
62
211
  export function Link({ prefetch = true, children, ...rest }) {
63
212
  return React.createElement("a", { ...rest, "data-prefetch": prefetch ? "true" : "false" }, children);
64
213
  }
65
- /** Provides page context to route and MDX descendants. */
214
+ /**
215
+ * Provides page context to route and MDX descendants. Page-authored fields
216
+ * (`frontmatter`, `slug`, `headings`) come from the `pageContext` prop; the
217
+ * location fields (`path`, `query`, `params`) are derived from the router so
218
+ * they stay reactive and there is a single source of truth — `usePageContext()`
219
+ * exposes the same `query`/`pathname` as `useRouter()`. When rendered outside a
220
+ * `RouterProvider` (no live router) it falls back to the seed's own location.
221
+ */
66
222
  export function PageContextProvider({ children, pageContext, }) {
67
- return React.createElement(PageContextContext.Provider, { value: pageContext ?? defaultPageContext }, children);
223
+ const seed = pageContext ?? defaultPageContext;
224
+ const router = React.useContext(RouterContext);
225
+ const hasRouter = router !== defaultRouter;
226
+ const value = React.useMemo(() => hasRouter
227
+ ? { ...seed, path: router.pathname, query: router.query, params: router.params }
228
+ : seed, [seed, hasRouter, router.pathname, router.query, router.params]);
229
+ return React.createElement(PageContextContext.Provider, { value }, children);
68
230
  }
69
231
  /** Reads the current page context. */
70
232
  export function usePageContext() {
@@ -14,6 +14,7 @@ import {
14
14
  import { validateTrustedHtml } from "#veryfront/security/client/html-sanitizer.ts";
15
15
  import { consumeNdjsonStream, getContainer } from "./client-dom.ts";
16
16
  import { hydrateAllClientBoundaries } from "./hydrate-client.ts";
17
+ import { wrapWithRouterProvider } from "./hydration-router.ts";
17
18
  import { RSC_PATH_PREFIX, RSC_ROOT_ID } from "./constants.ts";
18
19
 
19
20
  /**
@@ -173,7 +174,10 @@ async function hydratePageComponent(
173
174
  const hydrationRoot = shouldWrapPageHydrationRoot(root, document.body)
174
175
  ? createPageHydrationRoot(bodyChildren, document.body)
175
176
  : root;
176
- const component = React.createElement(Component, {});
177
+ const component = await wrapWithRouterProvider(
178
+ React.createElement(Component, {}),
179
+ readHydrationData(document),
180
+ );
177
181
 
178
182
  if (shouldRenderPageComponent(strategy)) {
179
183
  ReactDOM.createRoot(hydrationRoot).render(component);
@@ -7,6 +7,12 @@ export interface ClientRuntimeHydrationData {
7
7
  pagePath?: string;
8
8
  clientModuleStrategy?: ClientModuleStrategy;
9
9
  dev?: boolean;
10
+ /** Route slug for the current page (from the route match). */
11
+ slug?: string;
12
+ /** Route params from the initial match — used to seed the reactive router. */
13
+ params?: Record<string, string | string[]>;
14
+ /** Page frontmatter — exposed reactively via `usePageContext()`. */
15
+ frontmatter?: Record<string, unknown>;
10
16
  }
11
17
  export interface ClientModuleUrlOptions {
12
18
  strategy: ClientModuleStrategy;
@@ -24,4 +30,12 @@ export declare function getHydrationReactImportSpecifiers(doc?: Document, versio
24
30
  react: string;
25
31
  reactDomClient: string;
26
32
  };
33
+ /**
34
+ * The import specifier for the framework router module, or `null` if the page's
35
+ * import map does not own it. Returned as a value (not a literal) so callers can
36
+ * `import(specifier)` and have the bundler leave it as a runtime import — the
37
+ * module resolves to the app's React instance, which is required for the
38
+ * provider's hooks to run under the same React as the hydrated component.
39
+ */
40
+ export declare function getHydrationRouterImportSpecifier(doc?: Document): string | null;
27
41
  //# sourceMappingURL=client-module-strategy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-module-strategy.d.ts","sourceRoot":"","sources":["../../../../src/src/rendering/rsc/client-module-strategy.ts"],"names":[],"mappings":"AAYA,MAAM,MAAM,oBAAoB,GAAG,IAAI,GAAG,YAAY,CAAC;AAEvD,MAAM,WAAW,2BAA2B;IAC1C,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,WAAW,CAAC,EAAE,SAAS,GAAG,YAAY,CAAC;CACxC;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;IAC5C,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAED,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,2BAA2B,GACnC,oBAAoB,CAUtB;AAED,wBAAgB,iBAAiB,CAC/B,GAAG,GAAE,QAAmB,GACvB,0BAA0B,GAAG,IAAI,CASnC;AAED,wBAAgB,2BAA2B,CACzC,aAAa,EAAE,0BAA0B,GAAG,IAAI,GAC/C,oBAAoB,CAMtB;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAGvE;AAED,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,sBAAsB,GAAG,MAAM,GAAG,IAAI,CAOnF;AAED,wBAAgB,iCAAiC,CAC/C,GAAG,GAAE,QAAmB,EACxB,OAAO,GAAE,MAA8B,GACtC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,CAS3C"}
1
+ {"version":3,"file":"client-module-strategy.d.ts","sourceRoot":"","sources":["../../../../src/src/rendering/rsc/client-module-strategy.ts"],"names":[],"mappings":"AAYA,MAAM,MAAM,oBAAoB,GAAG,IAAI,GAAG,YAAY,CAAC;AAEvD,MAAM,WAAW,2BAA2B;IAC1C,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,WAAW,CAAC,EAAE,SAAS,GAAG,YAAY,CAAC;CACxC;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;IAC5C,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,8DAA8D;IAC9D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;IAC3C,oEAAoE;IACpE,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,2BAA2B,GACnC,oBAAoB,CAUtB;AAED,wBAAgB,iBAAiB,CAC/B,GAAG,GAAE,QAAmB,GACvB,0BAA0B,GAAG,IAAI,CASnC;AAED,wBAAgB,2BAA2B,CACzC,aAAa,EAAE,0BAA0B,GAAG,IAAI,GAC/C,oBAAoB,CAMtB;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAGvE;AAED,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,sBAAsB,GAAG,MAAM,GAAG,IAAI,CAOnF;AAED,wBAAgB,iCAAiC,CAC/C,GAAG,GAAE,QAAmB,EACxB,OAAO,GAAE,MAA8B,GACtC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,CAS3C;AAED;;;;;;GAMG;AACH,wBAAgB,iCAAiC,CAAC,GAAG,GAAE,QAAmB,GAAG,MAAM,GAAG,IAAI,CAGzF"}
@@ -54,3 +54,14 @@ export function getHydrationReactImportSpecifiers(doc = document, version = REAC
54
54
  : getReactDOMClientCDNUrl(version),
55
55
  };
56
56
  }
57
+ /**
58
+ * The import specifier for the framework router module, or `null` if the page's
59
+ * import map does not own it. Returned as a value (not a literal) so callers can
60
+ * `import(specifier)` and have the bundler leave it as a runtime import — the
61
+ * module resolves to the app's React instance, which is required for the
62
+ * provider's hooks to run under the same React as the hydrated component.
63
+ */
64
+ export function getHydrationRouterImportSpecifier(doc = document) {
65
+ const imports = getDocumentImportMapImports(doc);
66
+ return importMapOwnsSpecifier("veryfront/router", imports) ? "veryfront/router" : null;
67
+ }
@@ -10,6 +10,7 @@ import {
10
10
  readHydrationData,
11
11
  resolveClientModuleStrategy,
12
12
  } from "./client-module-strategy.ts";
13
+ import { wrapWithRouterProvider } from "./hydration-router.ts";
13
14
  type Manifest = {
14
15
  version: number;
15
16
  hash?: string;
@@ -143,7 +144,8 @@ export async function hydrateAllClientBoundaries(doc: Document = document): Prom
143
144
  return;
144
145
  }
145
146
 
146
- const clientModuleStrategy = resolveClientModuleStrategy(readHydrationData(doc));
147
+ const hydrationData = readHydrationData(doc);
148
+ const clientModuleStrategy = resolveClientModuleStrategy(hydrationData);
147
149
 
148
150
  try {
149
151
  if (globalThis.__VF_TEST_MODE__) {
@@ -176,7 +178,12 @@ export async function hydrateAllClientBoundaries(doc: Document = document): Prom
176
178
 
177
179
  try {
178
180
  const root: ReactRoot = createRoot(el);
179
- root.render(React.createElement(Cmp as React.FC, {}));
181
+ const tree = await wrapWithRouterProvider(
182
+ React.createElement(Cmp as React.FC, {}),
183
+ hydrationData,
184
+ doc,
185
+ );
186
+ root.render(tree);
180
187
  el.dataset.hydrated = "true";
181
188
  } catch (e) {
182
189
  rscLogger.warn("hydrate: render failed", e);
@@ -1 +1 @@
1
- {"version":3,"file":"rsc-bundles.generated.d.ts","sourceRoot":"","sources":["../../../../../../src/src/server/services/rsc/endpoints/rsc-bundles.generated.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,eAAO,MAAM,kBAAkB,EAAE,MAC2u2B,CAAC;AAE7w2B,eAAO,MAAM,iBAAiB,EAAE,MACsunB,CAAC"}
1
+ {"version":3,"file":"rsc-bundles.generated.d.ts","sourceRoot":"","sources":["../../../../../../src/src/server/services/rsc/endpoints/rsc-bundles.generated.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,eAAO,MAAM,kBAAkB,EAAE,MAC8v3B,CAAC;AAEhy3B,eAAO,MAAM,iBAAiB,EAAE,MACsunB,CAAC"}
@@ -5,5 +5,5 @@
5
5
  * Do not edit manually — run `deno task generate` to regenerate.
6
6
  * @module
7
7
  */
8
- export const CLIENT_BOOT_BUNDLE = 'var ot=Object.defineProperty;var nt=(t,e,o)=>e in t?ot(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var p=(t,e,o)=>nt(t,typeof e!="symbol"?e+"":e,o);var st="3.2.3";function it(t,e,o,n){let s=[];if(n?.external?.length&&s.push(`external=${n.external.join(",")}`),s.push(`target=${n?.target??"es2022"}`),n?.deps){let d=Object.entries(n.deps).map(([l,m])=>`${l}@${m}`).join(",");s.push(`deps=${d}`)}let u=e?`@${e}`:"",a=o??"",i=s.length?`?${s.join("&")}`:"";return`https://esm.sh/${t}${u}${a}${i}`}function f(t,e,o,n=!1){return it(t,e,o,{external:n?["react"]:void 0,deps:{csstype:st}})}var ct="19.2.4",E=ct;function w(t=E){return{react:f("react",t),"react-dom":f("react-dom",t,void 0,!0),"react-dom/client":f("react-dom",t,"/client",!0),"react-dom/server":f("react-dom",t,"/server",!0),"react/jsx-runtime":f("react",t,"/jsx-runtime",!0),"react/jsx-dev-runtime":f("react",t,"/jsx-dev-runtime",!0)}}function V(t=E){return w(t).react}function H(t=E){return w(t)["react-dom/client"]}function lt(t){return t.replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function D(t){return lt(btoa(t))}var Tr=Object.freeze({react:"","react-dom":"","react-dom/client":"","react-dom/server":"","react/jsx-runtime":"","react/jsx-dev-runtime":""});function v(t,e){if(!e)return!1;if(Object.prototype.hasOwnProperty.call(e,t))return!0;for(let o of Object.keys(e))if(o.endsWith("/")&&t.startsWith(o))return!0;return!1}function ut(t){try{return JSON.parse(t)?.imports??{}}catch{return{}}}function F(t=document){let e=t.querySelector(\'script[type="importmap"]\');return e?.textContent?ut(e.textContent):{}}var c="/_veryfront",b={RSC:`${c}/rsc/`,FS:`${c}/fs/`,MODULES:`${c}/modules/`,PAGES:`${c}/pages/`,DATA:`${c}/data/`,LIB:`${c}/lib/`,CHUNKS:`${c}/chunks/`,CLIENT:`${c}/client/`},$={HMR_RUNTIME:`${c}/hmr-runtime.js`,HMR:`${c}/hmr.js`,ERROR_OVERLAY:`${c}/error-overlay.js`,DEV_LOADER:`${c}/dev-loader.js`,CLIENT_LOG:`${c}/log`,CLIENT_JS:`${c}/client.js`,ROUTER_JS:`${c}/router.js`,PREFETCH_JS:`${c}/prefetch.js`,MANIFEST_JSON:`${c}/manifest.json`,APP_JS:`${c}/app.js`,RSC_CLIENT:`${c}/rsc/client.js`,RSC_MANIFEST:`${c}/rsc/manifest`,RSC_STREAM:`${c}/rsc/stream`,RSC_PAYLOAD:`${c}/rsc/payload`,RSC_RENDER:`${c}/rsc/render`,RSC_PAGE:`${c}/rsc/page`,RSC_MODULE:`${c}/rsc/module`,RSC_DOM:`${c}/rsc/dom.js`,LIB_CHAT_REACT:`${c}/lib/chat/react.js`,LIB_CHAT_COMPONENTS:`${c}/lib/chat/components.js`,LIB_CHAT_PRIMITIVES:`${c}/lib/chat/primitives.js`};var dt={ROOT:".veryfront",CACHE:".veryfront/cache",KV:".veryfront/kv",LOGS:".veryfront/logs",TMP:".veryfront/tmp"},Dr=dt.CACHE;var vr={HMR_RUNTIME:$.HMR_RUNTIME,ERROR_OVERLAY:$.ERROR_OVERLAY};var y=b.RSC,G=b.FS,k="veryfront-hydration-data",_="rsc-root";function I(t=document){try{let e=t.getElementById(k);return e?JSON.parse(e.textContent||"{}"):null}catch(e){return console.debug?.("[RSC] hydration data parse failed",e),null}}function T(t){return t?.clientModuleStrategy?t.clientModuleStrategy:t?.dev?"fs":"rsc-module"}function pt(t){return`${G}${D(t)}.js`}function mt(t,e){let o=e?`&v=${encodeURIComponent(e)}`:"";return`${y}module?rel=${encodeURIComponent(t)}${o}`}function C(t){if(t.strategy==="fs"){let e=t.absPath??t.rel;return e?pt(e):null}return mt(t.rel,t.version)}function O(t=document,e=E){let o=F(t);return{react:v("react",o)?"react":V(e),reactDomClient:v("react-dom/client",o)?"react-dom/client":H(e)}}function r(t){return{...t,create(e){return new M(e?.message||e?.detail||t.title,{slug:t.slug,category:t.category,status:e?.status??t.status,title:t.title,suggestion:t.suggestion,detail:e?.detail,cause:e?.cause,instance:e?.instance,context:e?.context})}}}var M=class extends Error{constructor(o,n){super(o);p(this,"slug");p(this,"category");p(this,"status");p(this,"title");p(this,"suggestion");p(this,"detail");p(this,"cause");p(this,"instance");p(this,"context");this.name="VeryfrontError",this.slug=n.slug,this.category=n.category,this.status=n.status,this.title=n.title,this.suggestion=n.suggestion,this.detail=n.detail,this.cause=n.cause,this.instance=n.instance,this.context=n.context}toRFC9457(){return{type:`https://veryfront.com/docs/errors/${this.slug}`,title:this.title,status:this.status,detail:this.detail,instance:this.instance,category:this.category,suggestion:this.suggestion,cause:typeof this.cause=="string"?this.cause:void 0}}getDocsUrl(){return`https://veryfront.com/docs/errors/${this.slug}`}};var ft=r({slug:"config-not-found",category:"CONFIG",status:404,title:"Configuration file not found",suggestion:"Run \'vf init\' to create a configuration file"}),Rt=r({slug:"config-invalid",category:"CONFIG",status:400,title:"Invalid configuration format",suggestion:"Check your veryfront.config.ts for syntax errors"}),Et=r({slug:"config-parse-error",category:"CONFIG",status:400,title:"Failed to parse configuration",suggestion:"Ensure your configuration file is valid TypeScript/JSON"}),yt=r({slug:"config-validation-error",category:"CONFIG",status:422,title:"Configuration validation failed",suggestion:"Check the configuration against the schema requirements"}),_t=r({slug:"config-type-error",category:"CONFIG",status:400,title:"Configuration type mismatch",suggestion:"Ensure configuration values match expected types"}),ht=r({slug:"import-map-invalid",category:"CONFIG",status:400,title:"Invalid import map configuration",suggestion:"Check your import map syntax and paths"}),St=r({slug:"cors-config-invalid",category:"CONFIG",status:400,title:"Invalid CORS configuration",suggestion:"Review CORS settings in your configuration"}),xt=r({slug:"config-validation-failed",category:"CONFIG",status:400,title:"Configuration validation failed",suggestion:"Check configuration values against requirements"}),Y={"config-not-found":ft,"config-invalid":Rt,"config-parse-error":Et,"config-validation-error":yt,"config-type-error":_t,"import-map-invalid":ht,"cors-config-invalid":St,"config-validation-failed":xt};var It=r({slug:"build-failed",category:"BUILD",status:500,title:"Build process failed",suggestion:"Check the build output for specific errors"}),Tt=r({slug:"bundle-error",category:"BUILD",status:500,title:"Bundle generation failed",suggestion:"Review bundler output for details"}),Ct=r({slug:"typescript-error",category:"BUILD",status:500,title:"TypeScript compilation error",suggestion:"Fix TypeScript errors shown in the output"}),Ot=r({slug:"mdx-compile-error",category:"BUILD",status:500,title:"MDX compilation failed",suggestion:"Check your MDX file syntax"}),At=r({slug:"asset-optimization-error",category:"BUILD",status:500,title:"Asset optimization failed",suggestion:"Check asset file formats and paths"}),Nt=r({slug:"ssg-generation-error",category:"BUILD",status:500,title:"Static site generation failed",suggestion:"Review SSG configuration and data fetching"}),Dt=r({slug:"sourcemap-error",category:"BUILD",status:500,title:"Source map generation failed",suggestion:"Check source map configuration"}),vt=r({slug:"compilation-error",category:"BUILD",status:500,title:"Compilation failed",suggestion:"Review compiler output for specific errors"}),B={"build-failed":It,"bundle-error":Tt,"typescript-error":Ct,"mdx-compile-error":Ot,"asset-optimization-error":At,"ssg-generation-error":Nt,"sourcemap-error":Dt,"compilation-error":vt};var bt=r({slug:"hydration-mismatch",category:"RUNTIME",status:500,title:"Client/server hydration mismatch",suggestion:"Ensure server and client render the same content"}),Mt=r({slug:"render-error",category:"RUNTIME",status:500,title:"Component render failed",suggestion:"Check component for runtime errors"}),Lt=r({slug:"component-error",category:"RUNTIME",status:500,title:"Component execution error",suggestion:"Review component logic and props"}),Ut=r({slug:"layout-not-found",category:"RUNTIME",status:404,title:"Layout component not found",suggestion:"Ensure layout file exists at the expected path"}),Pt=r({slug:"page-not-found",category:"RUNTIME",status:404,title:"Page component not found",suggestion:"Check that the page file exists in the routes directory"}),wt=r({slug:"api-error",category:"RUNTIME",status:500,title:"API route handler error",suggestion:"Review API route handler for errors"}),Vt=r({slug:"middleware-error",category:"RUNTIME",status:500,title:"Middleware execution error",suggestion:"Check middleware function for errors"}),j={"hydration-mismatch":bt,"render-error":Mt,"component-error":Lt,"layout-not-found":Ut,"page-not-found":Pt,"api-error":wt,"middleware-error":Vt};var Ht=r({slug:"route-conflict",category:"ROUTE",status:409,title:"Conflicting route definitions",suggestion:"Rename or reorganize conflicting route files"}),Ft=r({slug:"invalid-route-file",category:"ROUTE",status:400,title:"Invalid route file structure",suggestion:"Ensure route file exports required functions"}),$t=r({slug:"route-handler-invalid",category:"ROUTE",status:400,title:"Invalid route handler export",suggestion:"Export a valid handler function from the route file"}),Gt=r({slug:"dynamic-route-error",category:"ROUTE",status:500,title:"Dynamic route parsing failed",suggestion:"Check dynamic route segment syntax"}),kt=r({slug:"route-params-error",category:"ROUTE",status:400,title:"Route parameters invalid",suggestion:"Validate route parameter values"}),Yt=r({slug:"api-route-error",category:"ROUTE",status:500,title:"API route definition error",suggestion:"Review API route configuration"}),W={"route-conflict":Ht,"invalid-route-file":Ft,"route-handler-invalid":$t,"dynamic-route-error":Gt,"route-params-error":kt,"api-route-error":Yt};var Bt=r({slug:"module-not-found",category:"MODULE",status:404,title:"Module could not be resolved",suggestion:"Check the import path and ensure the module is installed"}),jt=r({slug:"import-resolution-error",category:"MODULE",status:500,title:"Import path resolution failed",suggestion:"Verify import paths and module configuration"}),Wt=r({slug:"circular-dependency",category:"MODULE",status:500,title:"Circular dependency detected",suggestion:"Refactor imports to break the circular dependency"}),qt=r({slug:"invalid-import",category:"MODULE",status:400,title:"Invalid import statement",suggestion:"Fix import syntax or path"}),zt=r({slug:"dependency-missing",category:"MODULE",status:404,title:"Required dependency not installed",suggestion:"Install the missing dependency with your package manager"}),Xt=r({slug:"version-mismatch",category:"MODULE",status:409,title:"Dependency version mismatch",suggestion:"Update dependencies to compatible versions"}),q={"module-not-found":Bt,"import-resolution-error":jt,"circular-dependency":Wt,"invalid-import":qt,"dependency-missing":zt,"version-mismatch":Xt};var Jt=r({slug:"port-in-use",category:"SERVER",status:409,title:"Server port already in use",suggestion:"Use a different port or stop the process using this port"}),Kt=r({slug:"server-start-error",category:"SERVER",status:500,title:"Server failed to start",suggestion:"Check server configuration and port availability"}),Zt=r({slug:"cache-error",category:"SERVER",status:500,title:"Cache operation failed",suggestion:"Clear the cache and try again"}),Qt=r({slug:"file-watch-error",category:"SERVER",status:500,title:"File watcher error",suggestion:"Restart the development server"}),te=r({slug:"request-error",category:"SERVER",status:500,title:"HTTP request handling error",suggestion:"Check request handler and middleware"}),ee=r({slug:"service-overloaded",category:"SERVER",status:503,title:"Service overloaded",suggestion:"Reduce load or scale up resources"}),re=r({slug:"semaphore-timeout",category:"SERVER",status:503,title:"Semaphore acquire timeout",suggestion:"Reduce concurrency or increase the semaphore acquire timeout"}),oe=r({slug:"circuit-breaker-open",category:"SERVER",status:503,title:"Circuit breaker is open",suggestion:"Wait for the breaker reset timeout before retrying"}),ne=r({slug:"cache-path-mismatch",category:"SERVER",status:500,title:"Cache path mismatch",suggestion:"Clear the cache directory and rebuild"}),se=r({slug:"network-error",category:"SERVER",status:502,title:"Network operation failed",suggestion:"Check network connectivity and retry"}),ie=r({slug:"api-client-error",category:"SERVER",status:500,title:"API client request failed",suggestion:"Check API connectivity and authentication"}),ae=r({slug:"token-storage-error",category:"SERVER",status:500,title:"Token storage operation failed",suggestion:"Check token storage backend and credentials"}),ce=r({slug:"cache-invariant-violation",category:"SERVER",status:500,title:"Cache path invariant violated",suggestion:"Clear the cache and rebuild"}),le=r({slug:"release-not-found",category:"SERVER",status:404,title:"No active release found",suggestion:"Deploy the project to create a release for this environment"}),ue=r({slug:"fallback-exhausted",category:"SERVER",status:500,title:"Primary and fallback operations both failed",suggestion:"Check service availability and connectivity"}),z={"port-in-use":Jt,"server-start-error":Kt,"cache-error":Zt,"file-watch-error":Qt,"request-error":te,"service-overloaded":ee,"semaphore-timeout":re,"circuit-breaker-open":oe,"cache-path-mismatch":ne,"network-error":se,"api-client-error":ie,"token-storage-error":ae,"cache-invariant-violation":ce,"release-not-found":le,"fallback-exhausted":ue};var ge=r({slug:"client-boundary-violation",category:"BOUNDARY",status:400,title:"Client boundary rule violation",suggestion:"Add \'use client\' directive or move code to a client component"}),de=r({slug:"server-only-in-client",category:"BOUNDARY",status:400,title:"Server-only code in client component",suggestion:"Move server-only code to a server component"}),pe=r({slug:"client-only-in-server",category:"BOUNDARY",status:400,title:"Client-only code in server component",suggestion:"Move client-only code to a client component"}),me=r({slug:"invalid-use-client",category:"BOUNDARY",status:400,title:"Invalid \'use client\' directive",suggestion:"Place \'use client\' at the top of the file"}),fe=r({slug:"invalid-use-server",category:"BOUNDARY",status:400,title:"Invalid \'use server\' directive",suggestion:"Place \'use server\' at the top of the file or function"}),Re=r({slug:"rsc-payload-error",category:"BOUNDARY",status:500,title:"RSC payload serialization error",suggestion:"Ensure props are serializable (no functions, symbols, etc.)"}),X={"client-boundary-violation":ge,"server-only-in-client":de,"client-only-in-server":pe,"invalid-use-client":me,"invalid-use-server":fe,"rsc-payload-error":Re};var Ee=r({slug:"hmr-error",category:"DEV",status:500,title:"Hot module replacement error",suggestion:"Restart the development server"}),ye=r({slug:"dev-server-error",category:"DEV",status:500,title:"Development server error",suggestion:"Check the dev server logs and restart"}),_e=r({slug:"fast-refresh-error",category:"DEV",status:500,title:"Fast refresh failed",suggestion:"Save the file again or restart the dev server"}),he=r({slug:"error-overlay-error",category:"DEV",status:500,title:"Error overlay failed",suggestion:"Check browser console for details"}),Se=r({slug:"source-map-error",category:"DEV",status:500,title:"Source map loading error",suggestion:"Rebuild or clear cache"}),J={"hmr-error":Ee,"dev-server-error":ye,"fast-refresh-error":_e,"error-overlay-error":he,"source-map-error":Se};var xe=r({slug:"deployment-error",category:"DEPLOY",status:500,title:"Deployment process failed",suggestion:"Check deployment logs for details"}),Ie=r({slug:"platform-error",category:"DEPLOY",status:500,title:"Platform-specific error",suggestion:"Check platform documentation and requirements"}),Te=r({slug:"env-var-missing",category:"DEPLOY",status:500,title:"Required environment variable missing",suggestion:"Set the required environment variable"}),Ce=r({slug:"production-build-required",category:"DEPLOY",status:400,title:"Production build required",suggestion:"Run \'vf build\' before deploying"}),K={"deployment-error":xe,"platform-error":Ie,"env-var-missing":Te,"production-build-required":Ce};var Oe=r({slug:"agent-error",category:"AGENT",status:500,title:"Agent operation error",suggestion:"Check agent configuration and logs"}),Ae=r({slug:"agent-not-found",category:"AGENT",status:404,title:"Agent not found",suggestion:"Verify the agent ID exists"}),Ne=r({slug:"agent-timeout",category:"AGENT",status:408,title:"Agent operation timed out",suggestion:"Increase timeout or simplify the request"}),De=r({slug:"agent-intent-error",category:"AGENT",status:400,title:"Agent intent parsing error",suggestion:"Rephrase the request more clearly"}),ve=r({slug:"orchestration-error",category:"AGENT",status:500,title:"Multi-agent orchestration error",suggestion:"Check agent coordination logic"}),be=r({slug:"cost-limit-exceeded",category:"AGENT",status:429,title:"Cost limit exceeded",suggestion:"Wait for the budget period to reset or increase the limit"}),Me=r({slug:"tool-id-conflict",category:"AGENT",status:409,title:"Tool ID conflict",suggestion:"Use a unique tool ID or rename one of the conflicting tools"}),Z={"agent-error":Oe,"agent-not-found":Ae,"agent-timeout":Ne,"agent-intent-error":De,"orchestration-error":ve,"cost-limit-exceeded":be,"tool-id-conflict":Me};var Le=r({slug:"unknown-error",category:"GENERAL",status:500,title:"Unknown/unclassified error",suggestion:"Check logs for more details"}),Ue=r({slug:"permission-denied",category:"GENERAL",status:403,title:"File/resource permission denied",suggestion:"Check file permissions and access rights"}),Pe=r({slug:"file-not-found",category:"GENERAL",status:404,title:"File not found",suggestion:"Verify the file path exists"}),we=r({slug:"resource-not-found",category:"GENERAL",status:404,title:"Requested resource not found",suggestion:"Verify the referenced resource ID or name exists"}),Ve=r({slug:"invalid-argument",category:"GENERAL",status:400,title:"Invalid function argument",suggestion:"Check argument types and values"}),He=r({slug:"timeout-error",category:"GENERAL",status:408,title:"Operation timed out",suggestion:"Increase timeout or optimize the operation"}),Fe=r({slug:"initialization-error",category:"GENERAL",status:500,title:"Initialization failed",suggestion:"Check initialization requirements and dependencies"}),$e=r({slug:"not-supported",category:"GENERAL",status:501,title:"Feature not supported",suggestion:"Check documentation for supported features"}),L=r({slug:"security-violation",category:"GENERAL",status:403,title:"Security violation detected",suggestion:"Check for path traversal or unauthorized access attempts"}),Ge=r({slug:"input-validation-failed",category:"GENERAL",status:400,title:"Input validation failed",suggestion:"Check request input against validation rules"}),Q={"unknown-error":Le,"permission-denied":Ue,"file-not-found":Pe,"resource-not-found":we,"invalid-argument":Ve,"timeout-error":He,"initialization-error":Fe,"not-supported":$e,"security-violation":L,"input-validation-failed":Ge};var No={...Y,...B,...j,...W,...q,...z,...X,...J,...K,...Z,...Q};var ke=[{source:String.raw`<script[^>]*>[\\s\\S]*?<\\/script>`,flags:"gi",name:"inline script"},{source:String.raw`javascript:`,flags:"gi",name:"javascript: URL"},{source:String.raw`\\bon\\w+\\s*=`,flags:"gi",name:"event handler attribute"},{source:String.raw`data:\\s*text\\/html`,flags:"gi",name:"data: HTML URL"}];function Ye(){return ke.map(({source:t,flags:e,name:o})=>({pattern:new RegExp(t,e),name:o}))}function Be(){let t=globalThis;return t.__VERYFRONT_DEV__===!0||t.Deno?.env?.get?.("VERYFRONT_ENV")==="development"}function h(t,e={}){let{allowInlineScripts:o=!1,strict:n=!1,warn:s=!0}=e;for(let{pattern:u,name:a}of Ye())if(!(o&&a==="inline script")&&(u.lastIndex=0,!!u.test(t)&&(s&&console.warn(`[Security] Suspicious ${a} detected in server HTML`),n||!Be())))throw L.create({detail:`Potentially unsafe HTML: ${a} detected`});return t}var R=class{constructor(e,o){p(this,"prefix",e);p(this,"level",o)}log(e,o,n,...s){this.level>e||o?.(n,...s)}debug(e,...o){this.log(0,console.debug,`[${this.prefix}] DEBUG: ${e}`,...o)}info(e,...o){this.log(1,console.log,`[${this.prefix}] ${e}`,...o)}warn(e,...o){this.log(2,console.warn,`[${this.prefix}] WARN: ${e}`,...o)}error(e,...o){this.log(3,console.error,`[${this.prefix}] ERROR: ${e}`,...o)}};function je(){if(typeof window>"u")return 2;let t=globalThis;return t.__VERYFRONT_DEV__||t.__RSC_DEV__?t.__VERYFRONT_DEBUG__||t.__RSC_DEBUG__?0:1:2}var A=je(),g=new R("RSC",A),jo=new R("PREFETCH",A),Wo=new R("HYDRATE",A),qo=new R("VERYFRONT",A);function S(t,e){let o=e==="root"?_:`rsc-slot-${e}`,n=t.getElementById(o);if(n)return n;let s=t.createElement("div");return s.id=o,t.body.appendChild(s),s}function We(t,e){if(e.type!=="slot")return;let o=S(t,e.id);o.innerHTML=h(String(e.html??""))}function tt(t,e){let o=e.split(`\n`),n=o.pop()??"";for(let s of o){let u=s.trim();if(!u)continue;let a;try{a=JSON.parse(u)}catch(d){g.debug("[client-dom] malformed NDJSON line",{line:u,error:d instanceof Error?d.message:String(d)});continue}if(!a||typeof a!="object")continue;let i=a;if(i.type==="slot"){We(t,i);try{Xe(t,i.id||"root")}catch(d){g.debug("[client-dom] hydration optional failed",d)}}}return n}function qe(t){return new Promise((e,o)=>{let n=()=>o(new DOMException("aborted","AbortError"));if(t.aborted){n();return}t.addEventListener("abort",n,{once:!0})})}async function et(t,e=document,o){let n="body"in t?t:null,s=n?.body??t;if(!s)return;let u=s.getReader(),a=new TextDecoder,i="",d=!1;try{for(;;){if(o?.aborted)throw new DOMException("aborted","AbortError");let l=u.read(),{done:m,value:x}=o?await Promise.race([l,qe(o)]):await l;if(m){d=!0;break}i+=a.decode(x,{stream:!0}),i=tt(e,i)}i&&tt(e,`${i}\n`)}catch(l){throw l instanceof Error&&l.name==="AbortError"||g.debug("[client-dom] consumeNdjsonStream error",l),l}finally{try{await u.cancel()}catch(l){d||g.debug("[client-dom] reader.cancel failed",l)}try{u.releaseLock()}catch(l){g.debug("[client-dom] reader.releaseLock failed",l)}if(typeof s.cancel=="function")try{await s.cancel()}catch(l){g.debug("[client-dom] stream.cancel failed",l)}if(typeof n?.body?.cancel=="function")try{await n.body.cancel()}catch(l){g.debug("[client-dom] response.body.cancel failed",l)}}}function ze(t,e){let o=S(t,e),n=[],s=u=>{let a=u;a.dataset?.clientRef&&n.push(a);for(let i of u.children)s(i)};return s(o),n}function Xe(t,e){let o=ze(t,e);for(let n of o){let s=n.dataset?.clientRef;s&&(n.dataset.hydrated="true",g.debug("[client-dom] marked for hydration",s))}}var Je=100;function Ke(t,e){if(globalThis.__VF_CLIENT_MOD_CACHE??(globalThis.__VF_CLIENT_MOD_CACHE=new Map),globalThis.__VF_CLIENT_MOD_CACHE.size>=Je){let o=globalThis.__VF_CLIENT_MOD_CACHE.keys().next().value;o&&globalThis.__VF_CLIENT_MOD_CACHE.delete(o)}globalThis.__VF_CLIENT_MOD_CACHE.set(t,e)}function Ze(t){let e=t.match(/^\\/app\\/(.+)#([A-Za-z0-9_]+)$/);return e?{rel:`/${e[1]||""}`,exportName:e[2]||"default"}:null}async function Qe(){try{let t=await fetch("/_veryfront/rsc/manifest");return t.ok?await t.json():null}catch{return null}}async function tr(t,e,o){let n=t.graphIds?.client.find(a=>a.rel===e)?.path,s=`${e}#${t.hash??""}`;try{let a=globalThis.__VF_CLIENT_MOD_CACHE?.get(s);if(a)return a}catch(a){g.debug("hydrate: cache get failed",a)}let u=C({strategy:o,rel:e,absPath:n,version:t.hash});if(!u)return null;try{let a=await import(u);try{Ke(s,a)}catch(i){g.debug("hydrate: cache set failed",i)}return a}catch(a){return g.debug("hydrate: failed to import module",{moduleUrl:u,error:a}),null}}async function rt(t=document){let e=null;try{e=await Qe()}catch(i){g.debug("hydrate: fetch manifest failed",i)}if(!e){g.debug("hydrate: no manifest");return}let o=Array.from(t.querySelectorAll("[data-client-ref]"));try{let i=globalThis.__VF_MANIFEST_HASH;if(!o.some(l=>l.dataset?.hydrated!=="true")&&i&&e.hash&&i===e.hash)return}catch(i){g.debug("hydrate: hmr hash read failed",i)}if(o.length===0){try{globalThis.__VF_MANIFEST_HASH=e.hash??""}catch(i){g.debug("hydrate: set hash failed",i)}return}let n=T(I(t));try{if(globalThis.__VF_TEST_MODE__){globalThis.__VF_HYDRATE_CALLED=!0,globalThis.__VF_MANIFEST_HASH=e.hash??"";return}}catch(i){g.debug("hydrate: test mode flags failed",i)}let s=O(t),[{default:u},{createRoot:a}]=await Promise.all([import(s.react),import(s.reactDomClient)]);for(let i of o){let d=i.dataset?.clientRef??"";if(!d||i.dataset?.hydrated==="true")continue;let l=Ze(d);if(!l)continue;let m=await tr(e,l.rel,n);if(!m)continue;let x=m[l.exportName]??m.default;if(typeof x=="function")try{a(i).render(u.createElement(x,{})),i.dataset.hydrated="true"}catch(P){g.warn("hydrate: render failed",P)}}try{globalThis.__VF_MANIFEST_HASH=e.hash??""}catch(i){g.debug("hydrate: set hash failed (post)",i)}}async function er(){let t=O(document),[e,o]=await Promise.all([import(t.react),import(t.reactDomClient)]);return{React:e,ReactDOM:o}}var rr=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE"]);function U(t){let e=t.getAttribute("style")??"";return t.hasAttribute("data-veryfront-head")||t.hasAttribute("hidden")||/(?:^|;)\\s*display\\s*:\\s*none(?:\\s*;|$)/i.test(e)||rr.has(t.tagName.toUpperCase())}function or(t,e){return t.find(o=>o.tagName.toUpperCase()==="DIV"&&!!o.getAttribute("class")?.trim()&&!U(o))??e}function nr(t,e){return t===e}function sr(t,e){let o=document.createElement("div");o.setAttribute("data-veryfront-hydration-root","page");let n=t.find(s=>!U(s));n?.parentNode===e?e.insertBefore(o,n):e.appendChild(o);for(let s of t)!U(s)&&s.parentNode===e&&o.appendChild(s);return o}function ir(t,e,o=document){return!!e?.pagePath&&typeof t?.__veryfrontRenderPage=="function"&&!!o.getElementById("root")}function ar(t,e){return e?.pagePath?!1:!!t.getElementById(_)}function cr(t=import.meta.url){try{return new URL(t,"http://veryfront.local").searchParams.get("hydrate")==="1"}catch{return!1}}function lr(t){return t==="rsc-module"}async function ur(t){try{let e=await fetch(y+"stream"+t);if(!e.ok||!e.body)return!1;let o=new AbortController;return addEventListener("pagehide",()=>o.abort(),{once:!0}),await et(e,document,o.signal),!0}catch(e){return console.debug?.("[RSC] tryStream failed",e),!1}}async function N(){try{await rt(document)}catch(t){console.debug?.("[RSC] hydration failed",t)}}async function gr(t,e){try{let{React:o,ReactDOM:n}=await er(),s=C({strategy:e,rel:t});if(!s)return!1;console.debug?.("[RSC] Loading component from:",s);let a=(await import(s)).default;if(typeof a!="function")return console.debug?.("[RSC] Page component is not a function"),!1;let i=Array.from(document.body.children),d=or(i,document.body),l=nr(d,document.body)?sr(i,document.body):d,m=o.createElement(a,{});return lr(e)?n.createRoot(l).render(m):n.hydrateRoot(l,m,{identifierPrefix:"vf",onRecoverableError:()=>{}}),console.debug?.("[RSC] Page component hydrated successfully"),!0}catch(o){return console.error("[RSC] Page hydration failed",o),!1}}async function dr(t){try{let e=await fetch(y+"payload"+t);if(!e.ok)return!1;let o=await e.json();if(o?.slots){for(let[n,s]of Object.entries(o.slots))S(document,n).innerHTML=h(String(s||""));return!0}return S(document,_).innerHTML=h(String(o?.html||"")),!0}catch(e){return console.debug?.("[RSC] payload fetch failed",e),!1}}async function pr(){try{let t=globalThis.window?.location.search??"",e=I(document);if(cr()){await N();return}let o=e?.pagePath,n=T(e);if(o){if(ir(globalThis.window,e,document)){console.debug?.("[RSC] Page renderer owns hydration");return}console.debug?.("[RSC] Found page component in hydration data:",o),await gr(o,n)&&console.debug?.("[RSC] Client component hydrated successfully");return}if(!ar(document,e))return;if(await ur(t)){await N();return}if(await dr(t)){await N();return}await N()}catch(t){console.error("[RSC] boot failed",t)}}if(typeof document<"u"){let t=()=>{pr()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}export{pr as boot,or as selectHydrationRoot,ar as shouldAttemptRSCTransport,cr as shouldHydrateOnly,lr as shouldRenderPageComponent,ir as shouldUsePageRendererHydration,nr as shouldWrapPageHydrationRoot};\n';
8
+ export const CLIENT_BOOT_BUNDLE = 'var at=Object.defineProperty;var ct=(t,e,r)=>e in t?at(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var p=(t,e,r)=>ct(t,typeof e!="symbol"?e+"":e,r);var lt="3.2.3";function ut(t,e,r,n){let s=[];if(n?.external?.length&&s.push(`external=${n.external.join(",")}`),s.push(`target=${n?.target??"es2022"}`),n?.deps){let a=Object.entries(n.deps).map(([u,m])=>`${u}@${m}`).join(",");s.push(`deps=${a}`)}let l=e?`@${e}`:"",i=r??"",g=s.length?`?${s.join("&")}`:"";return`https://esm.sh/${t}${l}${i}${g}`}function f(t,e,r,n=!1){return ut(t,e,r,{external:n?["react"]:void 0,deps:{csstype:lt}})}var dt="19.2.4",y=dt;function F(t=y){return{react:f("react",t),"react-dom":f("react-dom",t,void 0,!0),"react-dom/client":f("react-dom",t,"/client",!0),"react-dom/server":f("react-dom",t,"/server",!0),"react/jsx-runtime":f("react",t,"/jsx-runtime",!0),"react/jsx-dev-runtime":f("react",t,"/jsx-dev-runtime",!0)}}function $(t=y){return F(t).react}function k(t=y){return F(t)["react-dom/client"]}function pt(t){return t.replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function M(t){return pt(btoa(t))}var Dr=Object.freeze({react:"","react-dom":"","react-dom/client":"","react-dom/server":"","react/jsx-runtime":"","react/jsx-dev-runtime":""});function I(t,e){if(!e)return!1;if(Object.prototype.hasOwnProperty.call(e,t))return!0;for(let r of Object.keys(e))if(r.endsWith("/")&&t.startsWith(r))return!0;return!1}function mt(t){try{return JSON.parse(t)?.imports??{}}catch{return{}}}function L(t=document){let e=t.querySelector(\'script[type="importmap"]\');return e?.textContent?mt(e.textContent):{}}var c="/_veryfront",U={RSC:`${c}/rsc/`,FS:`${c}/fs/`,MODULES:`${c}/modules/`,PAGES:`${c}/pages/`,DATA:`${c}/data/`,LIB:`${c}/lib/`,CHUNKS:`${c}/chunks/`,CLIENT:`${c}/client/`},G={HMR_RUNTIME:`${c}/hmr-runtime.js`,HMR:`${c}/hmr.js`,ERROR_OVERLAY:`${c}/error-overlay.js`,DEV_LOADER:`${c}/dev-loader.js`,CLIENT_LOG:`${c}/log`,CLIENT_JS:`${c}/client.js`,ROUTER_JS:`${c}/router.js`,PREFETCH_JS:`${c}/prefetch.js`,MANIFEST_JSON:`${c}/manifest.json`,APP_JS:`${c}/app.js`,RSC_CLIENT:`${c}/rsc/client.js`,RSC_MANIFEST:`${c}/rsc/manifest`,RSC_STREAM:`${c}/rsc/stream`,RSC_PAYLOAD:`${c}/rsc/payload`,RSC_RENDER:`${c}/rsc/render`,RSC_PAGE:`${c}/rsc/page`,RSC_MODULE:`${c}/rsc/module`,RSC_DOM:`${c}/rsc/dom.js`,LIB_CHAT_REACT:`${c}/lib/chat/react.js`,LIB_CHAT_COMPONENTS:`${c}/lib/chat/components.js`,LIB_CHAT_PRIMITIVES:`${c}/lib/chat/primitives.js`};var Rt={ROOT:".veryfront",CACHE:".veryfront/cache",KV:".veryfront/kv",LOGS:".veryfront/logs",TMP:".veryfront/tmp"},Ur=Rt.CACHE;var Pr={HMR_RUNTIME:G.HMR_RUNTIME,ERROR_OVERLAY:G.ERROR_OVERLAY};var _=U.RSC,Y=U.FS,B="veryfront-hydration-data",h="rsc-root";function S(t=document){try{let e=t.getElementById(B);return e?JSON.parse(e.textContent||"{}"):null}catch(e){return console.debug?.("[RSC] hydration data parse failed",e),null}}function C(t){return t?.clientModuleStrategy?t.clientModuleStrategy:t?.dev?"fs":"rsc-module"}function Et(t){return`${Y}${M(t)}.js`}function yt(t,e){let r=e?`&v=${encodeURIComponent(e)}`:"";return`${_}module?rel=${encodeURIComponent(t)}${r}`}function O(t){if(t.strategy==="fs"){let e=t.absPath??t.rel;return e?Et(e):null}return yt(t.rel,t.version)}function A(t=document,e=y){let r=L(t);return{react:I("react",r)?"react":$(e),reactDomClient:I("react-dom/client",r)?"react-dom/client":k(e)}}function j(t=document){let e=L(t);return I("veryfront/router",e)?"veryfront/router":null}function o(t){return{...t,create(e){return new P(e?.message||e?.detail||t.title,{slug:t.slug,category:t.category,status:e?.status??t.status,title:t.title,suggestion:t.suggestion,detail:e?.detail,cause:e?.cause,instance:e?.instance,context:e?.context})}}}var P=class extends Error{constructor(r,n){super(r);p(this,"slug");p(this,"category");p(this,"status");p(this,"title");p(this,"suggestion");p(this,"detail");p(this,"cause");p(this,"instance");p(this,"context");this.name="VeryfrontError",this.slug=n.slug,this.category=n.category,this.status=n.status,this.title=n.title,this.suggestion=n.suggestion,this.detail=n.detail,this.cause=n.cause,this.instance=n.instance,this.context=n.context}toRFC9457(){return{type:`https://veryfront.com/docs/errors/${this.slug}`,title:this.title,status:this.status,detail:this.detail,instance:this.instance,category:this.category,suggestion:this.suggestion,cause:typeof this.cause=="string"?this.cause:void 0}}getDocsUrl(){return`https://veryfront.com/docs/errors/${this.slug}`}};var _t=o({slug:"config-not-found",category:"CONFIG",status:404,title:"Configuration file not found",suggestion:"Run \'vf init\' to create a configuration file"}),ht=o({slug:"config-invalid",category:"CONFIG",status:400,title:"Invalid configuration format",suggestion:"Check your veryfront.config.ts for syntax errors"}),St=o({slug:"config-parse-error",category:"CONFIG",status:400,title:"Failed to parse configuration",suggestion:"Ensure your configuration file is valid TypeScript/JSON"}),xt=o({slug:"config-validation-error",category:"CONFIG",status:422,title:"Configuration validation failed",suggestion:"Check the configuration against the schema requirements"}),Tt=o({slug:"config-type-error",category:"CONFIG",status:400,title:"Configuration type mismatch",suggestion:"Ensure configuration values match expected types"}),It=o({slug:"import-map-invalid",category:"CONFIG",status:400,title:"Invalid import map configuration",suggestion:"Check your import map syntax and paths"}),Ct=o({slug:"cors-config-invalid",category:"CONFIG",status:400,title:"Invalid CORS configuration",suggestion:"Review CORS settings in your configuration"}),Ot=o({slug:"config-validation-failed",category:"CONFIG",status:400,title:"Configuration validation failed",suggestion:"Check configuration values against requirements"}),W={"config-not-found":_t,"config-invalid":ht,"config-parse-error":St,"config-validation-error":xt,"config-type-error":Tt,"import-map-invalid":It,"cors-config-invalid":Ct,"config-validation-failed":Ot};var At=o({slug:"build-failed",category:"BUILD",status:500,title:"Build process failed",suggestion:"Check the build output for specific errors"}),Nt=o({slug:"bundle-error",category:"BUILD",status:500,title:"Bundle generation failed",suggestion:"Review bundler output for details"}),Dt=o({slug:"typescript-error",category:"BUILD",status:500,title:"TypeScript compilation error",suggestion:"Fix TypeScript errors shown in the output"}),vt=o({slug:"mdx-compile-error",category:"BUILD",status:500,title:"MDX compilation failed",suggestion:"Check your MDX file syntax"}),bt=o({slug:"asset-optimization-error",category:"BUILD",status:500,title:"Asset optimization failed",suggestion:"Check asset file formats and paths"}),Mt=o({slug:"ssg-generation-error",category:"BUILD",status:500,title:"Static site generation failed",suggestion:"Review SSG configuration and data fetching"}),Lt=o({slug:"sourcemap-error",category:"BUILD",status:500,title:"Source map generation failed",suggestion:"Check source map configuration"}),Ut=o({slug:"compilation-error",category:"BUILD",status:500,title:"Compilation failed",suggestion:"Review compiler output for specific errors"}),q={"build-failed":At,"bundle-error":Nt,"typescript-error":Dt,"mdx-compile-error":vt,"asset-optimization-error":bt,"ssg-generation-error":Mt,"sourcemap-error":Lt,"compilation-error":Ut};var Pt=o({slug:"hydration-mismatch",category:"RUNTIME",status:500,title:"Client/server hydration mismatch",suggestion:"Ensure server and client render the same content"}),wt=o({slug:"render-error",category:"RUNTIME",status:500,title:"Component render failed",suggestion:"Check component for runtime errors"}),Ht=o({slug:"component-error",category:"RUNTIME",status:500,title:"Component execution error",suggestion:"Review component logic and props"}),Vt=o({slug:"layout-not-found",category:"RUNTIME",status:404,title:"Layout component not found",suggestion:"Ensure layout file exists at the expected path"}),Ft=o({slug:"page-not-found",category:"RUNTIME",status:404,title:"Page component not found",suggestion:"Check that the page file exists in the routes directory"}),$t=o({slug:"api-error",category:"RUNTIME",status:500,title:"API route handler error",suggestion:"Review API route handler for errors"}),kt=o({slug:"middleware-error",category:"RUNTIME",status:500,title:"Middleware execution error",suggestion:"Check middleware function for errors"}),z={"hydration-mismatch":Pt,"render-error":wt,"component-error":Ht,"layout-not-found":Vt,"page-not-found":Ft,"api-error":$t,"middleware-error":kt};var Gt=o({slug:"route-conflict",category:"ROUTE",status:409,title:"Conflicting route definitions",suggestion:"Rename or reorganize conflicting route files"}),Yt=o({slug:"invalid-route-file",category:"ROUTE",status:400,title:"Invalid route file structure",suggestion:"Ensure route file exports required functions"}),Bt=o({slug:"route-handler-invalid",category:"ROUTE",status:400,title:"Invalid route handler export",suggestion:"Export a valid handler function from the route file"}),jt=o({slug:"dynamic-route-error",category:"ROUTE",status:500,title:"Dynamic route parsing failed",suggestion:"Check dynamic route segment syntax"}),Wt=o({slug:"route-params-error",category:"ROUTE",status:400,title:"Route parameters invalid",suggestion:"Validate route parameter values"}),qt=o({slug:"api-route-error",category:"ROUTE",status:500,title:"API route definition error",suggestion:"Review API route configuration"}),X={"route-conflict":Gt,"invalid-route-file":Yt,"route-handler-invalid":Bt,"dynamic-route-error":jt,"route-params-error":Wt,"api-route-error":qt};var zt=o({slug:"module-not-found",category:"MODULE",status:404,title:"Module could not be resolved",suggestion:"Check the import path and ensure the module is installed"}),Xt=o({slug:"import-resolution-error",category:"MODULE",status:500,title:"Import path resolution failed",suggestion:"Verify import paths and module configuration"}),Jt=o({slug:"circular-dependency",category:"MODULE",status:500,title:"Circular dependency detected",suggestion:"Refactor imports to break the circular dependency"}),Kt=o({slug:"invalid-import",category:"MODULE",status:400,title:"Invalid import statement",suggestion:"Fix import syntax or path"}),Zt=o({slug:"dependency-missing",category:"MODULE",status:404,title:"Required dependency not installed",suggestion:"Install the missing dependency with your package manager"}),Qt=o({slug:"version-mismatch",category:"MODULE",status:409,title:"Dependency version mismatch",suggestion:"Update dependencies to compatible versions"}),J={"module-not-found":zt,"import-resolution-error":Xt,"circular-dependency":Jt,"invalid-import":Kt,"dependency-missing":Zt,"version-mismatch":Qt};var te=o({slug:"port-in-use",category:"SERVER",status:409,title:"Server port already in use",suggestion:"Use a different port or stop the process using this port"}),ee=o({slug:"server-start-error",category:"SERVER",status:500,title:"Server failed to start",suggestion:"Check server configuration and port availability"}),re=o({slug:"cache-error",category:"SERVER",status:500,title:"Cache operation failed",suggestion:"Clear the cache and try again"}),oe=o({slug:"file-watch-error",category:"SERVER",status:500,title:"File watcher error",suggestion:"Restart the development server"}),ne=o({slug:"request-error",category:"SERVER",status:500,title:"HTTP request handling error",suggestion:"Check request handler and middleware"}),se=o({slug:"service-overloaded",category:"SERVER",status:503,title:"Service overloaded",suggestion:"Reduce load or scale up resources"}),ie=o({slug:"semaphore-timeout",category:"SERVER",status:503,title:"Semaphore acquire timeout",suggestion:"Reduce concurrency or increase the semaphore acquire timeout"}),ae=o({slug:"circuit-breaker-open",category:"SERVER",status:503,title:"Circuit breaker is open",suggestion:"Wait for the breaker reset timeout before retrying"}),ce=o({slug:"cache-path-mismatch",category:"SERVER",status:500,title:"Cache path mismatch",suggestion:"Clear the cache directory and rebuild"}),le=o({slug:"network-error",category:"SERVER",status:502,title:"Network operation failed",suggestion:"Check network connectivity and retry"}),ue=o({slug:"api-client-error",category:"SERVER",status:500,title:"API client request failed",suggestion:"Check API connectivity and authentication"}),ge=o({slug:"token-storage-error",category:"SERVER",status:500,title:"Token storage operation failed",suggestion:"Check token storage backend and credentials"}),de=o({slug:"cache-invariant-violation",category:"SERVER",status:500,title:"Cache path invariant violated",suggestion:"Clear the cache and rebuild"}),pe=o({slug:"release-not-found",category:"SERVER",status:404,title:"No active release found",suggestion:"Deploy the project to create a release for this environment"}),me=o({slug:"fallback-exhausted",category:"SERVER",status:500,title:"Primary and fallback operations both failed",suggestion:"Check service availability and connectivity"}),K={"port-in-use":te,"server-start-error":ee,"cache-error":re,"file-watch-error":oe,"request-error":ne,"service-overloaded":se,"semaphore-timeout":ie,"circuit-breaker-open":ae,"cache-path-mismatch":ce,"network-error":le,"api-client-error":ue,"token-storage-error":ge,"cache-invariant-violation":de,"release-not-found":pe,"fallback-exhausted":me};var fe=o({slug:"client-boundary-violation",category:"BOUNDARY",status:400,title:"Client boundary rule violation",suggestion:"Add \'use client\' directive or move code to a client component"}),Re=o({slug:"server-only-in-client",category:"BOUNDARY",status:400,title:"Server-only code in client component",suggestion:"Move server-only code to a server component"}),Ee=o({slug:"client-only-in-server",category:"BOUNDARY",status:400,title:"Client-only code in server component",suggestion:"Move client-only code to a client component"}),ye=o({slug:"invalid-use-client",category:"BOUNDARY",status:400,title:"Invalid \'use client\' directive",suggestion:"Place \'use client\' at the top of the file"}),_e=o({slug:"invalid-use-server",category:"BOUNDARY",status:400,title:"Invalid \'use server\' directive",suggestion:"Place \'use server\' at the top of the file or function"}),he=o({slug:"rsc-payload-error",category:"BOUNDARY",status:500,title:"RSC payload serialization error",suggestion:"Ensure props are serializable (no functions, symbols, etc.)"}),Z={"client-boundary-violation":fe,"server-only-in-client":Re,"client-only-in-server":Ee,"invalid-use-client":ye,"invalid-use-server":_e,"rsc-payload-error":he};var Se=o({slug:"hmr-error",category:"DEV",status:500,title:"Hot module replacement error",suggestion:"Restart the development server"}),xe=o({slug:"dev-server-error",category:"DEV",status:500,title:"Development server error",suggestion:"Check the dev server logs and restart"}),Te=o({slug:"fast-refresh-error",category:"DEV",status:500,title:"Fast refresh failed",suggestion:"Save the file again or restart the dev server"}),Ie=o({slug:"error-overlay-error",category:"DEV",status:500,title:"Error overlay failed",suggestion:"Check browser console for details"}),Ce=o({slug:"source-map-error",category:"DEV",status:500,title:"Source map loading error",suggestion:"Rebuild or clear cache"}),Q={"hmr-error":Se,"dev-server-error":xe,"fast-refresh-error":Te,"error-overlay-error":Ie,"source-map-error":Ce};var Oe=o({slug:"deployment-error",category:"DEPLOY",status:500,title:"Deployment process failed",suggestion:"Check deployment logs for details"}),Ae=o({slug:"platform-error",category:"DEPLOY",status:500,title:"Platform-specific error",suggestion:"Check platform documentation and requirements"}),Ne=o({slug:"env-var-missing",category:"DEPLOY",status:500,title:"Required environment variable missing",suggestion:"Set the required environment variable"}),De=o({slug:"production-build-required",category:"DEPLOY",status:400,title:"Production build required",suggestion:"Run \'vf build\' before deploying"}),tt={"deployment-error":Oe,"platform-error":Ae,"env-var-missing":Ne,"production-build-required":De};var ve=o({slug:"agent-error",category:"AGENT",status:500,title:"Agent operation error",suggestion:"Check agent configuration and logs"}),be=o({slug:"agent-not-found",category:"AGENT",status:404,title:"Agent not found",suggestion:"Verify the agent ID exists"}),Me=o({slug:"agent-timeout",category:"AGENT",status:408,title:"Agent operation timed out",suggestion:"Increase timeout or simplify the request"}),Le=o({slug:"agent-intent-error",category:"AGENT",status:400,title:"Agent intent parsing error",suggestion:"Rephrase the request more clearly"}),Ue=o({slug:"orchestration-error",category:"AGENT",status:500,title:"Multi-agent orchestration error",suggestion:"Check agent coordination logic"}),Pe=o({slug:"cost-limit-exceeded",category:"AGENT",status:429,title:"Cost limit exceeded",suggestion:"Wait for the budget period to reset or increase the limit"}),we=o({slug:"tool-id-conflict",category:"AGENT",status:409,title:"Tool ID conflict",suggestion:"Use a unique tool ID or rename one of the conflicting tools"}),et={"agent-error":ve,"agent-not-found":be,"agent-timeout":Me,"agent-intent-error":Le,"orchestration-error":Ue,"cost-limit-exceeded":Pe,"tool-id-conflict":we};var He=o({slug:"unknown-error",category:"GENERAL",status:500,title:"Unknown/unclassified error",suggestion:"Check logs for more details"}),Ve=o({slug:"permission-denied",category:"GENERAL",status:403,title:"File/resource permission denied",suggestion:"Check file permissions and access rights"}),Fe=o({slug:"file-not-found",category:"GENERAL",status:404,title:"File not found",suggestion:"Verify the file path exists"}),$e=o({slug:"resource-not-found",category:"GENERAL",status:404,title:"Requested resource not found",suggestion:"Verify the referenced resource ID or name exists"}),ke=o({slug:"invalid-argument",category:"GENERAL",status:400,title:"Invalid function argument",suggestion:"Check argument types and values"}),Ge=o({slug:"timeout-error",category:"GENERAL",status:408,title:"Operation timed out",suggestion:"Increase timeout or optimize the operation"}),Ye=o({slug:"initialization-error",category:"GENERAL",status:500,title:"Initialization failed",suggestion:"Check initialization requirements and dependencies"}),Be=o({slug:"not-supported",category:"GENERAL",status:501,title:"Feature not supported",suggestion:"Check documentation for supported features"}),w=o({slug:"security-violation",category:"GENERAL",status:403,title:"Security violation detected",suggestion:"Check for path traversal or unauthorized access attempts"}),je=o({slug:"input-validation-failed",category:"GENERAL",status:400,title:"Input validation failed",suggestion:"Check request input against validation rules"}),rt={"unknown-error":He,"permission-denied":Ve,"file-not-found":Fe,"resource-not-found":$e,"invalid-argument":ke,"timeout-error":Ge,"initialization-error":Ye,"not-supported":Be,"security-violation":w,"input-validation-failed":je};var Lo={...W,...q,...z,...X,...J,...K,...Z,...Q,...tt,...et,...rt};var We=[{source:String.raw`<script[^>]*>[\\s\\S]*?<\\/script>`,flags:"gi",name:"inline script"},{source:String.raw`javascript:`,flags:"gi",name:"javascript: URL"},{source:String.raw`\\bon\\w+\\s*=`,flags:"gi",name:"event handler attribute"},{source:String.raw`data:\\s*text\\/html`,flags:"gi",name:"data: HTML URL"}];function qe(){return We.map(({source:t,flags:e,name:r})=>({pattern:new RegExp(t,e),name:r}))}function ze(){let t=globalThis;return t.__VERYFRONT_DEV__===!0||t.Deno?.env?.get?.("VERYFRONT_ENV")==="development"}function x(t,e={}){let{allowInlineScripts:r=!1,strict:n=!1,warn:s=!0}=e;for(let{pattern:l,name:i}of qe())if(!(r&&i==="inline script")&&(l.lastIndex=0,!!l.test(t)&&(s&&console.warn(`[Security] Suspicious ${i} detected in server HTML`),n||!ze())))throw w.create({detail:`Potentially unsafe HTML: ${i} detected`});return t}var R=class{constructor(e,r){p(this,"prefix",e);p(this,"level",r)}log(e,r,n,...s){this.level>e||r?.(n,...s)}debug(e,...r){this.log(0,console.debug,`[${this.prefix}] DEBUG: ${e}`,...r)}info(e,...r){this.log(1,console.log,`[${this.prefix}] ${e}`,...r)}warn(e,...r){this.log(2,console.warn,`[${this.prefix}] WARN: ${e}`,...r)}error(e,...r){this.log(3,console.error,`[${this.prefix}] ERROR: ${e}`,...r)}};function Xe(){if(typeof window>"u")return 2;let t=globalThis;return t.__VERYFRONT_DEV__||t.__RSC_DEV__?t.__VERYFRONT_DEBUG__||t.__RSC_DEBUG__?0:1:2}var N=Xe(),d=new R("RSC",N),Jo=new R("PREFETCH",N),Ko=new R("HYDRATE",N),Zo=new R("VERYFRONT",N);function T(t,e){let r=e==="root"?h:`rsc-slot-${e}`,n=t.getElementById(r);if(n)return n;let s=t.createElement("div");return s.id=r,t.body.appendChild(s),s}function Je(t,e){if(e.type!=="slot")return;let r=T(t,e.id);r.innerHTML=x(String(e.html??""))}function ot(t,e){let r=e.split(`\n`),n=r.pop()??"";for(let s of r){let l=s.trim();if(!l)continue;let i;try{i=JSON.parse(l)}catch(a){d.debug("[client-dom] malformed NDJSON line",{line:l,error:a instanceof Error?a.message:String(a)});continue}if(!i||typeof i!="object")continue;let g=i;if(g.type==="slot"){Je(t,g);try{Qe(t,g.id||"root")}catch(a){d.debug("[client-dom] hydration optional failed",a)}}}return n}function Ke(t){return new Promise((e,r)=>{let n=()=>r(new DOMException("aborted","AbortError"));if(t.aborted){n();return}t.addEventListener("abort",n,{once:!0})})}async function nt(t,e=document,r){let n="body"in t?t:null,s=n?.body??t;if(!s)return;let l=s.getReader(),i=new TextDecoder,g="",a=!1;try{for(;;){if(r?.aborted)throw new DOMException("aborted","AbortError");let u=l.read(),{done:m,value:E}=r?await Promise.race([u,Ke(r)]):await u;if(m){a=!0;break}g+=i.decode(E,{stream:!0}),g=ot(e,g)}g&&ot(e,`${g}\n`)}catch(u){throw u instanceof Error&&u.name==="AbortError"||d.debug("[client-dom] consumeNdjsonStream error",u),u}finally{try{await l.cancel()}catch(u){a||d.debug("[client-dom] reader.cancel failed",u)}try{l.releaseLock()}catch(u){d.debug("[client-dom] reader.releaseLock failed",u)}if(typeof s.cancel=="function")try{await s.cancel()}catch(u){d.debug("[client-dom] stream.cancel failed",u)}if(typeof n?.body?.cancel=="function")try{await n.body.cancel()}catch(u){d.debug("[client-dom] response.body.cancel failed",u)}}}function Ze(t,e){let r=T(t,e),n=[],s=l=>{let i=l;i.dataset?.clientRef&&n.push(i);for(let g of l.children)s(g)};return s(r),n}function Qe(t,e){let r=Ze(t,e);for(let n of r){let s=n.dataset?.clientRef;s&&(n.dataset.hydrated="true",d.debug("[client-dom] marked for hydration",s))}}function tr(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]=Array.isArray(n)?n.join("/"):n;return e}async function D(t,e,r=document){try{let n=j(r);if(!n)return t;let l=(await import(n)).wrapForHydration;return typeof l!="function"?t:l(t,{params:tr(e?.params),frontmatter:e?.frontmatter??{}})}catch(n){return console.debug?.("[RSC] router provider wrap failed",n),t}}var er=100;function rr(t,e){if(globalThis.__VF_CLIENT_MOD_CACHE??(globalThis.__VF_CLIENT_MOD_CACHE=new Map),globalThis.__VF_CLIENT_MOD_CACHE.size>=er){let r=globalThis.__VF_CLIENT_MOD_CACHE.keys().next().value;r&&globalThis.__VF_CLIENT_MOD_CACHE.delete(r)}globalThis.__VF_CLIENT_MOD_CACHE.set(t,e)}function or(t){let e=t.match(/^\\/app\\/(.+)#([A-Za-z0-9_]+)$/);return e?{rel:`/${e[1]||""}`,exportName:e[2]||"default"}:null}async function nr(){try{let t=await fetch("/_veryfront/rsc/manifest");return t.ok?await t.json():null}catch{return null}}async function sr(t,e,r){let n=t.graphIds?.client.find(i=>i.rel===e)?.path,s=`${e}#${t.hash??""}`;try{let i=globalThis.__VF_CLIENT_MOD_CACHE?.get(s);if(i)return i}catch(i){d.debug("hydrate: cache get failed",i)}let l=O({strategy:r,rel:e,absPath:n,version:t.hash});if(!l)return null;try{let i=await import(l);try{rr(s,i)}catch(g){d.debug("hydrate: cache set failed",g)}return i}catch(i){return d.debug("hydrate: failed to import module",{moduleUrl:l,error:i}),null}}async function st(t=document){let e=null;try{e=await nr()}catch(a){d.debug("hydrate: fetch manifest failed",a)}if(!e){d.debug("hydrate: no manifest");return}let r=Array.from(t.querySelectorAll("[data-client-ref]"));try{let a=globalThis.__VF_MANIFEST_HASH;if(!r.some(m=>m.dataset?.hydrated!=="true")&&a&&e.hash&&a===e.hash)return}catch(a){d.debug("hydrate: hmr hash read failed",a)}if(r.length===0){try{globalThis.__VF_MANIFEST_HASH=e.hash??""}catch(a){d.debug("hydrate: set hash failed",a)}return}let n=S(t),s=C(n);try{if(globalThis.__VF_TEST_MODE__){globalThis.__VF_HYDRATE_CALLED=!0,globalThis.__VF_MANIFEST_HASH=e.hash??"";return}}catch(a){d.debug("hydrate: test mode flags failed",a)}let l=A(t),[{default:i},{createRoot:g}]=await Promise.all([import(l.react),import(l.reactDomClient)]);for(let a of r){let u=a.dataset?.clientRef??"";if(!u||a.dataset?.hydrated==="true")continue;let m=or(u);if(!m)continue;let E=await sr(e,m.rel,s);if(!E)continue;let V=E[m.exportName]??E.default;if(typeof V=="function")try{let b=g(a),it=await D(i.createElement(V,{}),n,t);b.render(it),a.dataset.hydrated="true"}catch(b){d.warn("hydrate: render failed",b)}}try{globalThis.__VF_MANIFEST_HASH=e.hash??""}catch(a){d.debug("hydrate: set hash failed (post)",a)}}async function ir(){let t=A(document),[e,r]=await Promise.all([import(t.react),import(t.reactDomClient)]);return{React:e,ReactDOM:r}}var ar=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE"]);function H(t){let e=t.getAttribute("style")??"";return t.hasAttribute("data-veryfront-head")||t.hasAttribute("hidden")||/(?:^|;)\\s*display\\s*:\\s*none(?:\\s*;|$)/i.test(e)||ar.has(t.tagName.toUpperCase())}function cr(t,e){return t.find(r=>r.tagName.toUpperCase()==="DIV"&&!!r.getAttribute("class")?.trim()&&!H(r))??e}function lr(t,e){return t===e}function ur(t,e){let r=document.createElement("div");r.setAttribute("data-veryfront-hydration-root","page");let n=t.find(s=>!H(s));n?.parentNode===e?e.insertBefore(r,n):e.appendChild(r);for(let s of t)!H(s)&&s.parentNode===e&&r.appendChild(s);return r}function gr(t,e,r=document){return!!e?.pagePath&&typeof t?.__veryfrontRenderPage=="function"&&!!r.getElementById("root")}function dr(t,e){return e?.pagePath?!1:!!t.getElementById(h)}function pr(t=import.meta.url){try{return new URL(t,"http://veryfront.local").searchParams.get("hydrate")==="1"}catch{return!1}}function mr(t){return t==="rsc-module"}async function fr(t){try{let e=await fetch(_+"stream"+t);if(!e.ok||!e.body)return!1;let r=new AbortController;return addEventListener("pagehide",()=>r.abort(),{once:!0}),await nt(e,document,r.signal),!0}catch(e){return console.debug?.("[RSC] tryStream failed",e),!1}}async function v(){try{await st(document)}catch(t){console.debug?.("[RSC] hydration failed",t)}}async function Rr(t,e){try{let{React:r,ReactDOM:n}=await ir(),s=O({strategy:e,rel:t});if(!s)return!1;console.debug?.("[RSC] Loading component from:",s);let i=(await import(s)).default;if(typeof i!="function")return console.debug?.("[RSC] Page component is not a function"),!1;let g=Array.from(document.body.children),a=cr(g,document.body),u=lr(a,document.body)?ur(g,document.body):a,m=await D(r.createElement(i,{}),S(document));return mr(e)?n.createRoot(u).render(m):n.hydrateRoot(u,m,{identifierPrefix:"vf",onRecoverableError:()=>{}}),console.debug?.("[RSC] Page component hydrated successfully"),!0}catch(r){return console.error("[RSC] Page hydration failed",r),!1}}async function Er(t){try{let e=await fetch(_+"payload"+t);if(!e.ok)return!1;let r=await e.json();if(r?.slots){for(let[n,s]of Object.entries(r.slots))T(document,n).innerHTML=x(String(s||""));return!0}return T(document,h).innerHTML=x(String(r?.html||"")),!0}catch(e){return console.debug?.("[RSC] payload fetch failed",e),!1}}async function yr(){try{let t=globalThis.window?.location.search??"",e=S(document);if(pr()){await v();return}let r=e?.pagePath,n=C(e);if(r){if(gr(globalThis.window,e,document)){console.debug?.("[RSC] Page renderer owns hydration");return}console.debug?.("[RSC] Found page component in hydration data:",r),await Rr(r,n)&&console.debug?.("[RSC] Client component hydrated successfully");return}if(!dr(document,e))return;if(await fr(t)){await v();return}if(await Er(t)){await v();return}await v()}catch(t){console.error("[RSC] boot failed",t)}}if(typeof document<"u"){let t=()=>{yr()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}export{yr as boot,cr as selectHydrationRoot,dr as shouldAttemptRSCTransport,pr as shouldHydrateOnly,mr as shouldRenderPageComponent,gr as shouldUsePageRendererHydration,lr as shouldWrapPageHydrationRoot};\n';
9
9
  export const CLIENT_DOM_BUNDLE = 'var G=Object.defineProperty;var w=(r,t,o)=>t in r?G(r,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):r[t]=o;var l=(r,t,o)=>w(r,typeof t!="symbol"?t+"":t,o);function e(r){return{...r,create(t){return new f(t?.message||t?.detail||r.title,{slug:r.slug,category:r.category,status:t?.status??r.status,title:r.title,suggestion:r.suggestion,detail:t?.detail,cause:t?.cause,instance:t?.instance,context:t?.context})}}}var f=class extends Error{constructor(o,n){super(o);l(this,"slug");l(this,"category");l(this,"status");l(this,"title");l(this,"suggestion");l(this,"detail");l(this,"cause");l(this,"instance");l(this,"context");this.name="VeryfrontError",this.slug=n.slug,this.category=n.category,this.status=n.status,this.title=n.title,this.suggestion=n.suggestion,this.detail=n.detail,this.cause=n.cause,this.instance=n.instance,this.context=n.context}toRFC9457(){return{type:`https://veryfront.com/docs/errors/${this.slug}`,title:this.title,status:this.status,detail:this.detail,instance:this.instance,category:this.category,suggestion:this.suggestion,cause:typeof this.cause=="string"?this.cause:void 0}}getDocsUrl(){return`https://veryfront.com/docs/errors/${this.slug}`}};var F=e({slug:"config-not-found",category:"CONFIG",status:404,title:"Configuration file not found",suggestion:"Run \'vf init\' to create a configuration file"}),k=e({slug:"config-invalid",category:"CONFIG",status:400,title:"Invalid configuration format",suggestion:"Check your veryfront.config.ts for syntax errors"}),Y=e({slug:"config-parse-error",category:"CONFIG",status:400,title:"Failed to parse configuration",suggestion:"Ensure your configuration file is valid TypeScript/JSON"}),H=e({slug:"config-validation-error",category:"CONFIG",status:422,title:"Configuration validation failed",suggestion:"Check the configuration against the schema requirements"}),B=e({slug:"config-type-error",category:"CONFIG",status:400,title:"Configuration type mismatch",suggestion:"Ensure configuration values match expected types"}),$=e({slug:"import-map-invalid",category:"CONFIG",status:400,title:"Invalid import map configuration",suggestion:"Check your import map syntax and paths"}),j=e({slug:"cors-config-invalid",category:"CONFIG",status:400,title:"Invalid CORS configuration",suggestion:"Review CORS settings in your configuration"}),q=e({slug:"config-validation-failed",category:"CONFIG",status:400,title:"Configuration validation failed",suggestion:"Check configuration values against requirements"}),y={"config-not-found":F,"config-invalid":k,"config-parse-error":Y,"config-validation-error":H,"config-type-error":B,"import-map-invalid":$,"cors-config-invalid":j,"config-validation-failed":q};var z=e({slug:"build-failed",category:"BUILD",status:500,title:"Build process failed",suggestion:"Check the build output for specific errors"}),W=e({slug:"bundle-error",category:"BUILD",status:500,title:"Bundle generation failed",suggestion:"Review bundler output for details"}),J=e({slug:"typescript-error",category:"BUILD",status:500,title:"TypeScript compilation error",suggestion:"Fix TypeScript errors shown in the output"}),X=e({slug:"mdx-compile-error",category:"BUILD",status:500,title:"MDX compilation failed",suggestion:"Check your MDX file syntax"}),K=e({slug:"asset-optimization-error",category:"BUILD",status:500,title:"Asset optimization failed",suggestion:"Check asset file formats and paths"}),Z=e({slug:"ssg-generation-error",category:"BUILD",status:500,title:"Static site generation failed",suggestion:"Review SSG configuration and data fetching"}),Q=e({slug:"sourcemap-error",category:"BUILD",status:500,title:"Source map generation failed",suggestion:"Check source map configuration"}),ee=e({slug:"compilation-error",category:"BUILD",status:500,title:"Compilation failed",suggestion:"Review compiler output for specific errors"}),O={"build-failed":z,"bundle-error":W,"typescript-error":J,"mdx-compile-error":X,"asset-optimization-error":K,"ssg-generation-error":Z,"sourcemap-error":Q,"compilation-error":ee};var te=e({slug:"hydration-mismatch",category:"RUNTIME",status:500,title:"Client/server hydration mismatch",suggestion:"Ensure server and client render the same content"}),re=e({slug:"render-error",category:"RUNTIME",status:500,title:"Component render failed",suggestion:"Check component for runtime errors"}),oe=e({slug:"component-error",category:"RUNTIME",status:500,title:"Component execution error",suggestion:"Review component logic and props"}),ne=e({slug:"layout-not-found",category:"RUNTIME",status:404,title:"Layout component not found",suggestion:"Ensure layout file exists at the expected path"}),se=e({slug:"page-not-found",category:"RUNTIME",status:404,title:"Page component not found",suggestion:"Check that the page file exists in the routes directory"}),ie=e({slug:"api-error",category:"RUNTIME",status:500,title:"API route handler error",suggestion:"Review API route handler for errors"}),ae=e({slug:"middleware-error",category:"RUNTIME",status:500,title:"Middleware execution error",suggestion:"Check middleware function for errors"}),I={"hydration-mismatch":te,"render-error":re,"component-error":oe,"layout-not-found":ne,"page-not-found":se,"api-error":ie,"middleware-error":ae};var ce=e({slug:"route-conflict",category:"ROUTE",status:409,title:"Conflicting route definitions",suggestion:"Rename or reorganize conflicting route files"}),ue=e({slug:"invalid-route-file",category:"ROUTE",status:400,title:"Invalid route file structure",suggestion:"Ensure route file exports required functions"}),le=e({slug:"route-handler-invalid",category:"ROUTE",status:400,title:"Invalid route handler export",suggestion:"Export a valid handler function from the route file"}),ge=e({slug:"dynamic-route-error",category:"ROUTE",status:500,title:"Dynamic route parsing failed",suggestion:"Check dynamic route segment syntax"}),pe=e({slug:"route-params-error",category:"ROUTE",status:400,title:"Route parameters invalid",suggestion:"Validate route parameter values"}),Ee=e({slug:"api-route-error",category:"ROUTE",status:500,title:"API route definition error",suggestion:"Review API route configuration"}),T={"route-conflict":ce,"invalid-route-file":ue,"route-handler-invalid":le,"dynamic-route-error":ge,"route-params-error":pe,"api-route-error":Ee};var de=e({slug:"module-not-found",category:"MODULE",status:404,title:"Module could not be resolved",suggestion:"Check the import path and ensure the module is installed"}),Re=e({slug:"import-resolution-error",category:"MODULE",status:500,title:"Import path resolution failed",suggestion:"Verify import paths and module configuration"}),fe=e({slug:"circular-dependency",category:"MODULE",status:500,title:"Circular dependency detected",suggestion:"Refactor imports to break the circular dependency"}),me=e({slug:"invalid-import",category:"MODULE",status:400,title:"Invalid import statement",suggestion:"Fix import syntax or path"}),_e=e({slug:"dependency-missing",category:"MODULE",status:404,title:"Required dependency not installed",suggestion:"Install the missing dependency with your package manager"}),ye=e({slug:"version-mismatch",category:"MODULE",status:409,title:"Dependency version mismatch",suggestion:"Update dependencies to compatible versions"}),x={"module-not-found":de,"import-resolution-error":Re,"circular-dependency":fe,"invalid-import":me,"dependency-missing":_e,"version-mismatch":ye};var Oe=e({slug:"port-in-use",category:"SERVER",status:409,title:"Server port already in use",suggestion:"Use a different port or stop the process using this port"}),Ie=e({slug:"server-start-error",category:"SERVER",status:500,title:"Server failed to start",suggestion:"Check server configuration and port availability"}),Te=e({slug:"cache-error",category:"SERVER",status:500,title:"Cache operation failed",suggestion:"Clear the cache and try again"}),xe=e({slug:"file-watch-error",category:"SERVER",status:500,title:"File watcher error",suggestion:"Restart the development server"}),Se=e({slug:"request-error",category:"SERVER",status:500,title:"HTTP request handling error",suggestion:"Check request handler and middleware"}),he=e({slug:"service-overloaded",category:"SERVER",status:503,title:"Service overloaded",suggestion:"Reduce load or scale up resources"}),Ne=e({slug:"semaphore-timeout",category:"SERVER",status:503,title:"Semaphore acquire timeout",suggestion:"Reduce concurrency or increase the semaphore acquire timeout"}),Ae=e({slug:"circuit-breaker-open",category:"SERVER",status:503,title:"Circuit breaker is open",suggestion:"Wait for the breaker reset timeout before retrying"}),ve=e({slug:"cache-path-mismatch",category:"SERVER",status:500,title:"Cache path mismatch",suggestion:"Clear the cache directory and rebuild"}),Ce=e({slug:"network-error",category:"SERVER",status:502,title:"Network operation failed",suggestion:"Check network connectivity and retry"}),De=e({slug:"api-client-error",category:"SERVER",status:500,title:"API client request failed",suggestion:"Check API connectivity and authentication"}),Le=e({slug:"token-storage-error",category:"SERVER",status:500,title:"Token storage operation failed",suggestion:"Check token storage backend and credentials"}),Ue=e({slug:"cache-invariant-violation",category:"SERVER",status:500,title:"Cache path invariant violated",suggestion:"Clear the cache and rebuild"}),be=e({slug:"release-not-found",category:"SERVER",status:404,title:"No active release found",suggestion:"Deploy the project to create a release for this environment"}),Me=e({slug:"fallback-exhausted",category:"SERVER",status:500,title:"Primary and fallback operations both failed",suggestion:"Check service availability and connectivity"}),S={"port-in-use":Oe,"server-start-error":Ie,"cache-error":Te,"file-watch-error":xe,"request-error":Se,"service-overloaded":he,"semaphore-timeout":Ne,"circuit-breaker-open":Ae,"cache-path-mismatch":ve,"network-error":Ce,"api-client-error":De,"token-storage-error":Le,"cache-invariant-violation":Ue,"release-not-found":be,"fallback-exhausted":Me};var Pe=e({slug:"client-boundary-violation",category:"BOUNDARY",status:400,title:"Client boundary rule violation",suggestion:"Add \'use client\' directive or move code to a client component"}),Ve=e({slug:"server-only-in-client",category:"BOUNDARY",status:400,title:"Server-only code in client component",suggestion:"Move server-only code to a server component"}),Ge=e({slug:"client-only-in-server",category:"BOUNDARY",status:400,title:"Client-only code in server component",suggestion:"Move client-only code to a client component"}),we=e({slug:"invalid-use-client",category:"BOUNDARY",status:400,title:"Invalid \'use client\' directive",suggestion:"Place \'use client\' at the top of the file"}),Fe=e({slug:"invalid-use-server",category:"BOUNDARY",status:400,title:"Invalid \'use server\' directive",suggestion:"Place \'use server\' at the top of the file or function"}),ke=e({slug:"rsc-payload-error",category:"BOUNDARY",status:500,title:"RSC payload serialization error",suggestion:"Ensure props are serializable (no functions, symbols, etc.)"}),h={"client-boundary-violation":Pe,"server-only-in-client":Ve,"client-only-in-server":Ge,"invalid-use-client":we,"invalid-use-server":Fe,"rsc-payload-error":ke};var Ye=e({slug:"hmr-error",category:"DEV",status:500,title:"Hot module replacement error",suggestion:"Restart the development server"}),He=e({slug:"dev-server-error",category:"DEV",status:500,title:"Development server error",suggestion:"Check the dev server logs and restart"}),Be=e({slug:"fast-refresh-error",category:"DEV",status:500,title:"Fast refresh failed",suggestion:"Save the file again or restart the dev server"}),$e=e({slug:"error-overlay-error",category:"DEV",status:500,title:"Error overlay failed",suggestion:"Check browser console for details"}),je=e({slug:"source-map-error",category:"DEV",status:500,title:"Source map loading error",suggestion:"Rebuild or clear cache"}),N={"hmr-error":Ye,"dev-server-error":He,"fast-refresh-error":Be,"error-overlay-error":$e,"source-map-error":je};var qe=e({slug:"deployment-error",category:"DEPLOY",status:500,title:"Deployment process failed",suggestion:"Check deployment logs for details"}),ze=e({slug:"platform-error",category:"DEPLOY",status:500,title:"Platform-specific error",suggestion:"Check platform documentation and requirements"}),We=e({slug:"env-var-missing",category:"DEPLOY",status:500,title:"Required environment variable missing",suggestion:"Set the required environment variable"}),Je=e({slug:"production-build-required",category:"DEPLOY",status:400,title:"Production build required",suggestion:"Run \'vf build\' before deploying"}),A={"deployment-error":qe,"platform-error":ze,"env-var-missing":We,"production-build-required":Je};var Xe=e({slug:"agent-error",category:"AGENT",status:500,title:"Agent operation error",suggestion:"Check agent configuration and logs"}),Ke=e({slug:"agent-not-found",category:"AGENT",status:404,title:"Agent not found",suggestion:"Verify the agent ID exists"}),Ze=e({slug:"agent-timeout",category:"AGENT",status:408,title:"Agent operation timed out",suggestion:"Increase timeout or simplify the request"}),Qe=e({slug:"agent-intent-error",category:"AGENT",status:400,title:"Agent intent parsing error",suggestion:"Rephrase the request more clearly"}),et=e({slug:"orchestration-error",category:"AGENT",status:500,title:"Multi-agent orchestration error",suggestion:"Check agent coordination logic"}),tt=e({slug:"cost-limit-exceeded",category:"AGENT",status:429,title:"Cost limit exceeded",suggestion:"Wait for the budget period to reset or increase the limit"}),rt=e({slug:"tool-id-conflict",category:"AGENT",status:409,title:"Tool ID conflict",suggestion:"Use a unique tool ID or rename one of the conflicting tools"}),v={"agent-error":Xe,"agent-not-found":Ke,"agent-timeout":Ze,"agent-intent-error":Qe,"orchestration-error":et,"cost-limit-exceeded":tt,"tool-id-conflict":rt};var ot=e({slug:"unknown-error",category:"GENERAL",status:500,title:"Unknown/unclassified error",suggestion:"Check logs for more details"}),nt=e({slug:"permission-denied",category:"GENERAL",status:403,title:"File/resource permission denied",suggestion:"Check file permissions and access rights"}),st=e({slug:"file-not-found",category:"GENERAL",status:404,title:"File not found",suggestion:"Verify the file path exists"}),it=e({slug:"resource-not-found",category:"GENERAL",status:404,title:"Requested resource not found",suggestion:"Verify the referenced resource ID or name exists"}),at=e({slug:"invalid-argument",category:"GENERAL",status:400,title:"Invalid function argument",suggestion:"Check argument types and values"}),ct=e({slug:"timeout-error",category:"GENERAL",status:408,title:"Operation timed out",suggestion:"Increase timeout or optimize the operation"}),ut=e({slug:"initialization-error",category:"GENERAL",status:500,title:"Initialization failed",suggestion:"Check initialization requirements and dependencies"}),lt=e({slug:"not-supported",category:"GENERAL",status:501,title:"Feature not supported",suggestion:"Check documentation for supported features"}),m=e({slug:"security-violation",category:"GENERAL",status:403,title:"Security violation detected",suggestion:"Check for path traversal or unauthorized access attempts"}),gt=e({slug:"input-validation-failed",category:"GENERAL",status:400,title:"Input validation failed",suggestion:"Check request input against validation rules"}),C={"unknown-error":ot,"permission-denied":nt,"file-not-found":st,"resource-not-found":it,"invalid-argument":at,"timeout-error":ct,"initialization-error":ut,"not-supported":lt,"security-violation":m,"input-validation-failed":gt};var lr={...y,...O,...I,...T,...x,...S,...h,...N,...A,...v,...C};var pt=[{source:String.raw`<script[^>]*>[\\s\\S]*?<\\/script>`,flags:"gi",name:"inline script"},{source:String.raw`javascript:`,flags:"gi",name:"javascript: URL"},{source:String.raw`\\bon\\w+\\s*=`,flags:"gi",name:"event handler attribute"},{source:String.raw`data:\\s*text\\/html`,flags:"gi",name:"data: HTML URL"}];function Et(){return pt.map(({source:r,flags:t,name:o})=>({pattern:new RegExp(r,t),name:o}))}function dt(){let r=globalThis;return r.__VERYFRONT_DEV__===!0||r.Deno?.env?.get?.("VERYFRONT_ENV")==="development"}function D(r,t={}){let{allowInlineScripts:o=!1,strict:n=!1,warn:i=!0}=t;for(let{pattern:c,name:u}of Et())if(!(o&&u==="inline script")&&(c.lastIndex=0,!!c.test(r)&&(i&&console.warn(`[Security] Suspicious ${u} detected in server HTML`),n||!dt())))throw m.create({detail:`Potentially unsafe HTML: ${u} detected`});return r}var d=class{constructor(t,o){l(this,"prefix",t);l(this,"level",o)}log(t,o,n,...i){this.level>t||o?.(n,...i)}debug(t,...o){this.log(0,console.debug,`[${this.prefix}] DEBUG: ${t}`,...o)}info(t,...o){this.log(1,console.log,`[${this.prefix}] ${t}`,...o)}warn(t,...o){this.log(2,console.warn,`[${this.prefix}] WARN: ${t}`,...o)}error(t,...o){this.log(3,console.error,`[${this.prefix}] ERROR: ${t}`,...o)}};function Rt(){if(typeof window>"u")return 2;let r=globalThis;return r.__VERYFRONT_DEV__||r.__RSC_DEV__?r.__VERYFRONT_DEBUG__||r.__RSC_DEBUG__?0:1:2}var R=Rt(),p=new d("RSC",R),Ar=new d("PREFETCH",R),vr=new d("HYDRATE",R),Cr=new d("VERYFRONT",R);var s="/_veryfront",_={RSC:`${s}/rsc/`,FS:`${s}/fs/`,MODULES:`${s}/modules/`,PAGES:`${s}/pages/`,DATA:`${s}/data/`,LIB:`${s}/lib/`,CHUNKS:`${s}/chunks/`,CLIENT:`${s}/client/`},L={HMR_RUNTIME:`${s}/hmr-runtime.js`,HMR:`${s}/hmr.js`,ERROR_OVERLAY:`${s}/error-overlay.js`,DEV_LOADER:`${s}/dev-loader.js`,CLIENT_LOG:`${s}/log`,CLIENT_JS:`${s}/client.js`,ROUTER_JS:`${s}/router.js`,PREFETCH_JS:`${s}/prefetch.js`,MANIFEST_JSON:`${s}/manifest.json`,APP_JS:`${s}/app.js`,RSC_CLIENT:`${s}/rsc/client.js`,RSC_MANIFEST:`${s}/rsc/manifest`,RSC_STREAM:`${s}/rsc/stream`,RSC_PAYLOAD:`${s}/rsc/payload`,RSC_RENDER:`${s}/rsc/render`,RSC_PAGE:`${s}/rsc/page`,RSC_MODULE:`${s}/rsc/module`,RSC_DOM:`${s}/rsc/dom.js`,LIB_CHAT_REACT:`${s}/lib/chat/react.js`,LIB_CHAT_COMPONENTS:`${s}/lib/chat/components.js`,LIB_CHAT_PRIMITIVES:`${s}/lib/chat/primitives.js`};var mt={ROOT:".veryfront",CACHE:".veryfront/cache",KV:".veryfront/kv",LOGS:".veryfront/logs",TMP:".veryfront/tmp"},Pr=mt.CACHE;var Vr={HMR_RUNTIME:L.HMR_RUNTIME,ERROR_OVERLAY:L.ERROR_OVERLAY};var kr=_.RSC,Yr=_.FS;var U="rsc-root";function M(r,t){let o=t==="root"?U:`rsc-slot-${t}`,n=r.getElementById(o);if(n)return n;let i=r.createElement("div");return i.id=o,r.body.appendChild(i),i}function _t(r,t){if(t.type!=="slot")return;let o=M(r,t.id);o.innerHTML=D(String(t.html??""))}function b(r,t){let o=t.split(`\n`),n=o.pop()??"";for(let i of o){let c=i.trim();if(!c)continue;let u;try{u=JSON.parse(c)}catch(E){p.debug("[client-dom] malformed NDJSON line",{line:c,error:E instanceof Error?E.message:String(E)});continue}if(!u||typeof u!="object")continue;let g=u;if(g.type==="slot"){_t(r,g);try{It(r,g.id||"root")}catch(E){p.debug("[client-dom] hydration optional failed",E)}}}return n}function yt(r){return new Promise((t,o)=>{let n=()=>o(new DOMException("aborted","AbortError"));if(r.aborted){n();return}r.addEventListener("abort",n,{once:!0})})}async function qr(r,t=document,o){let n="body"in r?r:null,i=n?.body??r;if(!i)return;let c=i.getReader(),u=new TextDecoder,g="",E=!1;try{for(;;){if(o?.aborted)throw new DOMException("aborted","AbortError");let a=c.read(),{done:P,value:V}=o?await Promise.race([a,yt(o)]):await a;if(P){E=!0;break}g+=u.decode(V,{stream:!0}),g=b(t,g)}g&&b(t,`${g}\n`)}catch(a){throw a instanceof Error&&a.name==="AbortError"||p.debug("[client-dom] consumeNdjsonStream error",a),a}finally{try{await c.cancel()}catch(a){E||p.debug("[client-dom] reader.cancel failed",a)}try{c.releaseLock()}catch(a){p.debug("[client-dom] reader.releaseLock failed",a)}if(typeof i.cancel=="function")try{await i.cancel()}catch(a){p.debug("[client-dom] stream.cancel failed",a)}if(typeof n?.body?.cancel=="function")try{await n.body.cancel()}catch(a){p.debug("[client-dom] response.body.cancel failed",a)}}}function Ot(r,t){let o=M(r,t),n=[],i=c=>{let u=c;u.dataset?.clientRef&&n.push(u);for(let g of c.children)i(g)};return i(o),n}function It(r,t){let o=Ot(r,t);for(let n of o){let i=n.dataset?.clientRef;i&&(n.dataset.hydrated="true",p.debug("[client-dom] marked for hydration",i))}}export{qr as consumeNdjsonStream,M as getContainer};\n';
@@ -1,3 +1,3 @@
1
1
  /** Shared version value. */
2
- export declare const VERSION = "0.1.991";
2
+ export declare const VERSION = "0.1.993";
3
3
  //# sourceMappingURL=version-constant.d.ts.map
@@ -1,4 +1,4 @@
1
1
  // Keep in sync with deno.json version.
2
2
  // scripts/release.ts updates this constant during releases.
3
3
  /** Shared version value. */
4
- export const VERSION = "0.1.991";
4
+ export const VERSION = "0.1.993";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "veryfront",
3
- "version": "0.1.991",
3
+ "version": "0.1.993",
4
4
  "description": "The simplest way to build AI-powered apps",
5
5
  "keywords": [
6
6
  "react",