@openstax/ts-utils 1.1.31 → 1.1.33

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,12 @@
1
+ import type { HttpHeaders } from '.';
2
+ export declare const getHeader: (headers: HttpHeaders, name: string) => string | undefined;
3
+ export declare const getRequestBody: (request: {
4
+ headers: HttpHeaders;
5
+ body?: string | undefined;
6
+ }) => any;
7
+ export declare const unsafePayloadValidator: <T>() => (input: any) => input is T;
8
+ export declare const requestPayloadProvider: <T>(validator: (input: any) => input is T) => () => <M extends {
9
+ request: Parameters<typeof getRequestBody>[0];
10
+ }>(requestServices: M) => M & {
11
+ payload: T;
12
+ };
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requestPayloadProvider = exports.unsafePayloadValidator = exports.getRequestBody = exports.getHeader = void 0;
4
+ const assertions_1 = require("../assertions");
5
+ const errors_1 = require("../errors");
6
+ const guards_1 = require("../guards");
7
+ // use this to support case insensitive header keys
8
+ // note if there are multiple headers of the same value, this only returns the first value
9
+ const getHeader = (headers, name) => {
10
+ const key = Object.keys(headers).find(header => header.toLowerCase() === name.toLowerCase());
11
+ const value = key ? headers[key] : undefined;
12
+ return value instanceof Array
13
+ ? value[0]
14
+ : value;
15
+ };
16
+ exports.getHeader = getHeader;
17
+ const getRequestBody = (request) => {
18
+ if ((0, exports.getHeader)(request.headers, 'content-type') !== 'application/json') {
19
+ throw new errors_1.InvalidRequestError('unknown content type: ' + (0, exports.getHeader)(request.headers, 'content-type'));
20
+ }
21
+ if (!request.body) {
22
+ return {};
23
+ }
24
+ try {
25
+ return JSON.parse(request.body);
26
+ }
27
+ catch (error) {
28
+ // Since the body is provided by the user, invalid JSON in the body is an invalid request
29
+ // We return the message which tells them why the JSON is invalid, but no backtrace
30
+ throw new errors_1.InvalidRequestError((0, assertions_1.assertErrorInstanceOf)(error, SyntaxError).message);
31
+ }
32
+ };
33
+ exports.getRequestBody = getRequestBody;
34
+ /* utils and middleware for loading request payload (must follow this pattern for `PayloadForRoute` to work) */
35
+ // stub validator because writing validators is annoying
36
+ const unsafePayloadValidator = () => (input) => {
37
+ return (0, guards_1.isPlainObject)(input) && Object.keys(input).length > 0;
38
+ };
39
+ exports.unsafePayloadValidator = unsafePayloadValidator;
40
+ /*
41
+ * the given validator is a guard, which provides the correct type this helper loads the body, runs the validator, throws if it isn't valid, or returns it as
42
+ * the correct type if it is valid.
43
+ *
44
+ * this accomplishes a few things:
45
+ * - establishes type of payload for route body logic
46
+ * - validates the payload for route logic
47
+ * - establishes type of payload for client logic calling this route
48
+ *
49
+ * eg:
50
+ * export const exampleRoute = createRoute({name: 'exampleRoute', method: METHOD.POST, path: '/example/:id',
51
+ * requestServiceProvider: composeServiceMiddleware(
52
+ * requestServiceProvider, // previously compiled middleware can be re-composed if you have something to add
53
+ * requestPayloadProvider(validatePayload)
54
+ * )},
55
+ * async(params: {id: string}, services) => {
56
+ * const result = await services.myDocumentStore.putItem({
57
+ * ...services.payload,
58
+ * id: params.id,
59
+ * });
60
+ * return apiJsonResponse(201, result);
61
+ * }
62
+ * );
63
+ * */
64
+ const requestPayloadProvider = (validator) => () => (requestServices) => {
65
+ const payload = (0, exports.getRequestBody)(requestServices.request);
66
+ // for more precise error messages, throw your own InvalidRequestError from your validator function
67
+ if (!validator(payload)) {
68
+ throw new errors_1.InvalidRequestError();
69
+ }
70
+ return { ...requestServices, payload };
71
+ };
72
+ exports.requestPayloadProvider = requestPayloadProvider;
@@ -0,0 +1,96 @@
1
+ import { Track } from '../profile';
2
+ export declare type QueryParams = Record<string, string | undefined | string[] | null>;
3
+ export declare type RouteParams = {
4
+ [key: string]: string;
5
+ };
6
+ export declare type AnyRoute<R> = R extends Route<infer N, infer P, infer Sa, infer Sr, infer Ri, infer Ro> ? Route<N, P, Sa, Sr, Ri, Ro> : never;
7
+ export declare type AnySpecificRoute<R, Sa, Ri, Ro> = R extends Route<infer N, infer P, Sa, infer Sr, Ri, Ro> & infer E ? Route<N, P, Sa, Sr, Ri, Ro> & E : never;
8
+ export declare type OutputForRoute<R> = R extends Route<any, any, any, any, any, infer Ro> ? Ro : never;
9
+ export declare type ParamsForRoute<R> = R extends Route<any, infer P, any, any, any, any> ? P : never;
10
+ export declare type RequestServicesForRoute<R> = R extends Route<any, any, any, infer Sr, any, any> ? Sr : never;
11
+ export declare type ParamsForRouteOrEmpty<R> = ParamsForRoute<R> extends undefined ? {} : Exclude<ParamsForRoute<R>, undefined>;
12
+ export declare type RouteMatchRecord<R> = R extends AnyRoute<R> ? {
13
+ route: R;
14
+ params: ParamsForRoute<R>;
15
+ } : never;
16
+ export declare type PayloadForRoute<R> = RequestServicesForRoute<R> extends {
17
+ payload: any;
18
+ } ? RequestServicesForRoute<R>['payload'] : undefined;
19
+ declare type RequestServiceProvider<Sa, Sr, Ri> = (app: Sa) => <R>(middleware: {
20
+ request: Ri;
21
+ profile: Track;
22
+ }, match: RouteMatchRecord<R>) => Sr;
23
+ declare type RouteHandler<P, Sr, Ro> = (params: P, request: Sr) => Ro;
24
+ declare type Route<N extends string, P extends RouteParams | undefined, Sa, Sr, Ri, Ro> = (Sr extends undefined ? {
25
+ requestServiceProvider?: RequestServiceProvider<Sa, Sr, Ri> | undefined;
26
+ } : {
27
+ requestServiceProvider: RequestServiceProvider<Sa, Sr, Ri>;
28
+ }) & {
29
+ name: N;
30
+ path: string;
31
+ handler: (params: P, request: Sr) => Ro;
32
+ };
33
+ declare type CreateRouteConfig<Sa, Sr, Ri, N extends string, Ex> = (Sr extends undefined ? {
34
+ requestServiceProvider?: RequestServiceProvider<Sa, Sr, Ri> | undefined;
35
+ } : {
36
+ requestServiceProvider: RequestServiceProvider<Sa, Sr, Ri>;
37
+ }) & {
38
+ name: N;
39
+ path: string;
40
+ } & Ex;
41
+ export interface CreateRoute<Sa, Ri, Ex> {
42
+ <N extends string, Ro, Sr extends unknown | undefined = undefined, P extends RouteParams | undefined = undefined>(config: CreateRouteConfig<Sa, Sr, Ri, N, Ex> & {
43
+ handler: RouteHandler<P, Sr, Ro>;
44
+ }): Route<N, P, Sa, Sr, Ri, Ro> & Ex;
45
+ <N extends string, Ro, Sr extends unknown | undefined, P extends RouteParams | undefined = undefined>(config: CreateRouteConfig<Sa, Sr, Ri, N, Ex>, handler: RouteHandler<P, Sr, Ro>): Route<N, P, Sa, Sr, Ri, Ro> & Ex;
46
+ }
47
+ export declare const makeCreateRoute: <Sa, Ri, Ex = {}>() => CreateRoute<Sa, Ri, Ex>;
48
+ export declare const makeRenderRouteUrl: <Ru extends {
49
+ path: string;
50
+ }>() => <R extends Ru>(route: R, params: ParamsForRoute<R>, query?: QueryParams) => string;
51
+ export declare const renderAnyRouteUrl: <R extends any>(route: R, params: ParamsForRoute<R>, query?: QueryParams) => string;
52
+ declare type RequestPathExtractor<Ri> = (request: Ri) => string;
53
+ declare type RequestRouteMatcher<Ri, R> = (request: Ri, route: R) => boolean;
54
+ declare type RequestResponder<Sa, Ri, Ro> = {
55
+ (services: Sa): (request: Ri) => Ro | undefined;
56
+ <RoF>(services: Sa, responseMiddleware: (app: Sa) => (response: Ro | undefined, request: {
57
+ request: Ri;
58
+ profile: Track;
59
+ }) => RoF): (request: Ri) => RoF;
60
+ };
61
+ export declare const makeGetRequestResponder: <Sa, Ru, Ri, Ro>() => ({ routes, pathExtractor, routeMatcher, errorHandler }: {
62
+ routes: () => AnySpecificRoute<Ru, Sa, Ri, Ro>[];
63
+ pathExtractor: RequestPathExtractor<Ri>;
64
+ routeMatcher?: RequestRouteMatcher<Ri, AnySpecificRoute<Ru, Sa, Ri, Ro>> | undefined;
65
+ errorHandler?: ((e: Error) => Ro) | undefined;
66
+ }) => RequestResponder<Sa, Ri, Ro>;
67
+ export declare type HttpHeaders = {
68
+ [key: string]: string | undefined | string[];
69
+ };
70
+ export declare type JsonCompatibleValue = string | number | null | undefined | boolean;
71
+ export declare type JsonCompatibleArray = Array<JsonCompatibleValue | JsonCompatibleStruct | JsonCompatibleStruct>;
72
+ export declare type JsonCompatibleStruct = {
73
+ [key: string]: JsonCompatibleStruct | JsonCompatibleValue | JsonCompatibleArray;
74
+ };
75
+ export declare type ApiResponse<S extends number, T> = {
76
+ isBase64Encoded?: boolean;
77
+ statusCode: S;
78
+ data: T;
79
+ body: string;
80
+ headers?: {
81
+ [key: string]: string;
82
+ };
83
+ };
84
+ export declare const apiJsonResponse: <S extends number, T extends JsonCompatibleStruct>(statusCode: S, data: T, headers?: HttpHeaders | undefined) => ApiResponse<S, T>;
85
+ export declare const apiTextResponse: <S extends number>(statusCode: S, data: string, headers?: HttpHeaders | undefined) => ApiResponse<S, string>;
86
+ export declare const apiHtmlResponse: <S extends number>(statusCode: S, data: string, headers?: HttpHeaders | undefined) => ApiResponse<S, string>;
87
+ export declare enum METHOD {
88
+ GET = "GET",
89
+ HEAD = "HEAD",
90
+ POST = "POST",
91
+ PUT = "PUT",
92
+ PATCH = "PATCH",
93
+ DELETE = "DELETE",
94
+ OPTIONS = "OPTIONS"
95
+ }
96
+ export * from './helpers';
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
26
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
27
+ };
28
+ var __importDefault = (this && this.__importDefault) || function (mod) {
29
+ return (mod && mod.__esModule) ? mod : { "default": mod };
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.METHOD = exports.apiHtmlResponse = exports.apiTextResponse = exports.apiJsonResponse = exports.makeGetRequestResponder = exports.renderAnyRouteUrl = exports.makeRenderRouteUrl = exports.makeCreateRoute = void 0;
33
+ const pathToRegexp = __importStar(require("path-to-regexp"));
34
+ const query_string_1 = __importDefault(require("query-string"));
35
+ const helpers_1 = require("../misc/helpers");
36
+ const profile_1 = require("../profile");
37
+ /*
38
+ * route definition helper. the only required params of the route are the name, path, and handler. other params
39
+ * can be added to the type and then later used in the routeMatcher. when defining the `createRoute` method, only
40
+ * the request input format is defined, the result format is derived from the routes.
41
+ *
42
+ * eg:
43
+ * export const createRoute = makeCreateRoute<AppServices, ApiRouteRequest, {
44
+ * method: METHOD;
45
+ * }>();
46
+ *
47
+ * eg when defining requestServiceProvider in line, the types have a hard time, it helps to put in another argument:
48
+ * export const exampleRoute = createRoute({name: 'exampleRoute', method: METHOD.GET, path: '/api/example/:key',
49
+ * requestServiceProvider: requestServiceProvider({
50
+ * cookieAuthMiddleware,
51
+ * documentStoreMiddleware,
52
+ * }},
53
+ * async(params: {key: string}, services) => {
54
+ * const result = await services.myDocumentStore.getItem(params.key);
55
+ *
56
+ * if (!result) {
57
+ * throw new NotFoundError('requested item not found');
58
+ * }
59
+ *
60
+ * return apiJsonResponse(200, result);
61
+ * }
62
+ * );
63
+ *
64
+ * eg when using a pre-existing provider variable the types work better:
65
+ * export const exampleRoute = createRoute({name: 'exampleRoute', method: METHOD.GET, path: '/api/example/:key',
66
+ * requestServiceProvider,
67
+ * handler: async(params: {key: string}, services) => {
68
+ * const result = await services.myDocumentStore.getItem(params.key);
69
+ *
70
+ * if (!result) {
71
+ * throw new NotFoundError('requested item not found');
72
+ * }
73
+ *
74
+ * return apiJsonResponse(200, result);
75
+ * }
76
+ * });
77
+ */
78
+ const makeCreateRoute = () => (...args) => {
79
+ return (args.length === 1
80
+ ? args[0]
81
+ : { ...args[0], handler: args[1] });
82
+ };
83
+ exports.makeCreateRoute = makeCreateRoute;
84
+ /* begin reverse routing utils */
85
+ const makeRenderRouteUrl = () => (route, params, query = {}) => {
86
+ const getPathForParams = pathToRegexp.compile(route.path, { encode: encodeURIComponent });
87
+ const search = query_string_1.default.stringify(query);
88
+ const path = getPathForParams(params) + (search ? `?${search}` : '');
89
+ return path;
90
+ };
91
+ exports.makeRenderRouteUrl = makeRenderRouteUrl;
92
+ exports.renderAnyRouteUrl = (0, exports.makeRenderRouteUrl)();
93
+ const bindRoute = (services, appBinder, pathExtractor, matcher) => (route) => {
94
+ const getParamsFromPath = pathToRegexp.match(route.path, { decode: decodeURIComponent });
95
+ const boundServiceProvider = route.requestServiceProvider && appBinder(services, route.requestServiceProvider);
96
+ return (request, profile) => {
97
+ const path = pathExtractor(request);
98
+ const match = getParamsFromPath(path);
99
+ if ((!matcher || matcher(request, route)) && match) {
100
+ return profile.track(route.name, routeProfile => () => route.handler(match.params, boundServiceProvider ? boundServiceProvider({ request, profile: routeProfile }, { route, params: match.params }) : undefined));
101
+ }
102
+ };
103
+ };
104
+ /*
105
+ * here among other things we're specifying a generic response format that the response and error handling middleware can use,
106
+ * if any routes have responses that don't adhere to this it'll complain about it.
107
+ *
108
+ * eg:
109
+ * export const getRequestResponder = makeGetRequestResponder<AppServices, TRoutes, ApiRouteRequest, Promise<ApiRouteResponse>>()({
110
+ * routes: apiRoutes, // the route definitions
111
+ * pathExtractor, // how to get the path out of the request format
112
+ * routeMatcher, // logic for matching route (if there is any in addition to the path matching)
113
+ * errorHandler, // any special error handling
114
+ * });
115
+ *
116
+ * eg an lambda entrypoint:
117
+ * export const handler: (request: APIGatewayProxyEventV2) => Promise<ApiRouteResponse> =
118
+ * getRequestResponder(
119
+ * lambdaServices, // the AppServices for this entrypoint
120
+ * lambdaMiddleware // environment specific response middleware (like cors)
121
+ * );
122
+ */
123
+ const makeGetRequestResponder = () => ({ routes, pathExtractor, routeMatcher, errorHandler }) => (services, responseMiddleware) => {
124
+ const appBinderImpl = (app, middleware) => middleware(app, appBinder);
125
+ const appBinder = (0, helpers_1.memoize)(appBinderImpl);
126
+ const boundRoutes = routes().map(bindRoute(services, appBinder, pathExtractor, routeMatcher));
127
+ const boundResponseMiddleware = responseMiddleware ? responseMiddleware(services) : undefined;
128
+ // *note* this opaque promise guard is less generic than i hoped so
129
+ // i'm leaving it here instead of the guards file.
130
+ //
131
+ // its less than ideal because it enforces that the handlers return
132
+ // the same type as the parent promise, usually a handler can be either a
133
+ // promise or a non-promise value and the promise figures it out, but those
134
+ // types are getting complicated quickly here.
135
+ const isPromise = (thing) => thing instanceof Promise;
136
+ return (request) => {
137
+ const { end, ...profile } = (0, profile_1.createProfile)(new Date().toISOString()).start();
138
+ try {
139
+ const executor = (0, helpers_1.mapFind)(boundRoutes, (route) => route(request, profile));
140
+ if (executor) {
141
+ const result = boundResponseMiddleware ?
142
+ boundResponseMiddleware(executor(), { request, profile }) : executor();
143
+ if (isPromise(result) && errorHandler) {
144
+ const errorHandlerWithMiddleware = (e) => boundResponseMiddleware ?
145
+ boundResponseMiddleware(errorHandler(e), { request, profile }) : errorHandler(e);
146
+ return result.catch(errorHandlerWithMiddleware);
147
+ }
148
+ else {
149
+ return result;
150
+ }
151
+ }
152
+ else if (boundResponseMiddleware) {
153
+ return boundResponseMiddleware(undefined, { request, profile });
154
+ }
155
+ }
156
+ catch (e) {
157
+ if (errorHandler && e instanceof Error) {
158
+ return boundResponseMiddleware ? boundResponseMiddleware(errorHandler(e), { request, profile }) : errorHandler(e);
159
+ }
160
+ throw e;
161
+ }
162
+ return undefined;
163
+ };
164
+ };
165
+ exports.makeGetRequestResponder = makeGetRequestResponder;
166
+ const apiJsonResponse = (statusCode, data, headers) => ({ statusCode, data, body: JSON.stringify(data), headers: { ...headers, 'content-type': 'application/json' } });
167
+ exports.apiJsonResponse = apiJsonResponse;
168
+ const apiTextResponse = (statusCode, data, headers) => ({ statusCode, data, body: data, headers: { ...headers, 'content-type': 'text/plain' } });
169
+ exports.apiTextResponse = apiTextResponse;
170
+ const apiHtmlResponse = (statusCode, data, headers) => ({ statusCode, data, body: data, headers: { ...headers, 'content-type': 'text/html' } });
171
+ exports.apiHtmlResponse = apiHtmlResponse;
172
+ var METHOD;
173
+ (function (METHOD) {
174
+ METHOD["GET"] = "GET";
175
+ METHOD["HEAD"] = "HEAD";
176
+ METHOD["POST"] = "POST";
177
+ METHOD["PUT"] = "PUT";
178
+ METHOD["PATCH"] = "PATCH";
179
+ METHOD["DELETE"] = "DELETE";
180
+ METHOD["OPTIONS"] = "OPTIONS";
181
+ })(METHOD = exports.METHOD || (exports.METHOD = {}));
182
+ __exportStar(require("./helpers"), exports);
@@ -1,4 +1,4 @@
1
- import { ConfigProviderForConfig } from '../../config';
1
+ import type { ConfigProviderForConfig } from '../../config';
2
2
  import { CookieAuthProvider } from '.';
3
3
  declare type Config = {
4
4
  cookieName: string;
@@ -1,6 +1,6 @@
1
- import { FetchConfig } from '../../fetch';
2
- import { Track } from '../../profile';
3
- import { HttpHeaders } from '../../routing';
1
+ import type { FetchConfig } from '../../fetch';
2
+ import type { Track } from '../../profile';
3
+ import type { HttpHeaders } from '../../routing';
4
4
  export interface User {
5
5
  id: number;
6
6
  name: string;
@@ -5,8 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getAuthTokenOrCookie = exports.stubAuthProvider = void 0;
7
7
  const cookie_1 = __importDefault(require("cookie"));
8
- const __1 = require("../..");
9
- const routing_1 = require("../../routing");
8
+ const helpers_1 = require("../../misc/helpers");
9
+ const helpers_2 = require("../../routing/helpers");
10
10
  const stubAuthProvider = (user) => ({
11
11
  getUser: () => Promise.resolve(user),
12
12
  getAuthorizedFetchConfig: () => Promise.resolve(user ? { headers: { Authorization: user.uuid } } : {})
@@ -14,10 +14,10 @@ const stubAuthProvider = (user) => ({
14
14
  exports.stubAuthProvider = stubAuthProvider;
15
15
  const getAuthTokenOrCookie = (request, cookieName) => {
16
16
  var _a;
17
- const authHeader = (0, routing_1.getHeader)(request.headers, 'authorization');
17
+ const authHeader = (0, helpers_2.getHeader)(request.headers, 'authorization');
18
18
  const cookieValue = cookie_1.default.parse(((_a = request.cookies) === null || _a === void 0 ? void 0 : _a.join('; ')) || '')[cookieName];
19
19
  return authHeader && authHeader.length >= 8 && authHeader.startsWith('Bearer ')
20
- ? (0, __1.tuple)(authHeader.slice(7), { Authorization: authHeader })
21
- : (0, __1.tuple)(cookieValue, { cookie: cookie_1.default.serialize(cookieName, cookieValue) });
20
+ ? (0, helpers_1.tuple)(authHeader.slice(7), { Authorization: authHeader })
21
+ : (0, helpers_1.tuple)(cookieValue, { cookie: cookie_1.default.serialize(cookieName, cookieValue) });
22
22
  };
23
23
  exports.getAuthTokenOrCookie = getAuthTokenOrCookie;