@rest-vir/define-service 0.0.2

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 (50) hide show
  1. package/LICENSE-CC0 +121 -0
  2. package/LICENSE-MIT +21 -0
  3. package/README.md +88 -0
  4. package/dist/augments/json.d.ts +8 -0
  5. package/dist/augments/json.js +13 -0
  6. package/dist/dev-port/find-dev-port.d.ts +132 -0
  7. package/dist/dev-port/find-dev-port.js +156 -0
  8. package/dist/endpoint/endpoint-path.d.ts +27 -0
  9. package/dist/endpoint/endpoint-path.js +14 -0
  10. package/dist/endpoint/endpoint.d.ts +198 -0
  11. package/dist/endpoint/endpoint.js +80 -0
  12. package/dist/frontend-connect/connect-web-socket.d.ts +95 -0
  13. package/dist/frontend-connect/connect-web-socket.js +64 -0
  14. package/dist/frontend-connect/fetch-endpoint.d.ts +199 -0
  15. package/dist/frontend-connect/fetch-endpoint.js +135 -0
  16. package/dist/frontend-connect/generate-api.d.ts +102 -0
  17. package/dist/frontend-connect/generate-api.js +83 -0
  18. package/dist/frontend-connect/mock-client-web-socket.d.ts +187 -0
  19. package/dist/frontend-connect/mock-client-web-socket.js +198 -0
  20. package/dist/frontend-connect/web-socket-protocol-parse.d.ts +10 -0
  21. package/dist/frontend-connect/web-socket-protocol-parse.js +111 -0
  22. package/dist/index.d.ts +23 -0
  23. package/dist/index.js +23 -0
  24. package/dist/service/define-service.d.ts +19 -0
  25. package/dist/service/define-service.js +133 -0
  26. package/dist/service/match-url.d.ts +30 -0
  27. package/dist/service/match-url.js +31 -0
  28. package/dist/service/minimal-service.d.ts +44 -0
  29. package/dist/service/minimal-service.js +1 -0
  30. package/dist/service/service-definition.d.ts +80 -0
  31. package/dist/service/service-definition.error.d.ts +35 -0
  32. package/dist/service/service-definition.error.js +34 -0
  33. package/dist/service/service-definition.js +1 -0
  34. package/dist/util/mock-fetch.d.ts +107 -0
  35. package/dist/util/mock-fetch.js +199 -0
  36. package/dist/util/no-param.d.ts +16 -0
  37. package/dist/util/no-param.js +8 -0
  38. package/dist/util/origin.d.ts +43 -0
  39. package/dist/util/origin.js +19 -0
  40. package/dist/util/path-to-regexp.d.ts +54 -0
  41. package/dist/util/path-to-regexp.js +307 -0
  42. package/dist/util/search-params.d.ts +9 -0
  43. package/dist/util/search-params.js +1 -0
  44. package/dist/web-socket/common-web-socket.d.ts +103 -0
  45. package/dist/web-socket/common-web-socket.js +28 -0
  46. package/dist/web-socket/overwrite-web-socket-methods.d.ts +276 -0
  47. package/dist/web-socket/overwrite-web-socket-methods.js +210 -0
  48. package/dist/web-socket/web-socket-definition.d.ts +170 -0
  49. package/dist/web-socket/web-socket-definition.js +78 -0
  50. package/package.json +68 -0
package/LICENSE-CC0 ADDED
@@ -0,0 +1,121 @@
1
+ CC0 1.0 Universal
2
+
3
+ Creative Commons Legal Code
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 electrovir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @rest-vir/define-service
2
+
3
+ Part of the rest-vir suite. This package is used for defining a declarative and type safe REST service with both endpoints and WebSockets.
4
+
5
+ See the full docs at https://electrovir.github.io/rest-vir
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ npm i @rest-vir/define-service
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Define your service:
16
+
17
+ <!-- example-link: src/examples/my-service.example.ts -->
18
+
19
+ ```TypeScript
20
+ import {AnyOrigin, defineService, HttpMethod} from '@rest-vir/define-service';
21
+
22
+ export const myService = defineService({
23
+ /** The name of your service. This will be visible to all consumers of this service definition. */
24
+ serviceName: 'my-service',
25
+ /**
26
+ * The origin at which the service will be hosted. Fetch requests and WebSocket connections will
27
+ * be sent to this service will be sent to this origin.
28
+ *
29
+ * It is recommended to use a ternary to switch between dev and prod origins.
30
+ */
31
+ serviceOrigin: isDev ? 'http://localhost:3000' : 'https://example.com',
32
+ /**
33
+ * The service's `origin` requirement for all endpoint requests and WebSocket connections. This
34
+ * is used for CORS handshakes.
35
+ *
36
+ * This can be a string, a RegExp, a function, or an array of any of those. (If this is an
37
+ * array, the first matching array element will be used.)
38
+ *
39
+ * Set this to `AnyOrigin` (imported from `'@rest-vir/define-service'`) to allow any origins.
40
+ * Make sure that you're okay with the security impact this may have on your users of doing so.
41
+ */
42
+ requiredClientOrigin: AnyOrigin,
43
+ endpoints: {
44
+ '/my-endpoint': {
45
+ /** This endpoint requires all requests to contain a string body. */
46
+ requestDataShape: '',
47
+ /** This endpoint's response body will always be empty. */
48
+ responseDataShape: undefined,
49
+
50
+ methods: {
51
+ [HttpMethod.Post]: true,
52
+ },
53
+ },
54
+ /** Express-style path params are allowed. */
55
+ '/my-endpoint/:user-id': {
56
+ /** This endpoint expects no request body data. */
57
+ requestDataShape: undefined,
58
+ /**
59
+ * This endpoint will always response with data that matches:
60
+ *
61
+ * {
62
+ * username: string,
63
+ * firstName: string,
64
+ * lastName: string
65
+ * }
66
+ */
67
+ responseDataShape: {
68
+ username: '',
69
+ firstName: '',
70
+ lastName: '',
71
+ },
72
+ methods: {
73
+ [HttpMethod.Get]: true,
74
+ },
75
+ /** Each endpoint may override the service's origin requirement. */
76
+ requiredClientOrigin: 'https://example.com',
77
+ },
78
+ },
79
+ webSockets: {
80
+ '/my-web-socket': {
81
+ /** This WebSocket requires all messages from the client to be a string. */
82
+ messageFromClientShape: '',
83
+ /** Same for messages from the host. */
84
+ messageFromHostShape: '',
85
+ },
86
+ },
87
+ });
88
+ ```
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Parses a JSON string and converts `'undefined'` to `undefined`.
3
+ *
4
+ * @category Internal
5
+ * @category Package : @rest-vir/define-service
6
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
7
+ */
8
+ export declare function parseJsonWithUndefined(data: string): any;
@@ -0,0 +1,13 @@
1
+ import { wrapInTry } from '@augment-vir/common';
2
+ /**
3
+ * Parses a JSON string and converts `'undefined'` to `undefined`.
4
+ *
5
+ * @category Internal
6
+ * @category Package : @rest-vir/define-service
7
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
8
+ */
9
+ export function parseJsonWithUndefined(data) {
10
+ return wrapInTry(() => JSON.parse(data), {
11
+ fallbackValue: data === 'undefined' ? undefined : data,
12
+ });
13
+ }
@@ -0,0 +1,132 @@
1
+ import { type MaybePromise, type PartialWithUndefined, type SelectFrom } from '@augment-vir/common';
2
+ import { type AnyDuration } from 'date-vir';
3
+ import type { EndpointPathBase } from '../endpoint/endpoint-path.js';
4
+ import { GenericFetchEndpointParams } from '../frontend-connect/fetch-endpoint.js';
5
+ import type { ServiceDefinition } from '../service/service-definition.js';
6
+ /**
7
+ * This header is set on all responses handled by rest-vir so we know what service a response came
8
+ * from.
9
+ *
10
+ * @category Internal
11
+ * @category Package : @rest-vir/define-service
12
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
13
+ */
14
+ export declare const restVirServiceNameHeader = "rest-vir-service";
15
+ /**
16
+ * Options for {@link findDevServicePort} and {@link findLivePort}.
17
+ *
18
+ * @category Internal
19
+ * @category Package : @rest-vir/define-service
20
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
21
+ */
22
+ export type FindPortOptions = Pick<GenericFetchEndpointParams, 'fetch'> & PartialWithUndefined<{
23
+ /**
24
+ * The maximum number of ports that are scanned before giving up.
25
+ *
26
+ * @default 100
27
+ */
28
+ maxScanDistance: number;
29
+ /**
30
+ * A callback that is used to determine if a port's response is valid.
31
+ *
32
+ * If this is not provided, the check is simply `!!response.ok`.
33
+ *
34
+ * If this is provided, returning `true` determines that a port response is valid. This will
35
+ * only be called if `response.ok` is already `true`.
36
+ */
37
+ isValidResponse: (response: Readonly<Response>) => MaybePromise<boolean>;
38
+ /**
39
+ * Max duration that port finding is allowed to go on for.
40
+ *
41
+ * @default {seconds: 10}
42
+ */
43
+ timeout: AnyDuration;
44
+ /**
45
+ * A starting origin used to replace the service definition's origin, in case you need to
46
+ * keep your service definition's origin static for API publishing purposes.
47
+ *
48
+ * This defaults to whatever origin is already set on the given service definition.
49
+ */
50
+ startingOriginOverride: string;
51
+ }>;
52
+ /**
53
+ * Use this to find a service's port number when started without a locked-in port. This allows a
54
+ * client (usually a website frontend) to find which port the server started on by scanning ports
55
+ * starting with the port defined in the service's `serviceOrigin` property.
56
+ *
57
+ * If the service has no port in its `serviceOrigin` property, this function throws an error.
58
+ *
59
+ * Note that the service given must have at least one endpoint defined for this function to work.
60
+ *
61
+ * This is used in `defineService` if the `findActiveDevPort` option is set to true.
62
+ *
63
+ * @category Internal
64
+ * @category Package : @rest-vir/define-service
65
+ * @example
66
+ *
67
+ * ```ts
68
+ * import {findDevServicePort, defineService, AnyOrigin} from '@rest-vir/define-service';
69
+ *
70
+ * const myService = defineService({
71
+ * serviceName: 'my-service',
72
+ * serviceOrigin: 'https://localhost:3000',
73
+ * requiredClientOrigin: AnyOrigin,
74
+ * endpoints: {
75
+ * '/my-path': {
76
+ * methods: {
77
+ * [HttpMethod.Get]: true,
78
+ * },
79
+ * requestDataShape: undefined,
80
+ * responseDataShape: undefined,
81
+ * },
82
+ * },
83
+ * });
84
+ *
85
+ * const {origin} = await findDevServicePort(myService);
86
+ * ```
87
+ *
88
+ * @throws Error if no valid starting port can be found or if the max scan distance has been reached
89
+ * without finding a valid port.
90
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
91
+ */
92
+ export declare function findDevServicePort(service: Readonly<SelectFrom<ServiceDefinition, {
93
+ endpoints: true;
94
+ serviceOrigin: true;
95
+ serviceName: true;
96
+ }>>, options?: Readonly<Omit<FindPortOptions, 'isValidResponse'>>): Promise<{
97
+ port: number;
98
+ origin: string;
99
+ }>;
100
+ /**
101
+ * Find the first port, starting with the port in the given origin, that, with the given path, is
102
+ * alive and matches, if provided, `isValidResponse`.
103
+ *
104
+ * @category Internal
105
+ * @category Package : @rest-vir/define-service
106
+ * @throws Error if no valid starting port can be found or if the max scan distance has been reached
107
+ * without finding a valid port.
108
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
109
+ */
110
+ export declare function findLivePort(originWithStartingPort: string, pathToCheck: EndpointPathBase, { fetch, maxScanDistance, isValidResponse, timeout, }?: Readonly<Omit<FindPortOptions, 'overwriteOrigin'>>): Promise<number>;
111
+ /**
112
+ * Creates a copy of a service definition (without mutating the original service definition) that
113
+ * maps the service's origin port to find the live port that's actually running.
114
+ *
115
+ * This is useful for situations in dev where backend automatically starts on a different port if
116
+ * the original port is already in use.
117
+ *
118
+ * @category Client (Frontend) Connection
119
+ * @category Package : @rest-vir/define-service
120
+ * @example
121
+ *
122
+ * ```ts
123
+ * import {mapServiceDevPort} from '@rest-vir/define-service';
124
+ *
125
+ * const mappedService = await mapServiceDevPort(myServiceDefinition);
126
+ * ```
127
+ *
128
+ * @throws Error if no valid starting port can be found or if the max scan distance has been reached
129
+ * without finding a valid port.
130
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
131
+ */
132
+ export declare function mapServiceDevPort<const SpecificService extends ServiceDefinition>(service: Readonly<SpecificService>, options?: Readonly<Omit<FindPortOptions, 'isValidResponse'>>): Promise<SpecificService>;
@@ -0,0 +1,156 @@
1
+ import { assert, check, waitUntil } from '@augment-vir/assert';
2
+ import { ensureErrorAndPrependMessage, HttpMethod, wrapInTry, } from '@augment-vir/common';
3
+ import { convertDuration } from 'date-vir';
4
+ import { buildUrl, parseUrl } from 'url-vir';
5
+ import { defineService } from '../service/define-service.js';
6
+ /**
7
+ * This header is set on all responses handled by rest-vir so we know what service a response came
8
+ * from.
9
+ *
10
+ * @category Internal
11
+ * @category Package : @rest-vir/define-service
12
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
13
+ */
14
+ export const restVirServiceNameHeader = 'rest-vir-service';
15
+ /**
16
+ * Use this to find a service's port number when started without a locked-in port. This allows a
17
+ * client (usually a website frontend) to find which port the server started on by scanning ports
18
+ * starting with the port defined in the service's `serviceOrigin` property.
19
+ *
20
+ * If the service has no port in its `serviceOrigin` property, this function throws an error.
21
+ *
22
+ * Note that the service given must have at least one endpoint defined for this function to work.
23
+ *
24
+ * This is used in `defineService` if the `findActiveDevPort` option is set to true.
25
+ *
26
+ * @category Internal
27
+ * @category Package : @rest-vir/define-service
28
+ * @example
29
+ *
30
+ * ```ts
31
+ * import {findDevServicePort, defineService, AnyOrigin} from '@rest-vir/define-service';
32
+ *
33
+ * const myService = defineService({
34
+ * serviceName: 'my-service',
35
+ * serviceOrigin: 'https://localhost:3000',
36
+ * requiredClientOrigin: AnyOrigin,
37
+ * endpoints: {
38
+ * '/my-path': {
39
+ * methods: {
40
+ * [HttpMethod.Get]: true,
41
+ * },
42
+ * requestDataShape: undefined,
43
+ * responseDataShape: undefined,
44
+ * },
45
+ * },
46
+ * });
47
+ *
48
+ * const {origin} = await findDevServicePort(myService);
49
+ * ```
50
+ *
51
+ * @throws Error if no valid starting port can be found or if the max scan distance has been reached
52
+ * without finding a valid port.
53
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
54
+ */
55
+ export async function findDevServicePort(service, options = {}) {
56
+ try {
57
+ const startingOrigin = options.startingOriginOverride || service.serviceOrigin;
58
+ const endpoint = Object.values(service.endpoints)[0];
59
+ if (!endpoint) {
60
+ throw new Error(`Service has no endpoints.`);
61
+ }
62
+ const port = await waitUntil.isNumber(() => findLivePort(startingOrigin, endpoint.path, {
63
+ ...options,
64
+ isValidResponse(response) {
65
+ return (response.headers.get(restVirServiceNameHeader) === service.serviceName);
66
+ },
67
+ }), {
68
+ timeout: options.timeout,
69
+ });
70
+ const { origin } = buildUrl(startingOrigin, {
71
+ port,
72
+ });
73
+ return {
74
+ port,
75
+ origin,
76
+ };
77
+ }
78
+ catch (error) {
79
+ throw ensureErrorAndPrependMessage(error, `Cannot find dev origin for service '${service.serviceName}'`);
80
+ }
81
+ }
82
+ /**
83
+ * Find the first port, starting with the port in the given origin, that, with the given path, is
84
+ * alive and matches, if provided, `isValidResponse`.
85
+ *
86
+ * @category Internal
87
+ * @category Package : @rest-vir/define-service
88
+ * @throws Error if no valid starting port can be found or if the max scan distance has been reached
89
+ * without finding a valid port.
90
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
91
+ */
92
+ export async function findLivePort(originWithStartingPort, pathToCheck, { fetch = globalThis.fetch, maxScanDistance = 100, isValidResponse, timeout = { seconds: 10 }, } = {}) {
93
+ const { port: originalPort } = parseUrl(originWithStartingPort);
94
+ if (!originalPort) {
95
+ throw new Error(`Given origin doesn't use a port.`);
96
+ }
97
+ const startingPort = Number(originalPort);
98
+ assert.isNumber(startingPort, `Given origin doesn't have a valid port.`);
99
+ let findDistance = 0;
100
+ let foundValidPort = false;
101
+ const timeoutMs = convertDuration(timeout, { milliseconds: true }).milliseconds;
102
+ const startTime = Date.now();
103
+ while (!foundValidPort) {
104
+ const port = findDistance + startingPort;
105
+ if (Date.now() - startTime >= timeoutMs) {
106
+ throw new Error(`Port scan timeout reached. Last scanned port: ${port - 1}`);
107
+ }
108
+ const newUrl = buildUrl(originWithStartingPort, {
109
+ pathname: pathToCheck,
110
+ port,
111
+ }).href;
112
+ const response = await wrapInTry(() => fetch(newUrl, {
113
+ method: HttpMethod.Options,
114
+ }));
115
+ if (!check.instanceOf(response, Error) &&
116
+ response.ok &&
117
+ (isValidResponse ? isValidResponse(response) : true)) {
118
+ foundValidPort = true;
119
+ }
120
+ else if (findDistance >= maxScanDistance) {
121
+ throw new Error(`Max port scan distance reached. Last scanned port: ${port}`);
122
+ }
123
+ else {
124
+ findDistance++;
125
+ }
126
+ }
127
+ return findDistance + startingPort;
128
+ }
129
+ /**
130
+ * Creates a copy of a service definition (without mutating the original service definition) that
131
+ * maps the service's origin port to find the live port that's actually running.
132
+ *
133
+ * This is useful for situations in dev where backend automatically starts on a different port if
134
+ * the original port is already in use.
135
+ *
136
+ * @category Client (Frontend) Connection
137
+ * @category Package : @rest-vir/define-service
138
+ * @example
139
+ *
140
+ * ```ts
141
+ * import {mapServiceDevPort} from '@rest-vir/define-service';
142
+ *
143
+ * const mappedService = await mapServiceDevPort(myServiceDefinition);
144
+ * ```
145
+ *
146
+ * @throws Error if no valid starting port can be found or if the max scan distance has been reached
147
+ * without finding a valid port.
148
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
149
+ */
150
+ export async function mapServiceDevPort(service, options = {}) {
151
+ const { origin } = await findDevServicePort(service, options);
152
+ return defineService({
153
+ ...service.init,
154
+ serviceOrigin: origin,
155
+ });
156
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Extracts all path parameters from an endpoint path.
3
+ *
4
+ * @category Internal
5
+ * @category Package : @rest-vir/define-service
6
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
7
+ */
8
+ export type PathParams<EndpointPath extends string> = string extends EndpointPath ? Record<string, string> : EndpointPath extends `${string}:${infer Param}/${infer Rest}` ? Param | PathParams<`/${Rest}`> : EndpointPath extends `${string}:${infer Param}` ? Param : never;
9
+ /**
10
+ * Base requirement for endpoint paths.
11
+ *
12
+ * Note that this whole thing should be lowercase. Technically, we should use `Lowercase<string>`
13
+ * because of that. However, that makes the type requirements way too strict and hard to deal with.
14
+ *
15
+ * @category Internal
16
+ * @category Package : @rest-vir/define-service
17
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
18
+ */
19
+ export type EndpointPathBase = `/${string}` | '/';
20
+ /**
21
+ * Asserts that the given endpoint or WebSocket path is valid.
22
+ *
23
+ * @category Internal
24
+ * @category Package : @rest-vir/define-service
25
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
26
+ */
27
+ export declare function assertValidEndpointPath(path: string): void;
@@ -0,0 +1,14 @@
1
+ import { assert } from '@augment-vir/assert';
2
+ /**
3
+ * Asserts that the given endpoint or WebSocket path is valid.
4
+ *
5
+ * @category Internal
6
+ * @category Package : @rest-vir/define-service
7
+ * @package [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service)
8
+ */
9
+ export function assertValidEndpointPath(path) {
10
+ if (path !== '/') {
11
+ assert.startsWith(path, '/', 'Path does not start with /');
12
+ assert.endsWithout(path, '/', 'Path cannot end with /');
13
+ }
14
+ }