diff --git a/packages/account/package.json b/packages/account/package.json index ac85bafc778..c26c253c682 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -7,6 +7,7 @@ "license": "MIT", "type": "module", "exports": { + "./boundedOperation": "./src/core/boundedOperation.ts", "./session": "./src/core/session.ts", "./billing": "./src/core/billing/index.ts", "./firebase": "./src/firebase/index.ts", diff --git a/packages/account/src/core/boundedOperation.test.ts b/packages/account/src/core/boundedOperation.test.ts new file mode 100644 index 00000000000..3cb5f209ee4 --- /dev/null +++ b/packages/account/src/core/boundedOperation.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest' + +import { createBoundedOperation } from './boundedOperation.js' + +describe('createBoundedOperation', () => { + it('captures a handle that is live until the operation is abandoned', () => { + const operation = createBoundedOperation() + const handle = operation.capture() + + expect(handle.live()).toBe(true) + operation.abandon() + expect( + handle.live(), + 'a captured attempt must not survive its own abandonment' + ).toBe(false) + }) + + it('invalidates every outstanding handle when abandoned, not only the latest', () => { + const operation = createBoundedOperation() + const first = operation.capture() + const second = operation.capture() + + operation.abandon() + + expect(first.live()).toBe(false) + expect( + second.live(), + 'one abandonment must drop all in-flight attempts, not just the newest' + ).toBe(false) + }) + + it('leaves an earlier handle live when a later capture supersedes nothing', () => { + const operation = createBoundedOperation() + const earlier = operation.capture() + operation.capture() + + expect( + earlier.live(), + 'capture alone is not invalidation; only abandon ends prior attempts' + ).toBe(true) + }) + + it('keeps each prior cycle dead while the latest capture stays live', () => { + const operation = createBoundedOperation() + + const first = operation.capture() + operation.abandon() + const second = operation.capture() + + expect(first.live()).toBe(false) + expect(second.live()).toBe(true) + + operation.abandon() + const third = operation.capture() + + expect( + second.live(), + 'each abandonment must end its own cycle, not only the first' + ).toBe(false) + expect(third.live()).toBe(true) + }) + + it('discards a result that resolves after the operation was abandoned mid-flight', async () => { + const operation = createBoundedOperation() + const handle = operation.capture() + + const pendingRead = (async () => { + await Promise.resolve() + return handle.live() + })() + operation.abandon() + + expect( + await pendingRead, + 'work re-checked across an await must not publish once superseded' + ).toBe(false) + }) +}) diff --git a/packages/account/src/core/boundedOperation.ts b/packages/account/src/core/boundedOperation.ts new file mode 100644 index 00000000000..d5a8cb1f04e --- /dev/null +++ b/packages/account/src/core/boundedOperation.ts @@ -0,0 +1,29 @@ +/** + * A monotonic owner for work that outlives an await: each `capture()` snapshots + * the current generation and returns a handle whose `live()` stays true until + * `abandon()` bumps the generation. A flag flip, a reset, or teardown calls + * `abandon()`; the in-flight work re-checks `live()` after every await and drops + * its result once superseded, so a stale sign-in, mint, or fetch can never + * publish for an attempt that no longer owns the outcome. + */ +export interface OperationHandle { + live: () => boolean +} + +export interface BoundedOperation { + capture: () => OperationHandle + abandon: () => void +} + +export function createBoundedOperation(): BoundedOperation { + let generation = 0 + return { + capture() { + const captured = generation + return { live: () => captured === generation } + }, + abandon() { + generation += 1 + } + } +} diff --git a/packages/account/src/vue/index.ts b/packages/account/src/vue/index.ts index 083397f91be..f8ede68354c 100644 --- a/packages/account/src/vue/index.ts +++ b/packages/account/src/vue/index.ts @@ -2,6 +2,9 @@ export type { PasswordRulesCopy } from './PasswordRules.vue' export { default as PasswordRules } from './PasswordRules.vue' export { default as SocialAuthButtons } from './SocialAuthButtons.vue' export { default as TurnstileWidget } from './TurnstileWidget.vue' +export { createLifecycleScope } from './lifecycleScope' +export type { LifecycleScope } from './lifecycleScope' export type { RegionGateStatus } from './regionGate' export { useRegionGate } from './regionGate' export { useTurnstileGate } from './turnstileGate' +export { useGenerationGuard } from './useGenerationGuard' diff --git a/packages/account/src/vue/lifecycleScope.test.ts b/packages/account/src/vue/lifecycleScope.test.ts new file mode 100644 index 00000000000..1f249240bdb --- /dev/null +++ b/packages/account/src/vue/lifecycleScope.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it, vi } from 'vitest' +import { onScopeDispose, ref, watch } from 'vue' + +import { createLifecycleScope } from './lifecycleScope' + +describe('createLifecycleScope', () => { + it('runs the setup once and ignores a second start while running', () => { + const lifecycle = createLifecycleScope() + const setup = vi.fn() + + lifecycle.start(setup) + lifecycle.start(setup) + + expect( + setup, + 'a module singleton must install its listeners once, not per caller' + ).toHaveBeenCalledOnce() + }) + + it('disposes the running scope so its watchers stop', () => { + const lifecycle = createLifecycleScope() + const source = ref(0) + const seen: number[] = [] + lifecycle.start(() => { + watch(source, (value) => seen.push(value), { flush: 'sync' }) + }) + + source.value = 1 + lifecycle.stop() + source.value = 2 + + expect( + seen, + 'a disposed scope must not keep reacting to its sources' + ).toEqual([1]) + }) + + it('restarts after an explicit stop', () => { + const lifecycle = createLifecycleScope() + const setup = vi.fn() + + lifecycle.start(setup) + lifecycle.stop() + lifecycle.start(setup) + + expect( + setup, + 'stop reopens the latch, so a later start must run setup again' + ).toHaveBeenCalledTimes(2) + }) + + it('reopens the latch when setup throws synchronously', () => { + const lifecycle = createLifecycleScope() + const good = vi.fn() + + expect(() => + lifecycle.start(() => { + throw new Error('install failed') + }) + ).toThrow('install failed') + lifecycle.start(good) + + expect( + good, + 'a synchronous install failure disposes its scope and reopens the latch, so the next start still installs' + ).toHaveBeenCalledOnce() + }) + + it('fires scope-disposal hooks registered by the setup on stop', () => { + const lifecycle = createLifecycleScope() + const disposed = vi.fn() + lifecycle.start(() => { + onScopeDispose(disposed) + }) + + lifecycle.stop() + + expect(disposed).toHaveBeenCalledOnce() + }) +}) diff --git a/packages/account/src/vue/lifecycleScope.ts b/packages/account/src/vue/lifecycleScope.ts new file mode 100644 index 00000000000..3de82344477 --- /dev/null +++ b/packages/account/src/vue/lifecycleScope.ts @@ -0,0 +1,43 @@ +import { effectScope } from 'vue' +import type { EffectScope } from 'vue' + +/** + * A detached {@link effectScope} for a module singleton that must own its + * watchers' lifetime rather than borrow it from whichever component reaches it + * first. `start` installs the scope once and latches; `stop` disposes it and + * reopens the latch so `start` may be called again. + * + * On the server (`window` undefined) `start` is a no-op that does not latch, so + * the client's first `start` still installs. + * + * `start` is synchronous. A synchronous throw from `setup` disposes the scope, + * reopens the latch, and rethrows, so a failed install leaves no stuck latch or + * leaked effects. Async failures are the setup's own to catch: a `setup` that + * launches a promise catches it and calls `stop` from that handler. + */ +export interface LifecycleScope { + start: (setup: () => void) => void + stop: () => void +} + +export function createLifecycleScope(): LifecycleScope { + let scope: EffectScope | undefined + return { + start(setup) { + if (scope || typeof window === 'undefined') return + const created = effectScope(true) + scope = created + try { + created.run(setup) + } catch (error) { + created.stop() + scope = undefined + throw error + } + }, + stop() { + scope?.stop() + scope = undefined + } + } +} diff --git a/packages/account/src/vue/useGenerationGuard.test.ts b/packages/account/src/vue/useGenerationGuard.test.ts new file mode 100644 index 00000000000..2e06528aaa4 --- /dev/null +++ b/packages/account/src/vue/useGenerationGuard.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { effectScope } from 'vue' + +import { useGenerationGuard } from './useGenerationGuard' + +describe('useGenerationGuard', () => { + it('abandons every outstanding attempt when its owning scope is disposed', () => { + const scope = effectScope() + const guard = scope.run(() => useGenerationGuard())! + const handle = guard.capture() + + expect(handle.live()).toBe(true) + scope.stop() + + expect( + handle.live(), + 'teardown must invalidate in-flight work so a late resolve cannot act' + ).toBe(false) + }) + + it('invalidates a handle when its scope disposes mid-await', async () => { + const scope = effectScope() + const guard = scope.run(() => useGenerationGuard())! + const handle = guard.capture() + + const settled = (async () => { + await Promise.resolve() + return handle.live() + })() + scope.stop() + + expect( + await settled, + 'a continuation resuming after scope teardown must see a dead handle' + ).toBe(false) + }) + + it('still abandons attempts explicitly before teardown', () => { + const scope = effectScope() + const guard = scope.run(() => useGenerationGuard())! + const handle = guard.capture() + + guard.abandon() + + expect(handle.live()).toBe(false) + scope.stop() + }) +}) diff --git a/packages/account/src/vue/useGenerationGuard.ts b/packages/account/src/vue/useGenerationGuard.ts new file mode 100644 index 00000000000..72c1776f948 --- /dev/null +++ b/packages/account/src/vue/useGenerationGuard.ts @@ -0,0 +1,19 @@ +import { onScopeDispose } from 'vue' + +import { createBoundedOperation } from '../core/boundedOperation.js' +import type { BoundedOperation } from '../core/boundedOperation.js' + +/** + * A {@link createBoundedOperation} bound to the current Vue scope: when the + * component or effect scope disposes, every outstanding attempt is abandoned, + * so work resolving after teardown cannot act on an owner that is already gone. + * + * Call it from a component `setup` or an active `effectScope`. With no active + * scope `onScopeDispose` no-ops, so it never auto-abandons; use + * {@link createBoundedOperation} directly at module scope instead. + */ +export function useGenerationGuard(): BoundedOperation { + const operation = createBoundedOperation() + onScopeDispose(operation.abandon) + return operation +}