@molecule/app-svelte 3.3.0 → 3.5.0

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 (164) hide show
  1. package/README.md +2393 -220
  2. package/dist/agent-identity.js +0 -1
  3. package/dist/context.d.ts +101 -1
  4. package/dist/context.d.ts.map +1 -1
  5. package/dist/context.js +199 -3
  6. package/dist/hooks/external-store.d.ts +28 -0
  7. package/dist/hooks/external-store.d.ts.map +1 -0
  8. package/dist/hooks/external-store.js +95 -0
  9. package/dist/hooks/index.d.ts +37 -0
  10. package/dist/hooks/index.d.ts.map +1 -0
  11. package/dist/hooks/index.js +36 -0
  12. package/dist/hooks/live-store.d.ts +68 -0
  13. package/dist/hooks/live-store.d.ts.map +1 -0
  14. package/dist/hooks/live-store.js +76 -0
  15. package/dist/hooks/useAIModels.d.ts +58 -0
  16. package/dist/hooks/useAIModels.d.ts.map +1 -0
  17. package/dist/hooks/useAIModels.js +155 -0
  18. package/dist/hooks/useAsyncState.d.ts +52 -0
  19. package/dist/hooks/useAsyncState.d.ts.map +1 -0
  20. package/dist/hooks/useAsyncState.js +80 -0
  21. package/dist/hooks/useAuth.d.ts +99 -0
  22. package/dist/hooks/useAuth.d.ts.map +1 -0
  23. package/dist/hooks/useAuth.js +88 -0
  24. package/dist/hooks/useCapacitorApp.d.ts +51 -0
  25. package/dist/hooks/useCapacitorApp.d.ts.map +1 -0
  26. package/dist/hooks/useCapacitorApp.js +57 -0
  27. package/dist/hooks/useChangePassword.d.ts +41 -0
  28. package/dist/hooks/useChangePassword.d.ts.map +1 -0
  29. package/dist/hooks/useChangePassword.js +40 -0
  30. package/dist/hooks/useDevice.d.ts +48 -0
  31. package/dist/hooks/useDevice.d.ts.map +1 -0
  32. package/dist/hooks/useDevice.js +37 -0
  33. package/dist/hooks/useEditor.d.ts +65 -0
  34. package/dist/hooks/useEditor.d.ts.map +1 -0
  35. package/dist/hooks/useEditor.js +86 -0
  36. package/dist/hooks/useForm.d.ts +137 -0
  37. package/dist/hooks/useForm.d.ts.map +1 -0
  38. package/dist/hooks/useForm.js +221 -0
  39. package/dist/hooks/useHttp.d.ts +122 -0
  40. package/dist/hooks/useHttp.d.ts.map +1 -0
  41. package/dist/hooks/useHttp.js +220 -0
  42. package/dist/hooks/useLogger.d.ts +52 -0
  43. package/dist/hooks/useLogger.d.ts.map +1 -0
  44. package/dist/hooks/useLogger.js +64 -0
  45. package/dist/hooks/useLogin.d.ts +47 -0
  46. package/dist/hooks/useLogin.d.ts.map +1 -0
  47. package/dist/hooks/useLogin.js +44 -0
  48. package/dist/hooks/useOAuth.d.ts +96 -0
  49. package/dist/hooks/useOAuth.d.ts.map +1 -0
  50. package/dist/hooks/useOAuth.js +363 -0
  51. package/dist/hooks/useOptimisticValue.d.ts +58 -0
  52. package/dist/hooks/useOptimisticValue.d.ts.map +1 -0
  53. package/dist/hooks/useOptimisticValue.js +98 -0
  54. package/dist/hooks/usePasswordReset.d.ts +50 -0
  55. package/dist/hooks/usePasswordReset.d.ts.map +1 -0
  56. package/dist/hooks/usePasswordReset.js +50 -0
  57. package/dist/hooks/usePlatform.d.ts +45 -0
  58. package/dist/hooks/usePlatform.d.ts.map +1 -0
  59. package/dist/hooks/usePlatform.js +35 -0
  60. package/dist/hooks/usePreview.d.ts +54 -0
  61. package/dist/hooks/usePreview.d.ts.map +1 -0
  62. package/dist/hooks/usePreview.js +61 -0
  63. package/dist/hooks/useProfileForm.d.ts +100 -0
  64. package/dist/hooks/useProfileForm.d.ts.map +1 -0
  65. package/dist/hooks/useProfileForm.js +267 -0
  66. package/dist/hooks/usePromise.d.ts +62 -0
  67. package/dist/hooks/usePromise.d.ts.map +1 -0
  68. package/dist/hooks/usePromise.js +105 -0
  69. package/dist/hooks/usePush.d.ts +68 -0
  70. package/dist/hooks/usePush.d.ts.map +1 -0
  71. package/dist/hooks/usePush.js +79 -0
  72. package/dist/hooks/useRouter.d.ts +169 -0
  73. package/dist/hooks/useRouter.d.ts.map +1 -0
  74. package/dist/hooks/useRouter.js +212 -0
  75. package/dist/hooks/useSignup.d.ts +52 -0
  76. package/dist/hooks/useSignup.d.ts.map +1 -0
  77. package/dist/hooks/useSignup.js +42 -0
  78. package/dist/hooks/useStorage.d.ts +133 -0
  79. package/dist/hooks/useStorage.d.ts.map +1 -0
  80. package/dist/hooks/useStorage.js +228 -0
  81. package/dist/hooks/useStore.d.ts +69 -0
  82. package/dist/hooks/useStore.d.ts.map +1 -0
  83. package/dist/hooks/useStore.js +82 -0
  84. package/dist/hooks/useTheme.d.ts +55 -0
  85. package/dist/hooks/useTheme.d.ts.map +1 -0
  86. package/dist/hooks/useTheme.js +102 -0
  87. package/dist/hooks/useTranslation.d.ts +106 -0
  88. package/dist/hooks/useTranslation.d.ts.map +1 -0
  89. package/dist/hooks/useTranslation.js +159 -0
  90. package/dist/hooks/useVerifyPaymentReturn.d.ts +91 -0
  91. package/dist/hooks/useVerifyPaymentReturn.d.ts.map +1 -0
  92. package/dist/hooks/useVerifyPaymentReturn.js +189 -0
  93. package/dist/hooks/useVersion.d.ts +53 -0
  94. package/dist/hooks/useVersion.d.ts.map +1 -0
  95. package/dist/hooks/useVersion.js +70 -0
  96. package/dist/hooks/useWorkspace.d.ts +47 -0
  97. package/dist/hooks/useWorkspace.d.ts.map +1 -0
  98. package/dist/hooks/useWorkspace.js +68 -0
  99. package/dist/index.d.ts +2 -0
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +2 -1
  102. package/dist/session-ready/SessionReady.svelte +20 -0
  103. package/dist/session-ready/SessionReady.svelte.d.ts +5 -0
  104. package/dist/session-ready/SessionReady.svelte.d.ts.map +1 -0
  105. package/dist/session-ready/index.d.ts +7 -0
  106. package/dist/session-ready/index.d.ts.map +1 -0
  107. package/dist/session-ready/index.js +6 -0
  108. package/dist/stores/async-state.js +0 -1
  109. package/dist/stores/auth.js +0 -1
  110. package/dist/stores/capacitor-app.js +0 -1
  111. package/dist/stores/change-password.js +0 -1
  112. package/dist/stores/chat.d.ts.map +1 -1
  113. package/dist/stores/chat.js +3 -10
  114. package/dist/stores/device.js +0 -1
  115. package/dist/stores/forms.js +0 -1
  116. package/dist/stores/http.js +0 -1
  117. package/dist/stores/i18n.d.ts +3 -2
  118. package/dist/stores/i18n.d.ts.map +1 -1
  119. package/dist/stores/i18n.js +2 -3
  120. package/dist/stores/index.js +0 -1
  121. package/dist/stores/logger.js +0 -1
  122. package/dist/stores/login.js +0 -1
  123. package/dist/stores/oauth.js +0 -1
  124. package/dist/stores/password-reset.js +0 -1
  125. package/dist/stores/platform.js +0 -1
  126. package/dist/stores/promise.js +0 -1
  127. package/dist/stores/push.js +0 -1
  128. package/dist/stores/router.js +0 -1
  129. package/dist/stores/signup.js +0 -1
  130. package/dist/stores/state.js +0 -1
  131. package/dist/stores/storage.js +0 -1
  132. package/dist/stores/theme.js +0 -1
  133. package/dist/stores/version.js +0 -1
  134. package/dist/types.d.ts +20 -0
  135. package/dist/types.d.ts.map +1 -1
  136. package/dist/types.js +0 -1
  137. package/package.json +13 -8
  138. package/dist/agent-identity.js.map +0 -1
  139. package/dist/context.js.map +0 -1
  140. package/dist/index.js.map +0 -1
  141. package/dist/stores/async-state.js.map +0 -1
  142. package/dist/stores/auth.js.map +0 -1
  143. package/dist/stores/capacitor-app.js.map +0 -1
  144. package/dist/stores/change-password.js.map +0 -1
  145. package/dist/stores/chat.js.map +0 -1
  146. package/dist/stores/device.js.map +0 -1
  147. package/dist/stores/forms.js.map +0 -1
  148. package/dist/stores/http.js.map +0 -1
  149. package/dist/stores/i18n.js.map +0 -1
  150. package/dist/stores/index.js.map +0 -1
  151. package/dist/stores/logger.js.map +0 -1
  152. package/dist/stores/login.js.map +0 -1
  153. package/dist/stores/oauth.js.map +0 -1
  154. package/dist/stores/password-reset.js.map +0 -1
  155. package/dist/stores/platform.js.map +0 -1
  156. package/dist/stores/promise.js.map +0 -1
  157. package/dist/stores/push.js.map +0 -1
  158. package/dist/stores/router.js.map +0 -1
  159. package/dist/stores/signup.js.map +0 -1
  160. package/dist/stores/state.js.map +0 -1
  161. package/dist/stores/storage.js.map +0 -1
  162. package/dist/stores/theme.js.map +0 -1
  163. package/dist/stores/version.js.map +0 -1
  164. package/dist/types.js.map +0 -1
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Svelte hook for internationalization, porting React's `useTranslation`
3
+ * family: the locale-reactive values as readable stores, the translation and
4
+ * formatting functions as plain functions.
5
+ *
6
+ * @module
7
+ */
8
+ import { onDestroy } from 'svelte';
9
+ import { derived, fromStore, writable } from 'svelte/store';
10
+ import { I18nError } from '@molecule/app-i18n';
11
+ import { useI18nProvider } from '../context.js';
12
+ /**
13
+ * Subscribes the calling component to the provider's locale notifications,
14
+ * like React's `useLocaleSnapshot`.
15
+ *
16
+ * The store's value counts this hook's notifications, carries the active
17
+ * locale and includes the provider's `getRevision()` when it exposes one, so
18
+ * a notification, a locale switch or a revision bump (translations added for
19
+ * the active locale) makes every derived value re-read the provider.
20
+ *
21
+ * @param provider - The i18n provider from context.
22
+ * @returns A store whose value changes on every notification, revision and locale switch.
23
+ */
24
+ function localeVersionStore(provider) {
25
+ let notifications = 0;
26
+ const read = () => `${notifications}:${provider.getRevision?.() ?? 0}:${provider.getLocale()}`;
27
+ const version = writable(read());
28
+ const stop = provider.onLocaleChange(() => {
29
+ notifications += 1;
30
+ version.set(read());
31
+ });
32
+ onDestroy(stop);
33
+ return version;
34
+ }
35
+ /**
36
+ * A function that reads the locale version the way a rune does: calling it while a
37
+ * template, `$derived` or effect evaluates makes that evaluation re-run on every
38
+ * locale notification. A `t(…)` written straight into markup therefore follows a
39
+ * locale switch, as React's components do through `useTranslation()`.
40
+ *
41
+ * @param version - The store from {@link localeVersionStore}.
42
+ * @returns The reader.
43
+ */
44
+ function trackVersion(version) {
45
+ const tracked = fromStore(version);
46
+ return () => tracked.current;
47
+ }
48
+ /**
49
+ * A locale-reactive value: re-read from the provider whenever the locale
50
+ * version store changes.
51
+ *
52
+ * @param version - The store from {@link localeVersionStore}.
53
+ * @param read - Reads the provider's current value.
54
+ * @returns A readable store of the value.
55
+ */
56
+ function localeValue(version, read) {
57
+ return derived(version, () => read());
58
+ }
59
+ /**
60
+ * Internationalization, React's `useTranslation` in Svelte's idiom: call it
61
+ * during component init under `setMoleculeContext({ i18n })`.
62
+ *
63
+ * @returns The translation function and the locale values as stores.
64
+ * @example
65
+ * ```svelte
66
+ * <script>
67
+ * import { useTranslation } from '@molecule/app-svelte'
68
+ * const { t, locale } = useTranslation()
69
+ * </script>
70
+ *
71
+ * <h1>{t('welcome.title', { name: 'User' })}</h1>
72
+ * <select value={$locale} onchange={(e) => setLocale(e.currentTarget.value)}>
73
+ * ```
74
+ */
75
+ export function useTranslation() {
76
+ const provider = useI18nProvider();
77
+ const version = localeVersionStore(provider);
78
+ const readVersion = trackVersion(version);
79
+ return {
80
+ t: (key, values, options) => {
81
+ readVersion();
82
+ return provider.t(key, values, options);
83
+ },
84
+ locale: localeValue(version, () => provider.getLocale()),
85
+ setLocale: (code) => provider.setLocale(code),
86
+ locales: localeValue(version, () => provider.getLocales()),
87
+ formatNumber: (value, options) => provider.formatNumber(value, options),
88
+ formatDate: (value, options) => provider.formatDate(value, options),
89
+ direction: localeValue(version, () => provider.getDirection()),
90
+ };
91
+ }
92
+ /**
93
+ * The translation function alone, React's `useT` in Svelte's idiom.
94
+ *
95
+ * Call it in either of two compatible forms:
96
+ * - `t(key, values?, options?)` — the provider signature.
97
+ * - `t(key, fallback, options?)` — a string second argument is the inline
98
+ * English `defaultValue`.
99
+ *
100
+ * @returns The translation function.
101
+ */
102
+ export function useT() {
103
+ const provider = useI18nProvider();
104
+ // Each call reads the locale version, so markup that calls `t(…)` re-renders on a
105
+ // locale switch; the function keeps one identity, safe as a dependency.
106
+ const readVersion = trackVersion(localeVersionStore(provider));
107
+ return ((key, valuesOrDefault, options) => {
108
+ readVersion();
109
+ return typeof valuesOrDefault === 'string'
110
+ ? provider.t(key, undefined, { ...options, defaultValue: valuesOrDefault })
111
+ : provider.t(key, valuesOrDefault, options);
112
+ });
113
+ }
114
+ /**
115
+ * The current locale, React's `useLocale` in Svelte's idiom.
116
+ *
117
+ * @returns A readable store of the locale code.
118
+ */
119
+ export function useLocale() {
120
+ const { locale } = useTranslation();
121
+ return locale;
122
+ }
123
+ /**
124
+ * The text direction, React's `useDirection` in Svelte's idiom.
125
+ *
126
+ * @returns A readable store of 'ltr' or 'rtl'.
127
+ */
128
+ export function useDirection() {
129
+ const { direction } = useTranslation();
130
+ return direction;
131
+ }
132
+ /**
133
+ * Translates an error at render time so the displayed message updates
134
+ * automatically when the locale changes, React's `useI18nError` in Svelte's
135
+ * idiom: a readable store of the translated message.
136
+ *
137
+ * **Always use this hook to display errors** — reading `error.message`
138
+ * directly leaves stale text after a locale switch. If `error` is an
139
+ * `I18nError` (thrown via `throw new I18nError(key)`), its key is translated
140
+ * using the current locale. For plain `Error` instances, `error.message` is
141
+ * returned unchanged.
142
+ *
143
+ * @param error - The error to translate, or `null`/`undefined`.
144
+ * @returns A readable store of the translated error string, or null.
145
+ */
146
+ export function useI18nError(error) {
147
+ const { t, locale } = useTranslation();
148
+ return derived(locale, () => {
149
+ if (!error)
150
+ return null;
151
+ // defaultValue is the I18nError's own message — the fallback text its
152
+ // throw site provided. Without it, a key the CLIENT dictionary lacks
153
+ // renders as the raw key instead of a message.
154
+ if (error instanceof I18nError) {
155
+ return t(error.i18nKey, error.i18nValues, { defaultValue: error.message });
156
+ }
157
+ return error.message;
158
+ });
159
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Svelte hook for the post-checkout return: verify the purchase with the API
3
+ * from the APP origin, where the session cookie applies. Ports React's
4
+ * `useVerifyPaymentReturn`.
5
+ *
6
+ * @module
7
+ */
8
+ import { type Readable } from 'svelte/store';
9
+ /** How far the return-page verification has got. */
10
+ export type VerifyPaymentReturnStatus = 'idle' | 'verifying' | 'verified' | 'failed';
11
+ /** Options for {@link useVerifyPaymentReturn}. */
12
+ export interface UseVerifyPaymentReturnOptions {
13
+ /**
14
+ * Provider name to verify with, when the return URL carries no `provider`
15
+ * query parameter. Leave unset to verify only what the URL names.
16
+ */
17
+ provider?: string;
18
+ /** Set `false` to skip verification entirely (e.g. behind a feature flag). */
19
+ enabled?: boolean;
20
+ /**
21
+ * Remove the provider's query parameters from the address bar once the
22
+ * purchase is verified, so a reload (or a shared link) cannot replay the
23
+ * verification. Defaults to `true`.
24
+ */
25
+ cleanUrl?: boolean;
26
+ /** Called once, after the purchase verifies. */
27
+ onVerified?: () => void;
28
+ /** Called when verification fails. */
29
+ onError?: (error: Error) => void;
30
+ }
31
+ /** State of the post-checkout verification. */
32
+ export interface UseVerifyPaymentReturnResult {
33
+ /**
34
+ * `idle` when this page load is not a checkout return (no transaction id in
35
+ * the URL) or auth is still hydrating; `verifying` while the API call is in
36
+ * flight; then `verified` or `failed`.
37
+ */
38
+ status: Readable<VerifyPaymentReturnStatus>;
39
+ /** `true` when the URL identifies a purchase to verify. */
40
+ isReturn: Readable<boolean>;
41
+ /** The provider named by the URL (or the `provider` option). */
42
+ provider: Readable<string | null>;
43
+ /** The provider transaction/session id read from the URL. */
44
+ transactionId: Readable<string | null>;
45
+ /** Why verification failed, when it did. */
46
+ error: Readable<Error | null>;
47
+ /** Re-run the verification — wire this to a retry button. */
48
+ retry: () => void;
49
+ }
50
+ /**
51
+ * Reads the payment id a provider put in the return URL and confirms the
52
+ * purchase server-side with `POST /users/:id/verify-payment/:provider`,
53
+ * React's `useVerifyPaymentReturn` in Svelte's idiom: call it during component
54
+ * init under `setMoleculeContext({ auth, http })`.
55
+ *
56
+ * **This is why a hosted checkout returns the buyer to the APP and not the
57
+ * API.** Session cookies are host-only on the app's origin, so a top-level
58
+ * redirect from the provider straight to an authenticated API callback on a
59
+ * different host arrives with NO credentials — it answers 401 and the paid plan
60
+ * is never granted. The request this hook makes is a same-origin call from a
61
+ * loaded app page, so the credentials apply. It waits for auth to hydrate
62
+ * first: after the redirect the page is a cold load, and the session is
63
+ * restored from the httpOnly cookie via `GET /users/me`.
64
+ *
65
+ * Verification is idempotent server-side (first-claim-wins on the transaction),
66
+ * and this hook additionally runs at most once per transaction id per page.
67
+ * Safe on pages that are also reached normally: with no id in the URL it stays
68
+ * `idle` and issues no request.
69
+ *
70
+ * If the component unmounts while the request is in flight, a verified
71
+ * purchase still refreshes the cached profile (the plan is paid for), but the
72
+ * hook calls neither `onVerified` nor `onError` and leaves the URL alone: by
73
+ * then the address may belong to another page. A failure after unmount is
74
+ * logged instead.
75
+ *
76
+ * @param options - Provider fallback + lifecycle callbacks (see
77
+ * {@link UseVerifyPaymentReturnOptions}).
78
+ * @returns The verification state (see {@link UseVerifyPaymentReturnResult}).
79
+ * @example
80
+ * ```svelte
81
+ * <!-- /plan-updated — the page a provider returns the buyer to. -->
82
+ * <script>
83
+ * import { useVerifyPaymentReturn } from '@molecule/app-svelte'
84
+ * const { status, retry } = useVerifyPaymentReturn()
85
+ * </script>
86
+ *
87
+ * {#if $status === 'failed'}<button onclick={retry}>Try again</button>{/if}
88
+ * ```
89
+ */
90
+ export declare function useVerifyPaymentReturn(options?: UseVerifyPaymentReturnOptions): UseVerifyPaymentReturnResult;
91
+ //# sourceMappingURL=useVerifyPaymentReturn.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useVerifyPaymentReturn.d.ts","sourceRoot":"","sources":["../../src/hooks/useVerifyPaymentReturn.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,KAAK,QAAQ,EAAY,MAAM,cAAc,CAAA;AAoBtD,oDAAoD;AACpD,MAAM,MAAM,yBAAyB,GAAG,MAAM,GAAG,WAAW,GAAG,UAAU,GAAG,QAAQ,CAAA;AAEpF,kDAAkD;AAClD,MAAM,WAAW,6BAA6B;IAC5C;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IAEjB,8EAA8E;IAC9E,OAAO,CAAC,EAAE,OAAO,CAAA;IAEjB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB,gDAAgD;IAChD,UAAU,CAAC,EAAE,MAAM,IAAI,CAAA;IAEvB,sCAAsC;IACtC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CACjC;AAED,+CAA+C;AAC/C,MAAM,WAAW,4BAA4B;IAC3C;;;;OAIG;IACH,MAAM,EAAE,QAAQ,CAAC,yBAAyB,CAAC,CAAA;IAE3C,2DAA2D;IAC3D,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAA;IAE3B,gEAAgE;IAChE,QAAQ,EAAE,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC,CAAA;IAEjC,6DAA6D;IAC7D,aAAa,EAAE,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC,CAAA;IAEtC,4CAA4C;IAC5C,KAAK,EAAE,QAAQ,CAAC,KAAK,GAAG,IAAI,CAAC,CAAA;IAE7B,6DAA6D;IAC7D,KAAK,EAAE,MAAM,IAAI,CAAA;CAClB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,GAAE,6BAAkC,GAC1C,4BAA4B,CAsI9B"}
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Svelte hook for the post-checkout return: verify the purchase with the API
3
+ * from the APP origin, where the session cookie applies. Ports React's
4
+ * `useVerifyPaymentReturn`.
5
+ *
6
+ * @module
7
+ */
8
+ import { onDestroy } from 'svelte';
9
+ import { writable } from 'svelte/store';
10
+ import { getLogger } from '@molecule/app-logger';
11
+ import { useHttpClient } from '../context.js';
12
+ import { useAuth } from './useAuth.js';
13
+ /** Query parameters a payment provider may use for its transaction id. */
14
+ const TRANSACTION_ID_PARAMS = [
15
+ // What `resolveCheckoutRedirectUrls` (@molecule/api-payments) asks providers
16
+ // to substitute — Stripe's `{CHECKOUT_SESSION_ID}`.
17
+ 'sessionId',
18
+ 'session_id',
19
+ 'subscriptionId',
20
+ // PayPal appends its OWN names to the return URL after buyer approval.
21
+ 'subscription_id',
22
+ 'token',
23
+ ];
24
+ /**
25
+ * Reads the payment id a provider put in the return URL and confirms the
26
+ * purchase server-side with `POST /users/:id/verify-payment/:provider`,
27
+ * React's `useVerifyPaymentReturn` in Svelte's idiom: call it during component
28
+ * init under `setMoleculeContext({ auth, http })`.
29
+ *
30
+ * **This is why a hosted checkout returns the buyer to the APP and not the
31
+ * API.** Session cookies are host-only on the app's origin, so a top-level
32
+ * redirect from the provider straight to an authenticated API callback on a
33
+ * different host arrives with NO credentials — it answers 401 and the paid plan
34
+ * is never granted. The request this hook makes is a same-origin call from a
35
+ * loaded app page, so the credentials apply. It waits for auth to hydrate
36
+ * first: after the redirect the page is a cold load, and the session is
37
+ * restored from the httpOnly cookie via `GET /users/me`.
38
+ *
39
+ * Verification is idempotent server-side (first-claim-wins on the transaction),
40
+ * and this hook additionally runs at most once per transaction id per page.
41
+ * Safe on pages that are also reached normally: with no id in the URL it stays
42
+ * `idle` and issues no request.
43
+ *
44
+ * If the component unmounts while the request is in flight, a verified
45
+ * purchase still refreshes the cached profile (the plan is paid for), but the
46
+ * hook calls neither `onVerified` nor `onError` and leaves the URL alone: by
47
+ * then the address may belong to another page. A failure after unmount is
48
+ * logged instead.
49
+ *
50
+ * @param options - Provider fallback + lifecycle callbacks (see
51
+ * {@link UseVerifyPaymentReturnOptions}).
52
+ * @returns The verification state (see {@link UseVerifyPaymentReturnResult}).
53
+ * @example
54
+ * ```svelte
55
+ * <!-- /plan-updated — the page a provider returns the buyer to. -->
56
+ * <script>
57
+ * import { useVerifyPaymentReturn } from '@molecule/app-svelte'
58
+ * const { status, retry } = useVerifyPaymentReturn()
59
+ * </script>
60
+ *
61
+ * {#if $status === 'failed'}<button onclick={retry}>Try again</button>{/if}
62
+ * ```
63
+ */
64
+ export function useVerifyPaymentReturn(options = {}) {
65
+ const { provider: providerOption, enabled = true, cleanUrl = true, onVerified, onError } = options;
66
+ const http = useHttpClient();
67
+ const { state: authState, refresh } = useAuth();
68
+ // The URL-derived fields are re-read the way React's re-render is: on every
69
+ // auth change and after the verified path cleans the address, so a cleaned
70
+ // URL reads as "no transaction" the moment the hook renders again.
71
+ const transactionId = writable(null);
72
+ const provider = writable(null);
73
+ const isReturn = writable(false);
74
+ // The URL fields this mount last read (what the gate and retry close over —
75
+ // React's render-time values).
76
+ let currentTransactionId = null;
77
+ let currentProvider = null;
78
+ let currentIsReturn = false;
79
+ const readUrl = () => {
80
+ const search = typeof window === 'undefined' ? '' : window.location.search;
81
+ const params = new URLSearchParams(search);
82
+ const tid = TRANSACTION_ID_PARAMS.map((name) => params.get(name)).find((value) => !!value) ?? null;
83
+ const prov = params.get('provider') || providerOption || null;
84
+ const returnFlag = Boolean(enabled && tid && prov);
85
+ transactionId.set(tid);
86
+ provider.set(prov);
87
+ isReturn.set(returnFlag);
88
+ currentTransactionId = tid;
89
+ currentProvider = prov;
90
+ currentIsReturn = returnFlag;
91
+ };
92
+ readUrl();
93
+ const status = writable('idle');
94
+ const error = writable(null);
95
+ // One attempt per transaction id per page — an effect that re-fires (auth
96
+ // refresh) must not re-POST a purchase.
97
+ let attempted = null;
98
+ // Whether the component is mounted when a verification settles.
99
+ let mounted = true;
100
+ onDestroy(() => {
101
+ mounted = false;
102
+ });
103
+ const verify = async () => {
104
+ const userId = clientState?.user?.id ?? null;
105
+ const tid = currentTransactionId;
106
+ const prov = currentProvider;
107
+ if (!tid || !prov || !userId)
108
+ return;
109
+ status.set('verifying');
110
+ error.set(null);
111
+ try {
112
+ await http.post(`/users/${userId}/verify-payment/${prov}`, {
113
+ subscriptionId: tid,
114
+ });
115
+ // The plan on the cached profile is now stale — re-read it so the UI
116
+ // (plan badges, gated features) reflects what was just paid for.
117
+ await refresh().catch((refreshError) => {
118
+ // The payment is verified either way; only the cached plan may lag until the next refresh.
119
+ getLogger('useVerifyPaymentReturn').warn('Refreshing the profile after payment failed', {
120
+ error: refreshError,
121
+ });
122
+ });
123
+ if (!mounted)
124
+ return;
125
+ status.set('verified');
126
+ onVerified?.();
127
+ if (cleanUrl && typeof window !== 'undefined' && window.history?.replaceState) {
128
+ const url = new URL(window.location.href);
129
+ for (const name of TRANSACTION_ID_PARAMS)
130
+ url.searchParams.delete(name);
131
+ url.searchParams.delete('provider');
132
+ window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`);
133
+ }
134
+ // React re-renders with the cleaned address: the URL fields re-read.
135
+ readUrl();
136
+ }
137
+ catch (caught) {
138
+ const failure = caught instanceof Error ? caught : new Error(String(caught));
139
+ if (!mounted) {
140
+ getLogger('useVerifyPaymentReturn').warn('Verifying the payment failed after the page unmounted', { error: failure, provider: prov });
141
+ return;
142
+ }
143
+ status.set('failed');
144
+ error.set(failure);
145
+ onError?.(failure);
146
+ }
147
+ };
148
+ // The auth state this mount last saw; the verification gate reads it (React's
149
+ // effect dependencies `state.initialized` and `userId`).
150
+ let clientState = null;
151
+ // React's mount effect gate: verify once auth has hydrated and a user id is
152
+ // known, at most once per transaction id per page.
153
+ const runGate = () => {
154
+ if (!clientState)
155
+ return;
156
+ if (!currentIsReturn || !currentTransactionId)
157
+ return;
158
+ // Auth is still hydrating from the httpOnly cookie — verifying now would
159
+ // send the request unauthenticated.
160
+ if (!clientState.initialized)
161
+ return;
162
+ const userId = clientState.user?.id ?? null;
163
+ if (!userId)
164
+ return;
165
+ if (attempted === currentTransactionId)
166
+ return;
167
+ attempted = currentTransactionId;
168
+ void verify();
169
+ };
170
+ const stopAuth = authState.subscribe((current) => {
171
+ clientState = current;
172
+ // React re-renders on every auth change, re-reading the URL fields.
173
+ readUrl();
174
+ runGate();
175
+ });
176
+ onDestroy(stopAuth);
177
+ const retry = () => {
178
+ attempted = currentTransactionId;
179
+ void verify();
180
+ };
181
+ return {
182
+ status: { subscribe: status.subscribe },
183
+ isReturn: { subscribe: isReturn.subscribe },
184
+ provider: { subscribe: provider.subscribe },
185
+ transactionId: { subscribe: transactionId.subscribe },
186
+ error: { subscribe: error.subscribe },
187
+ retry,
188
+ };
189
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Svelte hook for version and update management, porting React's `useVersion`.
3
+ *
4
+ * @module
5
+ */
6
+ import type { Readable } from 'svelte/store';
7
+ import type { UpdateCheckOptions, VersionState } from '@molecule/app-version';
8
+ /**
9
+ * Hook return type.
10
+ */
11
+ export interface UseVersionResult {
12
+ /** The provider's full state. */
13
+ state: Readable<VersionState>;
14
+ /** Whether an update is available. */
15
+ isUpdateAvailable: Readable<boolean>;
16
+ /** Whether a check is running. */
17
+ isChecking: Readable<boolean>;
18
+ /** Whether a service worker waits to activate. */
19
+ isServiceWorkerWaiting: Readable<boolean>;
20
+ /** The version an available update reports. */
21
+ newVersion: Readable<string | undefined>;
22
+ /** Checks the provider for an update. */
23
+ checkForUpdates: () => Promise<boolean>;
24
+ /** Applies an available update. */
25
+ applyUpdate: (options?: {
26
+ force?: boolean;
27
+ }) => void;
28
+ /** Hides an available update. */
29
+ dismissUpdate: () => void;
30
+ /** Starts polling the provider for updates. */
31
+ startPeriodicChecks: (options?: UpdateCheckOptions) => void;
32
+ /** Stops the polling. */
33
+ stopPeriodicChecks: () => void;
34
+ }
35
+ /**
36
+ * Version state and update actions, React's `useVersion` in Svelte's idiom: a
37
+ * readable store per value field and plain functions for the actions, created
38
+ * during component init.
39
+ *
40
+ * Uses module-level `getProvider()` — version is a singleton, not
41
+ * context-provided.
42
+ *
43
+ * @returns Version state and action methods.
44
+ * @example
45
+ * ```svelte
46
+ * <script>
47
+ * import { useVersion } from '@molecule/app-svelte'
48
+ * const { isUpdateAvailable, newVersion, applyUpdate, dismissUpdate } = useVersion()
49
+ * </script>
50
+ * ```
51
+ */
52
+ export declare function useVersion(): UseVersionResult;
53
+ //# sourceMappingURL=useVersion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useVersion.d.ts","sourceRoot":"","sources":["../../src/hooks/useVersion.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAE5C,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAA;AAM7E;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,iCAAiC;IACjC,KAAK,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAA;IAC7B,sCAAsC;IACtC,iBAAiB,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAA;IACpC,kCAAkC;IAClC,UAAU,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAA;IAC7B,kDAAkD;IAClD,sBAAsB,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAA;IACzC,+CAA+C;IAC/C,UAAU,EAAE,QAAQ,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IACxC,yCAAyC;IACzC,eAAe,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;IACvC,mCAAmC;IACnC,WAAW,EAAE,CAAC,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAA;IACpD,iCAAiC;IACjC,aAAa,EAAE,MAAM,IAAI,CAAA;IACzB,+CAA+C;IAC/C,mBAAmB,EAAE,CAAC,OAAO,CAAC,EAAE,kBAAkB,KAAK,IAAI,CAAA;IAC3D,yBAAyB;IACzB,kBAAkB,EAAE,MAAM,IAAI,CAAA;CAC/B;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,IAAI,gBAAgB,CAiD7C"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Svelte hook for version and update management, porting React's `useVersion`.
3
+ *
4
+ * @module
5
+ */
6
+ import { getProvider } from '@molecule/app-version';
7
+ import { useSyncExternalStore } from './external-store.js';
8
+ import { fieldStore } from './live-store.js';
9
+ /**
10
+ * Version state and update actions, React's `useVersion` in Svelte's idiom: a
11
+ * readable store per value field and plain functions for the actions, created
12
+ * during component init.
13
+ *
14
+ * Uses module-level `getProvider()` — version is a singleton, not
15
+ * context-provided.
16
+ *
17
+ * @returns Version state and action methods.
18
+ * @example
19
+ * ```svelte
20
+ * <script>
21
+ * import { useVersion } from '@molecule/app-svelte'
22
+ * const { isUpdateAvailable, newVersion, applyUpdate, dismissUpdate } = useVersion()
23
+ * </script>
24
+ * ```
25
+ */
26
+ export function useVersion() {
27
+ const provider = getProvider();
28
+ // Cached previous state (React's cachedStateRef): a snapshot whose tracked
29
+ // fields all match the provider's keeps the previous object, so the value is
30
+ // referentially stable and no notification publishes a fresh copy.
31
+ let cachedState = null;
32
+ const getSnapshot = () => {
33
+ const next = provider.getState();
34
+ const prev = cachedState;
35
+ if (prev !== null &&
36
+ prev.isUpdateAvailable === next.isUpdateAvailable &&
37
+ prev.isChecking === next.isChecking &&
38
+ prev.isServiceWorkerWaiting === next.isServiceWorkerWaiting &&
39
+ prev.newVersion === next.newVersion &&
40
+ prev.buildId === next.buildId &&
41
+ prev.version === next.version) {
42
+ return prev;
43
+ }
44
+ cachedState = next;
45
+ return next;
46
+ };
47
+ const state = useSyncExternalStore((onChange) => {
48
+ const unsubs = [
49
+ provider.on('update-available', onChange),
50
+ provider.on('service-worker-waiting', onChange),
51
+ provider.on('service-worker-activated', onChange),
52
+ provider.on('check-start', onChange),
53
+ provider.on('check-complete', onChange),
54
+ provider.on('check-error', onChange),
55
+ ];
56
+ return () => unsubs.forEach((unsub) => unsub());
57
+ }, getSnapshot);
58
+ return {
59
+ state,
60
+ isUpdateAvailable: fieldStore(state, 'isUpdateAvailable'),
61
+ isChecking: fieldStore(state, 'isChecking'),
62
+ isServiceWorkerWaiting: fieldStore(state, 'isServiceWorkerWaiting'),
63
+ newVersion: fieldStore(state, 'newVersion'),
64
+ checkForUpdates: () => provider.checkForUpdates(),
65
+ applyUpdate: (options) => provider.applyUpdate(options),
66
+ dismissUpdate: () => provider.dismissUpdate(),
67
+ startPeriodicChecks: (options) => provider.startPeriodicChecks(options),
68
+ stopPeriodicChecks: () => provider.stopPeriodicChecks(),
69
+ };
70
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Svelte hook for IDE workspace management, porting React's `useWorkspace`.
3
+ *
4
+ * @module
5
+ */
6
+ import type { Readable } from 'svelte/store';
7
+ import type { PanelId, WorkspaceLayout } from '@molecule/app-ide';
8
+ /**
9
+ * Hook result for useWorkspace: the layout fields as readable stores and the
10
+ * layout actions as plain functions.
11
+ */
12
+ export interface UseWorkspaceResult {
13
+ /** The panel layout. */
14
+ layout: Readable<WorkspaceLayout>;
15
+ /** The panel showing the keyboard focus, if any. */
16
+ activePanel: Readable<PanelId | null>;
17
+ /** The panels collapsed. */
18
+ collapsedPanels: Readable<Set<PanelId>>;
19
+ /** Shows or hides a panel. */
20
+ togglePanel: (panelId: PanelId) => void;
21
+ /** Resizes a panel. */
22
+ resizePanel: (panelId: PanelId, size: number) => void;
23
+ /** Focuses a panel. */
24
+ setActivePanel: (panelId: PanelId) => void;
25
+ /** Restores the provider's default layout. */
26
+ resetLayout: () => void;
27
+ }
28
+ /**
29
+ * IDE workspace layout management, React's `useWorkspace` in Svelte's idiom:
30
+ * call it during component init under `setMoleculeContext({ workspace })`.
31
+ *
32
+ * The state is a snapshot store over `provider.subscribe`, cached the way
33
+ * React's `useSyncExternalStore` snapshot is (a provider without `getState`
34
+ * fabricates the non-layout fields from `getLayout()` until its first
35
+ * emission supplies the real ones).
36
+ *
37
+ * @returns The workspace state stores and management methods.
38
+ * @example
39
+ * ```svelte
40
+ * <script>
41
+ * import { useWorkspace } from '@molecule/app-svelte'
42
+ * const { layout, togglePanel } = useWorkspace()
43
+ * </script>
44
+ * ```
45
+ */
46
+ export declare function useWorkspace(): UseWorkspaceResult;
47
+ //# sourceMappingURL=useWorkspace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useWorkspace.d.ts","sourceRoot":"","sources":["../../src/hooks/useWorkspace.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAE5C,OAAO,KAAK,EAAE,OAAO,EAAE,eAAe,EAAqC,MAAM,mBAAmB,CAAA;AAMpG;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,wBAAwB;IACxB,MAAM,EAAE,QAAQ,CAAC,eAAe,CAAC,CAAA;IACjC,oDAAoD;IACpD,WAAW,EAAE,QAAQ,CAAC,OAAO,GAAG,IAAI,CAAC,CAAA;IACrC,4BAA4B;IAC5B,eAAe,EAAE,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAA;IACvC,8BAA8B;IAC9B,WAAW,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAA;IACvC,uBAAuB;IACvB,WAAW,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;IACrD,uBAAuB;IACvB,cAAc,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAA;IAC1C,8CAA8C;IAC9C,WAAW,EAAE,MAAM,IAAI,CAAA;CACxB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,YAAY,IAAI,kBAAkB,CA2CjD"}