@tenxyte/vue 0.5.0 → 0.5.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tenxyte
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,201 @@
1
+ # @tenxyte/vue
2
+
3
+ Vue 3 bindings for the [Tenxyte SDK](https://www.npmjs.com/package/@tenxyte/core). Provides reactive composables that automatically update when authentication state changes.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @tenxyte/core @tenxyte/vue
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ### 1. Install the plugin
14
+
15
+ ```ts
16
+ import { createApp } from 'vue';
17
+ import { TenxyteClient } from '@tenxyte/core';
18
+ import { tenxytePlugin } from '@tenxyte/vue';
19
+ import App from './App.vue';
20
+
21
+ const tx = new TenxyteClient({
22
+ baseUrl: 'https://api.example.com',
23
+ headers: { 'X-Access-Key': 'your-api-key' },
24
+ });
25
+
26
+ const app = createApp(App);
27
+ app.use(tenxytePlugin, tx);
28
+ app.mount('#app');
29
+ ```
30
+
31
+ ### 2. Use composables in any component
32
+
33
+ ```vue
34
+ <script setup lang="ts">
35
+ import { useAuth, useUser, useRbac, useOrganization } from '@tenxyte/vue';
36
+
37
+ const { isAuthenticated, loading, logout } = useAuth();
38
+ const { user } = useUser();
39
+ const { hasRole } = useRbac();
40
+ </script>
41
+
42
+ <template>
43
+ <p v-if="loading">Loading...</p>
44
+
45
+ <div v-else-if="isAuthenticated">
46
+ <p>Welcome, {{ user?.email }}</p>
47
+ <AdminPanel v-if="hasRole('admin')" />
48
+ <button @click="logout">Logout</button>
49
+ </div>
50
+
51
+ <LoginPage v-else />
52
+ </template>
53
+ ```
54
+
55
+ ## Composables
56
+
57
+ ### `useAuth()`
58
+
59
+ Reactive authentication state and actions.
60
+
61
+ ```ts
62
+ const {
63
+ isAuthenticated, // Readonly<Ref<boolean>> — true if access token is valid
64
+ loading, // Readonly<Ref<boolean>> — true while initial state loads
65
+ accessToken, // Readonly<Ref<string | null>> — raw JWT access token
66
+ loginWithEmail, // (data: { email, password, device_info?, totp_code? }) => Promise<void>
67
+ loginWithPhone, // (data: { phone_country_code, phone_number, password, device_info? }) => Promise<void>
68
+ logout, // () => Promise<void>
69
+ register, // (data) => Promise<void>
70
+ } = useAuth();
71
+ ```
72
+
73
+ **Example — Login form:**
74
+
75
+ ```vue
76
+ <script setup lang="ts">
77
+ import { ref } from 'vue';
78
+ import { useAuth } from '@tenxyte/vue';
79
+
80
+ const { isAuthenticated, loginWithEmail, logout, loading } = useAuth();
81
+ const email = ref('');
82
+ const password = ref('');
83
+
84
+ async function handleLogin() {
85
+ await loginWithEmail({ email: email.value, password: password.value });
86
+ }
87
+ </script>
88
+
89
+ <template>
90
+ <p v-if="loading">Loading...</p>
91
+ <button v-else-if="isAuthenticated" @click="logout">Logout</button>
92
+ <form v-else @submit.prevent="handleLogin">
93
+ <input v-model="email" placeholder="Email" />
94
+ <input v-model="password" type="password" placeholder="Password" />
95
+ <button type="submit">Sign In</button>
96
+ </form>
97
+ </template>
98
+ ```
99
+
100
+ ### `useUser()`
101
+
102
+ Decoded JWT user and profile management.
103
+
104
+ ```ts
105
+ const {
106
+ user, // Readonly<Ref<DecodedTenxyteToken | null>> — decoded JWT payload
107
+ loading, // Readonly<Ref<boolean>>
108
+ getProfile, // () => Promise<UserProfile> — fetch full profile from API
109
+ updateProfile, // (data) => Promise<unknown>
110
+ } = useUser();
111
+ ```
112
+
113
+ **Example:**
114
+
115
+ ```vue
116
+ <script setup lang="ts">
117
+ import { useUser } from '@tenxyte/vue';
118
+ const { user, loading } = useUser();
119
+ </script>
120
+
121
+ <template>
122
+ <span v-if="!loading && user">{{ user.email }}</span>
123
+ </template>
124
+ ```
125
+
126
+ ### `useOrganization()`
127
+
128
+ Multi-tenant organization context (B2B).
129
+
130
+ ```ts
131
+ const {
132
+ activeOrg, // Readonly<Ref<string | null>> — current org slug
133
+ switchOrganization, // (slug: string) => void
134
+ clearOrganization, // () => void
135
+ } = useOrganization();
136
+ ```
137
+
138
+ **Example:**
139
+
140
+ ```vue
141
+ <script setup lang="ts">
142
+ import { useOrganization } from '@tenxyte/vue';
143
+ const { activeOrg, switchOrganization, clearOrganization } = useOrganization();
144
+ </script>
145
+
146
+ <template>
147
+ <select
148
+ :value="activeOrg ?? ''"
149
+ @change="(e) => (e.target as HTMLSelectElement).value
150
+ ? switchOrganization((e.target as HTMLSelectElement).value)
151
+ : clearOrganization()"
152
+ >
153
+ <option value="">No organization</option>
154
+ <option v-for="org in orgs" :key="org.slug" :value="org.slug">
155
+ {{ org.name }}
156
+ </option>
157
+ </select>
158
+ </template>
159
+ ```
160
+
161
+ ### `useRbac()`
162
+
163
+ Synchronous role and permission checks from the current JWT.
164
+
165
+ ```ts
166
+ const {
167
+ hasRole, // (role: string) => boolean
168
+ hasPermission, // (permission: string) => boolean
169
+ hasAnyRole, // (roles: string[]) => boolean
170
+ hasAllRoles, // (roles: string[]) => boolean
171
+ } = useRbac();
172
+ ```
173
+
174
+ **Example:**
175
+
176
+ ```vue
177
+ <script setup lang="ts">
178
+ import { useRbac } from '@tenxyte/vue';
179
+ const { hasRole } = useRbac();
180
+ </script>
181
+
182
+ <template>
183
+ <AdminPanel v-if="hasRole('admin')" />
184
+ <p v-else>Access denied</p>
185
+ </template>
186
+ ```
187
+
188
+ ## How It Works
189
+
190
+ The `tenxytePlugin` provides the `TenxyteClient` instance via Vue's dependency injection (`app.provide`). Each composable calls `useTenxyteClient()` internally to retrieve the client, then subscribes to SDK events (`token:stored`, `token:refreshed`, `session:expired`) using `onMounted`/`onUnmounted` lifecycle hooks. Reactive state is exposed as `readonly(ref(...))` so templates update automatically.
191
+
192
+ ## Peer Dependencies
193
+
194
+ | Package | Version |
195
+ |---|---|
196
+ | `@tenxyte/core` | `^0.9.2` |
197
+ | `vue` | `^3.3.0` |
198
+
199
+ ## License
200
+
201
+ MIT — see [LICENSE](./LICENSE)
package/dist/index.cjs ADDED
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ TENXYTE_KEY: () => TENXYTE_KEY,
24
+ tenxytePlugin: () => tenxytePlugin,
25
+ useAuth: () => useAuth,
26
+ useOrganization: () => useOrganization,
27
+ useRbac: () => useRbac,
28
+ useTenxyteClient: () => useTenxyteClient,
29
+ useUser: () => useUser
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/plugin.ts
34
+ var import_vue = require("vue");
35
+ var TENXYTE_KEY = /* @__PURE__ */ Symbol("tenxyte");
36
+ var tenxytePlugin = {
37
+ install(app, client) {
38
+ app.provide(TENXYTE_KEY, client);
39
+ }
40
+ };
41
+ function useTenxyteClient() {
42
+ const client = (0, import_vue.inject)(TENXYTE_KEY);
43
+ if (!client) {
44
+ throw new Error(
45
+ "[@tenxyte/vue] useTenxyteClient() requires the tenxytePlugin to be installed. Call app.use(tenxytePlugin, client) in your main entry."
46
+ );
47
+ }
48
+ return client;
49
+ }
50
+
51
+ // src/composables.ts
52
+ var import_vue2 = require("vue");
53
+ function useAuth() {
54
+ const client = useTenxyteClient();
55
+ const isAuthenticated = (0, import_vue2.ref)(false);
56
+ const loading = (0, import_vue2.ref)(true);
57
+ const accessToken = (0, import_vue2.ref)(null);
58
+ const refresh = async () => {
59
+ const state = await client.getState();
60
+ isAuthenticated.value = state.isAuthenticated;
61
+ accessToken.value = state.accessToken;
62
+ loading.value = false;
63
+ };
64
+ const unsubs = [];
65
+ (0, import_vue2.onMounted)(() => {
66
+ refresh();
67
+ unsubs.push(
68
+ client.on("token:stored", () => {
69
+ refresh();
70
+ }),
71
+ client.on("token:refreshed", () => {
72
+ refresh();
73
+ }),
74
+ client.on("session:expired", () => {
75
+ refresh();
76
+ })
77
+ );
78
+ });
79
+ (0, import_vue2.onUnmounted)(() => {
80
+ unsubs.forEach((fn) => fn());
81
+ });
82
+ const loginWithEmail = async (data) => {
83
+ await client.auth.loginWithEmail({ ...data, device_info: data.device_info ?? "" });
84
+ };
85
+ const loginWithPhone = async (data) => {
86
+ await client.auth.loginWithPhone({ ...data, device_info: data.device_info ?? "" });
87
+ };
88
+ const logout = async () => {
89
+ await client.auth.logoutAll();
90
+ };
91
+ const register = async (data) => {
92
+ await client.auth.register(data);
93
+ };
94
+ return {
95
+ isAuthenticated: (0, import_vue2.readonly)(isAuthenticated),
96
+ loading: (0, import_vue2.readonly)(loading),
97
+ accessToken: (0, import_vue2.readonly)(accessToken),
98
+ loginWithEmail,
99
+ loginWithPhone,
100
+ logout,
101
+ register
102
+ };
103
+ }
104
+ function useUser() {
105
+ const client = useTenxyteClient();
106
+ const user = (0, import_vue2.ref)(null);
107
+ const loading = (0, import_vue2.ref)(true);
108
+ const refresh = async () => {
109
+ const state = await client.getState();
110
+ user.value = state.user;
111
+ loading.value = false;
112
+ };
113
+ const unsubs = [];
114
+ (0, import_vue2.onMounted)(() => {
115
+ refresh();
116
+ unsubs.push(
117
+ client.on("token:stored", () => {
118
+ refresh();
119
+ }),
120
+ client.on("token:refreshed", () => {
121
+ refresh();
122
+ }),
123
+ client.on("session:expired", () => {
124
+ refresh();
125
+ })
126
+ );
127
+ });
128
+ (0, import_vue2.onUnmounted)(() => {
129
+ unsubs.forEach((fn) => fn());
130
+ });
131
+ const getProfile = () => client.user.getProfile();
132
+ const updateProfile = (data) => client.user.updateProfile(data);
133
+ return {
134
+ user: (0, import_vue2.readonly)(user),
135
+ loading: (0, import_vue2.readonly)(loading),
136
+ getProfile,
137
+ updateProfile
138
+ };
139
+ }
140
+ function useOrganization() {
141
+ const client = useTenxyteClient();
142
+ const activeOrg = (0, import_vue2.ref)(null);
143
+ const refresh = async () => {
144
+ const state = await client.getState();
145
+ activeOrg.value = state.activeOrg;
146
+ };
147
+ (0, import_vue2.onMounted)(() => {
148
+ refresh();
149
+ });
150
+ const switchOrganization = (slug) => {
151
+ client.b2b.switchOrganization(slug);
152
+ activeOrg.value = slug;
153
+ };
154
+ const clearOrganization = () => {
155
+ client.b2b.clearOrganization();
156
+ activeOrg.value = null;
157
+ };
158
+ return {
159
+ activeOrg: (0, import_vue2.readonly)(activeOrg),
160
+ switchOrganization,
161
+ clearOrganization
162
+ };
163
+ }
164
+ function useRbac() {
165
+ const client = useTenxyteClient();
166
+ const token = (0, import_vue2.ref)(null);
167
+ const refresh = async () => {
168
+ token.value = await client.getAccessToken();
169
+ };
170
+ const unsubs = [];
171
+ (0, import_vue2.onMounted)(() => {
172
+ refresh();
173
+ unsubs.push(
174
+ client.on("token:stored", () => {
175
+ refresh();
176
+ }),
177
+ client.on("token:refreshed", () => {
178
+ refresh();
179
+ }),
180
+ client.on("session:expired", () => {
181
+ refresh();
182
+ })
183
+ );
184
+ });
185
+ (0, import_vue2.onUnmounted)(() => {
186
+ unsubs.forEach((fn) => fn());
187
+ });
188
+ const hasRole = (role) => client.rbac.hasRole(role, token.value ?? void 0);
189
+ const hasPermission = (permission) => client.rbac.hasPermission(permission, token.value ?? void 0);
190
+ const hasAnyRole = (roles) => client.rbac.hasAnyRole(roles, token.value ?? void 0);
191
+ const hasAllRoles = (roles) => client.rbac.hasAllRoles(roles, token.value ?? void 0);
192
+ return { hasRole, hasPermission, hasAnyRole, hasAllRoles };
193
+ }
194
+ // Annotate the CommonJS export names for ESM import in node:
195
+ 0 && (module.exports = {
196
+ TENXYTE_KEY,
197
+ tenxytePlugin,
198
+ useAuth,
199
+ useOrganization,
200
+ useRbac,
201
+ useTenxyteClient,
202
+ useUser
203
+ });
204
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/plugin.ts","../src/composables.ts"],"sourcesContent":["export { tenxytePlugin, TENXYTE_KEY, useTenxyteClient } from './plugin';\nexport { useAuth, useUser, useOrganization, useRbac } from './composables';\nexport type { UseAuthReturn, UseUserReturn, UseOrganizationReturn, UseRbacReturn } from './composables';\n","import { inject, type App, type InjectionKey } from 'vue';\nimport type { TenxyteClient } from '@tenxyte/core';\n\n/**\n * Vue injection key for the TenxyteClient instance.\n */\nexport const TENXYTE_KEY: InjectionKey<TenxyteClient> = Symbol('tenxyte');\n\n/**\n * Vue plugin that installs the TenxyteClient into the app.\n *\n * @example\n * ```ts\n * import { createApp } from 'vue';\n * import { TenxyteClient } from '@tenxyte/core';\n * import { tenxytePlugin } from '@tenxyte/vue';\n *\n * const tx = new TenxyteClient({ baseUrl: '...' });\n * const app = createApp(App);\n * app.use(tenxytePlugin, tx);\n * app.mount('#app');\n * ```\n */\nexport const tenxytePlugin = {\n install(app: App, client: TenxyteClient): void {\n app.provide(TENXYTE_KEY, client);\n },\n};\n\n/**\n * Internal helper to retrieve the TenxyteClient from Vue's injection system.\n * Throws if the plugin has not been installed.\n */\nexport function useTenxyteClient(): TenxyteClient {\n const client = inject(TENXYTE_KEY);\n if (!client) {\n throw new Error(\n '[@tenxyte/vue] useTenxyteClient() requires the tenxytePlugin to be installed. ' +\n 'Call app.use(tenxytePlugin, client) in your main entry.',\n );\n }\n return client;\n}\n","import { ref, readonly, onMounted, onUnmounted, computed, type Ref, type DeepReadonly } from 'vue';\nimport type { TenxyteClient, TenxyteClientState, DecodedTenxyteToken } from '@tenxyte/core';\nimport { useTenxyteClient } from './plugin';\n\n// ─── useAuth ───\n\nexport interface UseAuthReturn {\n /** Whether the user has a valid, non-expired access token. */\n isAuthenticated: DeepReadonly<Ref<boolean>>;\n /** Whether the initial state is still loading from storage. */\n loading: DeepReadonly<Ref<boolean>>;\n /** Raw access token string, or null. */\n accessToken: DeepReadonly<Ref<string | null>>;\n /** Login with email/password. */\n loginWithEmail: (data: { email: string; password: string; device_info?: string; totp_code?: string }) => Promise<void>;\n /** Login with phone/password. */\n loginWithPhone: (data: { phone_country_code: string; phone_number: string; password: string; device_info?: string }) => Promise<void>;\n /** Logout from all sessions. */\n logout: () => Promise<void>;\n /** Register a new account. */\n register: (data: Record<string, unknown>) => Promise<void>;\n}\n\n/**\n * Reactive authentication composable.\n * Automatically updates when the auth state changes (login, logout, refresh, expiry).\n *\n * @example\n * ```vue\n * <script setup lang=\"ts\">\n * import { useAuth } from '@tenxyte/vue';\n * const { isAuthenticated, loginWithEmail, logout, loading } = useAuth();\n * </script>\n *\n * <template>\n * <p v-if=\"loading\">Loading...</p>\n * <button v-else-if=\"isAuthenticated\" @click=\"logout\">Logout</button>\n * <button v-else @click=\"loginWithEmail({ email: '...', password: '...' })\">Login</button>\n * </template>\n * ```\n */\nexport function useAuth(): UseAuthReturn {\n const client = useTenxyteClient();\n const isAuthenticated = ref(false);\n const loading = ref(true);\n const accessToken = ref<string | null>(null);\n\n const refresh = async (): Promise<void> => {\n const state = await client.getState();\n isAuthenticated.value = state.isAuthenticated;\n accessToken.value = state.accessToken;\n loading.value = false;\n };\n\n const unsubs: Array<() => void> = [];\n\n onMounted(() => {\n refresh();\n unsubs.push(\n client.on('token:stored', () => { refresh(); }),\n client.on('token:refreshed', () => { refresh(); }),\n client.on('session:expired', () => { refresh(); }),\n );\n });\n\n onUnmounted(() => {\n unsubs.forEach((fn) => fn());\n });\n\n const loginWithEmail = async (data: { email: string; password: string; device_info?: string; totp_code?: string }): Promise<void> => {\n await client.auth.loginWithEmail({ ...data, device_info: data.device_info ?? '' });\n };\n\n const loginWithPhone = async (data: { phone_country_code: string; phone_number: string; password: string; device_info?: string }): Promise<void> => {\n await client.auth.loginWithPhone({ ...data, device_info: data.device_info ?? '' });\n };\n\n const logout = async (): Promise<void> => {\n await client.auth.logoutAll();\n };\n\n const register = async (data: Record<string, unknown>): Promise<void> => {\n await client.auth.register(data as any);\n };\n\n return {\n isAuthenticated: readonly(isAuthenticated),\n loading: readonly(loading),\n accessToken: readonly(accessToken),\n loginWithEmail,\n loginWithPhone,\n logout,\n register,\n };\n}\n\n// ─── useUser ───\n\nexport interface UseUserReturn {\n /** Decoded JWT payload of the current access token, or null. */\n user: DeepReadonly<Ref<DecodedTenxyteToken | null>>;\n /** Whether the initial state is still loading. */\n loading: DeepReadonly<Ref<boolean>>;\n /** Fetch the full user profile from the backend. */\n getProfile: () => ReturnType<TenxyteClient['user']['getProfile']>;\n /** Update the current user's profile. */\n updateProfile: (data: Record<string, unknown>) => Promise<unknown>;\n}\n\n/**\n * Reactive user composable.\n * Returns the decoded JWT user and convenience methods for profile management.\n *\n * @example\n * ```vue\n * <script setup lang=\"ts\">\n * import { useUser } from '@tenxyte/vue';\n * const { user, loading } = useUser();\n * </script>\n *\n * <template>\n * <span v-if=\"!loading && user\">{{ user.email }}</span>\n * </template>\n * ```\n */\nexport function useUser(): UseUserReturn {\n const client = useTenxyteClient();\n const user = ref<DecodedTenxyteToken | null>(null);\n const loading = ref(true);\n\n const refresh = async (): Promise<void> => {\n const state = await client.getState();\n user.value = state.user;\n loading.value = false;\n };\n\n const unsubs: Array<() => void> = [];\n\n onMounted(() => {\n refresh();\n unsubs.push(\n client.on('token:stored', () => { refresh(); }),\n client.on('token:refreshed', () => { refresh(); }),\n client.on('session:expired', () => { refresh(); }),\n );\n });\n\n onUnmounted(() => {\n unsubs.forEach((fn) => fn());\n });\n\n const getProfile = () => client.user.getProfile();\n const updateProfile = (data: Record<string, unknown>) => client.user.updateProfile(data);\n\n return {\n user: readonly(user) as DeepReadonly<Ref<DecodedTenxyteToken | null>>,\n loading: readonly(loading),\n getProfile,\n updateProfile,\n };\n}\n\n// ─── useOrganization ───\n\nexport interface UseOrganizationReturn {\n /** Currently active organization slug, or null. */\n activeOrg: DeepReadonly<Ref<string | null>>;\n /** Switch the SDK to operate within an organization context. */\n switchOrganization: (slug: string) => void;\n /** Clear the organization context. */\n clearOrganization: () => void;\n}\n\n/**\n * Reactive organization context composable.\n *\n * @example\n * ```vue\n * <script setup lang=\"ts\">\n * import { useOrganization } from '@tenxyte/vue';\n * const { activeOrg, switchOrganization, clearOrganization } = useOrganization();\n * </script>\n * ```\n */\nexport function useOrganization(): UseOrganizationReturn {\n const client = useTenxyteClient();\n const activeOrg = ref<string | null>(null);\n\n const refresh = async (): Promise<void> => {\n const state = await client.getState();\n activeOrg.value = state.activeOrg;\n };\n\n onMounted(() => { refresh(); });\n\n const switchOrganization = (slug: string): void => {\n client.b2b.switchOrganization(slug);\n activeOrg.value = slug;\n };\n\n const clearOrganization = (): void => {\n client.b2b.clearOrganization();\n activeOrg.value = null;\n };\n\n return {\n activeOrg: readonly(activeOrg),\n switchOrganization,\n clearOrganization,\n };\n}\n\n// ─── useRbac ───\n\nexport interface UseRbacReturn {\n /** Check if the current user has a specific role (synchronous JWT check). */\n hasRole: (role: string) => boolean;\n /** Check if the current user has a specific permission (synchronous JWT check). */\n hasPermission: (permission: string) => boolean;\n /** Check if the current user has any of the given roles. */\n hasAnyRole: (roles: string[]) => boolean;\n /** Check if the current user has all of the given roles. */\n hasAllRoles: (roles: string[]) => boolean;\n}\n\n/**\n * Reactive RBAC composable.\n * Provides synchronous role/permission checks based on the current JWT.\n *\n * @example\n * ```vue\n * <script setup lang=\"ts\">\n * import { useRbac } from '@tenxyte/vue';\n * const { hasRole } = useRbac();\n * </script>\n *\n * <template>\n * <AdminPanel v-if=\"hasRole('admin')\" />\n * <p v-else>Access denied</p>\n * </template>\n * ```\n */\nexport function useRbac(): UseRbacReturn {\n const client = useTenxyteClient();\n const token = ref<string | null>(null);\n\n const refresh = async (): Promise<void> => {\n token.value = await client.getAccessToken();\n };\n\n const unsubs: Array<() => void> = [];\n\n onMounted(() => {\n refresh();\n unsubs.push(\n client.on('token:stored', () => { refresh(); }),\n client.on('token:refreshed', () => { refresh(); }),\n client.on('session:expired', () => { refresh(); }),\n );\n });\n\n onUnmounted(() => {\n unsubs.forEach((fn) => fn());\n });\n\n const hasRole = (role: string): boolean =>\n client.rbac.hasRole(role, token.value ?? undefined);\n\n const hasPermission = (permission: string): boolean =>\n client.rbac.hasPermission(permission, token.value ?? undefined);\n\n const hasAnyRole = (roles: string[]): boolean =>\n client.rbac.hasAnyRole(roles, token.value ?? undefined);\n\n const hasAllRoles = (roles: string[]): boolean =>\n client.rbac.hasAllRoles(roles, token.value ?? undefined);\n\n return { hasRole, hasPermission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AC,eACnB,OAAO,KAAK,cAAc,YAAY,MAAM,SAAS,MAAS;AAElE,QAAM,aAAa,CAAC,UAChB,OAAO,KAAK,WAAW,OAAO,MAAM,SAAS,MAAS;AAE1D,QAAM,cAAc,CAAC,UACjB,OAAO,KAAK,YAAY,OAAO,MAAM,SAAS,MAAS;AAE3D,SAAO,EAAE,SAAS,eAAe,YAAY,YAAY;AAC7D;","names":["import_vue"]}
@@ -0,0 +1,153 @@
1
+ import { InjectionKey, App, DeepReadonly, Ref } from 'vue';
2
+ import { TenxyteClient, DecodedTenxyteToken } from '@tenxyte/core';
3
+
4
+ /**
5
+ * Vue injection key for the TenxyteClient instance.
6
+ */
7
+ declare const TENXYTE_KEY: InjectionKey<TenxyteClient>;
8
+ /**
9
+ * Vue plugin that installs the TenxyteClient into the app.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { createApp } from 'vue';
14
+ * import { TenxyteClient } from '@tenxyte/core';
15
+ * import { tenxytePlugin } from '@tenxyte/vue';
16
+ *
17
+ * const tx = new TenxyteClient({ baseUrl: '...' });
18
+ * const app = createApp(App);
19
+ * app.use(tenxytePlugin, tx);
20
+ * app.mount('#app');
21
+ * ```
22
+ */
23
+ declare const tenxytePlugin: {
24
+ install(app: App, client: TenxyteClient): void;
25
+ };
26
+ /**
27
+ * Internal helper to retrieve the TenxyteClient from Vue's injection system.
28
+ * Throws if the plugin has not been installed.
29
+ */
30
+ declare function useTenxyteClient(): TenxyteClient;
31
+
32
+ interface UseAuthReturn {
33
+ /** Whether the user has a valid, non-expired access token. */
34
+ isAuthenticated: DeepReadonly<Ref<boolean>>;
35
+ /** Whether the initial state is still loading from storage. */
36
+ loading: DeepReadonly<Ref<boolean>>;
37
+ /** Raw access token string, or null. */
38
+ accessToken: DeepReadonly<Ref<string | null>>;
39
+ /** Login with email/password. */
40
+ loginWithEmail: (data: {
41
+ email: string;
42
+ password: string;
43
+ device_info?: string;
44
+ totp_code?: string;
45
+ }) => Promise<void>;
46
+ /** Login with phone/password. */
47
+ loginWithPhone: (data: {
48
+ phone_country_code: string;
49
+ phone_number: string;
50
+ password: string;
51
+ device_info?: string;
52
+ }) => Promise<void>;
53
+ /** Logout from all sessions. */
54
+ logout: () => Promise<void>;
55
+ /** Register a new account. */
56
+ register: (data: Record<string, unknown>) => Promise<void>;
57
+ }
58
+ /**
59
+ * Reactive authentication composable.
60
+ * Automatically updates when the auth state changes (login, logout, refresh, expiry).
61
+ *
62
+ * @example
63
+ * ```vue
64
+ * <script setup lang="ts">
65
+ * import { useAuth } from '@tenxyte/vue';
66
+ * const { isAuthenticated, loginWithEmail, logout, loading } = useAuth();
67
+ * </script>
68
+ *
69
+ * <template>
70
+ * <p v-if="loading">Loading...</p>
71
+ * <button v-else-if="isAuthenticated" @click="logout">Logout</button>
72
+ * <button v-else @click="loginWithEmail({ email: '...', password: '...' })">Login</button>
73
+ * </template>
74
+ * ```
75
+ */
76
+ declare function useAuth(): UseAuthReturn;
77
+ interface UseUserReturn {
78
+ /** Decoded JWT payload of the current access token, or null. */
79
+ user: DeepReadonly<Ref<DecodedTenxyteToken | null>>;
80
+ /** Whether the initial state is still loading. */
81
+ loading: DeepReadonly<Ref<boolean>>;
82
+ /** Fetch the full user profile from the backend. */
83
+ getProfile: () => ReturnType<TenxyteClient['user']['getProfile']>;
84
+ /** Update the current user's profile. */
85
+ updateProfile: (data: Record<string, unknown>) => Promise<unknown>;
86
+ }
87
+ /**
88
+ * Reactive user composable.
89
+ * Returns the decoded JWT user and convenience methods for profile management.
90
+ *
91
+ * @example
92
+ * ```vue
93
+ * <script setup lang="ts">
94
+ * import { useUser } from '@tenxyte/vue';
95
+ * const { user, loading } = useUser();
96
+ * </script>
97
+ *
98
+ * <template>
99
+ * <span v-if="!loading && user">{{ user.email }}</span>
100
+ * </template>
101
+ * ```
102
+ */
103
+ declare function useUser(): UseUserReturn;
104
+ interface UseOrganizationReturn {
105
+ /** Currently active organization slug, or null. */
106
+ activeOrg: DeepReadonly<Ref<string | null>>;
107
+ /** Switch the SDK to operate within an organization context. */
108
+ switchOrganization: (slug: string) => void;
109
+ /** Clear the organization context. */
110
+ clearOrganization: () => void;
111
+ }
112
+ /**
113
+ * Reactive organization context composable.
114
+ *
115
+ * @example
116
+ * ```vue
117
+ * <script setup lang="ts">
118
+ * import { useOrganization } from '@tenxyte/vue';
119
+ * const { activeOrg, switchOrganization, clearOrganization } = useOrganization();
120
+ * </script>
121
+ * ```
122
+ */
123
+ declare function useOrganization(): UseOrganizationReturn;
124
+ interface UseRbacReturn {
125
+ /** Check if the current user has a specific role (synchronous JWT check). */
126
+ hasRole: (role: string) => boolean;
127
+ /** Check if the current user has a specific permission (synchronous JWT check). */
128
+ hasPermission: (permission: string) => boolean;
129
+ /** Check if the current user has any of the given roles. */
130
+ hasAnyRole: (roles: string[]) => boolean;
131
+ /** Check if the current user has all of the given roles. */
132
+ hasAllRoles: (roles: string[]) => boolean;
133
+ }
134
+ /**
135
+ * Reactive RBAC composable.
136
+ * Provides synchronous role/permission checks based on the current JWT.
137
+ *
138
+ * @example
139
+ * ```vue
140
+ * <script setup lang="ts">
141
+ * import { useRbac } from '@tenxyte/vue';
142
+ * const { hasRole } = useRbac();
143
+ * </script>
144
+ *
145
+ * <template>
146
+ * <AdminPanel v-if="hasRole('admin')" />
147
+ * <p v-else>Access denied</p>
148
+ * </template>
149
+ * ```
150
+ */
151
+ declare function useRbac(): UseRbacReturn;
152
+
153
+ export { TENXYTE_KEY, type UseAuthReturn, type UseOrganizationReturn, type UseRbacReturn, type UseUserReturn, tenxytePlugin, useAuth, useOrganization, useRbac, useTenxyteClient, useUser };
@@ -0,0 +1,153 @@
1
+ import { InjectionKey, App, DeepReadonly, Ref } from 'vue';
2
+ import { TenxyteClient, DecodedTenxyteToken } from '@tenxyte/core';
3
+
4
+ /**
5
+ * Vue injection key for the TenxyteClient instance.
6
+ */
7
+ declare const TENXYTE_KEY: InjectionKey<TenxyteClient>;
8
+ /**
9
+ * Vue plugin that installs the TenxyteClient into the app.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { createApp } from 'vue';
14
+ * import { TenxyteClient } from '@tenxyte/core';
15
+ * import { tenxytePlugin } from '@tenxyte/vue';
16
+ *
17
+ * const tx = new TenxyteClient({ baseUrl: '...' });
18
+ * const app = createApp(App);
19
+ * app.use(tenxytePlugin, tx);
20
+ * app.mount('#app');
21
+ * ```
22
+ */
23
+ declare const tenxytePlugin: {
24
+ install(app: App, client: TenxyteClient): void;
25
+ };
26
+ /**
27
+ * Internal helper to retrieve the TenxyteClient from Vue's injection system.
28
+ * Throws if the plugin has not been installed.
29
+ */
30
+ declare function useTenxyteClient(): TenxyteClient;
31
+
32
+ interface UseAuthReturn {
33
+ /** Whether the user has a valid, non-expired access token. */
34
+ isAuthenticated: DeepReadonly<Ref<boolean>>;
35
+ /** Whether the initial state is still loading from storage. */
36
+ loading: DeepReadonly<Ref<boolean>>;
37
+ /** Raw access token string, or null. */
38
+ accessToken: DeepReadonly<Ref<string | null>>;
39
+ /** Login with email/password. */
40
+ loginWithEmail: (data: {
41
+ email: string;
42
+ password: string;
43
+ device_info?: string;
44
+ totp_code?: string;
45
+ }) => Promise<void>;
46
+ /** Login with phone/password. */
47
+ loginWithPhone: (data: {
48
+ phone_country_code: string;
49
+ phone_number: string;
50
+ password: string;
51
+ device_info?: string;
52
+ }) => Promise<void>;
53
+ /** Logout from all sessions. */
54
+ logout: () => Promise<void>;
55
+ /** Register a new account. */
56
+ register: (data: Record<string, unknown>) => Promise<void>;
57
+ }
58
+ /**
59
+ * Reactive authentication composable.
60
+ * Automatically updates when the auth state changes (login, logout, refresh, expiry).
61
+ *
62
+ * @example
63
+ * ```vue
64
+ * <script setup lang="ts">
65
+ * import { useAuth } from '@tenxyte/vue';
66
+ * const { isAuthenticated, loginWithEmail, logout, loading } = useAuth();
67
+ * </script>
68
+ *
69
+ * <template>
70
+ * <p v-if="loading">Loading...</p>
71
+ * <button v-else-if="isAuthenticated" @click="logout">Logout</button>
72
+ * <button v-else @click="loginWithEmail({ email: '...', password: '...' })">Login</button>
73
+ * </template>
74
+ * ```
75
+ */
76
+ declare function useAuth(): UseAuthReturn;
77
+ interface UseUserReturn {
78
+ /** Decoded JWT payload of the current access token, or null. */
79
+ user: DeepReadonly<Ref<DecodedTenxyteToken | null>>;
80
+ /** Whether the initial state is still loading. */
81
+ loading: DeepReadonly<Ref<boolean>>;
82
+ /** Fetch the full user profile from the backend. */
83
+ getProfile: () => ReturnType<TenxyteClient['user']['getProfile']>;
84
+ /** Update the current user's profile. */
85
+ updateProfile: (data: Record<string, unknown>) => Promise<unknown>;
86
+ }
87
+ /**
88
+ * Reactive user composable.
89
+ * Returns the decoded JWT user and convenience methods for profile management.
90
+ *
91
+ * @example
92
+ * ```vue
93
+ * <script setup lang="ts">
94
+ * import { useUser } from '@tenxyte/vue';
95
+ * const { user, loading } = useUser();
96
+ * </script>
97
+ *
98
+ * <template>
99
+ * <span v-if="!loading && user">{{ user.email }}</span>
100
+ * </template>
101
+ * ```
102
+ */
103
+ declare function useUser(): UseUserReturn;
104
+ interface UseOrganizationReturn {
105
+ /** Currently active organization slug, or null. */
106
+ activeOrg: DeepReadonly<Ref<string | null>>;
107
+ /** Switch the SDK to operate within an organization context. */
108
+ switchOrganization: (slug: string) => void;
109
+ /** Clear the organization context. */
110
+ clearOrganization: () => void;
111
+ }
112
+ /**
113
+ * Reactive organization context composable.
114
+ *
115
+ * @example
116
+ * ```vue
117
+ * <script setup lang="ts">
118
+ * import { useOrganization } from '@tenxyte/vue';
119
+ * const { activeOrg, switchOrganization, clearOrganization } = useOrganization();
120
+ * </script>
121
+ * ```
122
+ */
123
+ declare function useOrganization(): UseOrganizationReturn;
124
+ interface UseRbacReturn {
125
+ /** Check if the current user has a specific role (synchronous JWT check). */
126
+ hasRole: (role: string) => boolean;
127
+ /** Check if the current user has a specific permission (synchronous JWT check). */
128
+ hasPermission: (permission: string) => boolean;
129
+ /** Check if the current user has any of the given roles. */
130
+ hasAnyRole: (roles: string[]) => boolean;
131
+ /** Check if the current user has all of the given roles. */
132
+ hasAllRoles: (roles: string[]) => boolean;
133
+ }
134
+ /**
135
+ * Reactive RBAC composable.
136
+ * Provides synchronous role/permission checks based on the current JWT.
137
+ *
138
+ * @example
139
+ * ```vue
140
+ * <script setup lang="ts">
141
+ * import { useRbac } from '@tenxyte/vue';
142
+ * const { hasRole } = useRbac();
143
+ * </script>
144
+ *
145
+ * <template>
146
+ * <AdminPanel v-if="hasRole('admin')" />
147
+ * <p v-else>Access denied</p>
148
+ * </template>
149
+ * ```
150
+ */
151
+ declare function useRbac(): UseRbacReturn;
152
+
153
+ export { TENXYTE_KEY, type UseAuthReturn, type UseOrganizationReturn, type UseRbacReturn, type UseUserReturn, tenxytePlugin, useAuth, useOrganization, useRbac, useTenxyteClient, useUser };
package/dist/index.js ADDED
@@ -0,0 +1,171 @@
1
+ // src/plugin.ts
2
+ import { inject } from "vue";
3
+ var TENXYTE_KEY = /* @__PURE__ */ Symbol("tenxyte");
4
+ var tenxytePlugin = {
5
+ install(app, client) {
6
+ app.provide(TENXYTE_KEY, client);
7
+ }
8
+ };
9
+ function useTenxyteClient() {
10
+ const client = inject(TENXYTE_KEY);
11
+ if (!client) {
12
+ throw new Error(
13
+ "[@tenxyte/vue] useTenxyteClient() requires the tenxytePlugin to be installed. Call app.use(tenxytePlugin, client) in your main entry."
14
+ );
15
+ }
16
+ return client;
17
+ }
18
+
19
+ // src/composables.ts
20
+ import { ref, readonly, onMounted, onUnmounted } from "vue";
21
+ function useAuth() {
22
+ const client = useTenxyteClient();
23
+ const isAuthenticated = ref(false);
24
+ const loading = ref(true);
25
+ const accessToken = ref(null);
26
+ const refresh = async () => {
27
+ const state = await client.getState();
28
+ isAuthenticated.value = state.isAuthenticated;
29
+ accessToken.value = state.accessToken;
30
+ loading.value = false;
31
+ };
32
+ const unsubs = [];
33
+ onMounted(() => {
34
+ refresh();
35
+ unsubs.push(
36
+ client.on("token:stored", () => {
37
+ refresh();
38
+ }),
39
+ client.on("token:refreshed", () => {
40
+ refresh();
41
+ }),
42
+ client.on("session:expired", () => {
43
+ refresh();
44
+ })
45
+ );
46
+ });
47
+ onUnmounted(() => {
48
+ unsubs.forEach((fn) => fn());
49
+ });
50
+ const loginWithEmail = async (data) => {
51
+ await client.auth.loginWithEmail({ ...data, device_info: data.device_info ?? "" });
52
+ };
53
+ const loginWithPhone = async (data) => {
54
+ await client.auth.loginWithPhone({ ...data, device_info: data.device_info ?? "" });
55
+ };
56
+ const logout = async () => {
57
+ await client.auth.logoutAll();
58
+ };
59
+ const register = async (data) => {
60
+ await client.auth.register(data);
61
+ };
62
+ return {
63
+ isAuthenticated: readonly(isAuthenticated),
64
+ loading: readonly(loading),
65
+ accessToken: readonly(accessToken),
66
+ loginWithEmail,
67
+ loginWithPhone,
68
+ logout,
69
+ register
70
+ };
71
+ }
72
+ function useUser() {
73
+ const client = useTenxyteClient();
74
+ const user = ref(null);
75
+ const loading = ref(true);
76
+ const refresh = async () => {
77
+ const state = await client.getState();
78
+ user.value = state.user;
79
+ loading.value = false;
80
+ };
81
+ const unsubs = [];
82
+ onMounted(() => {
83
+ refresh();
84
+ unsubs.push(
85
+ client.on("token:stored", () => {
86
+ refresh();
87
+ }),
88
+ client.on("token:refreshed", () => {
89
+ refresh();
90
+ }),
91
+ client.on("session:expired", () => {
92
+ refresh();
93
+ })
94
+ );
95
+ });
96
+ onUnmounted(() => {
97
+ unsubs.forEach((fn) => fn());
98
+ });
99
+ const getProfile = () => client.user.getProfile();
100
+ const updateProfile = (data) => client.user.updateProfile(data);
101
+ return {
102
+ user: readonly(user),
103
+ loading: readonly(loading),
104
+ getProfile,
105
+ updateProfile
106
+ };
107
+ }
108
+ function useOrganization() {
109
+ const client = useTenxyteClient();
110
+ const activeOrg = ref(null);
111
+ const refresh = async () => {
112
+ const state = await client.getState();
113
+ activeOrg.value = state.activeOrg;
114
+ };
115
+ onMounted(() => {
116
+ refresh();
117
+ });
118
+ const switchOrganization = (slug) => {
119
+ client.b2b.switchOrganization(slug);
120
+ activeOrg.value = slug;
121
+ };
122
+ const clearOrganization = () => {
123
+ client.b2b.clearOrganization();
124
+ activeOrg.value = null;
125
+ };
126
+ return {
127
+ activeOrg: readonly(activeOrg),
128
+ switchOrganization,
129
+ clearOrganization
130
+ };
131
+ }
132
+ function useRbac() {
133
+ const client = useTenxyteClient();
134
+ const token = ref(null);
135
+ const refresh = async () => {
136
+ token.value = await client.getAccessToken();
137
+ };
138
+ const unsubs = [];
139
+ onMounted(() => {
140
+ refresh();
141
+ unsubs.push(
142
+ client.on("token:stored", () => {
143
+ refresh();
144
+ }),
145
+ client.on("token:refreshed", () => {
146
+ refresh();
147
+ }),
148
+ client.on("session:expired", () => {
149
+ refresh();
150
+ })
151
+ );
152
+ });
153
+ onUnmounted(() => {
154
+ unsubs.forEach((fn) => fn());
155
+ });
156
+ const hasRole = (role) => client.rbac.hasRole(role, token.value ?? void 0);
157
+ const hasPermission = (permission) => client.rbac.hasPermission(permission, token.value ?? void 0);
158
+ const hasAnyRole = (roles) => client.rbac.hasAnyRole(roles, token.value ?? void 0);
159
+ const hasAllRoles = (roles) => client.rbac.hasAllRoles(roles, token.value ?? void 0);
160
+ return { hasRole, hasPermission, hasAnyRole, hasAllRoles };
161
+ }
162
+ export {
163
+ TENXYTE_KEY,
164
+ tenxytePlugin,
165
+ useAuth,
166
+ useOrganization,
167
+ useRbac,
168
+ useTenxyteClient,
169
+ useUser
170
+ };
171
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugin.ts","../src/composables.ts"],"sourcesContent":["import { inject, type App, type InjectionKey } from 'vue';\nimport type { TenxyteClient } from '@tenxyte/core';\n\n/**\n * Vue injection key for the TenxyteClient instance.\n */\nexport const TENXYTE_KEY: InjectionKey<TenxyteClient> = Symbol('tenxyte');\n\n/**\n * Vue plugin that installs the TenxyteClient into the app.\n *\n * @example\n * ```ts\n * import { createApp } from 'vue';\n * import { TenxyteClient } from '@tenxyte/core';\n * import { tenxytePlugin } from '@tenxyte/vue';\n *\n * const tx = new TenxyteClient({ baseUrl: '...' });\n * const app = createApp(App);\n * app.use(tenxytePlugin, tx);\n * app.mount('#app');\n * ```\n */\nexport const tenxytePlugin = {\n install(app: App, client: TenxyteClient): void {\n app.provide(TENXYTE_KEY, client);\n },\n};\n\n/**\n * Internal helper to retrieve the TenxyteClient from Vue's injection system.\n * Throws if the plugin has not been installed.\n */\nexport function useTenxyteClient(): TenxyteClient {\n const client = inject(TENXYTE_KEY);\n if (!client) {\n throw new Error(\n '[@tenxyte/vue] useTenxyteClient() requires the tenxytePlugin to be installed. ' +\n 'Call app.use(tenxytePlugin, client) in your main entry.',\n );\n }\n return client;\n}\n","import { ref, readonly, onMounted, onUnmounted, computed, type Ref, type DeepReadonly } from 'vue';\nimport type { TenxyteClient, TenxyteClientState, DecodedTenxyteToken } from '@tenxyte/core';\nimport { useTenxyteClient } from './plugin';\n\n// ─── useAuth ───\n\nexport interface UseAuthReturn {\n /** Whether the user has a valid, non-expired access token. */\n isAuthenticated: DeepReadonly<Ref<boolean>>;\n /** Whether the initial state is still loading from storage. */\n loading: DeepReadonly<Ref<boolean>>;\n /** Raw access token string, or null. */\n accessToken: DeepReadonly<Ref<string | null>>;\n /** Login with email/password. */\n loginWithEmail: (data: { email: string; password: string; device_info?: string; totp_code?: string }) => Promise<void>;\n /** Login with phone/password. */\n loginWithPhone: (data: { phone_country_code: string; phone_number: string; password: string; device_info?: string }) => Promise<void>;\n /** Logout from all sessions. */\n logout: () => Promise<void>;\n /** Register a new account. */\n register: (data: Record<string, unknown>) => Promise<void>;\n}\n\n/**\n * Reactive authentication composable.\n * Automatically updates when the auth state changes (login, logout, refresh, expiry).\n *\n * @example\n * ```vue\n * <script setup lang=\"ts\">\n * import { useAuth } from '@tenxyte/vue';\n * const { isAuthenticated, loginWithEmail, logout, loading } = useAuth();\n * </script>\n *\n * <template>\n * <p v-if=\"loading\">Loading...</p>\n * <button v-else-if=\"isAuthenticated\" @click=\"logout\">Logout</button>\n * <button v-else @click=\"loginWithEmail({ email: '...', password: '...' })\">Login</button>\n * </template>\n * ```\n */\nexport function useAuth(): UseAuthReturn {\n const client = useTenxyteClient();\n const isAuthenticated = ref(false);\n const loading = ref(true);\n const accessToken = ref<string | null>(null);\n\n const refresh = async (): Promise<void> => {\n const state = await client.getState();\n isAuthenticated.value = state.isAuthenticated;\n accessToken.value = state.accessToken;\n loading.value = false;\n };\n\n const unsubs: Array<() => void> = [];\n\n onMounted(() => {\n refresh();\n unsubs.push(\n client.on('token:stored', () => { refresh(); }),\n client.on('token:refreshed', () => { refresh(); }),\n client.on('session:expired', () => { refresh(); }),\n );\n });\n\n onUnmounted(() => {\n unsubs.forEach((fn) => fn());\n });\n\n const loginWithEmail = async (data: { email: string; password: string; device_info?: string; totp_code?: string }): Promise<void> => {\n await client.auth.loginWithEmail({ ...data, device_info: data.device_info ?? '' });\n };\n\n const loginWithPhone = async (data: { phone_country_code: string; phone_number: string; password: string; device_info?: string }): Promise<void> => {\n await client.auth.loginWithPhone({ ...data, device_info: data.device_info ?? '' });\n };\n\n const logout = async (): Promise<void> => {\n await client.auth.logoutAll();\n };\n\n const register = async (data: Record<string, unknown>): Promise<void> => {\n await client.auth.register(data as any);\n };\n\n return {\n isAuthenticated: readonly(isAuthenticated),\n loading: readonly(loading),\n accessToken: readonly(accessToken),\n loginWithEmail,\n loginWithPhone,\n logout,\n register,\n };\n}\n\n// ─── useUser ───\n\nexport interface UseUserReturn {\n /** Decoded JWT payload of the current access token, or null. */\n user: DeepReadonly<Ref<DecodedTenxyteToken | null>>;\n /** Whether the initial state is still loading. */\n loading: DeepReadonly<Ref<boolean>>;\n /** Fetch the full user profile from the backend. */\n getProfile: () => ReturnType<TenxyteClient['user']['getProfile']>;\n /** Update the current user's profile. */\n updateProfile: (data: Record<string, unknown>) => Promise<unknown>;\n}\n\n/**\n * Reactive user composable.\n * Returns the decoded JWT user and convenience methods for profile management.\n *\n * @example\n * ```vue\n * <script setup lang=\"ts\">\n * import { useUser } from '@tenxyte/vue';\n * const { user, loading } = useUser();\n * </script>\n *\n * <template>\n * <span v-if=\"!loading && user\">{{ user.email }}</span>\n * </template>\n * ```\n */\nexport function useUser(): UseUserReturn {\n const client = useTenxyteClient();\n const user = ref<DecodedTenxyteToken | null>(null);\n const loading = ref(true);\n\n const refresh = async (): Promise<void> => {\n const state = await client.getState();\n user.value = state.user;\n loading.value = false;\n };\n\n const unsubs: Array<() => void> = [];\n\n onMounted(() => {\n refresh();\n unsubs.push(\n client.on('token:stored', () => { refresh(); }),\n client.on('token:refreshed', () => { refresh(); }),\n client.on('session:expired', () => { refresh(); }),\n );\n });\n\n onUnmounted(() => {\n unsubs.forEach((fn) => fn());\n });\n\n const getProfile = () => client.user.getProfile();\n const updateProfile = (data: Record<string, unknown>) => client.user.updateProfile(data);\n\n return {\n user: readonly(user) as DeepReadonly<Ref<DecodedTenxyteToken | null>>,\n loading: readonly(loading),\n getProfile,\n updateProfile,\n };\n}\n\n// ─── useOrganization ───\n\nexport interface UseOrganizationReturn {\n /** Currently active organization slug, or null. */\n activeOrg: DeepReadonly<Ref<string | null>>;\n /** Switch the SDK to operate within an organization context. */\n switchOrganization: (slug: string) => void;\n /** Clear the organization context. */\n clearOrganization: () => void;\n}\n\n/**\n * Reactive organization context composable.\n *\n * @example\n * ```vue\n * <script setup lang=\"ts\">\n * import { useOrganization } from '@tenxyte/vue';\n * const { activeOrg, switchOrganization, clearOrganization } = useOrganization();\n * </script>\n * ```\n */\nexport function useOrganization(): UseOrganizationReturn {\n const client = useTenxyteClient();\n const activeOrg = ref<string | null>(null);\n\n const refresh = async (): Promise<void> => {\n const state = await client.getState();\n activeOrg.value = state.activeOrg;\n };\n\n onMounted(() => { refresh(); });\n\n const switchOrganization = (slug: string): void => {\n client.b2b.switchOrganization(slug);\n activeOrg.value = slug;\n };\n\n const clearOrganization = (): void => {\n client.b2b.clearOrganization();\n activeOrg.value = null;\n };\n\n return {\n activeOrg: readonly(activeOrg),\n switchOrganization,\n clearOrganization,\n };\n}\n\n// ─── useRbac ───\n\nexport interface UseRbacReturn {\n /** Check if the current user has a specific role (synchronous JWT check). */\n hasRole: (role: string) => boolean;\n /** Check if the current user has a specific permission (synchronous JWT check). */\n hasPermission: (permission: string) => boolean;\n /** Check if the current user has any of the given roles. */\n hasAnyRole: (roles: string[]) => boolean;\n /** Check if the current user has all of the given roles. */\n hasAllRoles: (roles: string[]) => boolean;\n}\n\n/**\n * Reactive RBAC composable.\n * Provides synchronous role/permission checks based on the current JWT.\n *\n * @example\n * ```vue\n * <script setup lang=\"ts\">\n * import { useRbac } from '@tenxyte/vue';\n * const { hasRole } = useRbac();\n * </script>\n *\n * <template>\n * <AdminPanel v-if=\"hasRole('admin')\" />\n * <p v-else>Access denied</p>\n * </template>\n * ```\n */\nexport function useRbac(): UseRbacReturn {\n const client = useTenxyteClient();\n const token = ref<string | null>(null);\n\n const refresh = async (): Promise<void> => {\n token.value = await client.getAccessToken();\n };\n\n const unsubs: Array<() => void> = [];\n\n onMounted(() => {\n refresh();\n unsubs.push(\n client.on('token:stored', () => { refresh(); }),\n client.on('token:refreshed', () => { refresh(); }),\n client.on('session:expired', () => { refresh(); }),\n );\n });\n\n onUnmounted(() => {\n unsubs.forEach((fn) => fn());\n });\n\n const hasRole = (role: string): boolean =>\n client.rbac.hasRole(role, token.value ?? undefined);\n\n const hasPermission = (permission: string): boolean =>\n client.rbac.hasPermission(permission, token.value ?? undefined);\n\n const hasAnyRole = (roles: string[]): boolean =>\n client.rbac.hasAnyRole(roles, token.value ?? undefined);\n\n const hasAllRoles = (roles: string[]): boolean =>\n client.rbac.hasAllRoles(roles, token.value ?? undefined);\n\n return { hasRole, hasPermission, hasAnyRole, hasAllRoles };\n}\n"],"mappings":";AAAA,SAAS,cAA2C;AAM7C,IAAM,cAA2C,uBAAO,SAAS;AAiBjE,IAAM,gBAAgB;AAAA,EACzB,QAAQ,KAAU,QAA6B;AAC3C,QAAI,QAAQ,aAAa,M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@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tenxyte/vue",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Vue bindings for the Tenxyte SDK",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -22,7 +22,8 @@
22
22
  ],
23
23
  "sideEffects": false,
24
24
  "publishConfig": {
25
- "access": "public"
25
+ "access": "public",
26
+ "provenance": true
26
27
  },
27
28
  "scripts": {
28
29
  "build": "tsup",
@@ -42,7 +43,7 @@
42
43
  "license": "MIT",
43
44
  "type": "module",
44
45
  "peerDependencies": {
45
- "@tenxyte/core": "^0.9.2",
46
+ "@tenxyte/core": "^0.9.3",
46
47
  "vue": "^3.3.0"
47
48
  },
48
49
  "devDependencies": {