elysia 2.0.0-beta.19 → 2.0.0-beta.20

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 (79) hide show
  1. package/dist/adapter/web-standard/handler.js +1 -0
  2. package/dist/adapter/web-standard/handler.mjs +1 -0
  3. package/dist/base.d.ts +3 -3
  4. package/dist/base.js +30 -3
  5. package/dist/base.mjs +31 -4
  6. package/dist/compile/aot-capture.js +4 -4
  7. package/dist/compile/aot-capture.mjs +5 -5
  8. package/dist/compile/aot-emit.d.ts +9 -7
  9. package/dist/compile/aot-emit.js +40 -9
  10. package/dist/compile/aot-emit.mjs +40 -10
  11. package/dist/compile/handler/index.js +26 -6
  12. package/dist/compile/handler/index.mjs +27 -7
  13. package/dist/compile/handler/jit.d.ts +5 -0
  14. package/dist/compile/handler/jit.js +19 -14
  15. package/dist/compile/handler/jit.mjs +20 -15
  16. package/dist/compile/handler/params.js +4 -0
  17. package/dist/compile/handler/params.mjs +5 -1
  18. package/dist/handler/error.js +3 -2
  19. package/dist/handler/error.mjs +3 -2
  20. package/dist/handler/utils.d.ts +5 -1
  21. package/dist/handler/utils.js +24 -1
  22. package/dist/handler/utils.mjs +23 -2
  23. package/dist/index.js +1 -1
  24. package/dist/index.mjs +1 -1
  25. package/dist/package.js +1 -1
  26. package/dist/package.mjs +1 -1
  27. package/dist/plugin/aot/bun.d.ts +8 -1
  28. package/dist/plugin/aot/bun.js +16 -6
  29. package/dist/plugin/aot/bun.mjs +17 -7
  30. package/dist/plugin/aot/core.d.ts +3 -2
  31. package/dist/plugin/aot/core.js +6 -0
  32. package/dist/plugin/aot/core.mjs +6 -1
  33. package/dist/plugin/aot/hooks.d.ts +2 -1
  34. package/dist/plugin/aot/hooks.js +21 -2
  35. package/dist/plugin/aot/hooks.mjs +22 -4
  36. package/dist/sucrose.js +7 -2
  37. package/dist/sucrose.mjs +7 -2
  38. package/dist/type/bridge-live.d.ts +1 -1
  39. package/dist/type/bridge-live.js +1 -1
  40. package/dist/type/bridge-live.mjs +1 -1
  41. package/dist/type/bridge.d.ts +1 -1
  42. package/dist/type/coerce.d.ts +1 -1
  43. package/dist/type/constants.d.ts +1 -1
  44. package/dist/type/elysia/file-type.d.ts +1 -1
  45. package/dist/type/elysia/file-type.js +1 -1
  46. package/dist/type/elysia/file-type.mjs +1 -1
  47. package/dist/type/elysia/file.js +1 -1
  48. package/dist/type/elysia/file.mjs +1 -1
  49. package/dist/type/index.js +1 -1
  50. package/dist/type/index.mjs +1 -1
  51. package/dist/type/typebox-system-require.js +1 -1
  52. package/dist/type/typebox-system-require.mjs +1 -1
  53. package/dist/type/typebox-type-live.d.ts +1 -1
  54. package/dist/type/typebox-type-live.js +8 -6
  55. package/dist/type/typebox-type-live.mjs +5 -3
  56. package/dist/type/typebox-value-live.d.ts +2 -2
  57. package/dist/type/typebox-value-live.js +2 -2
  58. package/dist/type/typebox-value-live.mjs +2 -2
  59. package/dist/type/typebox-value-ops.d.ts +2 -2
  60. package/dist/type/typebox-value-ops.js +2 -2
  61. package/dist/type/typebox-value-ops.mjs +2 -2
  62. package/dist/type/typebox-value.d.ts +6 -6
  63. package/dist/type/validator/frozen-check.js +5 -6
  64. package/dist/type/validator/frozen-check.mjs +6 -7
  65. package/dist/type/validator/index.d.ts +1 -0
  66. package/dist/type/validator/index.js +27 -8
  67. package/dist/type/validator/index.mjs +28 -9
  68. package/dist/type/validator/string-codec-aot.d.ts +2 -1
  69. package/dist/type/validator/string-codec-aot.js +8 -2
  70. package/dist/type/validator/string-codec-aot.mjs +7 -2
  71. package/dist/types.d.ts +167 -23
  72. package/dist/utils.d.ts +14 -2
  73. package/dist/utils.js +18 -4
  74. package/dist/utils.mjs +18 -5
  75. package/dist/validator/index.js +2 -3
  76. package/dist/validator/index.mjs +2 -3
  77. package/dist/ws/route.js +1 -1
  78. package/dist/ws/route.mjs +1 -1
  79. package/package.json +1 -1
@@ -23,6 +23,7 @@ function handleElysiaFile(file, set = { headers: require_utils.nullObject() }, r
23
23
  return require_adapter_utils.handleFile(file.value, set, request);
24
24
  }
25
25
  function responseTag(response) {
26
+ if (typeof response === "string") return "String";
26
27
  if (response == null) return;
27
28
  const constructor = Object.getPrototypeOf(response)?.constructor;
28
29
  if (typeof constructor !== "function") return typeof response.next === "function" ? "" : void 0;
@@ -22,6 +22,7 @@ function handleElysiaFile(file, set = { headers: nullObject() }, request) {
22
22
  return handleFile(file.value, set, request);
23
23
  }
24
24
  function responseTag(response) {
25
+ if (typeof response === "string") return "String";
25
26
  if (response == null) return;
26
27
  const constructor = Object.getPrototypeOf(response)?.constructor;
27
28
  if (typeof constructor !== "function") return typeof response.next === "function" ? "" : void 0;
package/dist/base.d.ts CHANGED
@@ -4,7 +4,7 @@ import { ChainNode } from "./utils.js";
4
4
  import { ListenCallback, Serve, Server } from "./universal/server.js";
5
5
  import { Context, ErrorContext, LifecycleContext } from "./context.js";
6
6
  import { TraceCapability, TraceHandler } from "./trace.js";
7
- import { AddRoute, AddWSRoute, AfterHandler, AfterResponseHandler, AnyErrorConstructor, AnyLocalHook, BodyHandler, CompiledHandler, CreateEden, DefaultEphemeral, DefaultMetadata, DefaultSingleton, DefinitionBase, ElysiaConfig, ElysiaHandlerToResponseSchemaAmbiguous, EphemeralType, ErrorDefinitionEntry, ErrorHandler, EventScope, ExcludeElysiaResponse, ExtractErrorFromHandle, GlobalHookReturn, GracefulHandler, GuardHookSingleton, GuardLocalHook, HTTPMethod, HistoryEntry, HookContextSchema, HookContextSingleton, InlineHandler, InlineHandlerNonMacro, InputSchema, InputSchemaKey, InternalRoute, IntersectIfObjectSchema, JoinPath, LocalHook, LocalHookReturn, Macro, MacroToContext, MacroToProperty, MapResponse, MaybeArray, MaybePromise, MergeElysiaInstances, MergeSchema, MergeScopedSchemas, MetadataBase, ObjectMacroDefs, OptionalHandler, PluginHookReturn, PreHandler, Prettify, PublicRoute, ResolveRouteErrors, RouteBase, ScopedHookReturn, ScopedMapDeriveReturn, SingletonBase, StaticMapAliases, TransformHandler, UnionResponseStatus, UnwrapRoute, WrapFn } from "./types.js";
7
+ import { AddRoute, AddWSRoute, AfterHandler, AfterResponseHandler, AnyErrorConstructor, AnyLocalHook, BodyHandler, CompiledHandler, CreateEden, DefaultEphemeral, DefaultMetadata, DefaultSingleton, DefinitionBase, ElysiaConfig, ElysiaHandlerToResponseSchemaAmbiguous, EphemeralType, ErrorDefinitionEntry, ErrorHandler, EventScope, ExcludeElysiaResponse, ExtractErrorFromHandle, GlobalHookReturn, GracefulHandler, GuardHookSingleton, GuardLocalHook, HTTPMethod, HistoryEntry, HookContextSchema, HookContextSingleton, InlineHandler, InlineHandlerNonMacro, InputSchema, InputSchemaKey, InternalRoute, IntersectIfObjectSchema, JoinPath, LocalHook, LocalHookReturn, Macro, MacroToContext, MacroToProperty, MapResponse, MaybeArray, MaybePromise, MergeElysiaInstances, MergeSchema, MergeScopedSchemas, MetadataBase, ObjectMacroDefs, OptionalHandler, ParentResponse, PluginHookReturn, PreHandler, Prettify, PublicRoute, ResolveRouteErrors, ResolveUsedRouteErrors, RouteBase, ScopedHookReturn, ScopedMapDeriveReturn, SingletonBase, StaticMapAliases, TransformHandler, UnionResponseStatus, UnwrapRoute, WrapFn } from "./types.js";
8
8
  import { AotFingerprint, CompilerSession, ProgramId } from "./compile/aot.js";
9
9
  import { WSCapability, WSHandlerResponse, WSLocalHook, WSMessageHandler, WSOptions, WSOptionsEntry } from "./ws/types.js";
10
10
  import { RouteTable } from "./route-table.js";
@@ -583,7 +583,7 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
583
583
  }, {
584
584
  typebox: Definitions['typebox'] & NewElysia['~Definitions']['typebox'];
585
585
  error: [...Definitions['error'], ...NewElysia['~Definitions']['error']];
586
- }, Metadata & NewElysia['~Metadata'], BasePath extends `` ? ResolveRouteErrors<Routes, [...NewElysia['~Definitions']['error'], ...NewElysia['~Ephemeral']['error']]> & ResolveRouteErrors<NewElysia['~Routes'], [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']]> : ResolveRouteErrors<Routes, [...NewElysia['~Definitions']['error'], ...NewElysia['~Ephemeral']['error']]> & CreateEden<BasePath, ResolveRouteErrors<NewElysia['~Routes'], [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']]>>, Ephemeral, {
586
+ }, Metadata & NewElysia['~Metadata'], BasePath extends `` ? ResolveRouteErrors<Routes, [...NewElysia['~Definitions']['error'], ...NewElysia['~Ephemeral']['error']]> & ResolveUsedRouteErrors<NewElysia['~Routes'], [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']], ParentResponse<Metadata, Ephemeral, Volatile>> : ResolveRouteErrors<Routes, [...NewElysia['~Definitions']['error'], ...NewElysia['~Ephemeral']['error']]> & CreateEden<BasePath, ResolveUsedRouteErrors<NewElysia['~Routes'], [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']], ParentResponse<Metadata, Ephemeral, Volatile>>>, Ephemeral, {
587
587
  derive: Volatile['derive'] & NewElysia['~Ephemeral']['derive'];
588
588
  schema: Volatile['schema'] & NewElysia['~Ephemeral']['schema'];
589
589
  schemas: Volatile['schemas'] & NewElysia['~Ephemeral']['schemas'];
@@ -629,7 +629,7 @@ declare class Elysia<const in out BasePath extends string = '', const in out Sco
629
629
  }, {
630
630
  typebox: Definitions['typebox'] & NewElysia['~Definitions']['typebox'];
631
631
  error: [...Definitions['error'], ...NewElysia['~Definitions']['error']];
632
- }, Metadata & NewElysia['~Metadata'], BasePath extends `` ? ResolveRouteErrors<Routes, [...NewElysia['~Definitions']['error'], ...NewElysia['~Ephemeral']['error']]> & ResolveRouteErrors<NewElysia['~Routes'], [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']]> : ResolveRouteErrors<Routes, [...NewElysia['~Definitions']['error'], ...NewElysia['~Ephemeral']['error']]> & CreateEden<BasePath, ResolveRouteErrors<NewElysia['~Routes'], [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']]>>, Ephemeral, {
632
+ }, Metadata & NewElysia['~Metadata'], BasePath extends `` ? ResolveRouteErrors<Routes, [...NewElysia['~Definitions']['error'], ...NewElysia['~Ephemeral']['error']]> & ResolveUsedRouteErrors<NewElysia['~Routes'], [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']], ParentResponse<Metadata, Ephemeral, Volatile>> : ResolveRouteErrors<Routes, [...NewElysia['~Definitions']['error'], ...NewElysia['~Ephemeral']['error']]> & CreateEden<BasePath, ResolveUsedRouteErrors<NewElysia['~Routes'], [...Definitions['error'], ...Ephemeral['error'], ...Volatile['error']], ParentResponse<Metadata, Ephemeral, Volatile>>>, Ephemeral, {
633
633
  derive: Volatile['derive'] & Partial<NewElysia['~Ephemeral']['derive']>;
634
634
  schema: Volatile['schema'] & NewElysia['~Ephemeral']['schema'];
635
635
  schemas: Volatile['schemas'] & NewElysia['~Ephemeral']['schemas'];
package/dist/base.js CHANGED
@@ -415,7 +415,7 @@ var Elysia = class Elysia {
415
415
  if (scopeOrFnOrError && typeof scopeOrFnOrError === "object") return this;
416
416
  return this.#onBranch("error", scopeOrFnOrError);
417
417
  case 2:
418
- if (typeof scopeOrFnOrError === "function" && (scopeOrFnOrError === Error || scopeOrFnOrError.prototype instanceof Error)) return this.#errorClass(scopeOrFnOrError, fnOrError);
418
+ if (typeof scopeOrFnOrError === "function" && scopeOrFnOrError.prototype instanceof Object) return this.#errorClass(scopeOrFnOrError, fnOrError);
419
419
  return this.#onBranch("error", scopeOrFnOrError, fnOrError);
420
420
  case 3: return this.#errorClass(fnOrError, fn, scopeOrFnOrError);
421
421
  }
@@ -915,13 +915,40 @@ var Elysia = class Elysia {
915
915
  #emitChildRoutes(app, preChain, name) {
916
916
  const declared = app.declaredRoutes;
917
917
  const limit = declared.length;
918
+ const tail = app["~hookChain"];
919
+ let recent;
920
+ let hasLocal = false;
918
921
  let lastChildChain;
919
922
  let lastCombined;
923
+ let lastTailChild = null;
924
+ let lastTailCombined;
920
925
  for (let i = 0; i < limit; i++) {
921
926
  const route = declared[i];
922
927
  const childChain = route[6];
928
+ const absorbed = tail !== void 0 && route[3] !== app;
929
+ if (absorbed && recent === void 0) {
930
+ recent = /* @__PURE__ */ new Set();
931
+ for (let node = tail; node && "added" in node; node = node.parent) {
932
+ recent.add(node);
933
+ if (require_utils.isLocalScope(node.scope)) {
934
+ hasLocal = true;
935
+ break;
936
+ }
937
+ }
938
+ }
923
939
  let inheritedChain;
924
- if (childChain === void 0) inheritedChain = preChain;
940
+ if (absorbed && hasLocal && !recent.has(require_utils.rootSnapshot(childChain))) {
941
+ if (childChain !== lastTailChild) {
942
+ lastTailChild = childChain;
943
+ lastTailCombined = {
944
+ combine: childChain,
945
+ over: preChain,
946
+ tail,
947
+ refs: !!(childChain?.refs || preChain?.refs || tail.refs)
948
+ };
949
+ }
950
+ inheritedChain = lastTailCombined;
951
+ } else if (childChain === void 0) inheritedChain = preChain;
925
952
  else if (preChain === void 0) inheritedChain = childChain;
926
953
  else if (childChain === lastChildChain) inheritedChain = lastCombined;
927
954
  else {
@@ -1372,7 +1399,7 @@ var Elysia = class Elysia {
1372
1399
  if (Elysia.#hookHasTypeBox(resolve ? resolve(node) : node.added, models)) return true;
1373
1400
  node = node.parent;
1374
1401
  } else {
1375
- if (Elysia.#chainHasTypeBox(node.combine, models, seen, resolve)) return true;
1402
+ if (Elysia.#chainHasTypeBox(node.combine, models, seen, resolve) || Elysia.#chainHasTypeBox(node.tail, models, seen, resolve)) return true;
1376
1403
  node = node.over;
1377
1404
  }
1378
1405
  }
package/dist/base.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { isBun } from "./universal/constants.mjs";
2
- import { clearFlattenChainMemo, clonePlainDecorators, clonePlainDeep, coalesceSchemas, createErrorEventHandler, eventProperties, fnOrigin, fnv1a, getLoosePath, guardNonPlainLeaves, hookToGuard, invalidateMacroEpoch, isEmpty, isHTMLBundle, isNotEmpty, isPlainObject, isRecordNumber, joinPath, macroOrigin, mapDeriveEntry, markSingletons, mergeDeep, mergeResponse, nullObject, pushField, schemaProperties, serializeMacroSeed, throwLifecycleErrors } from "./utils.mjs";
2
+ import { clearFlattenChainMemo, clonePlainDecorators, clonePlainDeep, coalesceSchemas, createErrorEventHandler, eventProperties, fnOrigin, fnv1a, getLoosePath, guardNonPlainLeaves, hookToGuard, invalidateMacroEpoch, isEmpty, isHTMLBundle, isLocalScope, isNotEmpty, isPlainObject, isRecordNumber, joinPath, macroOrigin, mapDeriveEntry, markSingletons, mergeDeep, mergeResponse, nullObject, pushField, rootSnapshot, schemaProperties, serializeMacroSeed, throwLifecycleErrors } from "./utils.mjs";
3
3
  import { Ref, warmTypebox } from "./type/bridge.mjs";
4
4
  import { isProduction } from "./universal/is-production.mjs";
5
5
  import { Capture, Compiled, beginCompilerSession, createAotFingerprint, endCompilerSession } from "./compile/aot.mjs";
@@ -412,7 +412,7 @@ var Elysia = class Elysia {
412
412
  if (scopeOrFnOrError && typeof scopeOrFnOrError === "object") return this;
413
413
  return this.#onBranch("error", scopeOrFnOrError);
414
414
  case 2:
415
- if (typeof scopeOrFnOrError === "function" && (scopeOrFnOrError === Error || scopeOrFnOrError.prototype instanceof Error)) return this.#errorClass(scopeOrFnOrError, fnOrError);
415
+ if (typeof scopeOrFnOrError === "function" && scopeOrFnOrError.prototype instanceof Object) return this.#errorClass(scopeOrFnOrError, fnOrError);
416
416
  return this.#onBranch("error", scopeOrFnOrError, fnOrError);
417
417
  case 3: return this.#errorClass(fnOrError, fn, scopeOrFnOrError);
418
418
  }
@@ -912,13 +912,40 @@ var Elysia = class Elysia {
912
912
  #emitChildRoutes(app, preChain, name) {
913
913
  const declared = app.declaredRoutes;
914
914
  const limit = declared.length;
915
+ const tail = app["~hookChain"];
916
+ let recent;
917
+ let hasLocal = false;
915
918
  let lastChildChain;
916
919
  let lastCombined;
920
+ let lastTailChild = null;
921
+ let lastTailCombined;
917
922
  for (let i = 0; i < limit; i++) {
918
923
  const route = declared[i];
919
924
  const childChain = route[6];
925
+ const absorbed = tail !== void 0 && route[3] !== app;
926
+ if (absorbed && recent === void 0) {
927
+ recent = /* @__PURE__ */ new Set();
928
+ for (let node = tail; node && "added" in node; node = node.parent) {
929
+ recent.add(node);
930
+ if (isLocalScope(node.scope)) {
931
+ hasLocal = true;
932
+ break;
933
+ }
934
+ }
935
+ }
920
936
  let inheritedChain;
921
- if (childChain === void 0) inheritedChain = preChain;
937
+ if (absorbed && hasLocal && !recent.has(rootSnapshot(childChain))) {
938
+ if (childChain !== lastTailChild) {
939
+ lastTailChild = childChain;
940
+ lastTailCombined = {
941
+ combine: childChain,
942
+ over: preChain,
943
+ tail,
944
+ refs: !!(childChain?.refs || preChain?.refs || tail.refs)
945
+ };
946
+ }
947
+ inheritedChain = lastTailCombined;
948
+ } else if (childChain === void 0) inheritedChain = preChain;
922
949
  else if (preChain === void 0) inheritedChain = childChain;
923
950
  else if (childChain === lastChildChain) inheritedChain = lastCombined;
924
951
  else {
@@ -1369,7 +1396,7 @@ var Elysia = class Elysia {
1369
1396
  if (Elysia.#hookHasTypeBox(resolve ? resolve(node) : node.added, models)) return true;
1370
1397
  node = node.parent;
1371
1398
  } else {
1372
- if (Elysia.#chainHasTypeBox(node.combine, models, seen, resolve)) return true;
1399
+ if (Elysia.#chainHasTypeBox(node.combine, models, seen, resolve) || Elysia.#chainHasTypeBox(node.tail, models, seen, resolve)) return true;
1373
1400
  node = node.over;
1374
1401
  }
1375
1402
  }
@@ -3,9 +3,9 @@ const require_runtime = require('../_virtual/_rolldown/runtime.js');
3
3
  const require_utils = require('../utils.js');
4
4
  const require_universal_env = require('../universal/env.js');
5
5
  const require_compile_aot = require('./aot.js');
6
- const require_type_elysia_file_type = require('../type/elysia/file-type.js');
7
6
  const require_compile_handler_frozen_validator = require('./handler/frozen-validator.js');
8
7
  const require_type_coerce = require('../type/coerce.js');
8
+ const require_type_elysia_file_type = require('../type/elysia/file-type.js');
9
9
  const require_type_validator_default_precompute = require('../type/validator/default-precompute.js');
10
10
  const require_compile_aot_reconstruct = require('./aot-reconstruct.js');
11
11
  const require_compile_aot_emit = require('./aot-emit.js');
@@ -13,8 +13,8 @@ const require_type_validator_frozen_check = require('../type/validator/frozen-ch
13
13
  const require_type_validator_custom_error = require('../type/validator/custom-error.js');
14
14
  const require_type_validator_exact_mirror = require('../type/validator/exact-mirror.js');
15
15
  const require_type_validator_string_codec_aot = require('../type/validator/string-codec-aot.js');
16
- let typebox_value = require("typebox/value");
17
16
  let typebox_schema = require("typebox/schema");
17
+ let typebox_value = require("typebox/value");
18
18
 
19
19
  //#region src/compile/aot-capture.ts
20
20
  function emptyContainers(node, depth) {
@@ -172,7 +172,7 @@ function captureMirror(schema, aot, slot, sanitize) {
172
172
  if (!createMirror) return;
173
173
  try {
174
174
  const emitted = createMirror(schema, {
175
- Compile: typebox_schema.Compile,
175
+ Compile: require_type_validator_string_codec_aot.compileWithBuild,
176
176
  sanitize,
177
177
  emit: true
178
178
  });
@@ -204,7 +204,7 @@ function captureCodecMirror(schema, aot, slot, sanitize, dir) {
204
204
  const dirOpt = dir === "decode" ? { decode: true } : { encode: true };
205
205
  try {
206
206
  const emitted = createMirror(schema, {
207
- Compile: typebox_schema.Compile,
207
+ Compile: require_type_validator_string_codec_aot.compileWithBuild,
208
208
  sanitize,
209
209
  ...dirOpt,
210
210
  emit: true
@@ -1,18 +1,18 @@
1
1
  import { nullObject } from "../utils.mjs";
2
2
  import { env } from "../universal/env.mjs";
3
3
  import { Capture, CompilerState, aotActivationError, captureImpl, setCaptureImpl } from "./aot.mjs";
4
- import { isAsyncPredicate } from "../type/elysia/file-type.mjs";
5
4
  import { isCapturedBridgeFree, isCompactWalkable } from "./handler/frozen-validator.mjs";
6
5
  import { buildCoercedFromPlan, captureCoercePlan } from "../type/coerce.mjs";
6
+ import { isAsyncPredicate } from "../type/elysia/file-type.mjs";
7
7
  import { applyPrecomputed, buildDefaultClonerSource, buildObjectDefaultMergeSource, canonical, createMergerFromSource, setDefaultProbeImpl, verifyPreallocatableDefault } from "../type/validator/default-precompute.mjs";
8
8
  import { collectExternals } from "./aot-reconstruct.mjs";
9
9
  import { captureMirrorCodecs, captureMirrorUnions, installReconstructImpl } from "./aot-emit.mjs";
10
10
  import { buildFrozenCheck } from "../type/validator/frozen-check.mjs";
11
11
  import { captureCustomErrors } from "../type/validator/custom-error.mjs";
12
12
  import { getExactMirror } from "../type/validator/exact-mirror.mjs";
13
- import { captureStringCodecEntries } from "../type/validator/string-codec-aot.mjs";
14
- import { Default } from "typebox/value";
13
+ import { captureStringCodecEntries, compileWithBuild } from "../type/validator/string-codec-aot.mjs";
15
14
  import { Build, Compile } from "typebox/schema";
15
+ import { Default } from "typebox/value";
16
16
 
17
17
  //#region src/compile/aot-capture.ts
18
18
  function emptyContainers(node, depth) {
@@ -170,7 +170,7 @@ function captureMirror(schema, aot, slot, sanitize) {
170
170
  if (!createMirror) return;
171
171
  try {
172
172
  const emitted = createMirror(schema, {
173
- Compile,
173
+ Compile: compileWithBuild,
174
174
  sanitize,
175
175
  emit: true
176
176
  });
@@ -202,7 +202,7 @@ function captureCodecMirror(schema, aot, slot, sanitize, dir) {
202
202
  const dirOpt = dir === "decode" ? { decode: true } : { encode: true };
203
203
  try {
204
204
  const emitted = createMirror(schema, {
205
- Compile,
205
+ Compile: compileWithBuild,
206
206
  sanitize,
207
207
  ...dirOpt,
208
208
  emit: true
@@ -6,6 +6,14 @@ declare function reconstructCheck(build: CheckBuildResult): {
6
6
  value: string;
7
7
  };
8
8
  declare function externalsMatch(a: unknown[], b: unknown[]): boolean;
9
+ /**
10
+ * Align a TypeBox build's externals with the layout the runtime rebuilds from
11
+ * the schema (`collectExternals`). Returns the build as is when they already
12
+ * match, a copy with a prepended remap when TypeBox >= 1.3.31 passed a lone
13
+ * refinement instead of its `~refine` array, or undefined (don't freeze) when
14
+ * a slot can't be proven equal, e.g. a 1.3.31+ format function
15
+ */
16
+ declare function alignBuildExternals(build: CheckBuildResult, schema: unknown): CheckBuildResult | undefined;
9
17
  declare const Source: {
10
18
  readonly checkFactory: (identifier: string, code: string) => string;
11
19
  readonly checkCode: (defs: string, value: string) => string;
@@ -13,12 +21,6 @@ declare const Source: {
13
21
  readonly mirrorFactory: (source: string, hasExternals: boolean) => string;
14
22
  readonly bothFactory: (identifier: string, checkDefs: string, checkValue: string, mirrorSource: string, mirrorHasExternals: boolean) => string;
15
23
  };
16
- /**
17
- * verify that mirror unions can be reconstructed in build time
18
- *
19
- * return undefined if not reconstructable
20
- * `truthUnions` is `mir.externals.unions` (compiled branches).
21
- */
22
24
  declare function captureMirrorUnions(schema: unknown, truthUnions: any[][]): {
23
25
  identifier: string;
24
26
  code: string;
@@ -26,4 +28,4 @@ declare function captureMirrorUnions(schema: unknown, truthUnions: any[][]): {
26
28
  declare function captureMirrorCodecs(schema: unknown, truthCodecs: Function[], dir?: 'decode' | 'encode'): boolean;
27
29
  declare function installReconstructImpl(): void;
28
30
  //#endregion
29
- export { Source, captureMirrorCodecs, captureMirrorUnions, externalsMatch, installReconstructImpl, reconstructCheck };
31
+ export { Source, alignBuildExternals, captureMirrorCodecs, captureMirrorUnions, externalsMatch, installReconstructImpl, reconstructCheck };
@@ -45,6 +45,41 @@ function externalsMatch(a, b) {
45
45
  }
46
46
  return true;
47
47
  }
48
+ /**
49
+ * Align a TypeBox build's externals with the layout the runtime rebuilds from
50
+ * the schema (`collectExternals`). Returns the build as is when they already
51
+ * match, a copy with a prepended remap when TypeBox >= 1.3.31 passed a lone
52
+ * refinement instead of its `~refine` array, or undefined (don't freeze) when
53
+ * a slot can't be proven equal, e.g. a 1.3.31+ format function
54
+ */
55
+ function alignBuildExternals(build, schema) {
56
+ const variables = build.external.variables;
57
+ const canonical = require_compile_aot_reconstruct.collectExternals(schema);
58
+ const id = build.external.identifier;
59
+ if (!/^[A-Za-z_$][\w$]*$/.test(id)) return;
60
+ const slots = [];
61
+ let j = 0;
62
+ let same = variables.length === canonical.length;
63
+ for (let i = 0; i < variables.length; i++) {
64
+ const v = variables[i];
65
+ const c = canonical[j];
66
+ if (j < canonical.length && externalsMatch([c], [v])) slots.push(`${id}[${j++}]`);
67
+ else if (Array.isArray(c) && c.length === 1 && c[0] === v) {
68
+ slots.push(`${id}[${j++}][0]`);
69
+ same = false;
70
+ } else return;
71
+ }
72
+ if (j !== canonical.length) return;
73
+ if (same) return build;
74
+ return {
75
+ ...build,
76
+ functions: [`${id}=[${slots.join(",")}]`, ...build.functions],
77
+ external: {
78
+ identifier: id,
79
+ variables: canonical
80
+ }
81
+ };
82
+ }
48
83
  const mirrorFactorySource = (source, hasExternals) => hasExternals ? `function(d){${source}}` : `function(v){${source}}`;
49
84
  const bothFactorySource = (identifier, checkDefs, checkValue, mirrorSource, mirrorHasExternals) => `function(${identifier},d){${checkDefs}; return{check:${checkValue},clean:${mirrorHasExternals ? `(function(d){${mirrorSource}})(d)` : `function(v){${mirrorSource}}`}}}`;
50
85
  const Source = {
@@ -54,12 +89,6 @@ const Source = {
54
89
  mirrorFactory: mirrorFactorySource,
55
90
  bothFactory: bothFactorySource
56
91
  };
57
- /**
58
- * verify that mirror unions can be reconstructed in build time
59
- *
60
- * return undefined if not reconstructable
61
- * `truthUnions` is `mir.externals.unions` (compiled branches).
62
- */
63
92
  function captureMirrorUnions(schema, truthUnions) {
64
93
  const branchSchemas = require_compile_aot_reconstruct.collectMirrorUnions(schema);
65
94
  if (branchSchemas.length !== truthUnions.length) return;
@@ -68,9 +97,10 @@ function captureMirrorUnions(schema, truthUnions) {
68
97
  if (!branchSchemas[ui] || branchSchemas[ui].length !== truthUnions[ui].length) return;
69
98
  const branch = [];
70
99
  for (let i = 0; i < truthUnions[ui].length; i++) {
71
- const build = truthUnions[ui][i]?.buildResult;
72
- if (!build?.functions?.length || !build.entry) return;
73
- if (!externalsMatch(require_compile_aot_reconstruct.collectExternals(branchSchemas[ui][i]), build.external.variables)) return;
100
+ const raw = truthUnions[ui][i]?.buildResult;
101
+ if (!raw?.functions?.length || !raw.entry) return;
102
+ const build = alignBuildExternals(raw, branchSchemas[ui][i]);
103
+ if (!build) return;
74
104
  branch.push({
75
105
  identifier: build.external.identifier,
76
106
  code: reconstructCheckCode(build)
@@ -92,6 +122,7 @@ function installReconstructImpl() {
92
122
 
93
123
  //#endregion
94
124
  exports.Source = Source;
125
+ exports.alignBuildExternals = alignBuildExternals;
95
126
  exports.captureMirrorCodecs = captureMirrorCodecs;
96
127
  exports.captureMirrorUnions = captureMirrorUnions;
97
128
  exports.externalsMatch = externalsMatch;
@@ -44,6 +44,41 @@ function externalsMatch(a, b) {
44
44
  }
45
45
  return true;
46
46
  }
47
+ /**
48
+ * Align a TypeBox build's externals with the layout the runtime rebuilds from
49
+ * the schema (`collectExternals`). Returns the build as is when they already
50
+ * match, a copy with a prepended remap when TypeBox >= 1.3.31 passed a lone
51
+ * refinement instead of its `~refine` array, or undefined (don't freeze) when
52
+ * a slot can't be proven equal, e.g. a 1.3.31+ format function
53
+ */
54
+ function alignBuildExternals(build, schema) {
55
+ const variables = build.external.variables;
56
+ const canonical = collectExternals(schema);
57
+ const id = build.external.identifier;
58
+ if (!/^[A-Za-z_$][\w$]*$/.test(id)) return;
59
+ const slots = [];
60
+ let j = 0;
61
+ let same = variables.length === canonical.length;
62
+ for (let i = 0; i < variables.length; i++) {
63
+ const v = variables[i];
64
+ const c = canonical[j];
65
+ if (j < canonical.length && externalsMatch([c], [v])) slots.push(`${id}[${j++}]`);
66
+ else if (Array.isArray(c) && c.length === 1 && c[0] === v) {
67
+ slots.push(`${id}[${j++}][0]`);
68
+ same = false;
69
+ } else return;
70
+ }
71
+ if (j !== canonical.length) return;
72
+ if (same) return build;
73
+ return {
74
+ ...build,
75
+ functions: [`${id}=[${slots.join(",")}]`, ...build.functions],
76
+ external: {
77
+ identifier: id,
78
+ variables: canonical
79
+ }
80
+ };
81
+ }
47
82
  const mirrorFactorySource = (source, hasExternals) => hasExternals ? `function(d){${source}}` : `function(v){${source}}`;
48
83
  const bothFactorySource = (identifier, checkDefs, checkValue, mirrorSource, mirrorHasExternals) => `function(${identifier},d){${checkDefs}; return{check:${checkValue},clean:${mirrorHasExternals ? `(function(d){${mirrorSource}})(d)` : `function(v){${mirrorSource}}`}}}`;
49
84
  const Source = {
@@ -53,12 +88,6 @@ const Source = {
53
88
  mirrorFactory: mirrorFactorySource,
54
89
  bothFactory: bothFactorySource
55
90
  };
56
- /**
57
- * verify that mirror unions can be reconstructed in build time
58
- *
59
- * return undefined if not reconstructable
60
- * `truthUnions` is `mir.externals.unions` (compiled branches).
61
- */
62
91
  function captureMirrorUnions(schema, truthUnions) {
63
92
  const branchSchemas = collectMirrorUnions(schema);
64
93
  if (branchSchemas.length !== truthUnions.length) return;
@@ -67,9 +96,10 @@ function captureMirrorUnions(schema, truthUnions) {
67
96
  if (!branchSchemas[ui] || branchSchemas[ui].length !== truthUnions[ui].length) return;
68
97
  const branch = [];
69
98
  for (let i = 0; i < truthUnions[ui].length; i++) {
70
- const build = truthUnions[ui][i]?.buildResult;
71
- if (!build?.functions?.length || !build.entry) return;
72
- if (!externalsMatch(collectExternals(branchSchemas[ui][i]), build.external.variables)) return;
99
+ const raw = truthUnions[ui][i]?.buildResult;
100
+ if (!raw?.functions?.length || !raw.entry) return;
101
+ const build = alignBuildExternals(raw, branchSchemas[ui][i]);
102
+ if (!build) return;
73
103
  branch.push({
74
104
  identifier: build.external.identifier,
75
105
  code: reconstructCheckCode(build)
@@ -90,4 +120,4 @@ function installReconstructImpl() {
90
120
  }
91
121
 
92
122
  //#endregion
93
- export { Source, captureMirrorCodecs, captureMirrorUnions, externalsMatch, installReconstructImpl, reconstructCheck };
123
+ export { Source, alignBuildExternals, captureMirrorCodecs, captureMirrorUnions, externalsMatch, installReconstructImpl, reconstructCheck };
@@ -6,6 +6,7 @@ const require_error = require('../../error.js');
6
6
  const require_adapter_web_standard_handler = require('../../adapter/web-standard/handler.js');
7
7
  const require_compile_aot = require('../aot.js');
8
8
  const require_generation = require('../../generation.js');
9
+ const require_handler_utils = require('../../handler/utils.js');
9
10
  const require_compile_handler_params = require('./params.js');
10
11
  const require_compile_handler_jit = require('./jit.js');
11
12
  const require_compile_handler_descriptor = require('./descriptor.js');
@@ -187,6 +188,17 @@ function mapStaticValue(response, map, set, value) {
187
188
  if ((typeof body === "string" || typeof body === "number" || typeof body === "boolean") && !mapped.headers.has("content-type")) mapped.headers.set("content-type", "text/plain;charset=utf-8");
188
189
  return mapped;
189
190
  }
191
+ function afterUseHooks(node, resolve) {
192
+ let after;
193
+ while (node && "combine" in node) {
194
+ if (node.tail) {
195
+ const own = require_utils.flattenChain(node.tail, require_utils.isLocalScope, require_utils.rootSnapshot(node.combine), resolve);
196
+ if (own) after = after ? require_utils.mergeHook(own, after, false, true) : own;
197
+ }
198
+ node = node.combine;
199
+ }
200
+ return after;
201
+ }
190
202
  function buildNativeStaticResponse(route, root) {
191
203
  const [, , handler, instance, localHook, appHook, inheritedChain, macroScope] = route;
192
204
  if (typeof handler === "function" || handler instanceof Error || handler instanceof Promise) return;
@@ -197,14 +209,17 @@ function buildNativeStaticResponse(route, root) {
197
209
  const flatAppHook = require_utils.flattenChainMemo(root, appHook, resolve);
198
210
  let rootHook;
199
211
  if (instance !== root) {
200
- const locals = require_utils.flattenChain(require_generation.frozenRootOf(root)["~hookChain"], require_utils.isLocalScope, inheritedChain, resolve);
212
+ const locals = require_utils.flattenChain(require_generation.frozenRootOf(root)["~hookChain"], require_utils.isLocalScope, require_utils.rootSnapshot(inheritedChain), resolve);
201
213
  const inherited = locals ? require_utils.flattenChainMemo(root, inheritedChain, resolve) : require_utils.flattenChainMemoReadonly(root, inheritedChain, resolve);
202
214
  if (!inherited) rootHook = locals;
203
215
  else if (!locals) rootHook = inherited;
204
216
  else rootHook = require_utils.mergeHook(inherited, locals);
217
+ const after = afterUseHooks(inheritedChain, resolve);
218
+ if (after) rootHook = rootHook ? require_utils.mergeHook(after, rootHook) : after;
205
219
  }
206
220
  const hook = applyHook(ownedHook, flatAppHook, rootHook);
207
221
  if (hook && !isEmptyPipelineHook(hook)) return;
222
+ if (require_handler_utils.returnedErrorClasses(hook, root)?.some((C) => handler instanceof C)) return;
208
223
  const rootHeaders = frozenRoot["~ext"]?.headers;
209
224
  if (handler instanceof Response && !rootHeaders) return handler;
210
225
  const response = adapter.response;
@@ -214,7 +229,7 @@ function buildNativeStaticResponse(route, root) {
214
229
  function toArray(name, hook) {
215
230
  if (typeof hook[name] === "function") hook[name] = [hook[name]];
216
231
  }
217
- function composeRouteHook(instance, localHook, appHook, inheritedChain, root, macroScope, allowCompactPrefix = true) {
232
+ function composeRouteHook(instance, localHook, appHook, inheritedChain, root, macroScope, allowCompactPrefix = false) {
218
233
  const resolve = chainResolver(root);
219
234
  localHook = resolveLocalHook(localMacroRoot(macroScope ?? instance, root), localHook, root);
220
235
  if (localHook && localHook.derive !== void 0) {
@@ -222,7 +237,7 @@ function composeRouteHook(instance, localHook, appHook, inheritedChain, root, ma
222
237
  promoteDerive(localHook);
223
238
  }
224
239
  const flatAppHook = appHook ? require_utils.flattenChainMemo(root, appHook, resolve) : void 0;
225
- let locals = instance !== root ? require_utils.flattenChain(require_generation.frozenRootOf(root)["~hookChain"], require_utils.isLocalScope, inheritedChain, resolve) : void 0;
240
+ let locals = instance !== root ? require_utils.flattenChain(require_generation.frozenRootOf(root)["~hookChain"], require_utils.isLocalScope, require_utils.rootSnapshot(inheritedChain), resolve) : void 0;
226
241
  const instanceLocal = instance !== root ? require_utils.flattenChain(instance["~hookChain"], require_utils.isLocalScope) : void 0;
227
242
  const compactPrefix = allowCompactPrefix && instance !== root && !require_compile_aot.Capture.isCapturing() && !require_compile_aot.Capture.isAotBuildEnv() && resolve === void 0 && require_utils.isCompactBeforeHandleOnly(localHook) && require_utils.isCompactBeforeHandleOnly(flatAppHook) && require_utils.isCompactBeforeHandleOnly(locals) && !instanceLocal?.error ? require_utils.compactBeforeHandlePrefix(inheritedChain) : void 0;
228
243
  let present = collectHookOrigins(localHook, void 0);
@@ -235,11 +250,14 @@ function composeRouteHook(instance, localHook, appHook, inheritedChain, root, ma
235
250
  return hook;
236
251
  }
237
252
  let inherited = instance !== root ? require_utils.flattenChainMemoReadonly(root, inheritedChain, resolve) : void 0;
238
- if ((inherited || locals) && (flatAppHook || localHook) && present?.size) {
253
+ let after = instance !== root ? afterUseHooks(inheritedChain, resolve) : void 0;
254
+ if ((inherited || after || locals) && (flatAppHook || localHook) && present?.size) {
239
255
  if (inherited) inherited = dropHooksByOrigin(inherited, present);
256
+ if (after) after = dropHooksByOrigin(after, present);
240
257
  if (locals) locals = dropHooksByOrigin(locals, present);
241
258
  }
242
259
  let hook = applyHook(localHook, flatAppHook, inherited ? require_utils.cloneHook(inherited) : void 0);
260
+ if (after) hook = hook ? require_utils.mergeHook(hook, after, false, true) : after;
243
261
  if (locals) hook = hook ? require_utils.mergeHook(hook, locals, false, true) : locals;
244
262
  if (instance !== root) {
245
263
  const errors = instanceLocal?.error;
@@ -308,7 +326,8 @@ function compileHandler(route, root, liveOnly = false) {
308
326
  toArray("error", hook);
309
327
  }
310
328
  const buildValidator = () => hook ? require_compile_handler_reconstruct.Reconstrct.validator(hook, root, method, path, liveOnly) : void 0;
311
- if (handler instanceof Error) {
329
+ const errorClasses = require_handler_utils.returnedErrorClasses(hook, root);
330
+ if (handler instanceof Error || typeof handler !== "function" && errorClasses?.some((C) => handler instanceof C)) {
312
331
  const error = handler;
313
332
  handler = () => {
314
333
  throw error;
@@ -341,7 +360,7 @@ function compileHandler(route, root, liveOnly = false) {
341
360
  cookieConfig: reconstructed.a.includes("cc") ? require_compile_handler_reconstruct.Reconstrct.cookie(hook, root) : void 0,
342
361
  tracers: reconstructed.a.includes("tr") ? require_compile_handler_reconstruct.Reconstrct.trace(hook, root) : void 0
343
362
  }));
344
- if (hook === void 0 && isHandleFunction && !mountMeta && (method === "GET" || method === "HEAD") && !root["~hasTrace"] && root["~introspect"] !== true && root["~config"]?.introspect !== true && !require_utils.isNotEmpty(frozenRoot["~ext"]?.headers) && !require_compile_aot.Capture.isAotBuildEnv() && !require_compile_aot.Capture.isCapturing()) {
363
+ if (hook === void 0 && !errorClasses && isHandleFunction && !mountMeta && (method === "GET" || method === "HEAD") && !root["~hasTrace"] && root["~introspect"] !== true && root["~config"]?.introspect !== true && !require_utils.isNotEmpty(frozenRoot["~ext"]?.headers) && !require_compile_aot.Capture.isAotBuildEnv() && !require_compile_aot.Capture.isCapturing()) {
345
364
  let isContextFree = false;
346
365
  if (!Object.hasOwn(handler, "toString")) {
347
366
  const source = Function.prototype.toString.call(handler);
@@ -382,6 +401,7 @@ function compileHandler(route, root, liveOnly = false) {
382
401
  isHandleFunction,
383
402
  isStaticResponse,
384
403
  isPromiseHandler,
404
+ errorClasses,
385
405
  state
386
406
  });
387
407
  }