@molecule/app-auth-modal-svelte 0.0.0-stage → 0.0.1-stage

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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @molecule/app-auth-modal-svelte
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ In-app login / signup modal + click-interceptor + popup OAuth — authenticate and upgrade without ever navigating away or losing work
4
+
5
+ ```
6
+ npm install @molecule/app-auth-modal-svelte
7
+ ```
8
+
9
+ Part of the [Molecule](https://www.molecule.dev) package fleet. This page carries the manifest summary; the full generated documentation ships with the package's first committed version.
10
+
11
+ License: Apache-2.0
@@ -0,0 +1,374 @@
1
+ <!--
2
+ AuthModal: the Svelte counterpart of `@molecule/app-auth-modal-react`'s
3
+ `AuthModal` — in-app login / signup tabs rendered in a Modal overlay, so the
4
+ user authenticates without leaving the page. Same props (React names), same
5
+ ClassMap tokens, same i18n keys, and the same DOM for the same input; the
6
+ auth hooks (`useLogin` / `useSignup` / `useOAuth` / `useAuth`) come from
7
+ `@molecule/app-svelte`, and OAuth runs in a popup so social login never
8
+ navigates the host either.
9
+ -->
10
+ <script lang="ts">
11
+ import { untrack } from 'svelte'
12
+ import { writable } from 'svelte/store'
13
+
14
+ import { useAuthFormState } from '@molecule/app-auth-shell-svelte'
15
+ import { OAuthButtons, OAuthDivider } from '@molecule/app-oauth-buttons-svelte'
16
+ import {
17
+ useAuth,
18
+ useAuthClient,
19
+ useI18nError,
20
+ useLogin,
21
+ useOAuth,
22
+ useSignup,
23
+ useTranslation,
24
+ } from '@molecule/app-svelte'
25
+ import { getClassMap } from '@molecule/app-ui'
26
+ import { Button, Icon, Modal } from '@molecule/app-ui-svelte'
27
+
28
+ import type { AuthModalMode } from './cta-intercept.js'
29
+ import type { AuthModalProps } from './types.js'
30
+ import { reactInputValue } from './value.js'
31
+
32
+ let {
33
+ open,
34
+ onClose,
35
+ initialMode = 'signup',
36
+ oauthConfig,
37
+ onBeforeAuth,
38
+ onAuthenticated,
39
+ captchaSlot,
40
+ captchaSolved = true,
41
+ }: AuthModalProps = $props()
42
+
43
+ const cm = $derived(getClassMap())
44
+ const { t } = useTranslation()
45
+
46
+ /**
47
+ * Matches phones (narrow viewport) OR touch-first devices (coarse primary
48
+ * pointer) — the contexts where a sub-16px input font makes iOS Safari zoom
49
+ * the whole page on focus. SSR-safe (`false` until mounted) and subscribes
50
+ * to media-query changes, like React's local hook.
51
+ */
52
+ let isTouchFirst = $state(false)
53
+ $effect(() => {
54
+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return
55
+ const mql = window.matchMedia('(max-width: 767px), (pointer: coarse)')
56
+ const onChange = (e: MediaQueryListEvent): void => {
57
+ isTouchFirst = e.matches
58
+ }
59
+ isTouchFirst = mql.matches
60
+ mql.addEventListener('change', onChange)
61
+ return () => {
62
+ mql.removeEventListener('change', onChange)
63
+ }
64
+ })
65
+
66
+ // React's `useState(initialMode)`: read once, then owned by the component.
67
+ let mode = $state<AuthModalMode>(untrack(() => initialMode))
68
+ const { refresh } = useAuth()
69
+ const authClient = useAuthClient()
70
+ const { status: loginStatus, error: loginError, login } = useLogin()
71
+ const { status: signupStatus, error: signupError, signup } = useSignup()
72
+ const { fields, setField, clear } = useAuthFormState()
73
+ let password = $state('')
74
+ let name = $state('')
75
+ let twoFactorToken = $state('')
76
+ let oauthError = $state<string | null>(null)
77
+ // Post-auth confirmation ("Signed up!" / "Logged in!") shown briefly before
78
+ // the modal closes — without it the modal just vanished, which read as
79
+ // "nothing happened".
80
+ let succeeded = $state(false)
81
+ // The email input element, for the dialog focus pattern below.
82
+ let emailEl = $state<HTMLInputElement | null>(null)
83
+
84
+ const isSignup = $derived(mode === 'signup')
85
+ const busy = $derived((isSignup ? $signupStatus : $loginStatus) === 'pending')
86
+ const email = $derived($fields.email ?? '')
87
+ // Universal post-auth state: every label below reads a `$derived`, so a
88
+ // locale switch re-runs it the way React's render-time `t` call does.
89
+ const signupTitle = $derived(
90
+ t('auth.modal.signupTitle', undefined, { defaultValue: 'Create your account' }),
91
+ )
92
+ const loginTitle = $derived(t('auth.modal.loginTitle', undefined, { defaultValue: 'Log in' }))
93
+ const signupBlurb = $derived(
94
+ t('auth.modal.signupBlurb', undefined, { defaultValue: 'Sign up to keep your work.' }),
95
+ )
96
+ const loginBlurb = $derived(
97
+ t('auth.modal.loginBlurb', undefined, { defaultValue: 'Log in to keep your work.' }),
98
+ )
99
+ const namePlaceholder = $derived(
100
+ t('auth.signup.name', undefined, { defaultValue: 'Name (optional)' }),
101
+ )
102
+ const emailPlaceholder = $derived(t('auth.login.email', undefined, { defaultValue: 'Email' }))
103
+ const passwordPlaceholder = $derived(
104
+ t('auth.login.password', undefined, { defaultValue: 'Password' }),
105
+ )
106
+ const twoFactorPlaceholder = $derived(
107
+ t('auth.login.twoFactor', undefined, { defaultValue: 'Two-Factor Token (If enabled)' }),
108
+ )
109
+ const workingLabel = $derived(
110
+ t('auth.modal.working', undefined, { defaultValue: 'Just a moment…' }),
111
+ )
112
+ const signUpLabel = $derived(t('auth.login.signUp', undefined, { defaultValue: 'Sign up' }))
113
+ const logInLabel = $derived(t('auth.login.logIn', undefined, { defaultValue: 'Log in' }))
114
+ const signedUpLabel = $derived(
115
+ t('auth.modal.signedUp', undefined, { defaultValue: 'Signed up!' }),
116
+ )
117
+ const loggedInLabel = $derived(
118
+ t('auth.modal.loggedIn', undefined, { defaultValue: 'Logged in!' }),
119
+ )
120
+ const loggedInAs = $derived(
121
+ t(
122
+ 'auth.modal.loggedInAs',
123
+ { who: whoJustAuthenticated() },
124
+ { defaultValue: 'Logged in as {{who}}' },
125
+ ),
126
+ )
127
+ const haveAccountLabel = $derived(
128
+ t('auth.modal.haveAccount', undefined, { defaultValue: 'Already have an account? Log in' }),
129
+ )
130
+ const needAccountLabel = $derived(
131
+ t('auth.modal.needAccount', undefined, { defaultValue: "Don't have an account? Sign up" }),
132
+ )
133
+
134
+ // The i18n-translated error text (React's `useI18nError`). `MaybeReadable`
135
+ // takes a store: this one mirrors whichever hook error the current mode
136
+ // shows, re-pushed by the effect when the mode or the errors change.
137
+ const selectedError = writable<Error | null | undefined>(null)
138
+ $effect(() => {
139
+ selectedError.set(isSignup ? $signupError : $loginError)
140
+ })
141
+ const i18nError = useI18nError(selectedError)
142
+ const errorMessage = $derived($i18nError)
143
+
144
+ /**
145
+ * Who just authenticated — shown under the headline so the confirmation
146
+ * names the account, not just the outcome (React reads the client in the
147
+ * success render; the success view is the only place this is shown).
148
+ * @returns The profile display name, or ''.
149
+ */
150
+ function whoJustAuthenticated(): string {
151
+ const profile = authClient.getUser() as {
152
+ name?: string | null
153
+ email?: string | null
154
+ username?: string | null
155
+ } | null
156
+ return profile?.name || profile?.email || profile?.username || ''
157
+ }
158
+
159
+ // Dialog pattern (WAI-ARIA): when the modal opens, keyboard and
160
+ // screen-reader users land on the form's primary field instead of on the
161
+ // page behind the overlay. This replaces the `autofocus` attribute, which
162
+ // jsx-a11y/no-autofocus bars: the attribute fires on EVERY mount of the
163
+ // input (e.g. the brief remount after the mode switches), while this effect
164
+ // runs exactly once per open transition — after the Modal child's own
165
+ // focus-trap effect (Svelte runs child effects first, like React), so the
166
+ // email field wins in both signup and login mode.
167
+ $effect(() => {
168
+ if (open) emailEl?.focus()
169
+ })
170
+
171
+ // Universal post-auth: refresh the session (guards + plan current), show a
172
+ // brief confirmation, run the app's hook, then close — all in place, no
173
+ // navigation.
174
+ /**
175
+ * Universal post-auth: refreshes the session, shows the brief confirmation,
176
+ * runs the app's `onAuthenticated` hook, then closes — all in place.
177
+ */
178
+ async function finishAuth(): Promise<void> {
179
+ try {
180
+ await refresh()
181
+ } catch (error) {
182
+ // Every path into finishAuth (password login/signup response, OAuth popup
183
+ // relay) has already established the session client-side, so the refresh
184
+ // is a freshness pass — a failure here (e.g. an API with neither a
185
+ // refresh endpoint nor cookie restore) must NOT strand an authenticated
186
+ // user in the modal with their account already created. Only a genuinely
187
+ // absent session is a real failure.
188
+ if (!authClient.isAuthenticated()) throw error
189
+ }
190
+ succeeded = true
191
+ // Hold the confirmation on screen while the app hook runs; whichever
192
+ // finishes last gates the close.
193
+ const minDisplay = new Promise((resolve) => setTimeout(resolve, 1000))
194
+ await onAuthenticated?.()
195
+ await minDisplay
196
+ onClose?.()
197
+ }
198
+
199
+ // OAuth (popup): success/error land back on THIS page; wire them into the
200
+ // hook. `MaybeReadable` takes a plain value or a store — a store of the
201
+ // composed config is what reaches the hook live (React re-creates the
202
+ // config object every render): the effect below re-pushes it whenever the
203
+ // `oauthConfig` prop changes. The result is read off the object —
204
+ // `providers` is a live getter there.
205
+ const handleOauthSuccess = (): void => {
206
+ // Surface a finishAuth failure (no session established) in the modal
207
+ // instead of dying as an unhandled rejection.
208
+ finishAuth().catch((error: unknown) => {
209
+ oauthError = error instanceof Error ? error.message : String(error)
210
+ })
211
+ }
212
+ const handleOauthError = (message: string): void => {
213
+ oauthError = message
214
+ }
215
+ // The initial capture is intentional: this seed makes the first render show
216
+ // the prop's provider list, and the effect below re-pushes the composed
217
+ // config whenever the prop changes afterwards.
218
+ // svelte-ignore state_referenced_locally
219
+ const composedOauthConfig = writable({
220
+ ...oauthConfig,
221
+ onSuccess: handleOauthSuccess,
222
+ onError: handleOauthError,
223
+ })
224
+ $effect(() => {
225
+ composedOauthConfig.set({
226
+ ...oauthConfig,
227
+ onSuccess: handleOauthSuccess,
228
+ onError: handleOauthError,
229
+ })
230
+ })
231
+ const oauth = useOAuth(composedOauthConfig)
232
+
233
+ /**
234
+ * The form's submit: runs `onBeforeAuth`, signs in / signs up through the
235
+ * hooks, clears the shared email and finishes in place.
236
+ *
237
+ * @param event - The submit event.
238
+ */
239
+ async function handleSubmit(event: SubmitEvent): Promise<void> {
240
+ event.preventDefault()
241
+ onBeforeAuth?.()
242
+ try {
243
+ if (isSignup) await signup({ email: $fields.email ?? '', password, name: name || undefined })
244
+ else await login({ email: $fields.email ?? '', password })
245
+ clear()
246
+ await finishAuth()
247
+ } catch (_error) {
248
+ // Auth errors are captured in the hook's error state and shown below; we
249
+ // deliberately do NOT navigate or reload on failure or success.
250
+ }
251
+ }
252
+
253
+ /** The shared input inline style, sized for the current viewport class. */
254
+ const fieldStyle = $derived(
255
+ `width: 100%; padding: 10px 12px; border-radius: 6px; border: 1px solid var(--mol-color-border, rgba(127,127,127,0.3)); background: var(--mol-color-surface-secondary, rgba(127,127,127,0.06)); color: inherit; outline: none; font-size: ${isTouchFirst ? '16px' : '14px'}`,
256
+ )
257
+ </script>
258
+
259
+ <Modal
260
+ {open}
261
+ onClose={() => onClose?.()}
262
+ size="sm"
263
+ title={isSignup ? signupTitle : loginTitle}
264
+ data-mol-id="auth-modal"
265
+ >
266
+ <div data-mol-id="auth-modal-body" style="display: flex; flex-direction: column">
267
+ {#if succeeded}
268
+ <div
269
+ data-mol-id="auth-modal-success"
270
+ style="display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 26px 0px 18px; text-align: center"
271
+ >
272
+ <Icon name="check-circle" size={44} className={cm.textSuccess} aria-hidden="true" />
273
+ <div style="font-size: 17px; font-weight: 600">
274
+ {isSignup ? signedUpLabel : loggedInLabel}
275
+ </div>
276
+ {#if whoJustAuthenticated() !== ''}
277
+ <div class={cm.textMuted} style="font-size: 13px">{loggedInAs}</div>
278
+ {/if}
279
+ </div>
280
+ {:else}
281
+ <div class={cm.textMuted} style="margin-bottom: 12px; font-size: 13px; line-height: 1.45">
282
+ {isSignup ? signupBlurb : loginBlurb}
283
+ </div>
284
+ <form style="display: grid; gap: 10px" onsubmit={(e) => void handleSubmit(e)}>
285
+ {#if isSignup}
286
+ <input
287
+ type="text"
288
+ use:reactInputValue={{ value: name }}
289
+ oninput={(e) => (name = e.currentTarget.value)}
290
+ autocomplete="name"
291
+ data-mol-id="auth-modal-name"
292
+ placeholder={namePlaceholder}
293
+ style={fieldStyle}
294
+ />
295
+ {/if}
296
+ <input
297
+ type="email"
298
+ use:reactInputValue={{ value: email }}
299
+ oninput={(e) => setField('email', e.currentTarget.value)}
300
+ autocomplete="email"
301
+ bind:this={emailEl}
302
+ required
303
+ data-mol-id="auth-modal-email"
304
+ placeholder={emailPlaceholder}
305
+ style={fieldStyle}
306
+ />
307
+ <input
308
+ type="password"
309
+ use:reactInputValue={{ value: password }}
310
+ oninput={(e) => (password = e.currentTarget.value)}
311
+ autocomplete={isSignup ? 'new-password' : 'current-password'}
312
+ required
313
+ data-mol-id="auth-modal-password"
314
+ placeholder={passwordPlaceholder}
315
+ style={fieldStyle}
316
+ />
317
+ {#if !isSignup}
318
+ <input
319
+ type="text"
320
+ inputmode="numeric"
321
+ use:reactInputValue={{ value: twoFactorToken }}
322
+ oninput={(e) => (twoFactorToken = e.currentTarget.value)}
323
+ autocomplete="one-time-code"
324
+ data-mol-id="auth-modal-2fa"
325
+ placeholder={twoFactorPlaceholder}
326
+ style={fieldStyle}
327
+ />
328
+ {/if}
329
+ <!-- Human-verification challenge — signup only (login is not gated). -->
330
+ {#if isSignup && captchaSlot}
331
+ <div data-mol-id="auth-modal-captcha" style="display: grid; margin-top: 2px">
332
+ {#if typeof captchaSlot === 'function'}{@render captchaSlot()}{:else}{captchaSlot}{/if}
333
+ </div>
334
+ {/if}
335
+ <Button
336
+ type="submit"
337
+ size="lg"
338
+ color="success"
339
+ disabled={busy || (isSignup && !captchaSolved)}
340
+ data-mol-id="auth-modal-submit"
341
+ style={{ width: '100%', marginTop: '2px' }}
342
+ >
343
+ {busy ? workingLabel : isSignup ? signUpLabel : logInLabel}
344
+ </Button>
345
+ {#if errorMessage || oauthError}
346
+ <div class={cm.authFormError}>{errorMessage || oauthError}</div>
347
+ {/if}
348
+ </form>
349
+ {#if oauth.providers.length > 0}
350
+ <div style="margin-top: 4px">
351
+ <OAuthDivider />
352
+ <!-- Popup OAuth — never navigates the host. -->
353
+ <OAuthButtons
354
+ providers={oauth.providers}
355
+ onSelect={(provider) => {
356
+ oauthError = null
357
+ onBeforeAuth?.()
358
+ oauth.loginViaPopup(provider)
359
+ }}
360
+ />
361
+ </div>
362
+ {/if}
363
+ <button
364
+ type="button"
365
+ data-mol-id="auth-modal-switch"
366
+ onclick={() => (mode = isSignup ? 'login' : 'signup')}
367
+ class={cm.cn(cm.button({ variant: 'ghost', size: 'sm' }))}
368
+ style="margin-top: 12px; align-self: center"
369
+ >
370
+ {isSignup ? haveAccountLabel : needAccountLabel}
371
+ </button>
372
+ {/if}
373
+ </div>
374
+ </Modal>
@@ -0,0 +1,5 @@
1
+ import type { AuthModalProps } from './types.js';
2
+ declare const AuthModal: import("svelte").Component<AuthModalProps, {}, "">;
3
+ type AuthModal = ReturnType<typeof AuthModal>;
4
+ export default AuthModal;
5
+ //# sourceMappingURL=AuthModal.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuthModal.svelte.d.ts","sourceRoot":"","sources":["../src/AuthModal.svelte"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AA+ShD,QAAA,MAAM,SAAS,oDAAwC,CAAC;AACxD,KAAK,SAAS,GAAG,UAAU,CAAC,OAAO,SAAS,CAAC,CAAC;AAC9C,eAAe,SAAS,CAAC"}
@@ -0,0 +1,129 @@
1
+ <!--
2
+ AuthModalMount: the Svelte counterpart of
3
+ `@molecule/app-auth-modal-react`'s `AuthModalMount` — one mount that renders
4
+ the (initially hidden) AuthModal and installs a capture-phase document click
5
+ handler opening it for in-app `/login` / `/signup` links (and routing
6
+ `/pricing` / `/billing` clicks to `onUpgradeIntercept`, else a new tab with a
7
+ focus-return session refresh). Same props (React names), same DOM for the
8
+ same input, same navigation calls.
9
+ -->
10
+ <script lang="ts">
11
+ import { useAuth } from '@molecule/app-svelte'
12
+
13
+ import AuthModal from './AuthModal.svelte'
14
+ import {
15
+ type AuthModalMode,
16
+ authModeForHref,
17
+ DEFAULT_AUTH_PATHS,
18
+ DEFAULT_UPGRADE_PATHS,
19
+ upgradePathForHref,
20
+ } from './cta-intercept.js'
21
+ import type { AuthModalMountProps } from './types.js'
22
+
23
+ let {
24
+ oauthConfig,
25
+ onBeforeAuth,
26
+ onAuthenticated,
27
+ onUpgradeReturn,
28
+ onUpgradeIntercept,
29
+ captchaSlot,
30
+ captchaSolved,
31
+ authPaths,
32
+ upgradePaths,
33
+ }: AuthModalMountProps = $props()
34
+
35
+ const { refresh } = useAuth()
36
+ let open = $state(false)
37
+ let mode = $state<AuthModalMode>('signup')
38
+
39
+ /**
40
+ * Opens the modal on the given form (React's `openAuth`).
41
+ *
42
+ * @param next - The form to show.
43
+ */
44
+ function openAuth(next: AuthModalMode): void {
45
+ mode = next
46
+ open = true
47
+ }
48
+
49
+ // Set when the user opens the upgrade/billing flow in a new tab, so we
50
+ // refresh when they return (a completed upgrade reflects with no manual
51
+ // reload).
52
+ let upgradeTabOpened = false
53
+ /**
54
+ * The window focus return: refresh the session and run `onUpgradeReturn`,
55
+ * but only after an upgrade tab was opened here.
56
+ */
57
+ function onFocus(): void {
58
+ if (!upgradeTabOpened) return
59
+ upgradeTabOpened = false
60
+ refresh().catch((_error: unknown) => {
61
+ // Best-effort freshness pass: the user may have returned without a
62
+ // session to refresh (never logged in, or the API has no refresh
63
+ // path) — not an error worth surfacing on a simple tab focus.
64
+ })
65
+ onUpgradeReturn?.()
66
+ }
67
+
68
+ // Intercept clicks on the in-app /login, /signup (→ modal) and /pricing,
69
+ // /billing (→ host's onUpgradeIntercept, else a new tab) CTAs — plain
70
+ // <a href> links from anywhere in the app, incl. ones opened with
71
+ // target="_blank". Capture-phase + preventDefault stops navigation. Plain
72
+ // left-clicks only — a modifier/middle click still opens the real page.
73
+ /**
74
+ * The capture-phase click interceptor (React's document click effect).
75
+ *
76
+ * @param e - The click event.
77
+ */
78
+ function onClick(e: MouseEvent): void {
79
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
80
+ return
81
+ const anchor = (e.target as HTMLElement | null)?.closest('a[href]') as HTMLAnchorElement | null
82
+ if (!anchor) return
83
+ const href = anchor.getAttribute('href')
84
+ const origin = window.location.origin
85
+ const authMode = authModeForHref(href, origin, authPaths ?? DEFAULT_AUTH_PATHS)
86
+ if (authMode) {
87
+ e.preventDefault()
88
+ e.stopPropagation()
89
+ openAuth(authMode)
90
+ return
91
+ }
92
+ const upgradePath = upgradePathForHref(href, origin, upgradePaths ?? DEFAULT_UPGRADE_PATHS)
93
+ if (upgradePath) {
94
+ e.preventDefault()
95
+ e.stopPropagation()
96
+ if (onUpgradeIntercept) {
97
+ onUpgradeIntercept(upgradePath)
98
+ return
99
+ }
100
+ upgradeTabOpened = true
101
+ window.open(upgradePath, '_blank', 'noopener,noreferrer')
102
+ }
103
+ }
104
+
105
+ // The listeners read the current props at call time (React re-subscribes
106
+ // when they change); the effect itself runs once per mount.
107
+ $effect(() => {
108
+ window.addEventListener('focus', onFocus)
109
+ document.addEventListener('click', onClick, true)
110
+ return () => {
111
+ window.removeEventListener('focus', onFocus)
112
+ document.removeEventListener('click', onClick, true)
113
+ }
114
+ })
115
+ </script>
116
+
117
+ <!-- Mounted only while open so the auth hooks don't run on every app render. -->
118
+ {#if open}
119
+ <AuthModal
120
+ {open}
121
+ onClose={() => (open = false)}
122
+ initialMode={mode}
123
+ {oauthConfig}
124
+ {onBeforeAuth}
125
+ {onAuthenticated}
126
+ {captchaSlot}
127
+ {captchaSolved}
128
+ />
129
+ {/if}
@@ -0,0 +1,5 @@
1
+ import type { AuthModalMountProps } from './types.js';
2
+ declare const AuthModalMount: import("svelte").Component<AuthModalMountProps, {}, "">;
3
+ type AuthModalMount = ReturnType<typeof AuthModalMount>;
4
+ export default AuthModalMount;
5
+ //# sourceMappingURL=AuthModalMount.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuthModalMount.svelte.d.ts","sourceRoot":"","sources":["../src/AuthModalMount.svelte"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AA+GtD,QAAA,MAAM,cAAc,yDAAwC,CAAC;AAC7D,KAAK,cAAc,GAAG,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC;AACxD,eAAe,cAAc,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The package's components: one Svelte 5 component per React component in
3
+ * `@molecule/app-auth-modal-react`, under the same React name.
4
+ *
5
+ * @module
6
+ */
7
+ export { default as AuthModal } from './AuthModal.svelte';
8
+ export { default as AuthModalMount } from './AuthModalMount.svelte';
9
+ //# sourceMappingURL=components.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"components.d.ts","sourceRoot":"","sources":["../src/components.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,yBAAyB,CAAA"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The package's components: one Svelte 5 component per React component in
3
+ * `@molecule/app-auth-modal-react`, under the same React name.
4
+ *
5
+ * @module
6
+ */
7
+ export { default as AuthModal } from './AuthModal.svelte';
8
+ export { default as AuthModalMount } from './AuthModalMount.svelte';
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Pure routing decisions for the in-app auth/upgrade click-interceptor.
3
+ *
4
+ * A click on an in-app `/login` or `/signup` link opens the {@link AuthModal}
5
+ * instead of navigating; a click on `/pricing` or `/billing` opens the upgrade
6
+ * flow without navigating the current tab — the host's `onUpgradeIntercept`
7
+ * (e.g. an in-app modal) when provided, else a new tab. These helpers turn a
8
+ * clicked link's href into that decision so the interceptor stays trivial and
9
+ * unit-testable.
10
+ *
11
+ * @module
12
+ */
13
+ /** Which form {@link AuthModal} should show. */
14
+ export type AuthModalMode = 'login' | 'signup';
15
+ /** The default in-app auth routes that open the modal. */
16
+ export declare const DEFAULT_AUTH_PATHS: Readonly<Record<string, AuthModalMode>>;
17
+ /** The default routes that open the upgrade/billing flow (modal or new tab). */
18
+ export declare const DEFAULT_UPGRADE_PATHS: readonly string[];
19
+ /**
20
+ * Map a CTA link's href to the auth mode it should open, or `null` if it is not
21
+ * an auth link (so the interceptor leaves it alone).
22
+ *
23
+ * @param href - The clicked anchor's href (relative or absolute).
24
+ * @param origin - The page origin to resolve a relative href against.
25
+ * @param authPaths - Path→mode map (defaults to {@link DEFAULT_AUTH_PATHS}).
26
+ * @returns `'login'` / `'signup'`, else `null`.
27
+ */
28
+ export declare function authModeForHref(href: string | null | undefined, origin: string, authPaths?: Readonly<Record<string, AuthModalMode>>): AuthModalMode | null;
29
+ /**
30
+ * Whether a CTA link's href points at the upgrade/billing flow (which the
31
+ * interceptor hands to the host's `onUpgradeIntercept`, else opens in a new tab).
32
+ *
33
+ * @param href - The clicked anchor's href (relative or absolute).
34
+ * @param origin - The page origin to resolve a relative href against.
35
+ * @param upgradePaths - The upgrade paths (defaults to {@link DEFAULT_UPGRADE_PATHS}).
36
+ * @returns The matched pathname, else `null`.
37
+ */
38
+ export declare function upgradePathForHref(href: string | null | undefined, origin: string, upgradePaths?: readonly string[]): string | null;
39
+ //# sourceMappingURL=cta-intercept.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cta-intercept.d.ts","sourceRoot":"","sources":["../src/cta-intercept.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,gDAAgD;AAChD,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,QAAQ,CAAA;AAE9C,0DAA0D;AAC1D,eAAO,MAAM,kBAAkB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAGtE,CAAA;AAED,gFAAgF;AAChF,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAA6B,CAAA;AAahF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC/B,MAAM,EAAE,MAAM,EACd,SAAS,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAsB,GACtE,aAAa,GAAG,IAAI,CAGtB;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC/B,MAAM,EAAE,MAAM,EACd,YAAY,GAAE,SAAS,MAAM,EAA0B,GACtD,MAAM,GAAG,IAAI,CAGf"}
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Pure routing decisions for the in-app auth/upgrade click-interceptor.
3
+ *
4
+ * A click on an in-app `/login` or `/signup` link opens the {@link AuthModal}
5
+ * instead of navigating; a click on `/pricing` or `/billing` opens the upgrade
6
+ * flow without navigating the current tab — the host's `onUpgradeIntercept`
7
+ * (e.g. an in-app modal) when provided, else a new tab. These helpers turn a
8
+ * clicked link's href into that decision so the interceptor stays trivial and
9
+ * unit-testable.
10
+ *
11
+ * @module
12
+ */
13
+ /** The default in-app auth routes that open the modal. */
14
+ export const DEFAULT_AUTH_PATHS = {
15
+ '/login': 'login',
16
+ '/signup': 'signup',
17
+ };
18
+ /** The default routes that open the upgrade/billing flow (modal or new tab). */
19
+ export const DEFAULT_UPGRADE_PATHS = ['/pricing', '/billing'];
20
+ /** Resolve an href to its pathname against `origin`, or `null` if malformed. */
21
+ function pathOf(href, origin) {
22
+ if (!href)
23
+ return null;
24
+ try {
25
+ return new URL(href, origin).pathname;
26
+ }
27
+ catch (_error) {
28
+ // A malformed href is not an in-app CTA — leave it alone (intentional noop).
29
+ return null;
30
+ }
31
+ }
32
+ /**
33
+ * Map a CTA link's href to the auth mode it should open, or `null` if it is not
34
+ * an auth link (so the interceptor leaves it alone).
35
+ *
36
+ * @param href - The clicked anchor's href (relative or absolute).
37
+ * @param origin - The page origin to resolve a relative href against.
38
+ * @param authPaths - Path→mode map (defaults to {@link DEFAULT_AUTH_PATHS}).
39
+ * @returns `'login'` / `'signup'`, else `null`.
40
+ */
41
+ export function authModeForHref(href, origin, authPaths = DEFAULT_AUTH_PATHS) {
42
+ const path = pathOf(href, origin);
43
+ return path != null ? (authPaths[path] ?? null) : null;
44
+ }
45
+ /**
46
+ * Whether a CTA link's href points at the upgrade/billing flow (which the
47
+ * interceptor hands to the host's `onUpgradeIntercept`, else opens in a new tab).
48
+ *
49
+ * @param href - The clicked anchor's href (relative or absolute).
50
+ * @param origin - The page origin to resolve a relative href against.
51
+ * @param upgradePaths - The upgrade paths (defaults to {@link DEFAULT_UPGRADE_PATHS}).
52
+ * @returns The matched pathname, else `null`.
53
+ */
54
+ export function upgradePathForHref(href, origin, upgradePaths = DEFAULT_UPGRADE_PATHS) {
55
+ const path = pathOf(href, origin);
56
+ return path != null && upgradePaths.includes(path) ? path : null;
57
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * `@molecule/app-auth-modal-svelte` — the shared in-app login / signup /
3
+ * upgrade flow. Mount {@link AuthModalMount} ONCE inside the app's
4
+ * providers (where the `@molecule/app-svelte` auth hooks work) and every
5
+ * in-app `/login` / `/signup` link opens the {@link AuthModal} instead of
6
+ * navigating, while `/pricing` / `/billing` links open the upgrade flow in
7
+ * a new tab (session auto-refreshes when the user returns) — no
8
+ * navigation, no reload, no lost work. OAuth runs in a popup
9
+ * (`loginViaPopup`), so social login never navigates the host either.
10
+ *
11
+ * @example
12
+ * ```svelte
13
+ * <script lang="ts">
14
+ * import { AuthModalMount } from '@molecule/app-auth-modal-svelte'
15
+ * import { oauthConfig } from './config.js'
16
+ * </script>
17
+ *
18
+ * <!-- Once, inside the app's providers (e.g. in App.svelte): -->
19
+ * <AuthModalMount {oauthConfig} onAuthenticated={() => claimGuestWork()} />
20
+ * <!-- Every plain <a href="/login">, <a href="/signup">, <a href="/pricing">
21
+ * anywhere in the app is now intercepted — no other wiring needed. -->
22
+ * ```
23
+ *
24
+ * @remarks
25
+ * Interception is capture-phase on `document` and matches plain
26
+ * left-clicks on `<a href>` whose resolved pathname is in `authPaths`
27
+ * (default `/login`, `/signup`) or `upgradePaths` (default `/pricing`,
28
+ * `/billing`) — modifier/middle clicks still navigate normally, and
29
+ * non-anchor buttons that call `navigate()` are NOT intercepted. Hosts
30
+ * that render pricing in-place pass `onUpgradeIntercept` and own that UI
31
+ * + the post-upgrade session refresh. `AuthModalMount` must render inside
32
+ * the app's auth/HTTP providers (it calls `useAuth`), and the standalone
33
+ * `/login` & `/signup` pages should stay routed — they are the fallback
34
+ * for modifier clicks and deep links. App-specific extras (stash a guest
35
+ * id, claim guest work, invalidate usage) go in `onBeforeAuth` /
36
+ * `onAuthenticated`. The modal's `auth.modal.*` strings are homed in the
37
+ * `@molecule/app-locales-common` bond (79 languages), alongside the
38
+ * `auth.login.*` / `auth.signup.*` keys the modal also renders.
39
+ *
40
+ * If the signup API requires a human-verification challenge (Turnstile /
41
+ * hCaptcha), pass BOTH `captchaSlot` (the widget, rendered in the signup
42
+ * form, as a snippet or plain text) and `captchaSolved` (which gates the
43
+ * submit). Rendering the widget on the standalone `/signup` page alone is
44
+ * NOT enough: this modal is what a `/signup` link actually opens, so the
45
+ * in-app signup would POST with no token and the API would answer "complete
46
+ * the verification challenge" while no challenge is on screen. Login is not
47
+ * gated, so the slot is unmounted in login mode.
48
+ *
49
+ * @module
50
+ */
51
+ export * from './components.js';
52
+ export * from './cta-intercept.js';
53
+ export * from './types.js';
54
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AAEH,cAAc,iBAAiB,CAAA;AAC/B,cAAc,oBAAoB,CAAA;AAClC,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * `@molecule/app-auth-modal-svelte` — the shared in-app login / signup /
3
+ * upgrade flow. Mount {@link AuthModalMount} ONCE inside the app's
4
+ * providers (where the `@molecule/app-svelte` auth hooks work) and every
5
+ * in-app `/login` / `/signup` link opens the {@link AuthModal} instead of
6
+ * navigating, while `/pricing` / `/billing` links open the upgrade flow in
7
+ * a new tab (session auto-refreshes when the user returns) — no
8
+ * navigation, no reload, no lost work. OAuth runs in a popup
9
+ * (`loginViaPopup`), so social login never navigates the host either.
10
+ *
11
+ * @example
12
+ * ```svelte
13
+ * <script lang="ts">
14
+ * import { AuthModalMount } from '@molecule/app-auth-modal-svelte'
15
+ * import { oauthConfig } from './config.js'
16
+ * </script>
17
+ *
18
+ * <!-- Once, inside the app's providers (e.g. in App.svelte): -->
19
+ * <AuthModalMount {oauthConfig} onAuthenticated={() => claimGuestWork()} />
20
+ * <!-- Every plain <a href="/login">, <a href="/signup">, <a href="/pricing">
21
+ * anywhere in the app is now intercepted — no other wiring needed. -->
22
+ * ```
23
+ *
24
+ * @remarks
25
+ * Interception is capture-phase on `document` and matches plain
26
+ * left-clicks on `<a href>` whose resolved pathname is in `authPaths`
27
+ * (default `/login`, `/signup`) or `upgradePaths` (default `/pricing`,
28
+ * `/billing`) — modifier/middle clicks still navigate normally, and
29
+ * non-anchor buttons that call `navigate()` are NOT intercepted. Hosts
30
+ * that render pricing in-place pass `onUpgradeIntercept` and own that UI
31
+ * + the post-upgrade session refresh. `AuthModalMount` must render inside
32
+ * the app's auth/HTTP providers (it calls `useAuth`), and the standalone
33
+ * `/login` & `/signup` pages should stay routed — they are the fallback
34
+ * for modifier clicks and deep links. App-specific extras (stash a guest
35
+ * id, claim guest work, invalidate usage) go in `onBeforeAuth` /
36
+ * `onAuthenticated`. The modal's `auth.modal.*` strings are homed in the
37
+ * `@molecule/app-locales-common` bond (79 languages), alongside the
38
+ * `auth.login.*` / `auth.signup.*` keys the modal also renders.
39
+ *
40
+ * If the signup API requires a human-verification challenge (Turnstile /
41
+ * hCaptcha), pass BOTH `captchaSlot` (the widget, rendered in the signup
42
+ * form, as a snippet or plain text) and `captchaSolved` (which gates the
43
+ * submit). Rendering the widget on the standalone `/signup` page alone is
44
+ * NOT enough: this modal is what a `/signup` link actually opens, so the
45
+ * in-app signup would POST with no token and the API would answer "complete
46
+ * the verification challenge" while no challenge is on screen. Login is not
47
+ * gated, so the slot is unmounted in login mode.
48
+ *
49
+ * @module
50
+ */
51
+ export * from './components.js';
52
+ export * from './cta-intercept.js';
53
+ export * from './types.js';
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Types for the Svelte in-app auth modal + the one-mount interceptor.
3
+ *
4
+ * @module
5
+ */
6
+ import type { Snippet } from 'svelte';
7
+ import type { UseOAuthConfig } from '@molecule/app-svelte';
8
+ import type { AuthModalMode } from './cta-intercept.js';
9
+ /**
10
+ * A React-node-valued field: a snippet (the conformance kit's node value), or
11
+ * plain text passed verbatim.
12
+ */
13
+ type ReactNodeProp = Snippet | string;
14
+ /** Props accepted by the {@link AuthModal} component. */
15
+ export interface AuthModalProps {
16
+ /** Whether the modal is open. */
17
+ open: boolean;
18
+ /** Close without authenticating (backdrop / Escape / ✕). */
19
+ onClose?: () => void;
20
+ /** Which form to open on. Defaults to `'signup'`. */
21
+ initialMode?: AuthModalMode;
22
+ /**
23
+ * OAuth config consumed by `useOAuth()` — `{ baseURL, oauthProviders, oauthEndpoint }`
24
+ * from the app's `config.ts`. Drives the popup OAuth buttons.
25
+ */
26
+ oauthConfig: UseOAuthConfig;
27
+ /**
28
+ * Run synchronously BEFORE any login/signup/OAuth attempt — e.g. stash the
29
+ * guest id so the new session can claim its work. Optional.
30
+ */
31
+ onBeforeAuth?: () => void;
32
+ /**
33
+ * Run AFTER a successful login/signup/OAuth (the session is already
34
+ * refreshed), still on the same page — e.g. claim guest projects, invalidate
35
+ * usage. Optional.
36
+ */
37
+ onAuthenticated?: () => void | Promise<void>;
38
+ /**
39
+ * A human-verification challenge rendered inside the SIGNUP form, above the
40
+ * submit button (e.g. the app's Turnstile/hCaptcha widget), as a snippet or
41
+ * plain text. Login is not gated, so the slot is unmounted in login mode —
42
+ * which lets the widget clear its own token when the user switches tabs and
43
+ * re-issue a fresh one on the way back.
44
+ *
45
+ * The modal stays provider-agnostic: it renders the node and never inspects
46
+ * it. An app whose signup API requires a challenge MUST pass `captchaSolved`
47
+ * as well, or the form will submit without a token and the API will reject
48
+ * it. Optional — omitted (the default for apps with no challenge) the signup
49
+ * form is unchanged.
50
+ */
51
+ captchaSlot?: ReactNodeProp;
52
+ /**
53
+ * Whether the `captchaSlot` challenge is currently solved. `false` disables
54
+ * the signup submit, so the form cannot POST a missing/expired token.
55
+ * Defaults to `true` (no challenge → nothing to wait for). Ignored in login
56
+ * mode.
57
+ */
58
+ captchaSolved?: boolean;
59
+ }
60
+ /** Props accepted by the {@link AuthModalMount} component. */
61
+ export interface AuthModalMountProps {
62
+ /** OAuth config from the app's `config.ts` (drives the popup OAuth buttons). */
63
+ oauthConfig: AuthModalProps['oauthConfig'];
64
+ /** Run before any login attempt (e.g. stash the guest id). Optional. */
65
+ onBeforeAuth?: () => void;
66
+ /** Run after a successful login (session already refreshed). Optional. */
67
+ onAuthenticated?: () => void | Promise<void>;
68
+ /**
69
+ * Run when the user returns to this tab after the upgrade tab (the session
70
+ * is already refreshed here) — e.g. invalidate usage so a budget banner
71
+ * clears. Only fires for the default new-tab flow; irrelevant when
72
+ * `onUpgradeIntercept` is set. Optional.
73
+ */
74
+ onUpgradeReturn?: () => void;
75
+ /**
76
+ * Take over upgrade/billing CTA clicks instead of opening a new tab: called
77
+ * with the matched upgrade path (e.g. `/pricing`), navigation already
78
+ * prevented. The host renders its own upgrade UI (typically a modal) and
79
+ * owns refreshing the session when that flow completes. Optional — when
80
+ * omitted, the default new-tab flow (+ focus-return refresh) applies.
81
+ */
82
+ onUpgradeIntercept?: (path: string) => void;
83
+ /**
84
+ * Human-verification challenge rendered inside the modal's SIGNUP form — see
85
+ * `AuthModalProps.captchaSlot`. Pass it together with `captchaSolved`
86
+ * whenever the app's signup API requires a challenge token, otherwise the
87
+ * in-app signup POSTs without one while the standalone `/signup` page (which
88
+ * renders its own widget) works — a mismatch the user experiences as
89
+ * "complete the challenge" with no challenge on screen. Optional.
90
+ */
91
+ captchaSlot?: AuthModalProps['captchaSlot'];
92
+ /** Whether `captchaSlot` is solved; `false` disables the signup submit. Defaults to `true`. */
93
+ captchaSolved?: boolean;
94
+ /** Override the auth path→mode map (defaults to `/login`,`/signup`). */
95
+ authPaths?: Readonly<Record<string, AuthModalMode>>;
96
+ /** Override the upgrade paths opened in a new tab (defaults to `/pricing`,`/billing`). */
97
+ upgradePaths?: readonly string[];
98
+ }
99
+ export {};
100
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAA;AAErC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAE1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAEvD;;;GAGG;AACH,KAAK,aAAa,GAAG,OAAO,GAAG,MAAM,CAAA;AAErC,yDAAyD;AACzD,MAAM,WAAW,cAAc;IAC7B,iCAAiC;IACjC,IAAI,EAAE,OAAO,CAAA;IACb,4DAA4D;IAC5D,OAAO,CAAC,EAAE,MAAM,IAAI,CAAA;IACpB,qDAAqD;IACrD,WAAW,CAAC,EAAE,aAAa,CAAA;IAC3B;;;OAGG;IACH,WAAW,EAAE,cAAc,CAAA;IAC3B;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,IAAI,CAAA;IACzB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5C;;;;;;;;;;;;OAYG;IACH,WAAW,CAAC,EAAE,aAAa,CAAA;IAC3B;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,8DAA8D;AAC9D,MAAM,WAAW,mBAAmB;IAClC,gFAAgF;IAChF,WAAW,EAAE,cAAc,CAAC,aAAa,CAAC,CAAA;IAC1C,wEAAwE;IACxE,YAAY,CAAC,EAAE,MAAM,IAAI,CAAA;IACzB,0EAA0E;IAC1E,eAAe,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5C;;;;;OAKG;IACH,eAAe,CAAC,EAAE,MAAM,IAAI,CAAA;IAC5B;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;IAC3C;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,cAAc,CAAC,aAAa,CAAC,CAAA;IAC3C,+FAA+F;IAC/F,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,wEAAwE;IACxE,SAAS,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAA;IACnD,0FAA0F;IAC1F,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CACjC"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Types for the Svelte in-app auth modal + the one-mount interceptor.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Svelte action reproducing react-dom's controlled-input `value` handling.
3
+ *
4
+ * Svelte's `value={x}` sets only the `value` property, while a React input
5
+ * carries BOTH the property and the `value` attribute (react-dom applies the
6
+ * value through the `defaultValue` property, whose reflection IS that
7
+ * attribute). The other framework ports get this for free, and
8
+ * `@molecule/app-ui-svelte` ships the same logic for its own `Input`
9
+ * (`reactInputValue` in its `src/dom.ts`, not exported) — the same copy
10
+ * `@molecule/app-amount-input-svelte` and `@molecule/app-copy-link-field-svelte`
11
+ * carry. This action applies React's documented behavior: the property, then
12
+ * the attribute, on mount and on every value change.
13
+ *
14
+ * @module
15
+ */
16
+ /**
17
+ * Applies `props.value` to the input the way react-dom applies a controlled
18
+ * `value`: through the `value` property (the live value) and the `value`
19
+ * attribute, so both reads of the field agree.
20
+ *
21
+ * @param node - The input element.
22
+ * @param props - The controlled value, as React's `<input value>` takes it.
23
+ * @returns The action's update, re-applying on a changed value.
24
+ */
25
+ export declare function reactInputValue(node: HTMLInputElement, props: {
26
+ value?: unknown;
27
+ }): {
28
+ update: (next: {
29
+ value?: unknown;
30
+ }) => void;
31
+ };
32
+ //# sourceMappingURL=value.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value.d.ts","sourceRoot":"","sources":["../src/value.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,gBAAgB,EACtB,KAAK,EAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,GACzB;IAAE,MAAM,EAAE,CAAC,IAAI,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAA;CAAE,CASjD"}
package/dist/value.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Svelte action reproducing react-dom's controlled-input `value` handling.
3
+ *
4
+ * Svelte's `value={x}` sets only the `value` property, while a React input
5
+ * carries BOTH the property and the `value` attribute (react-dom applies the
6
+ * value through the `defaultValue` property, whose reflection IS that
7
+ * attribute). The other framework ports get this for free, and
8
+ * `@molecule/app-ui-svelte` ships the same logic for its own `Input`
9
+ * (`reactInputValue` in its `src/dom.ts`, not exported) — the same copy
10
+ * `@molecule/app-amount-input-svelte` and `@molecule/app-copy-link-field-svelte`
11
+ * carry. This action applies React's documented behavior: the property, then
12
+ * the attribute, on mount and on every value change.
13
+ *
14
+ * @module
15
+ */
16
+ /**
17
+ * Applies `props.value` to the input the way react-dom applies a controlled
18
+ * `value`: through the `value` property (the live value) and the `value`
19
+ * attribute, so both reads of the field agree.
20
+ *
21
+ * @param node - The input element.
22
+ * @param props - The controlled value, as React's `<input value>` takes it.
23
+ * @returns The action's update, re-applying on a changed value.
24
+ */
25
+ export function reactInputValue(node, props) {
26
+ const apply = (next) => {
27
+ const { value } = next;
28
+ const text = value === undefined || value === null ? '' : String(value);
29
+ if (node.value !== text)
30
+ node.value = text;
31
+ if (node.getAttribute('value') !== text)
32
+ node.setAttribute('value', text);
33
+ };
34
+ apply(props);
35
+ return { update: apply };
36
+ }
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "@molecule/app-auth-modal-svelte",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1-stage",
4
+ "description": "In-app login / signup modal + click-interceptor + popup OAuth — authenticate and upgrade without ever navigating away or losing work",
5
+ "homepage": "https://www.molecule.dev/packages/app-auth-modal-svelte",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "svelte": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "svelte": "./dist/index.js",
18
+ "files": [
19
+ "dist",
20
+ "!dist/**/__tests__",
21
+ "!dist/**/*.test.*",
22
+ "!dist/**/*.spec.*",
23
+ "README.md"
24
+ ],
25
+ "scripts": {
26
+ "build": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings && svelte-package --input src --output dist --tsconfig ./tsconfig.json",
27
+ "dev": "svelte-package --input src --output dist --tsconfig ./tsconfig.json --watch",
28
+ "test": "vitest run",
29
+ "test:watch": "vitest"
30
+ },
31
+ "keywords": [
32
+ "molecule",
33
+ "auth",
34
+ "login",
35
+ "signup",
36
+ "modal",
37
+ "oauth",
38
+ "svelte"
39
+ ],
40
+ "author": "Molecule Dev, Inc. (https://molecule.dev)",
41
+ "license": "Apache-2.0",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/molecule-dev/molecule.git",
45
+ "directory": "packages/app/features/auth-modal-svelte"
46
+ },
47
+ "engines": {
48
+ "node": ">=20"
49
+ },
50
+ "bugs": "https://github.com/molecule-dev/molecule/issues",
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "peerDependencies": {
55
+ "@molecule/app-auth-shell-svelte": "^1.0.0",
56
+ "@molecule/app-i18n": "^1.0.1",
57
+ "@molecule/app-oauth-buttons-svelte": "^1.0.0",
58
+ "@molecule/app-svelte": "^3.5.0",
59
+ "@molecule/app-ui": "^1.0.1",
60
+ "@molecule/app-ui-svelte": "^1.1.0",
61
+ "svelte": "^5.0.0"
62
+ },
63
+ "devDependencies": {
64
+ "@molecule/app-auth-shell-svelte": "1.0.0",
65
+ "@molecule/app-framework-conformance": "0.0.0",
66
+ "@molecule/app-i18n": "1.2.2",
67
+ "@molecule/app-icons": "1.0.4",
68
+ "@molecule/app-oauth-buttons-svelte": "1.2.0",
69
+ "@molecule/app-svelte": "3.7.2",
70
+ "@molecule/app-ui": "1.4.0",
71
+ "@molecule/app-ui-svelte": "1.1.7",
72
+ "@sveltejs/package": "3.0.2",
73
+ "@sveltejs/vite-plugin-svelte": "7.1.2",
74
+ "@types/node": "26.6.5",
75
+ "jsdom": "30.1.3",
76
+ "svelte": "5.57.2",
77
+ "svelte-check": "4.7.7",
78
+ "typescript": "6.0.3",
79
+ "vite": "8.3.5",
80
+ "vitest": "4.1.12"
81
+ }
82
+ }