@orpc/openapi 0.0.0-next.7b09958 → 0.0.0-next.7d3bd71

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.
@@ -0,0 +1,165 @@
1
+ import {
2
+ standardizeHTTPPath
3
+ } from "./chunk-XGHV4TH3.js";
4
+
5
+ // src/adapters/standard/openapi-codec.ts
6
+ import { OpenAPISerializer } from "@orpc/client/openapi";
7
+ import { fallbackContractConfig } from "@orpc/contract";
8
+ import { isObject } from "@orpc/shared";
9
+ var OpenAPICodec = class {
10
+ serializer;
11
+ constructor(options) {
12
+ this.serializer = options?.serializer ?? new OpenAPISerializer();
13
+ }
14
+ async decode(request, params, procedure) {
15
+ const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
16
+ if (inputStructure === "compact") {
17
+ const data = request.method === "GET" ? this.serializer.deserialize(request.url.searchParams) : this.serializer.deserialize(await request.body());
18
+ if (data === void 0) {
19
+ return params;
20
+ }
21
+ if (isObject(data)) {
22
+ return {
23
+ ...params,
24
+ ...data
25
+ };
26
+ }
27
+ return data;
28
+ }
29
+ const deserializeSearchParams = () => {
30
+ return this.serializer.deserialize(request.url.searchParams);
31
+ };
32
+ return {
33
+ params,
34
+ get query() {
35
+ const value = deserializeSearchParams();
36
+ Object.defineProperty(this, "query", { value, writable: true });
37
+ return value;
38
+ },
39
+ set query(value) {
40
+ Object.defineProperty(this, "query", { value, writable: true });
41
+ },
42
+ headers: request.headers,
43
+ body: this.serializer.deserialize(await request.body())
44
+ };
45
+ }
46
+ encode(output, procedure) {
47
+ const successStatus = fallbackContractConfig("defaultSuccessStatus", procedure["~orpc"].route.successStatus);
48
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
49
+ if (outputStructure === "compact") {
50
+ return {
51
+ status: successStatus,
52
+ headers: {},
53
+ body: this.serializer.serialize(output)
54
+ };
55
+ }
56
+ if (!isObject(output)) {
57
+ throw new Error(
58
+ 'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
59
+ );
60
+ }
61
+ return {
62
+ status: successStatus,
63
+ headers: output.headers ?? {},
64
+ body: this.serializer.serialize(output.body)
65
+ };
66
+ }
67
+ encodeError(error) {
68
+ return {
69
+ status: error.status,
70
+ headers: {},
71
+ body: this.serializer.serialize(error.toJSON())
72
+ };
73
+ }
74
+ };
75
+
76
+ // src/adapters/standard/openapi-matcher.ts
77
+ import { fallbackContractConfig as fallbackContractConfig2 } from "@orpc/contract";
78
+ import { convertPathToHttpPath, createContractedProcedure, eachContractProcedure, getLazyRouterPrefix, getRouterChild, isProcedure, unlazy } from "@orpc/server";
79
+ import { addRoute, createRouter, findRoute } from "rou3";
80
+ var OpenAPIMatcher = class {
81
+ tree = createRouter();
82
+ ignoreUndefinedMethod;
83
+ constructor(options) {
84
+ this.ignoreUndefinedMethod = options?.ignoreUndefinedMethod ?? false;
85
+ }
86
+ pendingRouters = [];
87
+ init(router, path = []) {
88
+ const laziedOptions = eachContractProcedure({
89
+ router,
90
+ path
91
+ }, ({ path: path2, contract }) => {
92
+ if (!contract["~orpc"].route.method && this.ignoreUndefinedMethod) {
93
+ return;
94
+ }
95
+ const method = fallbackContractConfig2("defaultMethod", contract["~orpc"].route.method);
96
+ const httpPath = contract["~orpc"].route.path ? toRou3Pattern(contract["~orpc"].route.path) : convertPathToHttpPath(path2);
97
+ if (isProcedure(contract)) {
98
+ addRoute(this.tree, method, httpPath, {
99
+ path: path2,
100
+ contract,
101
+ procedure: contract,
102
+ // this mean dev not used contract-first so we can used contract as procedure directly
103
+ router
104
+ });
105
+ } else {
106
+ addRoute(this.tree, method, httpPath, {
107
+ path: path2,
108
+ contract,
109
+ procedure: void 0,
110
+ router
111
+ });
112
+ }
113
+ });
114
+ this.pendingRouters.push(...laziedOptions.map((option) => ({
115
+ ...option,
116
+ httpPathPrefix: convertPathToHttpPath(option.path),
117
+ laziedPrefix: getLazyRouterPrefix(option.lazied)
118
+ })));
119
+ }
120
+ async match(method, pathname) {
121
+ if (this.pendingRouters.length) {
122
+ const newPendingRouters = [];
123
+ for (const pendingRouter of this.pendingRouters) {
124
+ if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
125
+ const { default: router } = await unlazy(pendingRouter.lazied);
126
+ this.init(router, pendingRouter.path);
127
+ } else {
128
+ newPendingRouters.push(pendingRouter);
129
+ }
130
+ }
131
+ this.pendingRouters = newPendingRouters;
132
+ }
133
+ const match = findRoute(this.tree, method, pathname);
134
+ if (!match) {
135
+ return void 0;
136
+ }
137
+ if (!match.data.procedure) {
138
+ const { default: maybeProcedure } = await unlazy(getRouterChild(match.data.router, ...match.data.path));
139
+ if (!isProcedure(maybeProcedure)) {
140
+ throw new Error(`
141
+ [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.data.path)}.
142
+ Ensure that the procedure is correctly defined and matches the expected contract.
143
+ `);
144
+ }
145
+ match.data.procedure = createContractedProcedure(match.data.contract, maybeProcedure);
146
+ }
147
+ return {
148
+ path: match.data.path,
149
+ procedure: match.data.procedure,
150
+ params: match.params ? decodeParams(match.params) : void 0
151
+ };
152
+ }
153
+ };
154
+ function toRou3Pattern(path) {
155
+ return standardizeHTTPPath(path).replace(/\{\+([^}]+)\}/g, "**:$1").replace(/\{([^}]+)\}/g, ":$1");
156
+ }
157
+ function decodeParams(params) {
158
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, decodeURIComponent(value)]));
159
+ }
160
+
161
+ export {
162
+ OpenAPICodec,
163
+ OpenAPIMatcher
164
+ };
165
+ //# sourceMappingURL=chunk-LPBZEW4B.js.map
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  OpenAPICodec,
3
3
  OpenAPIMatcher
4
- } from "./chunk-PWOV66X6.js";
4
+ } from "./chunk-LPBZEW4B.js";
5
5
 
6
6
  // src/adapters/fetch/openapi-handler.ts
7
- import { fetchRequestToStandardRequest, standardResponseToFetchResponse } from "@orpc/server/fetch";
7
+ import { toFetchResponse, toStandardRequest } from "@orpc/server-standard-fetch";
8
8
  import { StandardHandler } from "@orpc/server/standard";
9
9
  var OpenAPIHandler = class {
10
10
  standardHandler;
@@ -14,14 +14,14 @@ var OpenAPIHandler = class {
14
14
  this.standardHandler = new StandardHandler(router, matcher, codec, options);
15
15
  }
16
16
  async handle(request, ...rest) {
17
- const standardRequest = fetchRequestToStandardRequest(request);
17
+ const standardRequest = toStandardRequest(request);
18
18
  const result = await this.standardHandler.handle(standardRequest, ...rest);
19
19
  if (!result.matched) {
20
20
  return result;
21
21
  }
22
22
  return {
23
23
  matched: true,
24
- response: standardResponseToFetchResponse(result.response)
24
+ response: toFetchResponse(result.response)
25
25
  };
26
26
  }
27
27
  };
@@ -29,4 +29,4 @@ var OpenAPIHandler = class {
29
29
  export {
30
30
  OpenAPIHandler
31
31
  };
32
- //# sourceMappingURL=chunk-ICLAXOVR.js.map
32
+ //# sourceMappingURL=chunk-UU2TTVB2.js.map
@@ -0,0 +1,13 @@
1
+ // src/utils.ts
2
+ function standardizeHTTPPath(path) {
3
+ return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
4
+ }
5
+ function toOpenAPI31RoutePattern(path) {
6
+ return standardizeHTTPPath(path).replace(/\{\+([^}]+)\}/g, "{$1}");
7
+ }
8
+
9
+ export {
10
+ standardizeHTTPPath,
11
+ toOpenAPI31RoutePattern
12
+ };
13
+ //# sourceMappingURL=chunk-XGHV4TH3.js.map
package/dist/fetch.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-ICLAXOVR.js";
4
- import "./chunk-PWOV66X6.js";
5
- import "./chunk-HC5PVG4R.js";
3
+ } from "./chunk-UU2TTVB2.js";
4
+ import "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };
package/dist/hono.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-ICLAXOVR.js";
4
- import "./chunk-PWOV66X6.js";
5
- import "./chunk-HC5PVG4R.js";
3
+ } from "./chunk-UU2TTVB2.js";
4
+ import "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };
package/dist/index.js CHANGED
@@ -1,7 +1,53 @@
1
1
  import {
2
- JSONSerializer,
3
- standardizeHTTPPath
4
- } from "./chunk-HC5PVG4R.js";
2
+ standardizeHTTPPath,
3
+ toOpenAPI31RoutePattern
4
+ } from "./chunk-XGHV4TH3.js";
5
+
6
+ // src/openapi-operation-extender.ts
7
+ import { isProcedure } from "@orpc/server";
8
+ var OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
9
+ function setOperationExtender(o, extend) {
10
+ return new Proxy(o, {
11
+ get(target, prop, receiver) {
12
+ if (prop === OPERATION_EXTENDER_SYMBOL) {
13
+ return extend;
14
+ }
15
+ return Reflect.get(target, prop, receiver);
16
+ }
17
+ });
18
+ }
19
+ function getOperationExtender(o) {
20
+ return o[OPERATION_EXTENDER_SYMBOL];
21
+ }
22
+ function extendOperation(operation, procedure) {
23
+ const operationExtenders = [];
24
+ for (const errorItem of Object.values(procedure["~orpc"].errorMap)) {
25
+ const maybeExtender = getOperationExtender(errorItem);
26
+ if (maybeExtender) {
27
+ operationExtenders.push(maybeExtender);
28
+ }
29
+ }
30
+ if (isProcedure(procedure)) {
31
+ for (const middleware of procedure["~orpc"].middlewares) {
32
+ const maybeExtender = getOperationExtender(middleware);
33
+ if (maybeExtender) {
34
+ operationExtenders.push(maybeExtender);
35
+ }
36
+ }
37
+ }
38
+ let currentOperation = operation;
39
+ for (const extender of operationExtenders) {
40
+ if (typeof extender === "function") {
41
+ currentOperation = extender(currentOperation, procedure);
42
+ } else {
43
+ currentOperation = {
44
+ ...currentOperation,
45
+ ...extender
46
+ };
47
+ }
48
+ }
49
+ return currentOperation;
50
+ }
5
51
 
6
52
  // src/openapi.ts
7
53
  import { OpenApiBuilder } from "openapi3-ts/oas31";
@@ -34,7 +80,9 @@ var OpenAPIContentBuilder = class {
34
80
  };
35
81
 
36
82
  // src/openapi-generator.ts
37
- import { fallbackContractConfig as fallbackContractConfig2, fallbackORPCErrorStatus } from "@orpc/contract";
83
+ import { fallbackORPCErrorStatus } from "@orpc/client";
84
+ import { OpenAPIJsonSerializer } from "@orpc/client/openapi";
85
+ import { fallbackContractConfig as fallbackContractConfig2, getEventIteratorSchemaDetails } from "@orpc/contract";
38
86
  import { eachAllContractProcedure } from "@orpc/server";
39
87
  import { group } from "@orpc/shared";
40
88
 
@@ -287,10 +335,10 @@ var NON_LOGIC_KEYWORDS = [
287
335
  // src/schema-utils.ts
288
336
  var SchemaUtils = class {
289
337
  isFileSchema(schema) {
290
- return typeof schema === "object" && schema.type === "string" && typeof schema.contentMediaType === "string";
338
+ return isObject2(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
291
339
  }
292
340
  isObjectSchema(schema) {
293
- return typeof schema === "object" && schema.type === "object";
341
+ return isObject2(schema) && schema.type === "object";
294
342
  }
295
343
  isAnySchema(schema) {
296
344
  return schema === true || Object.keys(schema).filter((key) => !NON_LOGIC_KEYWORDS.includes(key)).length === 0;
@@ -389,7 +437,7 @@ var OpenAPIGenerator = class {
389
437
  this.parametersBuilder = options?.parametersBuilder ?? new OpenAPIParametersBuilder();
390
438
  this.schemaConverter = new CompositeSchemaConverter(options?.schemaConverters ?? []);
391
439
  this.schemaUtils = options?.schemaUtils ?? new SchemaUtils();
392
- this.jsonSerializer = options?.jsonSerializer ?? new JSONSerializer();
440
+ this.jsonSerializer = options?.jsonSerializer ?? new OpenAPIJsonSerializer();
393
441
  this.contentBuilder = options?.contentBuilder ?? new OpenAPIContentBuilder(this.schemaUtils);
394
442
  this.pathParser = new OpenAPIPathParser();
395
443
  this.inputStructureParser = options?.inputStructureParser ?? new OpenAPIInputStructureParser(this.schemaConverter, this.schemaUtils, this.pathParser);
@@ -415,27 +463,124 @@ var OpenAPIGenerator = class {
415
463
  return;
416
464
  }
417
465
  const method = fallbackContractConfig2("defaultMethod", def.route?.method);
418
- const httpPath = def.route?.path ? standardizeHTTPPath(def.route?.path) : `/${path.map(encodeURIComponent).join("/")}`;
419
- const inputStructure = fallbackContractConfig2("defaultInputStructure", def.route?.inputStructure);
420
- const outputStructure = fallbackContractConfig2("defaultOutputStructure", def.route?.outputStructure);
421
- const { paramsSchema, querySchema, headersSchema, bodySchema } = this.inputStructureParser.parse(contract, inputStructure);
422
- const { headersSchema: resHeadersSchema, bodySchema: resBodySchema } = this.outputStructureParser.parse(contract, outputStructure);
423
- const params = paramsSchema ? this.parametersBuilder.build("path", paramsSchema, {
424
- required: true
425
- }) : [];
426
- const query = querySchema ? this.parametersBuilder.build("query", querySchema) : [];
427
- const headers = headersSchema ? this.parametersBuilder.build("header", headersSchema) : [];
428
- const parameters = [...params, ...query, ...headers];
429
- const requestBody = bodySchema !== void 0 ? {
430
- required: this.schemaUtils.isUndefinableSchema(bodySchema),
431
- content: this.contentBuilder.build(bodySchema)
432
- } : void 0;
433
- const responses = {};
434
- responses[fallbackContractConfig2("defaultSuccessStatus", def.route?.successStatus)] = {
435
- description: fallbackContractConfig2("defaultSuccessDescription", def.route?.successDescription),
436
- content: resBodySchema !== void 0 ? this.contentBuilder.build(resBodySchema) : void 0,
437
- headers: resHeadersSchema !== void 0 ? this.parametersBuilder.buildHeadersObject(resHeadersSchema) : void 0
438
- };
466
+ const httpPath = def.route?.path ? toOpenAPI31RoutePattern(def.route?.path) : `/${path.map(encodeURIComponent).join("/")}`;
467
+ const { parameters, requestBody } = (() => {
468
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(def.inputSchema);
469
+ if (eventIteratorSchemaDetails) {
470
+ const requestBody3 = {
471
+ required: true,
472
+ content: {
473
+ "text/event-stream": {
474
+ schema: {
475
+ oneOf: [
476
+ {
477
+ type: "object",
478
+ properties: {
479
+ event: { type: "string", const: "message" },
480
+ data: this.schemaConverter.convert(eventIteratorSchemaDetails.yields, { strategy: "input" }),
481
+ id: { type: "string" },
482
+ retry: { type: "number" }
483
+ },
484
+ required: ["event", "data"]
485
+ },
486
+ {
487
+ type: "object",
488
+ properties: {
489
+ event: { type: "string", const: "done" },
490
+ data: this.schemaConverter.convert(eventIteratorSchemaDetails.returns, { strategy: "input" }),
491
+ id: { type: "string" },
492
+ retry: { type: "number" }
493
+ },
494
+ required: ["event", "data"]
495
+ },
496
+ {
497
+ type: "object",
498
+ properties: {
499
+ event: { type: "string", const: "error" },
500
+ data: {},
501
+ id: { type: "string" },
502
+ retry: { type: "number" }
503
+ },
504
+ required: ["event", "data"]
505
+ }
506
+ ]
507
+ }
508
+ }
509
+ }
510
+ };
511
+ return { requestBody: requestBody3, parameters: [] };
512
+ }
513
+ const inputStructure = fallbackContractConfig2("defaultInputStructure", def.route?.inputStructure);
514
+ const { paramsSchema, querySchema, headersSchema, bodySchema } = this.inputStructureParser.parse(contract, inputStructure);
515
+ const params = paramsSchema ? this.parametersBuilder.build("path", paramsSchema, {
516
+ required: true
517
+ }) : [];
518
+ const query = querySchema ? this.parametersBuilder.build("query", querySchema) : [];
519
+ const headers = headersSchema ? this.parametersBuilder.build("header", headersSchema) : [];
520
+ const parameters2 = [...params, ...query, ...headers];
521
+ const requestBody2 = bodySchema !== void 0 ? {
522
+ required: this.schemaUtils.isUndefinableSchema(bodySchema),
523
+ content: this.contentBuilder.build(bodySchema)
524
+ } : void 0;
525
+ return { parameters: parameters2, requestBody: requestBody2 };
526
+ })();
527
+ const { responses } = (() => {
528
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(def.outputSchema);
529
+ if (eventIteratorSchemaDetails) {
530
+ const responses3 = {};
531
+ responses3[fallbackContractConfig2("defaultSuccessStatus", def.route?.successStatus)] = {
532
+ description: fallbackContractConfig2("defaultSuccessDescription", def.route?.successDescription),
533
+ content: {
534
+ "text/event-stream": {
535
+ schema: {
536
+ oneOf: [
537
+ {
538
+ type: "object",
539
+ properties: {
540
+ event: { type: "string", const: "message" },
541
+ data: this.schemaConverter.convert(eventIteratorSchemaDetails.yields, { strategy: "input" }),
542
+ id: { type: "string" },
543
+ retry: { type: "number" }
544
+ },
545
+ required: ["event", "data"]
546
+ },
547
+ {
548
+ type: "object",
549
+ properties: {
550
+ event: { type: "string", const: "done" },
551
+ data: this.schemaConverter.convert(eventIteratorSchemaDetails.returns, { strategy: "input" }),
552
+ id: { type: "string" },
553
+ retry: { type: "number" }
554
+ },
555
+ required: ["event", "data"]
556
+ },
557
+ {
558
+ type: "object",
559
+ properties: {
560
+ event: { type: "string", const: "error" },
561
+ data: {},
562
+ id: { type: "string" },
563
+ retry: { type: "number" }
564
+ },
565
+ required: ["event", "data"]
566
+ }
567
+ ]
568
+ }
569
+ }
570
+ }
571
+ };
572
+ return { responses: responses3 };
573
+ }
574
+ const outputStructure = fallbackContractConfig2("defaultOutputStructure", def.route?.outputStructure);
575
+ const { headersSchema: resHeadersSchema, bodySchema: resBodySchema } = this.outputStructureParser.parse(contract, outputStructure);
576
+ const responses2 = {};
577
+ responses2[fallbackContractConfig2("defaultSuccessStatus", def.route?.successStatus)] = {
578
+ description: fallbackContractConfig2("defaultSuccessDescription", def.route?.successDescription),
579
+ content: resBodySchema !== void 0 ? this.contentBuilder.build(resBodySchema) : void 0,
580
+ headers: resHeadersSchema !== void 0 ? this.parametersBuilder.buildHeadersObject(resHeadersSchema) : void 0
581
+ };
582
+ return { responses: responses2 };
583
+ })();
439
584
  const errors = group(Object.entries(def.errorMap ?? {}).filter(([_, config]) => config).map(([code, config]) => ({
440
585
  ...config,
441
586
  code,
@@ -506,8 +651,9 @@ var OpenAPIGenerator = class {
506
651
  requestBody,
507
652
  responses
508
653
  };
654
+ const extendedOperation = extendOperation(operation, contract);
509
655
  builder.addPath(httpPath, {
510
- [method.toLocaleLowerCase()]: operation
656
+ [method.toLocaleLowerCase()]: extendedOperation
511
657
  });
512
658
  } catch (e) {
513
659
  if (e instanceof OpenAPIError) {
@@ -529,11 +675,15 @@ var OpenAPIGenerator = class {
529
675
  return this.jsonSerializer.serialize(builder.getSpec());
530
676
  }
531
677
  };
678
+
679
+ // src/index.ts
680
+ var oo = {
681
+ spec: setOperationExtender
682
+ };
532
683
  export {
533
684
  CompositeSchemaConverter,
534
685
  JSONSchema,
535
686
  Format as JSONSchemaFormat,
536
- JSONSerializer,
537
687
  NON_LOGIC_KEYWORDS,
538
688
  OpenAPIContentBuilder,
539
689
  OpenAPIGenerator,
@@ -541,6 +691,11 @@ export {
541
691
  OpenAPIPathParser,
542
692
  OpenApiBuilder,
543
693
  SchemaUtils,
544
- standardizeHTTPPath
694
+ extendOperation,
695
+ getOperationExtender,
696
+ oo,
697
+ setOperationExtender,
698
+ standardizeHTTPPath,
699
+ toOpenAPI31RoutePattern
545
700
  };
546
701
  //# sourceMappingURL=index.js.map
package/dist/next.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  OpenAPIHandler
3
- } from "./chunk-ICLAXOVR.js";
4
- import "./chunk-PWOV66X6.js";
5
- import "./chunk-HC5PVG4R.js";
3
+ } from "./chunk-UU2TTVB2.js";
4
+ import "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
  export {
7
7
  OpenAPIHandler
8
8
  };
package/dist/node.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  OpenAPICodec,
3
3
  OpenAPIMatcher
4
- } from "./chunk-PWOV66X6.js";
5
- import "./chunk-HC5PVG4R.js";
4
+ } from "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
6
6
 
7
7
  // src/adapters/node/openapi-handler.ts
8
- import { nodeHttpResponseSendStandardResponse, nodeHttpToStandardRequest } from "@orpc/server/node";
8
+ import { sendStandardResponse, toStandardRequest } from "@orpc/server-standard-node";
9
9
  import { StandardHandler } from "@orpc/server/standard";
10
10
  var OpenAPIHandler = class {
11
11
  standardHandler;
@@ -15,12 +15,12 @@ var OpenAPIHandler = class {
15
15
  this.standardHandler = new StandardHandler(router, matcher, codec, { ...options });
16
16
  }
17
17
  async handle(req, res, ...rest) {
18
- const standardRequest = nodeHttpToStandardRequest(req, res);
18
+ const standardRequest = toStandardRequest(req, res);
19
19
  const result = await this.standardHandler.handle(standardRequest, ...rest);
20
20
  if (!result.matched) {
21
21
  return { matched: false };
22
22
  }
23
- await nodeHttpResponseSendStandardResponse(res, result.response);
23
+ await sendStandardResponse(res, result.response);
24
24
  return { matched: true };
25
25
  }
26
26
  };
@@ -1,10 +1,11 @@
1
1
  import type { Context, Router } from '@orpc/server';
2
2
  import type { FetchHandler, FetchHandleResult } from '@orpc/server/fetch';
3
- import type { StandardHandleRest } from '@orpc/server/standard';
3
+ import type { StandardHandleOptions } from '@orpc/server/standard';
4
+ import type { MaybeOptionalOptions } from '@orpc/shared';
4
5
  import type { OpenAPIHandlerOptions } from '../standard';
5
6
  export declare class OpenAPIHandler<T extends Context> implements FetchHandler<T> {
6
7
  private readonly standardHandler;
7
8
  constructor(router: Router<T, any>, options?: NoInfer<OpenAPIHandlerOptions<T>>);
8
- handle(request: Request, ...rest: StandardHandleRest<T>): Promise<FetchHandleResult>;
9
+ handle(request: Request, ...rest: MaybeOptionalOptions<StandardHandleOptions<T>>): Promise<FetchHandleResult>;
9
10
  }
10
11
  //# sourceMappingURL=openapi-handler.d.ts.map
@@ -1,10 +1,11 @@
1
1
  import type { Context, Router } from '@orpc/server';
2
2
  import type { NodeHttpHandler, NodeHttpHandleResult, NodeHttpRequest, NodeHttpResponse } from '@orpc/server/node';
3
- import type { StandardHandleRest } from '@orpc/server/standard';
3
+ import type { StandardHandleOptions } from '@orpc/server/standard';
4
+ import type { MaybeOptionalOptions } from '@orpc/shared';
4
5
  import type { OpenAPIHandlerOptions } from '../standard';
5
6
  export declare class OpenAPIHandler<T extends Context> implements NodeHttpHandler<T> {
6
7
  private readonly standardHandler;
7
8
  constructor(router: Router<T, any>, options?: NoInfer<OpenAPIHandlerOptions<T>>);
8
- handle(req: NodeHttpRequest, res: NodeHttpResponse, ...rest: StandardHandleRest<T>): Promise<NodeHttpHandleResult>;
9
+ handle(req: NodeHttpRequest, res: NodeHttpResponse, ...rest: MaybeOptionalOptions<StandardHandleOptions<T>>): Promise<NodeHttpHandleResult>;
9
10
  }
10
11
  //# sourceMappingURL=openapi-handler.d.ts.map
@@ -1,6 +1,4 @@
1
- export * as BracketNotation from './bracket-notation';
2
1
  export * from './openapi-codec';
3
2
  export * from './openapi-handler';
4
3
  export * from './openapi-matcher';
5
- export * from './openapi-serializer';
6
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,7 +1,8 @@
1
+ import type { ORPCError } from '@orpc/client';
1
2
  import type { AnyProcedure } from '@orpc/server';
2
- import type { StandardCodec, StandardParams, StandardRequest, StandardResponse } from '@orpc/server/standard';
3
- import { type ORPCError } from '@orpc/contract';
4
- import { OpenAPISerializer } from './openapi-serializer';
3
+ import type { StandardRequest, StandardResponse } from '@orpc/server-standard';
4
+ import type { StandardCodec, StandardParams } from '@orpc/server/standard';
5
+ import { OpenAPISerializer } from '@orpc/client/openapi';
5
6
  export interface OpenAPICodecOptions {
6
7
  serializer?: OpenAPISerializer;
7
8
  }
@@ -1,12 +1,16 @@
1
1
  /** unnoq */
2
- export * from './json-serializer';
2
+ import { setOperationExtender } from './openapi-operation-extender';
3
3
  export * from './openapi';
4
4
  export * from './openapi-content-builder';
5
5
  export * from './openapi-generator';
6
+ export * from './openapi-operation-extender';
6
7
  export * from './openapi-parameters-builder';
7
8
  export * from './openapi-path-parser';
8
9
  export * from './schema';
9
10
  export * from './schema-converter';
10
11
  export * from './schema-utils';
11
12
  export * from './utils';
13
+ export declare const oo: {
14
+ spec: typeof setOperationExtender;
15
+ };
12
16
  //# sourceMappingURL=index.d.ts.map
@@ -2,9 +2,9 @@ import type { PublicOpenAPIInputStructureParser } from './openapi-input-structur
2
2
  import type { PublicOpenAPIOutputStructureParser } from './openapi-output-structure-parser';
3
3
  import type { PublicOpenAPIPathParser } from './openapi-path-parser';
4
4
  import type { SchemaConverter } from './schema-converter';
5
+ import { type PublicOpenAPIJsonSerializer } from '@orpc/client/openapi';
5
6
  import { type ContractRouter } from '@orpc/contract';
6
7
  import { type AnyRouter } from '@orpc/server';
7
- import { type PublicJSONSerializer } from './json-serializer';
8
8
  import { type OpenAPI } from './openapi';
9
9
  import { type PublicOpenAPIContentBuilder } from './openapi-content-builder';
10
10
  import { type PublicOpenAPIParametersBuilder } from './openapi-parameters-builder';
@@ -15,7 +15,7 @@ export interface OpenAPIGeneratorOptions {
15
15
  parametersBuilder?: PublicOpenAPIParametersBuilder;
16
16
  schemaConverters?: SchemaConverter[];
17
17
  schemaUtils?: PublicSchemaUtils;
18
- jsonSerializer?: PublicJSONSerializer;
18
+ jsonSerializer?: PublicOpenAPIJsonSerializer;
19
19
  pathParser?: PublicOpenAPIPathParser;
20
20
  inputStructureParser?: PublicOpenAPIInputStructureParser;
21
21
  outputStructureParser?: PublicOpenAPIOutputStructureParser;
@@ -0,0 +1,7 @@
1
+ import type { AnyContractProcedure } from '@orpc/contract';
2
+ import type { OpenAPI } from './openapi';
3
+ export type OverrideOperationValue = OpenAPI.OperationObject | ((current: OpenAPI.OperationObject, procedure: AnyContractProcedure) => OpenAPI.OperationObject);
4
+ export declare function setOperationExtender<T extends object>(o: T, extend: OverrideOperationValue): T;
5
+ export declare function getOperationExtender(o: object): OverrideOperationValue | undefined;
6
+ export declare function extendOperation(operation: OpenAPI.OperationObject, procedure: AnyContractProcedure): OpenAPI.OperationObject;
7
+ //# sourceMappingURL=openapi-operation-extender.d.ts.map
@@ -1,3 +1,4 @@
1
1
  import type { HTTPPath } from '@orpc/contract';
2
2
  export declare function standardizeHTTPPath(path: HTTPPath): HTTPPath;
3
+ export declare function toOpenAPI31RoutePattern(path: HTTPPath): string;
3
4
  //# sourceMappingURL=utils.d.ts.map
package/dist/standard.js CHANGED
@@ -1,14 +1,10 @@
1
1
  import {
2
2
  OpenAPICodec,
3
- OpenAPIMatcher,
4
- OpenAPISerializer,
5
- bracket_notation_exports
6
- } from "./chunk-PWOV66X6.js";
7
- import "./chunk-HC5PVG4R.js";
3
+ OpenAPIMatcher
4
+ } from "./chunk-LPBZEW4B.js";
5
+ import "./chunk-XGHV4TH3.js";
8
6
  export {
9
- bracket_notation_exports as BracketNotation,
10
7
  OpenAPICodec,
11
- OpenAPIMatcher,
12
- OpenAPISerializer
8
+ OpenAPIMatcher
13
9
  };
14
10
  //# sourceMappingURL=standard.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/openapi",
3
3
  "type": "module",
4
- "version": "0.0.0-next.7b09958",
4
+ "version": "0.0.0-next.7d3bd71",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -54,18 +54,18 @@
54
54
  "dist"
55
55
  ],
56
56
  "dependencies": {
57
- "escape-string-regexp": "^5.0.0",
58
- "fast-content-type-parse": "^2.0.0",
57
+ "@orpc/server-standard": "^0.4.0",
58
+ "@orpc/server-standard-fetch": "^0.4.0",
59
+ "@orpc/server-standard-node": "^0.4.0",
59
60
  "json-schema-typed": "^8.0.1",
60
61
  "openapi3-ts": "^4.4.0",
61
62
  "rou3": "^0.5.1",
62
- "wildcard-match": "^5.1.3",
63
- "@orpc/contract": "0.0.0-next.7b09958",
64
- "@orpc/shared": "0.0.0-next.7b09958",
65
- "@orpc/server": "0.0.0-next.7b09958"
63
+ "@orpc/client": "0.0.0-next.7d3bd71",
64
+ "@orpc/server": "0.0.0-next.7d3bd71",
65
+ "@orpc/contract": "0.0.0-next.7d3bd71",
66
+ "@orpc/shared": "0.0.0-next.7d3bd71"
66
67
  },
67
68
  "devDependencies": {
68
- "@readme/openapi-parser": "^2.6.0",
69
69
  "zod": "^3.24.1"
70
70
  },
71
71
  "scripts": {
@@ -1,52 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/json-serializer.ts
8
- import { isObject } from "@orpc/shared";
9
- var JSONSerializer = class {
10
- serialize(payload) {
11
- if (payload instanceof Set)
12
- return this.serialize([...payload]);
13
- if (payload instanceof Map)
14
- return this.serialize([...payload.entries()]);
15
- if (Array.isArray(payload)) {
16
- return payload.map((v) => v === void 0 ? "undefined" : this.serialize(v));
17
- }
18
- if (Number.isNaN(payload))
19
- return "NaN";
20
- if (typeof payload === "bigint")
21
- return payload.toString();
22
- if (payload instanceof Date && Number.isNaN(payload.getTime())) {
23
- return "Invalid Date";
24
- }
25
- if (payload instanceof RegExp)
26
- return payload.toString();
27
- if (payload instanceof URL)
28
- return payload.toString();
29
- if (!isObject(payload))
30
- return payload;
31
- return Object.keys(payload).reduce(
32
- (carry, key) => {
33
- const val = payload[key];
34
- carry[key] = this.serialize(val);
35
- return carry;
36
- },
37
- {}
38
- );
39
- }
40
- };
41
-
42
- // src/utils.ts
43
- function standardizeHTTPPath(path) {
44
- return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
45
- }
46
-
47
- export {
48
- __export,
49
- JSONSerializer,
50
- standardizeHTTPPath
51
- };
52
- //# sourceMappingURL=chunk-HC5PVG4R.js.map
@@ -1,421 +0,0 @@
1
- import {
2
- JSONSerializer,
3
- __export,
4
- standardizeHTTPPath
5
- } from "./chunk-HC5PVG4R.js";
6
-
7
- // src/adapters/standard/bracket-notation.ts
8
- var bracket_notation_exports = {};
9
- __export(bracket_notation_exports, {
10
- deserialize: () => deserialize,
11
- escapeSegment: () => escapeSegment,
12
- parsePath: () => parsePath,
13
- serialize: () => serialize,
14
- stringifyPath: () => stringifyPath
15
- });
16
- import { isObject } from "@orpc/shared";
17
- function serialize(payload, parentKey = "") {
18
- if (!Array.isArray(payload) && !isObject(payload))
19
- return [["", payload]];
20
- const result = [];
21
- function helper(value, path) {
22
- if (Array.isArray(value)) {
23
- value.forEach((item, index) => {
24
- helper(item, [...path, String(index)]);
25
- });
26
- } else if (isObject(value)) {
27
- for (const [key, val] of Object.entries(value)) {
28
- helper(val, [...path, key]);
29
- }
30
- } else {
31
- result.push([stringifyPath(path), value]);
32
- }
33
- }
34
- helper(payload, parentKey ? [parentKey] : []);
35
- return result;
36
- }
37
- function deserialize(entities) {
38
- if (entities.length === 0) {
39
- return void 0;
40
- }
41
- const isRootArray = entities.every(([path]) => path === "");
42
- const result = isRootArray ? [] : {};
43
- const arrayPushPaths = /* @__PURE__ */ new Set();
44
- for (const [path, _] of entities) {
45
- const segments = parsePath(path);
46
- const base = segments.slice(0, -1).join(".");
47
- const last = segments[segments.length - 1];
48
- if (last === "") {
49
- arrayPushPaths.add(base);
50
- } else {
51
- arrayPushPaths.delete(base);
52
- }
53
- }
54
- function setValue(obj, segments, value, fullPath) {
55
- const [first, ...rest_] = segments;
56
- if (Array.isArray(obj) && first === "") {
57
- ;
58
- obj.push(value);
59
- return;
60
- }
61
- const objAsRecord = obj;
62
- if (rest_.length === 0) {
63
- objAsRecord[first] = value;
64
- return;
65
- }
66
- const rest = rest_;
67
- if (rest[0] === "") {
68
- const pathToCheck = segments.slice(0, -1).join(".");
69
- if (rest.length === 1 && arrayPushPaths.has(pathToCheck)) {
70
- if (!(first in objAsRecord)) {
71
- objAsRecord[first] = [];
72
- }
73
- if (Array.isArray(objAsRecord[first])) {
74
- ;
75
- objAsRecord[first].push(value);
76
- return;
77
- }
78
- }
79
- if (!(first in objAsRecord)) {
80
- objAsRecord[first] = {};
81
- }
82
- const target = objAsRecord[first];
83
- target[""] = value;
84
- return;
85
- }
86
- if (!(first in objAsRecord)) {
87
- objAsRecord[first] = {};
88
- }
89
- setValue(
90
- objAsRecord[first],
91
- rest,
92
- value,
93
- fullPath
94
- );
95
- }
96
- for (const [path, value] of entities) {
97
- const segments = parsePath(path);
98
- setValue(result, segments, value, path);
99
- }
100
- return result;
101
- }
102
- function escapeSegment(segment) {
103
- return segment.replace(/[\\[\]]/g, (match) => {
104
- switch (match) {
105
- case "\\":
106
- return "\\\\";
107
- case "[":
108
- return "\\[";
109
- case "]":
110
- return "\\]";
111
- default:
112
- return match;
113
- }
114
- });
115
- }
116
- function stringifyPath(path) {
117
- const [first, ...rest] = path;
118
- const firstSegment = escapeSegment(first);
119
- const base = first === "" ? "" : firstSegment;
120
- return rest.reduce(
121
- (result, segment) => `${result}[${escapeSegment(segment)}]`,
122
- base
123
- );
124
- }
125
- function parsePath(path) {
126
- if (path === "")
127
- return [""];
128
- const result = [];
129
- let currentSegment = "";
130
- let inBracket = false;
131
- let bracketContent = "";
132
- let backslashCount = 0;
133
- for (let i = 0; i < path.length; i++) {
134
- const char = path[i];
135
- if (char === "\\") {
136
- backslashCount++;
137
- continue;
138
- }
139
- if (backslashCount > 0) {
140
- const literalBackslashes = "\\".repeat(Math.floor(backslashCount / 2));
141
- if (char === "[" || char === "]") {
142
- if (backslashCount % 2 === 1) {
143
- if (inBracket) {
144
- bracketContent += literalBackslashes + char;
145
- } else {
146
- currentSegment += literalBackslashes + char;
147
- }
148
- } else {
149
- if (inBracket) {
150
- bracketContent += literalBackslashes;
151
- } else {
152
- currentSegment += literalBackslashes;
153
- }
154
- if (char === "[" && !inBracket) {
155
- if (currentSegment !== "" || result.length === 0) {
156
- result.push(currentSegment);
157
- }
158
- inBracket = true;
159
- bracketContent = "";
160
- currentSegment = "";
161
- } else if (char === "]" && inBracket) {
162
- result.push(bracketContent);
163
- inBracket = false;
164
- bracketContent = "";
165
- } else {
166
- if (inBracket) {
167
- bracketContent += char;
168
- } else {
169
- currentSegment += char;
170
- }
171
- }
172
- }
173
- } else {
174
- const allBackslashes = "\\".repeat(backslashCount);
175
- if (inBracket) {
176
- bracketContent += allBackslashes + char;
177
- } else {
178
- currentSegment += allBackslashes + char;
179
- }
180
- }
181
- backslashCount = 0;
182
- continue;
183
- }
184
- if (char === "[" && !inBracket) {
185
- if (currentSegment !== "" || result.length === 0) {
186
- result.push(currentSegment);
187
- }
188
- inBracket = true;
189
- bracketContent = "";
190
- currentSegment = "";
191
- continue;
192
- }
193
- if (char === "]" && inBracket) {
194
- result.push(bracketContent);
195
- inBracket = false;
196
- bracketContent = "";
197
- continue;
198
- }
199
- if (inBracket) {
200
- bracketContent += char;
201
- } else {
202
- currentSegment += char;
203
- }
204
- }
205
- if (backslashCount > 0) {
206
- const remainingBackslashes = "\\".repeat(backslashCount);
207
- if (inBracket) {
208
- bracketContent += remainingBackslashes;
209
- } else {
210
- currentSegment += remainingBackslashes;
211
- }
212
- }
213
- if (inBracket) {
214
- if (currentSegment !== "" || result.length === 0) {
215
- result.push(currentSegment);
216
- }
217
- result.push(`[${bracketContent}`);
218
- } else if (currentSegment !== "" || result.length === 0) {
219
- result.push(currentSegment);
220
- }
221
- return result;
222
- }
223
-
224
- // src/adapters/standard/openapi-codec.ts
225
- import { fallbackContractConfig } from "@orpc/contract";
226
- import { isObject as isObject2 } from "@orpc/shared";
227
-
228
- // src/adapters/standard/openapi-serializer.ts
229
- import { findDeepMatches } from "@orpc/shared";
230
- var OpenAPISerializer = class {
231
- jsonSerializer;
232
- constructor(options) {
233
- this.jsonSerializer = options?.jsonSerializer ?? new JSONSerializer();
234
- }
235
- serialize(data) {
236
- if (data instanceof Blob || data === void 0) {
237
- return data;
238
- }
239
- const serializedJSON = this.jsonSerializer.serialize(data);
240
- const { values: blobs } = findDeepMatches((v) => v instanceof Blob, serializedJSON);
241
- if (blobs.length === 0) {
242
- return serializedJSON;
243
- }
244
- const form = new FormData();
245
- for (const [path, value] of serialize(serializedJSON)) {
246
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
247
- form.append(path, value.toString());
248
- } else if (value instanceof Date) {
249
- form.append(path, value.toISOString());
250
- } else if (value instanceof Blob) {
251
- form.append(path, value);
252
- }
253
- }
254
- return form;
255
- }
256
- deserialize(serialized) {
257
- if (serialized instanceof URLSearchParams || serialized instanceof FormData) {
258
- return deserialize([...serialized.entries()]);
259
- }
260
- return serialized;
261
- }
262
- };
263
-
264
- // src/adapters/standard/openapi-codec.ts
265
- var OpenAPICodec = class {
266
- serializer;
267
- constructor(options) {
268
- this.serializer = options?.serializer ?? new OpenAPISerializer();
269
- }
270
- async decode(request, params, procedure) {
271
- const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
272
- if (inputStructure === "compact") {
273
- const data = request.method === "GET" ? this.serializer.deserialize(request.url.searchParams) : this.serializer.deserialize(await request.body());
274
- if (data === void 0) {
275
- return params;
276
- }
277
- if (isObject2(data)) {
278
- return {
279
- ...params,
280
- ...data
281
- };
282
- }
283
- return data;
284
- }
285
- const deserializeSearchParams = () => {
286
- return this.serializer.deserialize(request.url.searchParams);
287
- };
288
- return {
289
- params,
290
- get query() {
291
- const value = deserializeSearchParams();
292
- Object.defineProperty(this, "query", { value, writable: true });
293
- return value;
294
- },
295
- set query(value) {
296
- Object.defineProperty(this, "query", { value, writable: true });
297
- },
298
- headers: request.headers,
299
- body: this.serializer.deserialize(await request.body())
300
- };
301
- }
302
- encode(output, procedure) {
303
- const successStatus = fallbackContractConfig("defaultSuccessStatus", procedure["~orpc"].route.successStatus);
304
- const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
305
- if (outputStructure === "compact") {
306
- return {
307
- status: successStatus,
308
- headers: {},
309
- body: this.serializer.serialize(output)
310
- };
311
- }
312
- if (!isObject2(output)) {
313
- throw new Error(
314
- 'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
315
- );
316
- }
317
- return {
318
- status: successStatus,
319
- headers: output.headers ?? {},
320
- body: this.serializer.serialize(output.body)
321
- };
322
- }
323
- encodeError(error) {
324
- return {
325
- status: error.status,
326
- headers: {},
327
- body: this.serializer.serialize(error.toJSON())
328
- };
329
- }
330
- };
331
-
332
- // src/adapters/standard/openapi-matcher.ts
333
- import { fallbackContractConfig as fallbackContractConfig2 } from "@orpc/contract";
334
- import { convertPathToHttpPath, createContractedProcedure, eachContractProcedure, getLazyRouterPrefix, getRouterChild, isProcedure, unlazy } from "@orpc/server";
335
- import { addRoute, createRouter, findRoute } from "rou3";
336
- var OpenAPIMatcher = class {
337
- tree = createRouter();
338
- ignoreUndefinedMethod;
339
- constructor(options) {
340
- this.ignoreUndefinedMethod = options?.ignoreUndefinedMethod ?? false;
341
- }
342
- pendingRouters = [];
343
- init(router, path = []) {
344
- const laziedOptions = eachContractProcedure({
345
- router,
346
- path
347
- }, ({ path: path2, contract }) => {
348
- if (!contract["~orpc"].route.method && this.ignoreUndefinedMethod) {
349
- return;
350
- }
351
- const method = fallbackContractConfig2("defaultMethod", contract["~orpc"].route.method);
352
- const httpPath = contract["~orpc"].route.path ? convertOpenAPIPathToRouterPath(contract["~orpc"].route.path) : convertPathToHttpPath(path2);
353
- if (isProcedure(contract)) {
354
- addRoute(this.tree, method, httpPath, {
355
- path: path2,
356
- contract,
357
- procedure: contract,
358
- // this mean dev not used contract-first so we can used contract as procedure directly
359
- router
360
- });
361
- } else {
362
- addRoute(this.tree, method, httpPath, {
363
- path: path2,
364
- contract,
365
- procedure: void 0,
366
- router
367
- });
368
- }
369
- });
370
- this.pendingRouters.push(...laziedOptions.map((option) => ({
371
- ...option,
372
- httpPathPrefix: convertPathToHttpPath(option.path),
373
- laziedPrefix: getLazyRouterPrefix(option.lazied)
374
- })));
375
- }
376
- async match(method, pathname) {
377
- if (this.pendingRouters.length) {
378
- const newPendingRouters = [];
379
- for (const pendingRouter of this.pendingRouters) {
380
- if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
381
- const { default: router } = await unlazy(pendingRouter.lazied);
382
- this.init(router, pendingRouter.path);
383
- } else {
384
- newPendingRouters.push(pendingRouter);
385
- }
386
- }
387
- this.pendingRouters = newPendingRouters;
388
- }
389
- const match = findRoute(this.tree, method, pathname);
390
- if (!match) {
391
- return void 0;
392
- }
393
- if (!match.data.procedure) {
394
- const { default: maybeProcedure } = await unlazy(getRouterChild(match.data.router, ...match.data.path));
395
- if (!isProcedure(maybeProcedure)) {
396
- throw new Error(`
397
- [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.data.path)}.
398
- Ensure that the procedure is correctly defined and matches the expected contract.
399
- `);
400
- }
401
- match.data.procedure = createContractedProcedure(match.data.contract, maybeProcedure);
402
- }
403
- return {
404
- path: match.data.path,
405
- procedure: match.data.procedure,
406
- params: match.params ? { ...match.params } : void 0
407
- // normalize params
408
- };
409
- }
410
- };
411
- function convertOpenAPIPathToRouterPath(path) {
412
- return standardizeHTTPPath(path).replace(/\{([^}]+)\}/g, ":$1");
413
- }
414
-
415
- export {
416
- bracket_notation_exports,
417
- OpenAPISerializer,
418
- OpenAPICodec,
419
- OpenAPIMatcher
420
- };
421
- //# sourceMappingURL=chunk-PWOV66X6.js.map
@@ -1,84 +0,0 @@
1
- /**
2
- * Serialize an object or array into a list of [key, value] pairs.
3
- * The key will express by using bracket-notation.
4
- *
5
- * Notice: This way cannot express the empty object or array.
6
- *
7
- * @example
8
- * ```ts
9
- * const payload = {
10
- * name: 'John Doe',
11
- * pets: ['dog', 'cat'],
12
- * }
13
- *
14
- * const entities = serialize(payload)
15
- *
16
- * expect(entities).toEqual([
17
- * ['name', 'John Doe'],
18
- * ['name[pets][0]', 'dog'],
19
- * ['name[pets][1]', 'cat'],
20
- * ])
21
- * ```
22
- */
23
- export declare function serialize(payload: unknown, parentKey?: string): [string, unknown][];
24
- /**
25
- * Deserialize a list of [key, value] pairs into an object or array.
26
- * The key is expressed by using bracket-notation.
27
- *
28
- * @example
29
- * ```ts
30
- * const entities = [
31
- * ['name', 'John Doe'],
32
- * ['name[pets][0]', 'dog'],
33
- * ['name[pets][1]', 'cat'],
34
- * ['name[dogs][]', 'hello'],
35
- * ['name[dogs][]', 'kitty'],
36
- * ]
37
- *
38
- * const payload = deserialize(entities)
39
- *
40
- * expect(payload).toEqual({
41
- * name: 'John Doe',
42
- * pets: { 0: 'dog', 1: 'cat' },
43
- * dogs: ['hello', 'kitty'],
44
- * })
45
- * ```
46
- */
47
- export declare function deserialize(entities: readonly (readonly [string, unknown])[]): Record<string, unknown> | unknown[] | undefined;
48
- /**
49
- * Escape the `[`, `]`, and `\` chars in a path segment.
50
- *
51
- * @example
52
- * ```ts
53
- * expect(escapeSegment('name[pets')).toEqual('name\\[pets')
54
- * ```
55
- */
56
- export declare function escapeSegment(segment: string): string;
57
- /**
58
- * Convert an array of path segments into a path string using bracket-notation.
59
- *
60
- * For the special char `[`, `]`, and `\` will be escaped by adding `\` at start.
61
- *
62
- * @example
63
- * ```ts
64
- * expect(stringifyPath(['name', 'pets', '0'])).toEqual('name[pets][0]')
65
- * ```
66
- */
67
- export declare function stringifyPath(path: readonly [string, ...string[]]): string;
68
- /**
69
- * Convert a path string using bracket-notation into an array of path segments.
70
- *
71
- * For the special char `[`, `]`, and `\` you should escape by adding `\` at start.
72
- * It only treats a pair `[${string}]` as a path segment.
73
- * If missing or escape it will bypass and treat as normal string.
74
- *
75
- * @example
76
- * ```ts
77
- * expect(parsePath('name[pets][0]')).toEqual(['name', 'pets', '0'])
78
- * expect(parsePath('name[pets][0')).toEqual(['name', 'pets', '[0'])
79
- * expect(parsePath('name[pets[0]')).toEqual(['name', 'pets[0')
80
- * expect(parsePath('name\\[pets][0]')).toEqual(['name[pets]', '0'])
81
- * ```
82
- */
83
- export declare function parsePath(path: string): [string, ...string[]];
84
- //# sourceMappingURL=bracket-notation.d.ts.map
@@ -1,11 +0,0 @@
1
- import type { PublicJSONSerializer } from '../../json-serializer';
2
- export interface OpenAPISerializerOptions {
3
- jsonSerializer?: PublicJSONSerializer;
4
- }
5
- export declare class OpenAPISerializer {
6
- private readonly jsonSerializer;
7
- constructor(options?: OpenAPISerializerOptions);
8
- serialize(data: unknown): unknown;
9
- deserialize(serialized: unknown): unknown;
10
- }
11
- //# sourceMappingURL=openapi-serializer.d.ts.map
@@ -1,5 +0,0 @@
1
- export declare class JSONSerializer {
2
- serialize(payload: unknown): unknown;
3
- }
4
- export type PublicJSONSerializer = Pick<JSONSerializer, keyof JSONSerializer>;
5
- //# sourceMappingURL=json-serializer.d.ts.map