@witchcraft/nuxt-auth 0.4.1 → 0.5.1

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.
Files changed (37) hide show
  1. package/dist/module.d.mts +9 -4
  2. package/dist/module.json +2 -2
  3. package/dist/module.mjs +1 -1
  4. package/dist/runtime/components/ExternalCallback.d.vue.ts +2 -6
  5. package/dist/runtime/components/ExternalCallback.vue +2 -37
  6. package/dist/runtime/components/ExternalCallback.vue.d.ts +2 -6
  7. package/dist/runtime/components/ExternalCode.vue +3 -20
  8. package/dist/runtime/components/LoginProviderButtons.client.d.vue.ts +17 -14
  9. package/dist/runtime/components/LoginProviderButtons.client.vue +26 -56
  10. package/dist/runtime/components/LoginProviderButtons.client.vue.d.ts +17 -14
  11. package/dist/runtime/components/Mocker.vue +2 -18
  12. package/dist/runtime/components/UserRegistration.d.vue.ts +15 -39
  13. package/dist/runtime/components/UserRegistration.vue +40 -144
  14. package/dist/runtime/components/UserRegistration.vue.d.ts +15 -39
  15. package/dist/runtime/composables/useAuthExternalCallback.d.ts +17 -0
  16. package/dist/runtime/composables/useAuthExternalCallback.js +47 -0
  17. package/dist/runtime/composables/useAuthExternalCode.d.ts +5 -0
  18. package/dist/runtime/composables/useAuthExternalCode.js +29 -0
  19. package/dist/runtime/composables/useAuthMocker.d.ts +7 -0
  20. package/dist/runtime/composables/useAuthMocker.js +33 -0
  21. package/dist/runtime/composables/useAuthUserRegistration.d.ts +43 -0
  22. package/dist/runtime/composables/useAuthUserRegistration.js +84 -0
  23. package/dist/runtime/core/providers/github.d.ts +1 -6
  24. package/dist/runtime/core/providers/github.js +1 -6
  25. package/dist/runtime/core/providers/google.d.ts +1 -6
  26. package/dist/runtime/core/providers/google.js +1 -6
  27. package/dist/runtime/server/helpers/signJwt.d.ts +1 -3
  28. package/dist/runtime/server/utils/Auth.d.ts +5 -4
  29. package/dist/runtime/server/utils/Auth.js +21 -6
  30. package/dist/runtime/server/utils/SessionManager.d.ts +3 -3
  31. package/dist/runtime/server/utils/SessionManager.js +6 -5
  32. package/dist/runtime/server/utils/createAuthHandler.d.ts +2 -2
  33. package/dist/runtime/server/utils/createAuthMiddleware.js +2 -2
  34. package/dist/runtime/types.d.ts +1 -7
  35. package/dist/runtime/utils/getAuthApiRoute.d.ts +6 -3
  36. package/dist/types.d.mts +3 -2
  37. package/package.json +7 -4
package/dist/module.d.mts CHANGED
@@ -143,7 +143,7 @@ interface ModuleOptions {
143
143
  /**
144
144
  * Note the route is NOT defined by the module, you must extend the routes and define it yourself if you are using the UserRegistration component which makes use of it.
145
145
  *
146
- * @default "/api/auth/public/users/:username/valid"
146
+ * @default "/api/auth/users/username/valid"
147
147
  */
148
148
  usernameValid: string;
149
149
  }> & Partial<AdditionalApiRoutes>;
@@ -157,9 +157,14 @@ interface ModulePublicRuntimeConfig {
157
157
  isSecure: boolean;
158
158
  };
159
159
  }
160
+ interface ModulePrivateRuntimeConfig extends Secrets {
161
+ authSecret: string;
162
+ }
163
+ interface ModuleRuntimeConfig extends ModulePrivateRuntimeConfig {
164
+ public: ModulePublicRuntimeConfig;
165
+ }
160
166
  declare module "@nuxt/schema" {
161
- interface RuntimeConfig extends Secrets {
162
- authSecret: string;
167
+ interface RuntimeConfig extends ModulePrivateRuntimeConfig {
163
168
  }
164
169
  interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {
165
170
  }
@@ -167,4 +172,4 @@ declare module "@nuxt/schema" {
167
172
  declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
168
173
 
169
174
  export { _default as default };
170
- export type { ModuleOptions, ModulePublicRuntimeConfig };
175
+ export type { ModuleOptions, ModulePrivateRuntimeConfig, ModulePublicRuntimeConfig, ModuleRuntimeConfig };
package/dist/module.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "auth",
3
3
  "configKey": "auth",
4
- "version": "0.4.1",
4
+ "version": "0.5.1",
5
5
  "builder": {
6
- "@nuxt/module-builder": "1.0.2",
6
+ "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "unknown"
8
8
  }
9
9
  }
package/dist/module.mjs CHANGED
@@ -44,7 +44,7 @@ const module$1 = defineNuxtModule({
44
44
  login: "/login/:provider",
45
45
  callback: "/callback/:provider",
46
46
  register: "/register",
47
- usernameValid: "/public/users/:username/valid"
47
+ usernameValid: "/users/username/valid"
48
48
  },
49
49
  onlySaveUnregisteredUserAccountInfo: false,
50
50
  additionalMiddlewarePaths: {}
@@ -1,8 +1,4 @@
1
- type __VLS_Props = {
2
- saveSession: (accessToken: string) => Promise<void>;
3
- successPath?: string;
4
- cancelPath?: string;
5
- };
6
- declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
1
+ import type { ExternalCallbackOptions } from "../composables/useAuthExternalCallback.js";
2
+ declare const __VLS_export: import("vue").DefineComponent<ExternalCallbackOptions, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<ExternalCallbackOptions> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
7
3
  declare const _default: typeof __VLS_export;
8
4
  export default _default;
@@ -55,46 +55,11 @@
55
55
  </template>
56
56
 
57
57
  <script setup>
58
- import z from "zod";
59
- import { useRuntimeConfig } from "#app";
60
- import {
61
- navigateTo,
62
- ref,
63
- useRoute
64
- } from "#imports";
65
- import { zExternalCallbackPageQuery } from "../types.js";
58
+ import { useAuthExternalCallback } from "../composables/useAuthExternalCallback.js";
66
59
  const props = defineProps({
67
60
  saveSession: { type: Function, required: true },
68
61
  successPath: { type: String, required: false },
69
62
  cancelPath: { type: String, required: false }
70
63
  });
71
- const rc = useRuntimeConfig();
72
- const query = useRoute().query;
73
- const parsedQuery = zExternalCallbackPageQuery.safeParse(query);
74
- if (parsedQuery.error) throw new Error(z.prettifyError(parsedQuery.error));
75
- const initialAccessToken = "accessToken" in parsedQuery.data ? parsedQuery.data.accessToken : void 0;
76
- const authUri = "authUri" in parsedQuery.data ? parsedQuery.data.authUri : void 0;
77
- if (initialAccessToken) {
78
- void authorize(initialAccessToken, true);
79
- }
80
- const manualAccessToken = ref("");
81
- const error = ref();
82
- async function authorize(accessToken, initial = false) {
83
- if (!accessToken || accessToken.length === 0) {
84
- if (!initial) {
85
- error.value = "No code provided.";
86
- }
87
- return;
88
- }
89
- const res = await props.saveSession(accessToken).catch((err) => {
90
- error.value = err.message;
91
- return err;
92
- });
93
- if (!(res instanceof Error)) {
94
- await navigateTo(props.successPath ?? rc.public.auth.authRoutes.postRegisteredLogin);
95
- }
96
- }
97
- async function cancel() {
98
- await navigateTo(props.cancelPath ?? rc.public.auth.authRoutes.login);
99
- }
64
+ const { authUri, initialAccessToken, manualAccessToken, error, authorize, cancel } = useAuthExternalCallback(props);
100
65
  </script>
@@ -1,8 +1,4 @@
1
- type __VLS_Props = {
2
- saveSession: (accessToken: string) => Promise<void>;
3
- successPath?: string;
4
- cancelPath?: string;
5
- };
6
- declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
1
+ import type { ExternalCallbackOptions } from "../composables/useAuthExternalCallback.js";
2
+ declare const __VLS_export: import("vue").DefineComponent<ExternalCallbackOptions, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<ExternalCallbackOptions> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
7
3
  declare const _default: typeof __VLS_export;
8
4
  export default _default;
@@ -39,7 +39,7 @@
39
39
  hover:text-accent-500
40
40
  break-all
41
41
  "
42
- @click="copy(accessToken)"
42
+ @click="copyToken"
43
43
  >
44
44
  {{ accessToken }}
45
45
  </WButton>
@@ -47,28 +47,11 @@
47
47
  </template>
48
48
 
49
49
  <script setup>
50
- import { unreachable } from "@alanscodelog/utils/unreachable";
51
- import { copy } from "@witchcraft/ui/helpers/copy";
52
- import {
53
- navigateTo,
54
- onMounted,
55
- useRoute
56
- } from "#imports";
57
- import { zUriComponentCodec } from "../types.js";
58
- const query = useRoute().query;
59
- const accessToken = query.accessToken;
60
- if (typeof accessToken !== "string") {
61
- unreachable("No session_token.");
62
- }
63
- const deepLinkUrl = zUriComponentCodec.parse(query.deeplinkUri);
50
+ import { useAuthExternalCode } from "../composables/useAuthExternalCode.js";
51
+ const { accessToken, deepLinkUrl, copyToken } = useAuthExternalCode();
64
52
  defineProps({
65
53
  openAppText: { type: String, required: false, default: "Open App and Authorize" },
66
54
  promptText: { type: String, required: false, default: "If you are not prompted to open the app, try clicking below or copy this token into the app:" },
67
55
  copyTitle: { type: String, required: false, default: "Click to Copy" }
68
56
  });
69
- onMounted(() => {
70
- if (accessToken) {
71
- void navigateTo(deepLinkUrl, { external: true });
72
- }
73
- });
74
57
  </script>
@@ -1,27 +1,30 @@
1
1
  import { useAuth } from "../composables/useAuth.js";
2
2
  import type { ProviderNames, ProviderStyle, UseAuthComposableOptions } from "../types.js";
3
- type __VLS_Props = {
3
+ /**
4
+ * @deprecated This component is deprecated and will be removed in a future version.
5
+ */
6
+ declare const _default: typeof __VLS_export;
7
+ export default _default;
8
+ declare const __VLS_export: __VLS_WithSlots<import("vue").DefineComponent<{
4
9
  providerStyles?: Record<ProviderNames, Partial<ProviderStyle>>;
5
10
  useAuthOptions?: UseAuthComposableOptions;
6
11
  loginOptions?: Parameters<ReturnType<typeof useAuth>["login"]>[1];
7
- };
8
- declare var __VLS_20: {
9
- class: string;
10
- iconClass: string;
11
- };
12
- type __VLS_Slots = {} & {
13
- extra?: (props: typeof __VLS_20) => any;
14
- };
15
- declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {
12
+ }, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{
13
+ providerStyles?: Record<ProviderNames, Partial<ProviderStyle>>;
14
+ useAuthOptions?: UseAuthComposableOptions;
15
+ loginOptions?: Parameters<ReturnType<typeof useAuth>["login"]>[1];
16
+ }> & Readonly<{}>, {
16
17
  providerStyles: Record<ProviderNames, Partial<ProviderStyle>>;
17
18
  useAuthOptions: UseAuthComposableOptions;
18
19
  loginOptions: {
19
20
  devBypass?: boolean;
20
21
  };
21
- }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
22
- declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
23
- declare const _default: typeof __VLS_export;
24
- export default _default;
22
+ }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>, {
23
+ extra?: (props: {
24
+ class: string;
25
+ iconClass: string;
26
+ }) => any;
27
+ }>;
25
28
  type __VLS_WithSlots<T, S> = T & {
26
29
  new (): {
27
30
  $slots: S;
@@ -1,75 +1,45 @@
1
1
  <template>
2
- <div
3
- :class="twMerge(`
4
- flex-1
5
- flex
6
- flex-col
7
- items-stretch
8
- justify-center
9
- gap-2
10
- `, $attrs?.class)"
2
+ <WAuth
3
+ :class="$attrs?.class"
4
+ :providers="enabledProviders"
5
+ :provider-styles="providerStyles"
6
+ @login="onLogin"
11
7
  >
12
- <template
13
- v-for="provider in enabledProviders"
14
- :key="provider"
15
- >
16
- <!-- custom id is because useId is causing hydration mismtaches :/
17
- I think because of the for loop -->
18
- <WButton
19
- v-if="provider"
20
- :id="'login-provider-' + provider"
21
- type="button"
22
- class="text-l p-2 px-4 [&_label]:justify-start [&_label]:gap-4"
23
- :style="styles[provider]"
24
- :key="provider"
25
- @click="login(provider, loginOptions)"
26
- >
27
- <WIcon
28
- v-if="styles[provider]?.logo"
29
- class="text-xl"
30
- >
31
- <component
32
- :is="styles[provider]?.logo"
33
- />
34
- </WIcon>
35
- <div>
36
- Sign in / Register with {{ styles[provider]?.name ?? provider }}
37
- </div>
38
- </WButton>
8
+ <template #extra="slotProps">
9
+ <slot
10
+ name="extra"
11
+ v-bind="slotProps"
12
+ />
39
13
  </template>
40
- <slot
41
- name="extra"
42
- icon-class="text-xl"
43
- class="text-l p-2 px-4 [&_label]:justify-start [&_label]:gap-4"
44
- />
45
- </div>
14
+ </WAuth>
46
15
  </template>
47
16
 
17
+ <script>
18
+ export default {};
19
+ </script>
20
+
48
21
  <script setup>
49
- import { useInjectedDarkMode } from "@witchcraft/ui/composables/useInjectedDarkMode";
50
- import { twMerge } from "@witchcraft/ui/utils/twMerge";
51
- import defu from "defu";
22
+ import WAuth from "@witchcraft/ui/components/WAuth";
52
23
  import { useRuntimeConfig } from "#app";
53
- import { computed, useAttrs } from "#imports";
24
+ import { useAttrs } from "#imports";
54
25
  import { useAuth } from "../composables/useAuth.js";
55
- import { providerStyles as baseProviderStyles } from "../core/providerStyles.js";
26
+ if (import.meta.dev) {
27
+ console.warn("[nuxt-auth] <LoginProviderButtons> is deprecated and will be removed in a future version.");
28
+ }
29
+ defineOptions({
30
+ inheritAttrs: false
31
+ });
56
32
  const rc = useRuntimeConfig();
57
33
  const config = rc.public.auth;
58
34
  const enabledProviders = config.enabledProviders;
59
35
  const $attrs = useAttrs();
60
- const { darkMode: isDark } = useInjectedDarkMode();
61
36
  const props = defineProps({
62
37
  providerStyles: { type: Object, required: false, default: () => ({}) },
63
38
  useAuthOptions: { type: Object, required: false, default: () => ({}) },
64
39
  loginOptions: { type: null, required: false, default: () => ({}) }
65
40
  });
66
41
  const { login } = useAuth(props.useAuthOptions);
67
- const fullProviderStyles = computed(() => defu(props.providerStyles, baseProviderStyles));
68
- const styles = computed(() => Object.fromEntries(Object.entries(fullProviderStyles.value).map(([key, value]) => [key, {
69
- ...value,
70
- style: value?.style ? {
71
- backgroundColor: (isDark.value ? value.style.bgDark : value.style.bg) ?? "",
72
- color: (isDark.value ? value.style.textDark : value.style.text) ?? ""
73
- } : {}
74
- }])));
42
+ function onLogin(provider) {
43
+ login(provider, props.loginOptions);
44
+ }
75
45
  </script>
@@ -1,27 +1,30 @@
1
1
  import { useAuth } from "../composables/useAuth.js";
2
2
  import type { ProviderNames, ProviderStyle, UseAuthComposableOptions } from "../types.js";
3
- type __VLS_Props = {
3
+ /**
4
+ * @deprecated This component is deprecated and will be removed in a future version.
5
+ */
6
+ declare const _default: typeof __VLS_export;
7
+ export default _default;
8
+ declare const __VLS_export: __VLS_WithSlots<import("vue").DefineComponent<{
4
9
  providerStyles?: Record<ProviderNames, Partial<ProviderStyle>>;
5
10
  useAuthOptions?: UseAuthComposableOptions;
6
11
  loginOptions?: Parameters<ReturnType<typeof useAuth>["login"]>[1];
7
- };
8
- declare var __VLS_20: {
9
- class: string;
10
- iconClass: string;
11
- };
12
- type __VLS_Slots = {} & {
13
- extra?: (props: typeof __VLS_20) => any;
14
- };
15
- declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {
12
+ }, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{
13
+ providerStyles?: Record<ProviderNames, Partial<ProviderStyle>>;
14
+ useAuthOptions?: UseAuthComposableOptions;
15
+ loginOptions?: Parameters<ReturnType<typeof useAuth>["login"]>[1];
16
+ }> & Readonly<{}>, {
16
17
  providerStyles: Record<ProviderNames, Partial<ProviderStyle>>;
17
18
  useAuthOptions: UseAuthComposableOptions;
18
19
  loginOptions: {
19
20
  devBypass?: boolean;
20
21
  };
21
- }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
22
- declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
23
- declare const _default: typeof __VLS_export;
24
- export default _default;
22
+ }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>, {
23
+ extra?: (props: {
24
+ class: string;
25
+ iconClass: string;
26
+ }) => any;
27
+ }>;
25
28
  type __VLS_WithSlots<T, S> = T & {
26
29
  new (): {
27
30
  $slots: S;
@@ -18,22 +18,6 @@
18
18
  </template>
19
19
 
20
20
  <script setup>
21
- import { navigateTo, useRoute } from "#app";
22
- import { ref, useRuntimeConfig } from "#imports";
23
- import { getAuthApiRoute } from "../utils/getAuthApiRoute.js";
24
- const username = ref("");
25
- const bypassRegistration = ref(false);
26
- const provider = useRoute().query.provider;
27
- if (!provider || typeof provider !== "string") throw new Error("Missing provider query param.");
28
- async function submit() {
29
- const query = useRoute().query;
30
- delete query.provider;
31
- const route = getAuthApiRoute(useRuntimeConfig().public, "callback", { provider }, {
32
- devBypass: true,
33
- username: username.value,
34
- devBypassRegistration: bypassRegistration.value,
35
- ...query
36
- });
37
- await navigateTo(route, { external: true });
38
- }
21
+ import { useAuthMocker } from "../composables/useAuthMocker.js";
22
+ const { provider, username, bypassRegistration, submit } = useAuthMocker();
39
23
  </script>
@@ -1,44 +1,20 @@
1
- import z from "zod";
2
- import { type Ref } from "#imports";
3
- type __VLS_Props = {
4
- debounce?: number;
5
- /** Can throw to indicate the username is invalid (before a request to properly check it is even made. The default throws if the default username schema isn't met. */
6
- getValidUsernameRoute?: (username: string) => string;
7
- onSubmitRegistration?: (event: Event, username: string, error: Ref<string>, redirectUrl: string, deeplink?: string) => void;
8
- id?: string;
9
- /**
10
- * When a validator is provided, if it errors, the server is not queried so as to avoid invalid queries. Any errors it produces are also shown.
11
- *
12
- * @default defaultZodUsernameSchema
13
- */
14
- usernameSchema?: z.ZodType<string, any, any>;
15
- };
16
- declare var __VLS_12: {}, __VLS_19: {}, __VLS_26: {}, __VLS_33: {}, __VLS_41: {
17
- error: import("nuxt/app").NuxtError<unknown> | undefined;
18
- registrationError: string;
19
- localUsernameError: string | undefined;
20
- id: string;
21
- };
22
- type __VLS_Slots = {} & {
23
- 'username-icon-loading'?: (props: typeof __VLS_12) => any;
24
- } & {
25
- 'username-icon-valid'?: (props: typeof __VLS_19) => any;
26
- } & {
27
- 'username-icon-invalid'?: (props: typeof __VLS_26) => any;
28
- } & {
29
- default?: (props: typeof __VLS_33) => any;
30
- } & {
31
- error?: (props: typeof __VLS_41) => any;
32
- };
33
- declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {
34
- debounce: number;
35
- getValidUsernameRoute: (username: string) => string;
36
- onSubmitRegistration: (event: Event, username: string, error: Ref<string>, redirectUrl: string, deeplink?: string) => void;
37
- usernameSchema: z.ZodType<string, any, any>;
38
- }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
39
- declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ /**
3
+ * @deprecated This component is deprecated and will be removed in a future version.
4
+ */
40
5
  declare const _default: typeof __VLS_export;
41
6
  export default _default;
7
+ declare const __VLS_export: __VLS_WithSlots<import("vue").DefineComponent<{
8
+ debounce?: number;
9
+ usernameSchema?: StandardSchemaV1<string, string>;
10
+ id?: string;
11
+ }, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{
12
+ debounce?: number;
13
+ usernameSchema?: StandardSchemaV1<string, string>;
14
+ id?: string;
15
+ }> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>, {
16
+ default?: (props: {}) => any;
17
+ }>;
42
18
  type __VLS_WithSlots<T, S> = T & {
43
19
  new (): {
44
20
  $slots: S;
@@ -19,166 +19,62 @@
19
19
  >
20
20
  Username
21
21
  </label>
22
- <div>
23
- <div class="input-wrapper relative flex">
24
- <WSimpleInput
25
- :id="usernameId"
26
- :aria-busy="isLoading"
27
- :aria-describedby="`${usernameId}-error`"
28
- name="username"
29
- class="w-0 pr-[calc(1rem+var(--spacing)*2)]"
30
- :valid="!anyError && (username === '' || isValidUsername)"
31
- :aria-invalid="!!anyError || !isValidUsername && username !== ''"
32
- v-model="username"
33
- />
34
- <div
35
- class="absolute top-0 bottom-0 pr-1 right-0"
36
- aria-live="polite"
37
- >
38
- <WIcon class="w-[1rem] pointer-events-none mt-px">
39
- <slot
40
- v-if="isLoading"
41
- name="username-icon-loading"
42
- >
43
- <IconSpinner
44
- class="animate-spin text-neutral-500"
45
- />
46
- <span class="sr-only">Checking availability...</span>
47
- </slot>
48
- <slot
49
- v-else-if="isValidUsername"
50
- name="username-icon-valid"
51
- >
52
- <IconCheck
53
- class="text-green-500 scale-110"
54
- />
55
- <span class="sr-only">Username available.</span>
56
- </slot>
57
- <slot
58
- v-else-if="anyError || !isValidUsername && username !== ''"
59
- name="username-icon-invalid"
60
- >
61
- <IconInvalid
62
- class="text-red-500"
63
- />
64
- <span class="sr-only">Username unavailable.</span>
65
- </slot>
66
- </WIcon>
67
- </div>
68
- </div>
69
- </div>
22
+ <WAsyncValidatedInput
23
+ :id="usernameId"
24
+ :errors="isDebouncing || username === '' ? [] : errors"
25
+ :status="status"
26
+ :status-text="statusText"
27
+ :can-submit="canSubmit"
28
+ :input-valid="isDebouncing || inputValid"
29
+ v-model="username"
30
+ />
70
31
  </div>
71
32
  <slot/>
72
33
  <WButton
73
34
  :id="submitId"
74
- :disabled="!!error || isLoading || username === '' || !isValidUsername"
35
+ :disabled="!canSubmit"
75
36
  class="w-full"
76
37
  type="submit"
77
38
  >
78
39
  Register
79
40
  </WButton>
80
- <slot
81
- v-if="anyError"
82
- name="error"
83
- v-bind="{ error, registrationError, localUsernameError, id: `${usernameId}-error` }"
84
- >
85
- <div
86
- :id="`${usernameId}-error`"
87
- class="
88
- border
89
- border-red-500
90
- rounded-md
91
- p-2
92
- text-red-500
93
- bg-red-100
94
- dark:bg-red-950/50
95
- whitespace-pre-wrap
96
- break-all
97
- "
98
- >
99
- {{ localUsernameError || registrationError || error }}
100
- </div>
101
- </slot>
102
41
  </form>
103
42
  </template>
104
43
 
44
+ <script>
45
+ export default {};
46
+ </script>
47
+
105
48
  <script setup>
106
- import { refDebounced } from "@vueuse/core";
107
- import z from "zod";
108
- import { navigateTo, useAsyncData, useRuntimeConfig } from "#app";
109
- import { computed, ref, useId, useRoute } from "#imports";
110
- import IconCheck from "~icons/lucide/check";
111
- import IconSpinner from "~icons/lucide/loader-circle";
112
- import IconInvalid from "~icons/lucide/x";
113
- import { useAuth } from "../composables/useAuth.js";
114
- import { AUTH_ERROR, defaultZodUsernameSchema } from "../types.js";
115
- import { getAuthApiRoute } from "../utils/getAuthApiRoute.js";
116
- const query = useRoute().query;
117
- const submitId = useId();
49
+ import { WAsyncValidatedInput } from "@witchcraft/ui/components";
50
+ import { useId } from "#imports";
51
+ import { useAuthUserRegistration } from "../composables/useAuthUserRegistration.js";
52
+ if (import.meta.dev) {
53
+ console.warn("[nuxt-auth] <UserRegistration> is deprecated and will be removed in a future version.");
54
+ }
118
55
  const props = defineProps({
119
- debounce: { type: Number, required: false, default: 1e3 },
120
- getValidUsernameRoute: { type: Function, required: false, default: (username2) => {
121
- const res = defaultZodUsernameSchema.safeParse(username2);
122
- if (!res.success) throw new Error(res.error.format()._errors.join("\n"));
123
- return getAuthApiRoute(useRuntimeConfig().public, "usernameValid", { username: username2 });
124
- } },
125
- onSubmitRegistration: { type: Function, required: false, default: async (_event, username2, error2, redirectUrl, deeplink2) => {
126
- const res = await $fetch(`${getAuthApiRoute(useRuntimeConfig().public, "register")}${deeplink2 ? `?deeplink=${deeplink2}` : ""}`, {
127
- cache: "no-store",
128
- method: "post",
129
- body: {
130
- username: username2
131
- }
132
- }).catch(async (e) => {
133
- error2.value = `Registration Error: ${e.data.message}`;
134
- if (e?.data?.code === AUTH_ERROR.USER_ALREADY_REGISTERED) {
135
- useAuth().setFetchUserOnNavigation(true);
136
- await navigateTo(redirectUrl, { external: true });
137
- }
138
- });
139
- if (typeof res === "object" && res.redirectUrl) {
140
- await navigateTo(res.redirectUrl, { external: true });
141
- }
142
- } },
143
- id: { type: String, required: false },
144
- usernameSchema: { type: null, required: false, default: defaultZodUsernameSchema }
56
+ debounce: { type: Number, required: false },
57
+ usernameSchema: { type: Object, required: false },
58
+ id: { type: String, required: false }
145
59
  });
146
60
  const usernameId = props.id ?? useId();
147
- const username = ref("");
148
- const debouncedUsername = refDebounced(username, props.debounce);
149
- const registrationError = ref("");
150
- const localUsernameError = computed(() => {
151
- const res = props.usernameSchema.safeParse(username.value);
152
- if (res.success) return void 0;
153
- return z.prettifyError(res.error).replaceAll("\u2716", "\u274C");
154
- });
155
- const { data: isValidUsername, status, error } = await useAsyncData(
156
- "auth:username:valid",
157
- async () => {
158
- if (localUsernameError.value) return false;
159
- return $fetch(props.getValidUsernameRoute(debouncedUsername.value));
160
- },
161
- {
162
- watch: [localUsernameError, debouncedUsername],
163
- immediate: false,
164
- default: () => false
61
+ const submitId = useId();
62
+ const {
63
+ username,
64
+ errors,
65
+ status,
66
+ statusText,
67
+ canSubmit,
68
+ handleSubmit,
69
+ inputValid,
70
+ isDebouncing
71
+ } = useAuthUserRegistration({
72
+ debounce: props.debounce,
73
+ usernameSchema: props.usernameSchema,
74
+ statusTextMap: {
75
+ loading: "Checking availability...",
76
+ valid: "Username available.",
77
+ invalid: "Username unavailable."
165
78
  }
166
- );
167
- const isLoading = computed(() => {
168
- if (localUsernameError.value) return false;
169
- return username.value !== "" && (status.value === "pending" || username.value !== debouncedUsername.value);
170
79
  });
171
- const anyError = computed(() => localUsernameError.value || error.value || registrationError.value);
172
- const deeplink = typeof query.deeplink === "string" ? query.deeplink : void 0;
173
- const redirect = deeplink ? useRuntimeConfig().public.auth.authRoutes.externalCode : useRuntimeConfig().public.auth.authRoutes.register;
174
- if (!redirect) throw new Error("No externalCode or register route defined.");
175
- function handleSubmit(event) {
176
- props.onSubmitRegistration(
177
- event,
178
- username.value,
179
- registrationError,
180
- redirect,
181
- deeplink
182
- );
183
- }
184
80
  </script>