@tupik/core 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Zero-dependency core of **Tupik**, a multi-runtime TypeScript web framework: Radix Tree router,
4
4
  fluent modules (no decorators, no reflection), middleware pipeline and an app engine built on
5
5
  Web Standards (`Request`/`Response`). It never imports `node:*`, so the same app runs on Node.js,
6
- Bun and Cloudflare Workers through a driver package. Deno and Fastly are not verified yet (planned).
6
+ Bun and Cloudflare Workers through a driver package. Deno is verified on Deno 2.9.6 through `@tupik/edge`; Fastly is not verified yet (planned).
7
7
 
8
8
  ## Install
9
9
 
package/dist/index.d.mts CHANGED
@@ -434,7 +434,19 @@ type SuccessSchema<TSchema extends RouteSchema> = TSchema['response'] extends in
434
434
  } ? S : TResponse extends {
435
435
  201: infer S extends StandardSchemaV1;
436
436
  } ? S : never : never;
437
- type HandlerOutput<TResult> = [Extract<Awaited<TResult>, Response>] extends [never] ? Awaited<TResult> extends void ? undefined : Awaited<TResult> : unknown;
437
+ /**
438
+ * Type-cost note: most handlers return a plain object literal, which is its own
439
+ * output. One check answers that case (an object literal fits an index
440
+ * signature, an interface such as `Response` does not; `never` and `any` have
441
+ * every key, so `'then'` sends them down the general path too). Everything
442
+ * else takes the general path: `Awaited` once, then `Response` and `void`.
443
+ */
444
+ type HandlerOutput<TResult> = [TResult] extends [PlainOutput] ? 'then' extends keyof TResult ? AwaitedOutput<Awaited<TResult>> : TResult : AwaitedOutput<Awaited<TResult>>;
445
+ type PlainOutput = {
446
+ readonly then?: undefined;
447
+ readonly [key: string]: unknown;
448
+ };
449
+ type AwaitedOutput<TOutput> = [Extract<TOutput, Response>] extends [never] ? [TOutput] extends [void] ? undefined : TOutput : unknown;
438
450
  /**
439
451
  * Output type of a Standard Schema, preferring the spec's type-only
440
452
  * `~standard.types.output` (exposed by Zod, Valibot, ArkType) and falling back
package/dist/index.d.ts CHANGED
@@ -434,7 +434,19 @@ type SuccessSchema<TSchema extends RouteSchema> = TSchema['response'] extends in
434
434
  } ? S : TResponse extends {
435
435
  201: infer S extends StandardSchemaV1;
436
436
  } ? S : never : never;
437
- type HandlerOutput<TResult> = [Extract<Awaited<TResult>, Response>] extends [never] ? Awaited<TResult> extends void ? undefined : Awaited<TResult> : unknown;
437
+ /**
438
+ * Type-cost note: most handlers return a plain object literal, which is its own
439
+ * output. One check answers that case (an object literal fits an index
440
+ * signature, an interface such as `Response` does not; `never` and `any` have
441
+ * every key, so `'then'` sends them down the general path too). Everything
442
+ * else takes the general path: `Awaited` once, then `Response` and `void`.
443
+ */
444
+ type HandlerOutput<TResult> = [TResult] extends [PlainOutput] ? 'then' extends keyof TResult ? AwaitedOutput<Awaited<TResult>> : TResult : AwaitedOutput<Awaited<TResult>>;
445
+ type PlainOutput = {
446
+ readonly then?: undefined;
447
+ readonly [key: string]: unknown;
448
+ };
449
+ type AwaitedOutput<TOutput> = [Extract<TOutput, Response>] extends [never] ? [TOutput] extends [void] ? undefined : TOutput : unknown;
438
450
  /**
439
451
  * Output type of a Standard Schema, preferring the spec's type-only
440
452
  * `~standard.types.output` (exposed by Zod, Valibot, ArkType) and falling back
package/dist/index.mjs CHANGED
@@ -14,7 +14,6 @@ class MatchState {
14
14
  ends;
15
15
  count = 0;
16
16
  value = void 0;
17
- /** True when the last recorded parameter is a wildcard capture. */
18
17
  wildcard = false;
19
18
  #path = "";
20
19
  #entry = void 0;
@@ -30,7 +29,6 @@ class MatchState {
30
29
  this.wildcard = false;
31
30
  this.#entry = void 0;
32
31
  }
33
- /** @internal Links the cache entry the current match came from (memoizes params). */
34
32
  bind(entry) {
35
33
  this.#entry = entry;
36
34
  }
@@ -53,20 +51,14 @@ class MatchState {
53
51
  this.value = value;
54
52
  this.wildcard = wildcard;
55
53
  }
56
- /** Raw (still percent-encoded) value of a parameter. */
57
54
  rawParam(name) {
58
55
  const index = this.names.indexOf(name);
59
56
  return index === -1 || index >= this.count ? void 0 : this.#raw(index);
60
57
  }
61
- /**
62
- * Decoded parameter value (a wildcard keeps `%2F`, see `decodeWildcard`).
63
- * Throws `URIError` on malformed percent-encoding.
64
- */
65
58
  param(name) {
66
59
  const index = this.names.indexOf(name);
67
60
  return index === -1 || index >= this.count ? void 0 : this.#decoded(index);
68
61
  }
69
- /** Decoded parameters. Throws `URIError` on malformed percent-encoding. */
70
62
  params() {
71
63
  const entry = this.#entry;
72
64
  if (entry?.params !== void 0) return { ...entry.params };
@@ -108,7 +100,6 @@ class RadixNode {
108
100
  constructor(segment) {
109
101
  this.segment = segment;
110
102
  }
111
- /** Compares a path slice against stored segments without allocating. */
112
103
  findChild(path, start, end) {
113
104
  const length = end - start;
114
105
  for (let i = 0; i < this.children.length; i += 1) {
@@ -169,7 +160,6 @@ class RadixRouter {
169
160
  #stats = { hits: 0, misses: 0, evictions: 0 };
170
161
  #maxParams = 0;
171
162
  #size = 0;
172
- /** Reusable buffers for `match`; grow on demand like any `MatchState`. */
173
163
  #scratch = new MatchState(4);
174
164
  constructor(options = {}) {
175
165
  const cacheSize = options.cacheSize ?? 1024;
@@ -287,10 +277,6 @@ class RadixRouter {
287
277
  }
288
278
  return matched;
289
279
  }
290
- /**
291
- * Methods (in insertion order) with a route matching `path`, without the
292
- * HEAD → GET fallback and without touching the cache. Used for 405/OPTIONS.
293
- */
294
280
  allowedMethods(path) {
295
281
  const allowed = [];
296
282
  const state = this.#scratch;
@@ -590,7 +576,6 @@ function lightStatus(status) {
590
576
  return status >= 200 && status <= 599 && status !== 204 && status !== 205 && status !== 304;
591
577
  }
592
578
  class LightResponse {
593
- /** Cleared once a native `Response` exists: from then on it is the source of truth. */
594
579
  [LIGHT_RESPONSE];
595
580
  #data;
596
581
  #native = void 0;
@@ -608,7 +593,6 @@ class LightResponse {
608
593
  }
609
594
  return native;
610
595
  }
611
- /** Immutable on `Response`, so it never needs the native object. */
612
596
  get status() {
613
597
  return this.#data.status;
614
598
  }
@@ -699,13 +683,10 @@ class Context {
699
683
  deps;
700
684
  params;
701
685
  runtime;
702
- /** Set by the access guard; `null` until (and unless) `authenticate` ran. */
703
686
  principal = null;
704
687
  [SHAPE_RESPONSE] = void 0;
705
688
  #cookies = void 0;
706
- /** `undefined` until `status()` is called (200 for bodies, 204 for `undefined`). */
707
689
  #statusCode = void 0;
708
- /** Created on first use: most responses never set a custom header. */
709
690
  #resHeaders = void 0;
710
691
  #rawStore = void 0;
711
692
  #query;
@@ -728,7 +709,6 @@ class Context {
728
709
  this.#body = init.body;
729
710
  this.#authenticate = init.authenticate;
730
711
  }
731
- /** The principal is typed by `TupikRegister`; the engine only carries it. */
732
712
  getPrincipal() {
733
713
  return this.#principal ??= (async () => await this.#authenticate?.(this) ?? null)();
734
714
  }
@@ -956,23 +936,18 @@ class Lifecycle {
956
936
  this.#error.push(hook);
957
937
  return this;
958
938
  }
959
- /** True when at least one `onRequest` hook is registered (lets the engine skip the call). */
960
939
  get hasRequest() {
961
940
  return this.#request.length > 0;
962
941
  }
963
- /** True when at least one `preHandler` hook is registered. */
964
942
  get hasPreHandler() {
965
943
  return this.#preHandler.length > 0;
966
944
  }
967
- /** True when at least one `onSend` hook is registered. */
968
945
  get hasSend() {
969
946
  return this.#send.length > 0;
970
947
  }
971
- /** True when at least one `onError` hook is registered. */
972
948
  get hasError() {
973
949
  return this.#error.length > 0;
974
950
  }
975
- /** Appends every hook from another registry, preserving its registration order. */
976
951
  merge(other) {
977
952
  this.#startup.push(...other.#startup);
978
953
  this.#shutdown.push(...other.#shutdown);
@@ -993,7 +968,6 @@ class Lifecycle {
993
968
  if (hook) await hook(deps);
994
969
  }
995
970
  }
996
- /** Runs hooks in order; resolves with the first `Response` a hook returns. */
997
971
  async runRequest(ctx) {
998
972
  for (const hook of this.#request) {
999
973
  const response = await hook(ctx);
@@ -1001,7 +975,6 @@ class Lifecycle {
1001
975
  }
1002
976
  return void 0;
1003
977
  }
1004
- /** Runs hooks in order; resolves with the first `Response` a hook returns. */
1005
978
  async runPreHandler(ctx) {
1006
979
  for (const hook of this.#preHandler) {
1007
980
  const response = await hook(ctx);
@@ -1403,7 +1376,6 @@ class ModuleBuilder {
1403
1376
  access(access) {
1404
1377
  return this.#setAccess(access);
1405
1378
  }
1406
- /** Validated now (teaching error at the declaration); stored untyped like route handlers. */
1407
1379
  #setAccess(access) {
1408
1380
  planAccess(access, `module ${this.#prefix || "/"}`);
1409
1381
  this.#access = access;
@@ -1442,8 +1414,6 @@ class ModuleBuilder {
1442
1414
  method,
1443
1415
  path: resolved,
1444
1416
  middlewares: this.#middlewares.slice(),
1445
- // Registration erases the schema-specific input type. Runtime validation
1446
- // (Step 4) restores the declared shape before the handler runs.
1447
1417
  handler: options.handler,
1448
1418
  access,
1449
1419
  meta: declareMeta(access, options.schema, errors, collectTags(this.#middlewares, options.tags ?? []), label)
@@ -1723,18 +1693,12 @@ function validationResponse(issues) {
1723
1693
  const ACCEPTS_REQUEST_LIKE = Symbol.for("tupik.acceptsRequestLike");
1724
1694
  const DEFAULT_BODY_LIMIT = 1024 * 1024;
1725
1695
  class TupikApp {
1726
- /** `fetch` accepts `RequestLike`: drivers may skip building a native `Request`. */
1727
1696
  [ACCEPTS_REQUEST_LIKE] = true;
1728
1697
  #services;
1729
1698
  #exposeErrors;
1730
1699
  #bodyLimit;
1731
1700
  #settings;
1732
1701
  #router = new RadixRouter();
1733
- /**
1734
- * Reused by every `fetch`: matching is synchronous, and the route value and
1735
- * decoded params are copied out before the first `await`, so concurrent
1736
- * requests never observe each other's state.
1737
- */
1738
1702
  #state = this.#router.createState();
1739
1703
  #routes = [];
1740
1704
  #lifecycle = new Lifecycle();
@@ -1742,7 +1706,6 @@ class TupikApp {
1742
1706
  #middlewares = [];
1743
1707
  #middlewareVersion = 0;
1744
1708
  #notFound = void 0;
1745
- /** Pseudo-route for unmatched requests (global hooks only, no module scope). */
1746
1709
  #fallback;
1747
1710
  #started = false;
1748
1711
  constructor(options = {}) {
@@ -1755,7 +1718,6 @@ class TupikApp {
1755
1718
  this.#bodyLimit = bodyLimit;
1756
1719
  const principalId = options.principalId;
1757
1720
  this.#settings = {
1758
- // Erased to the engine's untyped principal; `TPrincipal` only types user code.
1759
1721
  authenticate: options.authenticate,
1760
1722
  principalId: principalId === void 0 ? defaultPrincipalId : (principal) => principalId(principal),
1761
1723
  response: options.response ?? "strip",
@@ -1769,7 +1731,6 @@ class TupikApp {
1769
1731
  get services() {
1770
1732
  return this.#services;
1771
1733
  }
1772
- /** Registered routes; each `meta.tags` includes the tags of the app-level middleware. */
1773
1734
  get routes() {
1774
1735
  return this.#routes.map((route) => withAppTags(route, this.#middlewares));
1775
1736
  }
@@ -1777,7 +1738,6 @@ class TupikApp {
1777
1738
  for (const module of modules) this.#registerOne(module);
1778
1739
  return this;
1779
1740
  }
1780
- /** Compiles every route first (a configuration error registers nothing), then inserts them. */
1781
1741
  #registerOne(module) {
1782
1742
  const scope = module.lifecycle;
1783
1743
  const entries = module.routes.map((contract) => compileRoute(contract, scope, this.#settings));
@@ -1787,7 +1747,6 @@ class TupikApp {
1787
1747
  }
1788
1748
  if (!this.#scopes.includes(scope)) this.#scopes.push(scope);
1789
1749
  }
1790
- /** App-level middleware, applied to every route before module middleware. */
1791
1750
  use(middleware) {
1792
1751
  this.#middlewares.push(middleware);
1793
1752
  this.#middlewareVersion += 1;
@@ -1817,27 +1776,13 @@ class TupikApp {
1817
1776
  this.#lifecycle.onError(hook);
1818
1777
  return this;
1819
1778
  }
1820
- /** Handler for requests no route matches (default: JSON 404 `NOT_FOUND`). */
1821
1779
  notFound(handler) {
1822
1780
  this.#notFound = createRunner([], handler);
1823
1781
  return this;
1824
1782
  }
1825
- /**
1826
- * Handles one request. `env` and `executionCtx` are optional platform
1827
- * bindings (Cloudflare Workers `fetch(request, env, ctx)`), exposed to
1828
- * handlers as `ctx.runtime`.
1829
- *
1830
- * `request` may be a native `Request` or a driver-provided `RequestLike`
1831
- * (see `ACCEPTS_REQUEST_LIKE`); either reaches handlers as `ctx.req`.
1832
- */
1833
1783
  async fetch(request, env, executionCtx) {
1834
1784
  return this.handle(request, env, executionCtx);
1835
1785
  }
1836
- /**
1837
- * `fetch` that returns the `Response` itself when nothing had to wait (no
1838
- * request/preHandler/send hook, no body, sync validators and handler), so
1839
- * drivers skip a microtask. Failures still become a response.
1840
- */
1841
1786
  handle(request, env, executionCtx) {
1842
1787
  const method = request.method.toUpperCase();
1843
1788
  const pathname = pathnameOf(request.url);
@@ -1877,7 +1822,6 @@ class TupikApp {
1877
1822
  return this.#fail(error, method, entry, ctx, pathname);
1878
1823
  }
1879
1824
  }
1880
- /** `onRequest` hooks and body; resolves with an early response, if any. */
1881
1825
  async #prelude(method, entry, ctx) {
1882
1826
  const { route, scope } = entry;
1883
1827
  const global = this.#lifecycle;
@@ -1920,11 +1864,6 @@ class TupikApp {
1920
1864
  async #fail(error, method, entry, ctx, pathname) {
1921
1865
  return this.#send(method, entry.scope, ctx, withContextHeaders(await this.#failure(error, entry, ctx, pathname), ctx));
1922
1866
  }
1923
- /**
1924
- * Response for a failed request: `HttpError` and declared `ctx.fail` codes
1925
- * answer directly; anything else goes to module then app `onError` hooks,
1926
- * falling back to a generic 500 (logged when no hook exists).
1927
- */
1928
1867
  async #failure(thrown, entry, ctx, pathname) {
1929
1868
  let error = thrown;
1930
1869
  if (error instanceof HttpError) return error.toResponse();
@@ -1956,7 +1895,6 @@ class TupikApp {
1956
1895
  }
1957
1896
  return handled ?? internalErrorResponse(error, this.#exposeErrors);
1958
1897
  }
1959
- /** Terminal handler of the fallback pipeline: 405, automatic OPTIONS or 404. */
1960
1898
  #unmatched(ctx) {
1961
1899
  const methods = this.#router.allowedMethods(pathnameOf(ctx.req.url));
1962
1900
  if (methods.length === 0) {
@@ -1967,7 +1905,6 @@ class TupikApp {
1967
1905
  const response = ctx.req.method.toUpperCase() === "OPTIONS" ? new Response(null, { status: 204, headers: { allow } }) : jsonError(405, "METHOD_NOT_ALLOWED", "Method not allowed", { allow });
1968
1906
  return withContextHeaders(response, ctx);
1969
1907
  }
1970
- /** Runs module then app `onSend` hooks, then strips the body of a HEAD response. */
1971
1908
  #send(method, scope, ctx, response) {
1972
1909
  const global = this.#lifecycle;
1973
1910
  if (!scope.hasSend && !global.hasSend) return finalize(method, response);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tupik/core",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Zero-dependency core of the Tupik TypeScript framework: Radix Tree router, typed modules, middleware pipeline and app engine on Web Standards.",
5
5
  "license": "MIT",
6
6
  "keywords": [