ag-common 0.0.4 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,7 @@
1
+ ISC License
2
+
3
+ Copyright 2021 Andrei Gec
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # ag-common
2
+
3
+ > Various reusable libaries for: common ts/js / api (aws cognito, aws-cdk) / ui (react)
4
+
5
+ [![NPM Version][npm-image]][npm-url]
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i -S ag-common
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Please raise any issues or requests you might have [here](https://github.com/andreigec/ag-common/issues)
16
+
17
+ ## License
18
+
19
+ [ISC](./LICENSE.md)
20
+
21
+ [npm-image]: https://img.shields.io/npm/v/ag-common.svg
22
+ [npm-url]: https://www.npmjs.com/package/ag-common
@@ -5,7 +5,7 @@ exports.openApiImpl = void 0;
5
5
  const aws_cdk_lib_1 = require("aws-cdk-lib");
6
6
  const distinctBy_1 = require("../../common/helpers/distinctBy");
7
7
  const log_1 = require("../../common/helpers/log");
8
- // eslint-disable-next-line @typescript-eslint/no-var-requires
8
+ // eslint-disable-next-line
9
9
  const getPaths = (schema) => Object.entries(schema.paths).map(([fullPath, verbs]) => ({
10
10
  fullPath,
11
11
  pathList: fullPath.split('/').filter((s) => s),
@@ -6,7 +6,8 @@ export declare type NextType<T> = ({ event, body, params, userProfile, }: {
6
6
  body: T;
7
7
  userProfile?: User;
8
8
  }) => Promise<APIGatewayProxyResult>;
9
- export declare function validateOpenApi<T>({ event, next, authorized, schema, }: {
9
+ export declare function validateOpenApi<T>({ event, next, authorized, schema, COGNITO_USER_POOL_ID, }: {
10
+ COGNITO_USER_POOL_ID: string;
10
11
  schema: any;
11
12
  event: APIGatewayEvent;
12
13
  next: NextType<T>;
@@ -41,7 +41,7 @@ const getOperation = ({ path, method, resource, schema, }) => {
41
41
  const pathParams = (re === null || re === void 0 ? void 0 : re.groups) && JSON.parse(JSON.stringify(re === null || re === void 0 ? void 0 : re.groups));
42
42
  return { operation, pathParams };
43
43
  };
44
- function validateOpenApi({ event, next, authorized, schema, }) {
44
+ function validateOpenApi({ event, next, authorized, schema, COGNITO_USER_POOL_ID, }) {
45
45
  var _a, _b, _c, _d;
46
46
  return __awaiter(this, void 0, void 0, function* () {
47
47
  const request = {
@@ -96,7 +96,10 @@ function validateOpenApi({ event, next, authorized, schema, }) {
96
96
  let error;
97
97
  const authHeader = ((_c = event.headers) === null || _c === void 0 ? void 0 : _c.Authorization) || ((_d = event.headers) === null || _d === void 0 ? void 0 : _d.authorization);
98
98
  if (authorized === true || (authorized === 'optional' && authHeader)) {
99
- ({ error, userProfile } = yield (0, validations_1.getAndValidateToken)(authHeader));
99
+ ({ error, userProfile } = yield (0, validations_1.getAndValidateToken)({
100
+ tokenRaw: authHeader,
101
+ COGNITO_USER_POOL_ID,
102
+ }));
100
103
  if (error) {
101
104
  return error;
102
105
  }
@@ -1,7 +1,10 @@
1
1
  import { APIGatewayProxyResult } from 'aws-lambda';
2
2
  import { User } from 'analytica.click';
3
3
  import { error } from '../../common/helpers/log';
4
- export declare const getAndValidateToken: (tokenRaw?: string | undefined) => Promise<{
4
+ export declare const getAndValidateToken: ({ tokenRaw, COGNITO_USER_POOL_ID, }: {
5
+ tokenRaw?: string | undefined;
6
+ COGNITO_USER_POOL_ID: string;
7
+ }) => Promise<{
5
8
  error?: APIGatewayProxyResult | undefined;
6
9
  token?: string | undefined;
7
10
  userProfile?: User | undefined;
@@ -17,17 +17,22 @@ const jwks_rsa_1 = __importDefault(require("jwks-rsa"));
17
17
  const jsonwebtoken_1 = require("jsonwebtoken");
18
18
  const log_1 = require("../../common/helpers/log");
19
19
  const api_1 = require("./api");
20
- const jwksUri = `https://cognito-idp.ap-southeast-2.amazonaws.com/${process.env.COGNITO_USER_POOL_ID}/.well-known/jwks.json`;
21
- const issuer = `https://cognito-idp.ap-southeast-2.amazonaws.com/${process.env.COGNITO_USER_POOL_ID}`;
22
- const jwksClient = (0, jwks_rsa_1.default)({
23
- cache: true,
24
- rateLimit: true,
25
- jwksRequestsPerMinute: 10,
26
- jwksUri,
27
- });
28
- const jwtVerify = (token) => __awaiter(void 0, void 0, void 0, function* () {
20
+ let jwksClient;
21
+ const jwtVerify = ({ COGNITO_USER_POOL_ID, token, }) => __awaiter(void 0, void 0, void 0, function* () {
22
+ const jwksUri = `https://cognito-idp.ap-southeast-2.amazonaws.com/${COGNITO_USER_POOL_ID}/.well-known/jwks.json`;
23
+ const issuer = `https://cognito-idp.ap-southeast-2.amazonaws.com/${COGNITO_USER_POOL_ID}`;
29
24
  return new Promise((resolve, reject) => {
30
25
  (0, jsonwebtoken_1.verify)(token, (header, callback) => {
26
+ if (!jwksClient) {
27
+ const jc = {
28
+ cache: true,
29
+ rateLimit: true,
30
+ jwksRequestsPerMinute: 10,
31
+ jwksUri,
32
+ };
33
+ (0, log_1.info)(`jwksClient config=`, jc);
34
+ jwksClient = (0, jwks_rsa_1.default)(jc);
35
+ }
31
36
  jwksClient.getSigningKey(header.kid, (errorV, key) => {
32
37
  if (errorV) {
33
38
  reject(errorV);
@@ -53,7 +58,7 @@ const jwtVerify = (token) => __awaiter(void 0, void 0, void 0, function* () {
53
58
  });
54
59
  });
55
60
  });
56
- const getAndValidateToken = (tokenRaw) => __awaiter(void 0, void 0, void 0, function* () {
61
+ const getAndValidateToken = ({ tokenRaw, COGNITO_USER_POOL_ID, }) => __awaiter(void 0, void 0, void 0, function* () {
57
62
  var _a, _b;
58
63
  let token = '';
59
64
  try {
@@ -63,10 +68,10 @@ const getAndValidateToken = (tokenRaw) => __awaiter(void 0, void 0, void 0, func
63
68
  error: (0, api_1.returnCode)(403, 'auth failed'),
64
69
  };
65
70
  }
66
- token = tokenRaw.substr(tokenRaw.indexOf(' ') + 1);
71
+ token = tokenRaw.substring(tokenRaw.indexOf(' ') + 1);
67
72
  let subject;
68
73
  try {
69
- yield jwtVerify(token);
74
+ yield jwtVerify({ token, COGNITO_USER_POOL_ID });
70
75
  const decoded = (0, jsonwebtoken_1.decode)(token);
71
76
  (0, log_1.debug)(`decoded=${JSON.stringify(decoded)}`);
72
77
  subject = decoded === null || decoded === void 0 ? void 0 : decoded.sub;
@@ -6,4 +6,13 @@ export interface ISite {
6
6
  siteUrl: string;
7
7
  niceSiteUrl: string;
8
8
  }
9
+ /**
10
+ * removes protocol, and trailing slashes
11
+ */
9
12
  export declare const niceUrl: (siteUrl: string) => string | ISite;
13
+ /**
14
+ * string -> String
15
+ * @param str
16
+ * @returns
17
+ */
18
+ export declare function toTitleCase(str: string): string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.niceUrl = exports.truncate = exports.trim = exports.trimSide = exports.csvJSON = void 0;
3
+ exports.toTitleCase = exports.niceUrl = exports.truncate = exports.trim = exports.trimSide = exports.csvJSON = void 0;
4
4
  const csvJSON = (csv) => {
5
5
  const lines = csv.split('\n');
6
6
  const result = [];
@@ -44,15 +44,18 @@ function truncate(str, n, ellip) {
44
44
  if (!str) {
45
45
  return undefined;
46
46
  }
47
- return str.length > n ? str.substr(0, n - 1) + ellip : str;
47
+ return str.length > n ? str.substring(0, n - 1) + ellip : str;
48
48
  }
49
49
  exports.truncate = truncate;
50
+ /**
51
+ * removes protocol, and trailing slashes
52
+ */
50
53
  const niceUrl = (siteUrl) => {
51
54
  if (!siteUrl) {
52
55
  return siteUrl;
53
56
  }
54
57
  let niceSiteUrl = siteUrl
55
- .substr(siteUrl.indexOf(':') + 1)
58
+ .substring(siteUrl.indexOf(':') + 1)
56
59
  .replace('sc-domain:', '')
57
60
  .replace('https://', '')
58
61
  .replace('http://', '');
@@ -60,3 +63,15 @@ const niceUrl = (siteUrl) => {
60
63
  return { siteUrl, niceSiteUrl };
61
64
  };
62
65
  exports.niceUrl = niceUrl;
66
+ /**
67
+ * string -> String
68
+ * @param str
69
+ * @returns
70
+ */
71
+ function toTitleCase(str) {
72
+ if (!str) {
73
+ return str;
74
+ }
75
+ return str.replace(/\w\S*/g, (txt) => txt && txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase());
76
+ }
77
+ exports.toTitleCase = toTitleCase;
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
+ /* eslint-disable prettier/prettier */
13
14
  __exportStar(require("./ui"), exports);
14
15
  __exportStar(require("./common"), exports);
15
16
  __exportStar(require("./api"), exports);
@@ -21,7 +21,7 @@ const LoginButton = ({ className, text = text_1.getstarted, invert, title, saveP
21
21
  const lp = loginPath(!savePath || typeof window === 'undefined'
22
22
  ? undefined
23
23
  : {
24
- redirect: window.location.href.substr(window.location.origin.length),
24
+ redirect: window.location.href.substring(window.location.origin.length),
25
25
  });
26
26
  return (react_1.default.createElement(Button_1.Button, { lang: lang, title: title, invert: invert, className: className, onKeyPress: () => __awaiter(void 0, void 0, void 0, function* () {
27
27
  yield pushPath(lp);
@@ -1,3 +1,3 @@
1
- import { TResource } from "../../../common/helpers/i18n";
1
+ import { TResource } from '../../../common/helpers/i18n';
2
2
  export declare const getstarted: TResource;
3
3
  export declare const login: TResource;
@@ -14,6 +14,7 @@ const cookie_1 = require("./cookie");
14
14
  const debounce_1 = require("./debounce");
15
15
  const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefaultApi, }) => __awaiter(void 0, void 0, void 0, function* () {
16
16
  var _a, _b, _c, _d, _e, _f;
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
18
  let error;
18
19
  let data;
19
20
  const config = {
@@ -45,6 +46,7 @@ const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefa
45
46
  throw new Error(JSON.stringify(resp.data) || resp.statusText);
46
47
  }
47
48
  catch (e) {
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
50
  const ae = e;
49
51
  const status = (_c = ae.response) === null || _c === void 0 ? void 0 : _c.status;
50
52
  const errorMessage = (((_d = ae.response) === null || _d === void 0 ? void 0 : _d.data) ||
@@ -1,6 +1,12 @@
1
1
  import { AxiosResponse } from 'axios';
2
2
  import { AxiosWrapper, User } from 'analytica.click';
3
3
  import { CacheItems } from './routes';
4
+ export declare const setMutexData: ({ key, data, ttlSeconds, }: {
5
+ key: string;
6
+ data: any;
7
+ ttlSeconds: number;
8
+ }) => void;
9
+ export declare const getMutexData: <T>(key: string) => AxiosWrapper<T>;
4
10
  export declare const useOpenApiStore: <T, TDefaultApi>({ func, cacheKey, ttlSeconds, logout, refreshToken, disabled, apiUrl, newDefaultApi, }: {
5
11
  ttlSeconds?: number | undefined;
6
12
  func: (f: TDefaultApi) => Promise<AxiosResponse<T, any>>;
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.setOpenApiCache = exports.useOpenApiStore = void 0;
12
+ exports.setOpenApiCache = exports.useOpenApiStore = exports.getMutexData = exports.setMutexData = void 0;
13
13
  const react_1 = require("react");
14
14
  const mutex_1 = require("./mutex");
15
15
  const mutexData_1 = require("./mutexData");
@@ -36,9 +36,13 @@ const setMutexData = ({ key, data, ttlSeconds = 3600, }) => {
36
36
  };
37
37
  mutexData.setData(key, wrap, ttlSeconds);
38
38
  };
39
+ exports.setMutexData = setMutexData;
39
40
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
41
  const getMutexData = (key) => mutexData.getData(key);
41
- function mLock(key, func, ttlSeconds, logout, refreshToken, apiUrl, newDefaultApi) {
42
+ exports.getMutexData = getMutexData;
43
+ function mLock(key, func, ttlSeconds, logout, refreshToken, apiUrl,
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ newDefaultApi) {
42
46
  return __awaiter(this, void 0, void 0, function* () {
43
47
  let unlock;
44
48
  try {
package/package.json CHANGED
@@ -1,36 +1,48 @@
1
1
  {
2
2
  "name": "ag-common",
3
- "version": "0.0.4",
3
+ "version": "0.0.8",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
+ "author": "Andrei Gec <@andreigec> (https://gec.dev/)",
7
+ "repository": "github:andreigec/ag-common",
8
+ "license": "ISC",
6
9
  "dependencies": {
10
+ "aws-lambda": "1.0.7",
11
+ "styled-components": "5.3.3",
7
12
  "axios": "0.24.0",
8
- "typescript": "4.5.4"
9
- },
10
- "devDependencies": {
11
- "@types/node": "^17.0.5",
12
- "@types/aws-lambda": "8.10.89",
13
- "@types/react": "*",
14
- "@types/react-dom": "*",
15
- "@types/styled-components": "*",
16
- "analytica.click": "*",
17
- "aws-cdk-lib": "*",
13
+ "typescript": "4.5.4",
14
+ "openapi-request-validator": "10.0.0",
15
+ "analytica.click": "0.0.123",
18
16
  "aws-sdk": "2.1048.0",
19
- "constructs": "*",
20
- "eslint": "*",
21
- "react": "*",
22
- "react-dom": "*",
17
+ "aws-cdk-lib": "2.3.0",
18
+ "constructs": "10.0.17",
19
+ "react": "17.0.2",
20
+ "react-dom": "17.0.2",
23
21
  "react-hot-toast": "2.1.1",
24
- "rimraf": "*",
25
- "typescript-styled-plugin": "*",
26
- "openapi-request-validator": "9.3.1",
27
- "@types/jsonwebtoken": "8.5.6",
28
22
  "jsonwebtoken": "8.5.1",
29
23
  "jwks-rsa": "2.0.5"
30
24
  },
31
- "peerDependencies": {
32
- "aws-lambda": "1.0.7",
33
- "styled-components": "*"
25
+ "devDependencies": {
26
+ "@typescript-eslint/eslint-plugin": "5.8.1",
27
+ "@typescript-eslint/parser": "5.8.1",
28
+ "prettier": "2.5.1",
29
+ "@types/node": "17.0.5",
30
+ "@types/aws-lambda": "8.10.89",
31
+ "@types/react": "17.0.38",
32
+ "@types/react-dom": "17.0.11",
33
+ "@types/styled-components": "5.1.19",
34
+ "eslint": "8.5.0",
35
+ "eslint-config-airbnb-typescript": "16.1.0",
36
+ "eslint-config-prettier": "8.3.0",
37
+ "eslint-config-react-app": "7.0.0",
38
+ "eslint-plugin-import": "2.25.3",
39
+ "eslint-plugin-jsx-a11y": "6.5.1",
40
+ "eslint-plugin-prettier": "4.0.0",
41
+ "eslint-plugin-react": "7.28.0",
42
+ "eslint-plugin-react-hooks": "4.3.0",
43
+ "rimraf": "3.0.2",
44
+ "typescript-styled-plugin": "0.18.2",
45
+ "@types/jsonwebtoken": "8.5.6"
34
46
  },
35
47
  "scripts": {
36
48
  "build": "rimraf dist && tsc",
@@ -39,6 +51,8 @@
39
51
  "start": "tsc --watch"
40
52
  },
41
53
  "files": [
42
- "dist/**/*"
54
+ "dist/**/*",
55
+ "README.md",
56
+ "LICENSE.md"
43
57
  ]
44
58
  }