gomtm 0.0.197 → 0.0.198

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.
@@ -5,7 +5,7 @@ import { MtLink } from "mtxuilib/common/mtlink";
5
5
  import { Avatar, AvatarFallback, AvatarImage } from "mtxuilib/ui/avatar";
6
6
  import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "mtxuilib/ui/dropdown-menu";
7
7
  import { usePathname } from "next/navigation";
8
- import { useAuth } from "../hooks/useAuth";
8
+ import { useAuth } from "../store/auth";
9
9
  function UserAvatorMenus() {
10
10
  const pathName = usePathname();
11
11
  const auth = useAuth();
@@ -1 +1,9 @@
1
- export declare function getMtmApiUrl(backendUrl: string): string;
1
+ import { ServiceType } from "@bufbuild/protobuf";
2
+ export declare function createMtmServiceClient<T extends ServiceType>(service: T, url?: string): import("@connectrpc/connect").PromiseClient<T>;
3
+ export declare function createMtmServiceClientByName<T extends ServiceType>(svcName: string, url?: string): import("@connectrpc/connect").PromiseClient<ServiceType>;
4
+ type CustomRequestInit = RequestInit & {
5
+ enableCache?: boolean;
6
+ enableLog?: boolean;
7
+ };
8
+ export declare const gomtmFetcher: (initGlobal?: CustomRequestInit) => (input: string | URL | globalThis.Request, init?: CustomRequestInit) => Promise<Response>;
9
+ export {};
@@ -1,6 +1,137 @@
1
- function getMtmApiUrl(backendUrl) {
2
- return backendUrl + "/api";
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+ import { createPromiseClient } from "@connectrpc/connect";
41
+ import { createConnectTransport } from "@connectrpc/connect-web";
42
+ import { merge } from "lodash";
43
+ import { fetchMiddleWithCache } from "mtxlib/http/fetchMiddleWithCache";
44
+ import { MtmService } from "./gomtmpb/mtm/sppb/mtm_connect";
45
+ function createMtmServiceClient(service, url) {
46
+ const baseUrl = url || process.env.MTM_BACKEND;
47
+ if (!baseUrl) {
48
+ throw new Error("missing mtm api url,\xB7MTM_BACKEND\xB7");
49
+ }
50
+ console.info("gomtm baseUrl:", baseUrl);
51
+ return createPromiseClient(
52
+ service,
53
+ createConnectTransport({
54
+ baseUrl,
55
+ fetch: gomtmFetcher()
56
+ })
57
+ );
3
58
  }
59
+ function createMtmServiceClientByName(svcName, url) {
60
+ const baseUrl = url || process.env.MTM_BACKEND;
61
+ if (!baseUrl) {
62
+ throw new Error("missing mtm api url,\xB7MTM_BACKEND\xB7");
63
+ }
64
+ console.info("gomtm baseUrl:", baseUrl);
65
+ let svcType = void 0;
66
+ for (const a of allServices) {
67
+ if (a.typeName == svcName) {
68
+ svcType = a;
69
+ }
70
+ }
71
+ if (!svcType) {
72
+ throw new Error(`unknown svcType ${svcName}`);
73
+ }
74
+ return createPromiseClient(
75
+ svcType,
76
+ createConnectTransport({
77
+ baseUrl,
78
+ fetch: gomtmFetcher()
79
+ })
80
+ );
81
+ }
82
+ const allServices = [MtmService];
83
+ const gomtmFetcher = (initGlobal) => {
84
+ return (input, init) => __async(void 0, null, function* () {
85
+ if (init) {
86
+ delete init.mode;
87
+ delete init.credentials;
88
+ }
89
+ const req = merge(init, initGlobal, {
90
+ redirect: "follow"
91
+ }) || {};
92
+ let headerCookie = "";
93
+ if (typeof window == "undefined") {
94
+ const reqHeaders = require("next/headers").headers();
95
+ headerCookie = reqHeaders.get("Cookie");
96
+ }
97
+ if (!init) {
98
+ init = {};
99
+ }
100
+ init = __spreadValues(__spreadValues({}, init), {
101
+ headers: __spreadValues(__spreadProps(__spreadValues({}, init.headers), {
102
+ "Content-Type": "application/json"
103
+ }), headerCookie && { "Cookie": headerCookie })
104
+ });
105
+ let fetcher = fetch;
106
+ req.enableCache = false;
107
+ if (req.enableCache) {
108
+ fetcher = fetchMiddleWithCache(fetch);
109
+ }
110
+ try {
111
+ const responseData = yield fetcher(input, init);
112
+ return responseData;
113
+ } catch (e) {
114
+ console.error("[mtmfetch error]", {
115
+ input,
116
+ error: e,
117
+ init
118
+ });
119
+ const errorRsp = {
120
+ errCode: "-1",
121
+ errMessage: (e == null ? void 0 : e.toString()) || "unknow error"
122
+ };
123
+ const errorResponse = new Response(JSON.stringify(errorRsp), {
124
+ status: 200,
125
+ headers: {
126
+ "Content-Type": "application/json"
127
+ }
128
+ });
129
+ return errorResponse;
130
+ }
131
+ });
132
+ };
4
133
  export {
5
- getMtmApiUrl
134
+ createMtmServiceClient,
135
+ createMtmServiceClientByName,
136
+ gomtmFetcher
6
137
  };
@@ -7,7 +7,7 @@ import { AtomsHydrator } from "mtxlib/jotai/jotai-helper";
7
7
  import { isDebugAtom } from "mtxuilib/store/app.atoms";
8
8
  import { useHotkeys } from "react-hotkeys-hook";
9
9
  import { TransportProvider } from "../connectquery";
10
- import { gomtmFetcher } from "../gomtm-clients-ss";
10
+ import { gomtmFetcher } from "../mtmFetcher";
11
11
  import { MtReactQueryProvider } from "./ReactQueryProvider";
12
12
  const mtmAppStore = createStore();
13
13
  const gomtmBaseUrlAtom = atom("");
@@ -1 +0,0 @@
1
- export declare const ssrGetBackendUrl: () => string;
@@ -1,19 +0,0 @@
1
- import { cookies } from "next/headers";
2
- import { MTM_SERVER_COOKIE_ACTIVATE_URL } from "./consts";
3
- const ssrGetBackendUrl = () => {
4
- var _a, _b;
5
- const activateServerUrl = (_a = cookies().get(MTM_SERVER_COOKIE_ACTIVATE_URL)) == null ? void 0 : _a.value;
6
- if (activateServerUrl) {
7
- return activateServerUrl;
8
- }
9
- if ((_b = process == null ? void 0 : process.env) == null ? void 0 : _b.MTM_BACKEND) {
10
- return process.env.MTM_BACKEND;
11
- }
12
- if (process.env.VERCEL_URL) {
13
- return `https://${process.env.VERCEL_URL}`;
14
- }
15
- return "https://localhost";
16
- };
17
- export {
18
- ssrGetBackendUrl
19
- };
@@ -0,0 +1,11 @@
1
+ export declare const isAdminAtom: import("jotai").PrimitiveAtom<boolean> & {
2
+ init: boolean;
3
+ };
4
+ export declare const useIsAdmin: () => boolean;
5
+ export declare function isRoleMatch(currentRoles: string[], allowRoles?: string[]): boolean;
6
+ import { MyJWTPayload } from "../lib/auth/jwt";
7
+ export declare function useAuth(): {
8
+ auth: MyJWTPayload | null;
9
+ userId: string | undefined;
10
+ isAdmin: boolean;
11
+ };
@@ -0,0 +1,75 @@
1
+ "use client";
2
+ var __async = (__this, __arguments, generator) => {
3
+ return new Promise((resolve, reject) => {
4
+ var fulfilled = (value) => {
5
+ try {
6
+ step(generator.next(value));
7
+ } catch (e) {
8
+ reject(e);
9
+ }
10
+ };
11
+ var rejected = (value) => {
12
+ try {
13
+ step(generator.throw(value));
14
+ } catch (e) {
15
+ reject(e);
16
+ }
17
+ };
18
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
19
+ step((generator = generator.apply(__this, __arguments)).next());
20
+ });
21
+ };
22
+ import { atom, useAtom } from "jotai";
23
+ const isAdminAtom = atom(false);
24
+ const useIsAdmin = () => {
25
+ const [isAdmin, setisAdmin] = useAtom(isAdminAtom);
26
+ return isAdmin;
27
+ };
28
+ function isRoleMatch(currentRoles, allowRoles) {
29
+ if (!currentRoles) {
30
+ return true;
31
+ }
32
+ if (!(allowRoles == null ? void 0 : allowRoles.length)) {
33
+ return true;
34
+ }
35
+ for (const roleName of allowRoles) {
36
+ const ok = currentRoles.find((x) => x == roleName);
37
+ if (ok) {
38
+ return true;
39
+ }
40
+ }
41
+ return false;
42
+ }
43
+ import React, { useEffect, useMemo } from "react";
44
+ import Cookies from "universal-cookie";
45
+ import { useSuspenseQuery } from "../connectquery";
46
+ import { userinfo } from "../gomtmpb/mtm/sppb/mtm-MtmService_connectquery";
47
+ import { verifyJwtToken } from "../lib/auth/jwt";
48
+ function useAuth() {
49
+ const [auth, setAuth] = React.useState(null);
50
+ const getVerifiedtoken = () => __async(this, null, function* () {
51
+ var _a;
52
+ const cookies = new Cookies();
53
+ const token = (_a = cookies.get("token")) != null ? _a : null;
54
+ const verifiedToken = yield verifyJwtToken(token);
55
+ setAuth(verifiedToken);
56
+ });
57
+ useEffect(() => {
58
+ getVerifiedtoken();
59
+ }, []);
60
+ const isAdmin = useMemo(() => {
61
+ return (auth == null ? void 0 : auth.role) == "admin";
62
+ }, [auth]);
63
+ const userInfoQuery = useSuspenseQuery(userinfo);
64
+ const userId = useMemo(() => {
65
+ var _a;
66
+ return (_a = userInfoQuery.data.userInfo) == null ? void 0 : _a.ID;
67
+ }, [userInfoQuery.data]);
68
+ return { auth, userId, isAdmin };
69
+ }
70
+ export {
71
+ isAdminAtom,
72
+ isRoleMatch,
73
+ useAuth,
74
+ useIsAdmin
75
+ };