ag-common 0.0.351 → 0.0.352

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 @@
1
+ export {};
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ /* eslint-disable import/no-extraneous-dependencies */
3
+ /* eslint-disable @typescript-eslint/no-var-requires */
4
+ /* eslint-disable no-console */
5
+ const fs = require('fs');
6
+ const process = require('process');
7
+ var pathV = require('path');
8
+ var cwd = process.cwd();
9
+ var resolvePath = (p) => pathV.resolve(cwd, p);
10
+ function run() {
11
+ var files = fs
12
+ .readdirSync(resolvePath('./dist/api'))
13
+ .filter((r) => r.endsWith('.js'))
14
+ .map((s) => `./dist/api/${s}`);
15
+ files.forEach((f) => {
16
+ if (fs.existsSync(f)) {
17
+ console.log('removing url_1 from ' + f);
18
+ var c = fs.readFileSync(f).toString();
19
+ c = c.replace(/url_1\./gi, '');
20
+ fs.writeFileSync(f, c);
21
+ }
22
+ });
23
+ if (!files.length) {
24
+ console.log('error: no files to url fix');
25
+ }
26
+ }
27
+ run();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ /* eslint-disable import/no-extraneous-dependencies */
12
+ /* eslint-disable @typescript-eslint/no-var-requires */
13
+ /* eslint-disable no-console */
14
+ var { load } = require('js-yaml');
15
+ const SwaggerParser = require('swagger-parser');
16
+ const fs = require('fs');
17
+ const process = require('process');
18
+ var pathV = require('path');
19
+ var cwd = process.cwd();
20
+ var resolvePath = (p) => pathV.resolve(cwd, p);
21
+ //
22
+ function cleanSrc() {
23
+ // eslint-disable-next-line no-console
24
+ console.log('fixing colons in field names');
25
+ let files = fs
26
+ .readdirSync(resolvePath('./src/api'))
27
+ .filter((r) => r.endsWith('.ts'))
28
+ .map((s) => `./src/api/${s}`);
29
+ files.forEach((f) => {
30
+ let c = fs.readFileSync(f).toString();
31
+ c = c.replace(/cognitopreferred_role/, "'cognito:preferred_role'");
32
+ c = c.replace(/cognitousername/, "'cognito:username'");
33
+ c = c.replace(/cognitogroups/, "'cognito:groups'");
34
+ c = `import {URL, URLSearchParams} from 'url'
35
+ ${c}`;
36
+ fs.writeFileSync(f, c);
37
+ });
38
+ //disable all errors
39
+ console.log('disable all api ts errors');
40
+ files = fs
41
+ .readdirSync(resolvePath('./src/api'))
42
+ .filter((r) => r.endsWith('.ts'))
43
+ .map((s) => `./src/api/${s}`);
44
+ files.forEach((f) => {
45
+ var c = fs.readFileSync(f);
46
+ c = '/* eslint-disable */\n// @ts-nocheck\n' + c;
47
+ fs.writeFileSync(f, c);
48
+ });
49
+ [resolvePath('./src/api/runtime.ts')].forEach((f) => {
50
+ if (fs.existsSync(f)) {
51
+ console.log('fix middleware');
52
+ let c = fs.readFileSync(f).toString();
53
+ c = c.replace('= configuration.middleware;', '= configuration.middleware || [];');
54
+ fs.writeFileSync(f, c);
55
+ }
56
+ else {
57
+ console.warn('no middleware to fix (src/api/runtime)');
58
+ }
59
+ });
60
+ }
61
+ //
62
+ function generateJs() {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ try {
65
+ console.log('generating openapi ts');
66
+ const yml = load(fs.readFileSync(resolvePath('./openapi.yml'), 'utf8'));
67
+ // eslint-disable-next-line
68
+ const schema = yield SwaggerParser.validate(yml);
69
+ const content = `var ret=${JSON.stringify(schema)};\nmodule.exports.default=ret`;
70
+ fs.writeFileSync(resolvePath('./openapi.generated.js'), content);
71
+ }
72
+ catch (e) {
73
+ // eslint-disable-next-line no-console
74
+ console.log('err=', e);
75
+ }
76
+ });
77
+ }
78
+ function run() {
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ console.log('start openapi fix in ' + cwd);
81
+ cleanSrc();
82
+ yield generateJs();
83
+ });
84
+ }
85
+ void run();
@@ -0,0 +1,27 @@
1
+ /// <reference types="react" />
2
+ import { AuthedUserContext } from '../../helpers/jwt';
3
+ import { IRequestCommon } from '../../helpers/routes';
4
+ /**
5
+ *
6
+ * @param param0 handles auth loading/error
7
+ * @returns
8
+ */
9
+ export declare const DashboardAuthValidation: ({ rc: { request, pushPath }, cac: { error: authError, loginWithRedirect, logout, isAuthenticated, loading: authLoading, }, getDashboardPath, getUnauthedPage, addToast, }: {
10
+ addToast: (m: string, options?: {
11
+ appearance: 'error' | 'success';
12
+ autoClose?: number;
13
+ } | undefined) => void;
14
+ getDashboardPath: () => string;
15
+ /**
16
+ * will goto when landing on page without auth. undefined will not redirect
17
+ */
18
+ getUnauthedPage: undefined | (() => string);
19
+ cac: AuthedUserContext;
20
+ rc: {
21
+ request: IRequestCommon;
22
+ pushPath: (p: string) => Promise<void>;
23
+ };
24
+ }) => {
25
+ render?: JSX.Element | undefined;
26
+ openApiDisabled: boolean;
27
+ };
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DashboardAuthValidation = void 0;
7
+ const react_1 = __importDefault(require("react"));
8
+ const log_1 = require("../../../common/helpers/log");
9
+ const string_1 = require("../../../common/helpers/string");
10
+ const useGranularHook_1 = require("../../helpers/useGranularHook");
11
+ const useQueryString_1 = require("../../helpers/useQueryString");
12
+ const Loader_1 = require("../Loader");
13
+ /**
14
+ *
15
+ * @param param0 handles auth loading/error
16
+ * @returns
17
+ */
18
+ const DashboardAuthValidation = ({ rc: { request, pushPath }, cac: { error: authError, loginWithRedirect, logout, isAuthenticated, loading: authLoading, }, getDashboardPath, getUnauthedPage, addToast, }) => {
19
+ (0, useGranularHook_1.useGranularEffect)(() => {
20
+ if (authError) {
21
+ const emailOption = authError.message.includes('email')
22
+ ? ` We require the use of your email for the functionality of this app.
23
+ You can update your settings at https://www.facebook.com/settings?tab=applications`
24
+ : '';
25
+ addToast(`An Error has occured with your login attempt.${emailOption}`, {
26
+ appearance: 'error',
27
+ });
28
+ (0, log_1.error)(`auth error:`, JSON.stringify(authError, null, 2));
29
+ void logout();
30
+ }
31
+ }, [authError], [authError, addToast, logout]);
32
+ const forceLogin = Object.keys(request.url.query || {}).includes('login');
33
+ if (forceLogin) {
34
+ if (!isAuthenticated) {
35
+ void loginWithRedirect(request.url.query.state);
36
+ return { render: react_1.default.createElement(react_1.default.Fragment, null), openApiDisabled: true };
37
+ }
38
+ if (isAuthenticated) {
39
+ void pushPath(getDashboardPath());
40
+ return { render: react_1.default.createElement(react_1.default.Fragment, null), openApiDisabled: true };
41
+ }
42
+ }
43
+ if (request.url.query.state && isAuthenticated) {
44
+ const decoded = JSON.parse((0, string_1.fromBase64)(request.url.query.state));
45
+ if (decoded.redirect) {
46
+ void pushPath(decoded.redirect);
47
+ return { render: react_1.default.createElement(react_1.default.Fragment, null), openApiDisabled: true };
48
+ }
49
+ }
50
+ const serverAuthLoading = useQueryString_1.isServer &&
51
+ !authError &&
52
+ !authLoading &&
53
+ !isAuthenticated &&
54
+ Object.keys(request.url.query || {}).includes('code');
55
+ if (authLoading || serverAuthLoading) {
56
+ return {
57
+ render: react_1.default.createElement(Loader_1.Loader, { name: "authload" }),
58
+ openApiDisabled: true,
59
+ };
60
+ }
61
+ if (!isAuthenticated && !authLoading && !authError && getUnauthedPage) {
62
+ void pushPath(getUnauthedPage());
63
+ return { render: react_1.default.createElement(react_1.default.Fragment, null), openApiDisabled: true };
64
+ }
65
+ const openApiDisabled = !isAuthenticated || authLoading || !!authError;
66
+ return { openApiDisabled };
67
+ };
68
+ exports.DashboardAuthValidation = DashboardAuthValidation;
@@ -3,6 +3,7 @@ export * from './Button';
3
3
  export * from './Chevron';
4
4
  export * from './Close';
5
5
  export * from './Confirm';
6
+ export * from './DashboardAuthValidation';
6
7
  export * from './DropdownList';
7
8
  export * from './FlexColumn';
8
9
  export * from './FlexRow';
@@ -19,6 +19,7 @@ __exportStar(require("./Button"), exports);
19
19
  __exportStar(require("./Chevron"), exports);
20
20
  __exportStar(require("./Close"), exports);
21
21
  __exportStar(require("./Confirm"), exports);
22
+ __exportStar(require("./DashboardAuthValidation"), exports);
22
23
  __exportStar(require("./DropdownList"), exports);
23
24
  __exportStar(require("./FlexColumn"), exports);
24
25
  __exportStar(require("./FlexRow"), exports);
@@ -50,6 +50,7 @@ const axiosHelper = ({ verb, url, body, headers, timeout = 30000, retryMax = 0,
50
50
  axios = axios_1.default.patch;
51
51
  }
52
52
  else if (verb === 'delete') {
53
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
54
  axios = axios_1.default.delete;
54
55
  noBody = true;
55
56
  }
@@ -14,6 +14,7 @@ const cookie_1 = require("../cookie");
14
14
  const sleep_1 = require("../../../common/helpers/sleep");
15
15
  const array_1 = require("../../../common/helpers/array");
16
16
  const useLocalStorage_1 = require("../useLocalStorage");
17
+ const axios_1 = require("axios");
17
18
  const const_1 = require("../../../common/const");
18
19
  /**
19
20
  * get the id_token from provided value, or cookie, or LS
@@ -58,7 +59,7 @@ function getIdTokenAuthHeader({ overrideAuth, refreshToken, }) {
58
59
  });
59
60
  }
60
61
  const callOpenApi = (p) => __awaiter(void 0, void 0, void 0, function* () {
61
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
62
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
62
63
  const { func, apiUrl, logout, newDefaultApi, headers } = p;
63
64
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
64
65
  let error;
@@ -66,10 +67,19 @@ const callOpenApi = (p) => __awaiter(void 0, void 0, void 0, function* () {
66
67
  const config = {
67
68
  basePath: apiUrl,
68
69
  baseOptions: { headers: Object.assign({ authorization: '' }, (headers || {})) },
70
+ middleware: [],
69
71
  };
70
72
  const idToken = yield getIdTokenAuthHeader(p);
71
73
  if (idToken) {
72
74
  config.baseOptions.headers.authorization = `Bearer ${idToken}`;
75
+ config.middleware = [
76
+ {
77
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
+ pre: (oldFetchParams) => {
79
+ oldFetchParams.init.headers = Object.assign({ authorization: `Bearer ${idToken}` }, oldFetchParams.init.headers);
80
+ },
81
+ },
82
+ ];
73
83
  }
74
84
  const cl = newDefaultApi(config);
75
85
  let errorCount = 0;
@@ -83,18 +93,19 @@ const callOpenApi = (p) => __awaiter(void 0, void 0, void 0, function* () {
83
93
  data = resp.data;
84
94
  break;
85
95
  }
86
- throw new Error(JSON.stringify(resp.data) || resp.statusText);
96
+ throw new axios_1.AxiosError(resp.statusText, ((_a = resp.status) === null || _a === void 0 ? void 0 : _a.toString()) || '500');
87
97
  }
88
98
  catch (e) {
89
99
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
90
100
  const ae = e;
91
- const status = (_b = (_a = ae.response) === null || _a === void 0 ? void 0 : _a.status) !== null && _b !== void 0 ? _b : 500;
101
+ const status = Number((_d = (_b = ae.code) !== null && _b !== void 0 ? _b : (_c = ae.response) === null || _c === void 0 ? void 0 : _c.status) !== null && _d !== void 0 ? _d : 500);
92
102
  const errorMessage = [
103
+ (_e = ae.status) !== null && _e !== void 0 ? _e : '',
93
104
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
- (_e = (_d = (_c = ae.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.toString()) !== null && _e !== void 0 ? _e : '',
95
- (_h = (_g = (_f = ae.response) === null || _f === void 0 ? void 0 : _f.statusText) === null || _g === void 0 ? void 0 : _g.toString()) !== null && _h !== void 0 ? _h : '',
96
- (_l = (_k = (_j = ae.response) === null || _j === void 0 ? void 0 : _j.status) === null || _k === void 0 ? void 0 : _k.toString()) !== null && _l !== void 0 ? _l : '',
97
- (_o = (_m = ae.message) === null || _m === void 0 ? void 0 : _m.toString()) !== null && _o !== void 0 ? _o : '',
105
+ (_h = (_g = (_f = ae.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.toString()) !== null && _h !== void 0 ? _h : '',
106
+ (_l = (_k = (_j = ae.response) === null || _j === void 0 ? void 0 : _j.statusText) === null || _k === void 0 ? void 0 : _k.toString()) !== null && _l !== void 0 ? _l : '',
107
+ (_p = (_o = (_m = ae.response) === null || _m === void 0 ? void 0 : _m.status) === null || _o === void 0 ? void 0 : _o.toString()) !== null && _p !== void 0 ? _p : '',
108
+ (_r = (_q = ae.message) === null || _q === void 0 ? void 0 : _q.toString()) !== null && _r !== void 0 ? _r : '',
98
109
  ]
99
110
  .filter(array_1.notEmpty)
100
111
  .sort((a, b) => (a.length < b.length ? -1 : 1))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ag-common",
3
- "version": "0.0.351",
3
+ "version": "0.0.352",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "author": "Andrei Gec <@andreigec> (https://gec.dev/)",