@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,221 @@
1
+ /**
2
+ * Svelte hooks for form handling, porting React's `useForm` family.
3
+ *
4
+ * @module
5
+ */
6
+ import { onDestroy } from 'svelte';
7
+ import { derived, writable } from 'svelte/store';
8
+ import { createForm as createBondedForm, formValuesEqual, snapshotFormValue, } from '@molecule/app-forms';
9
+ /** The previous host's lane, alive until its disarm timer runs. */
10
+ let formHandoff = null;
11
+ /**
12
+ * Hook for form state management, React's `useForm` in Svelte's idiom: call it
13
+ * during component init (no provider needed — the controller comes from the
14
+ * bonded forms provider).
15
+ *
16
+ * Creates its controller through the bonded forms provider, so an app wires a
17
+ * form library once (`setProvider` from `@molecule/app-forms`) and every form
18
+ * picks it up. Passing `createForm` overrides that for one form. When the
19
+ * `values` option changes by content, it becomes the new baseline;
20
+ * `resetOptions.keepDirtyValues` retains edited fields while pristine fields
21
+ * take the loaded values. A changed `resetKey` starts a fresh form; fresh
22
+ * `defaultValues` without one leave the drafts alone.
23
+ *
24
+ * @param options - Form options. `defaultValues`, `mode` and the form-level
25
+ * `validate` are forwarded to the provider.
26
+ * @returns Form state stores and methods
27
+ * @example
28
+ * ```svelte
29
+ * <script>
30
+ * import { useForm } from '@molecule/app-svelte'
31
+ * const { register, handleSubmit, formState, isSubmitting } = useForm({
32
+ * defaultValues: { email: '', password: '' },
33
+ * })
34
+ * const onSubmit = handleSubmit(async (values) => { await login(values) })
35
+ * </script>
36
+ *
37
+ * <form onsubmit={onSubmit}>
38
+ * <input {...$registerNotNeeded} />
39
+ * </form>
40
+ * ```
41
+ */
42
+ export function useForm(options = {}) {
43
+ const { createForm = createBondedForm, resetKey, ...formOptions } = options;
44
+ // A mount in the same turn as the previous host's destroy is React's
45
+ // re-render (an args step), not a new component: adopt its lane (when the
46
+ // resetKey did not change) so the controller and its state continue.
47
+ const adopted = formHandoff;
48
+ formHandoff = null;
49
+ const sameForm = adopted !== null && Object.is(adopted.resetKey, resetKey);
50
+ const form = sameForm ? adopted.form : createForm(formOptions);
51
+ const lane = sameForm
52
+ ? adopted
53
+ : { dead: false, form, resetKey, lastExternal: null, stateTuples: new Map() };
54
+ lane.resetKey = resetKey;
55
+ if (sameForm)
56
+ lane.dead = false;
57
+ // React's mounted flag: false once the host is gone with no replacement.
58
+ let mounted = !lane.dead;
59
+ onDestroy(() => {
60
+ mounted = false;
61
+ lane.dead = true;
62
+ // Offer the lane to a mount in the same turn (React's re-render); the
63
+ // timer clears it when no replacement adopted, so a mount after a settled
64
+ // teardown starts fresh. The controller itself stays as React leaves it:
65
+ // subscribed-to-nothing, never destroyed mid-flight.
66
+ formHandoff = lane;
67
+ const offered = lane;
68
+ setTimeout(() => {
69
+ if (formHandoff === offered)
70
+ formHandoff = null;
71
+ }, 0);
72
+ });
73
+ const keepDirtyValues = options.resetOptions?.keepDirtyValues !== false;
74
+ // External content has its own history. A reset may change the controller
75
+ // baseline without making an unchanged record external again.
76
+ const applyExternalValues = () => {
77
+ const values = options.values;
78
+ if (values === undefined) {
79
+ lane.lastExternal = null;
80
+ return;
81
+ }
82
+ if (lane.lastExternal !== null && formValuesEqual(lane.lastExternal.values, values))
83
+ return;
84
+ lane.lastExternal = { values: snapshotFormValue(values) };
85
+ form.updateValues(values, { keepDirtyValues });
86
+ };
87
+ applyExternalValues();
88
+ // Subscribed state (the controller rebuilds its state object only on change),
89
+ // read the way React's cached useSyncExternalStore snapshot is: one read at
90
+ // creation, one re-read right after subscribing, one per notification. The
91
+ // mirror is what asState's visible value reads (React's stateSnapshots).
92
+ let currentState = form.getState();
93
+ const state = writable(currentState);
94
+ const refresh = () => {
95
+ currentState = form.getState();
96
+ state.set(currentState);
97
+ };
98
+ const unsubscribe = form.subscribe(refresh);
99
+ refresh();
100
+ onDestroy(unsubscribe);
101
+ // Field methods
102
+ const register = (name, registerOptions) => form.register({ ...registerOptions, name: name });
103
+ const getValue = (name) => form.getValue(name);
104
+ const setValue = (name, value) => {
105
+ form.setValue(name, value);
106
+ };
107
+ const getError = (name) => form.getError(name);
108
+ const setError = (name, error) => {
109
+ if (error !== undefined) {
110
+ form.setError(name, error);
111
+ }
112
+ else {
113
+ form.clearError(name);
114
+ }
115
+ };
116
+ const clearErrors = () => form.clearErrors();
117
+ const reset = (values) => form.reset(values);
118
+ const updateValues = (values, resetOptions) => form.updateValues(values, resetOptions);
119
+ const validate = () => form.validate();
120
+ const asState = (name) => {
121
+ const read = () => name === undefined ? form.getState().values : form.getValue(name);
122
+ // The value the caller sees comes from the subscribed snapshot, not a
123
+ // fresh read: a fill that lands between renders must not jump ahead.
124
+ const visible = name === undefined ? currentState.values : currentState.values[name];
125
+ const existing = lane.stateTuples.get(name);
126
+ if (existing)
127
+ return [visible, ...existing];
128
+ const edit = (value) => {
129
+ const next = typeof value === 'function'
130
+ ? value(read())
131
+ : value;
132
+ if (name !== undefined) {
133
+ form.setValue(name, next);
134
+ return;
135
+ }
136
+ const values = next;
137
+ for (const field of Object.keys(Object.assign({}, form.getState().values, values))) {
138
+ if (!formValuesEqual(form.getValue(field), values[field]))
139
+ form.setValue(field, values[field]);
140
+ }
141
+ };
142
+ const fill = (value) => {
143
+ const next = typeof value === 'function'
144
+ ? value(read())
145
+ : value;
146
+ form.updateValues(name === undefined ? next : { [name]: next }, { keepDirtyValues: true });
147
+ };
148
+ lane.stateTuples.set(name, [edit, fill]);
149
+ return [visible, edit, fill];
150
+ };
151
+ const handleSubmit = (onSubmit, onError) => form.handleSubmit((values) => {
152
+ if (mounted && lane.form === form)
153
+ return onSubmit(values);
154
+ }, onError);
155
+ return {
156
+ formState: { subscribe: state.subscribe },
157
+ isValid: derived(state, (current) => current.isValid),
158
+ isDirty: derived(state, (current) => current.isDirty),
159
+ isSubmitting: derived(state, (current) => current.isSubmitting),
160
+ register,
161
+ getValue,
162
+ setValue,
163
+ getError,
164
+ setError,
165
+ clearErrors,
166
+ handleSubmit,
167
+ reset,
168
+ updateValues,
169
+ asState: asState,
170
+ validate,
171
+ };
172
+ }
173
+ /**
174
+ * Hook to watch a specific field value, React's `useWatch` in Svelte's idiom:
175
+ * a readable store of the field's current value.
176
+ *
177
+ * @param form - Form controller
178
+ * @param name - Field name to watch
179
+ * @returns A readable store of the current field value
180
+ * @example
181
+ * ```svelte
182
+ * <script>
183
+ * import { useForm, useWatch } from '@molecule/app-svelte'
184
+ * const { form } = useForm({ defaultValues: { country: '' } })
185
+ * const country = useWatch(form, 'country')
186
+ * </script>
187
+ *
188
+ * <p>{$country}</p>
189
+ * ```
190
+ */
191
+ export function useWatch(form, name) {
192
+ // The whole state as the cached snapshot (React's useFormSnapshot over
193
+ // getValue), one read at creation, one re-read after subscribing, one per
194
+ // notification.
195
+ const state = writable(form.getState());
196
+ const refresh = () => {
197
+ state.set(form.getState());
198
+ };
199
+ const unsubscribe = form.subscribe(refresh);
200
+ refresh();
201
+ onDestroy(unsubscribe);
202
+ return derived(state, (current) => current.values[name]);
203
+ }
204
+ /**
205
+ * Hook to get field-level state, React's `useFieldState` in Svelte's idiom: a
206
+ * readable store of the field's state.
207
+ *
208
+ * @param form - Form controller
209
+ * @param name - Field name
210
+ * @returns A readable store of the field state (value, error, touched, dirty, valid, validating)
211
+ */
212
+ export function useFieldState(form, name) {
213
+ const state = writable(form.getFieldState(name));
214
+ const refresh = () => {
215
+ state.set(form.getFieldState(name));
216
+ };
217
+ const unsubscribe = form.subscribe(refresh);
218
+ refresh();
219
+ onDestroy(unsubscribe);
220
+ return { subscribe: state.subscribe };
221
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Svelte hooks for HTTP requests, porting React's `useHttp` family.
3
+ *
4
+ * @module
5
+ */
6
+ import { type Readable } from 'svelte/store';
7
+ import type { RequestConfig } from '@molecule/app-http';
8
+ /** State for async HTTP operations. */
9
+ export interface UseHttpState<T> {
10
+ data: T | null;
11
+ loading: boolean;
12
+ error: Error | null;
13
+ }
14
+ /** What {@link useHttp} returns: the state fields as stores plus `execute` and `reset`. */
15
+ export interface UseHttpResult<T> {
16
+ /** The newest request's data, or null. */
17
+ data: Readable<T | null>;
18
+ /** Whether a request is in flight. */
19
+ loading: Readable<boolean>;
20
+ /** The newest request's failure. */
21
+ error: Readable<Error | null>;
22
+ /**
23
+ * Runs the request and resolves with its own data, or `null` on failure,
24
+ * even when a newer request or `reset` has superseded its displayed state.
25
+ *
26
+ * This function keeps ONE identity for the component's life, so it is safe
27
+ * wherever a stable function matters. Its request options are read when it
28
+ * is CALLED.
29
+ */
30
+ execute: () => Promise<T | null>;
31
+ /** Clears the state and supersedes any in-flight request. */
32
+ reset: () => void;
33
+ }
34
+ /**
35
+ * Options for the {@link useHttp} hooks.
36
+ *
37
+ * Every request option — headers, params, body `data`, `signal`, `onSuccess`,
38
+ * `onError` — is read at the moment `execute` runs, not when the hook was
39
+ * called. Only `immediate` is read on mount.
40
+ */
41
+ export interface UseHttpOptions<T> extends RequestConfig {
42
+ /** Whether to execute the request immediately on mount. */
43
+ immediate?: boolean;
44
+ /**
45
+ * Callback for each request that succeeds while mounted, including a request
46
+ * superseded by another `execute` or `reset`. Read `data` from the hook when
47
+ * only the newest request's result should drive the UI.
48
+ */
49
+ onSuccess?: (data: T) => void;
50
+ /** Callback for each request that fails while mounted, including a superseded one. */
51
+ onError?: (error: Error) => void;
52
+ }
53
+ /**
54
+ * HTTP requests with state management, React's `useHttp` in Svelte's idiom:
55
+ * call it during component init under `setMoleculeContext({ http })`.
56
+ *
57
+ * The newest request owns the displayed state: an older response answering
58
+ * after a newer `execute` or `reset` cannot touch it (callbacks still report
59
+ * every request's own outcome). A failure resolves `null` — it never rejects
60
+ * to the caller. `reset` takes ownership too, so a request it superseded
61
+ * cannot repopulate the state. `execute` keeps one identity per mount, and its
62
+ * options are read at call time. `immediate` runs its request once per host,
63
+ * on mount only, even when the host re-mounts the hook with new arguments.
64
+ *
65
+ * @param method - HTTP method.
66
+ * @param url - Request URL.
67
+ * @param options - Request options, read at call time.
68
+ * @returns Request state as stores and the controls.
69
+ * @example
70
+ * ```svelte
71
+ * <script>
72
+ * import { useGet } from '@molecule/app-svelte'
73
+ * const { data, loading, error, execute } = useGet('/api/users')
74
+ * </script>
75
+ *
76
+ * {#if $loading}<Spinner />
77
+ * {:else if $error}<p>{$error.message}</p>
78
+ * {:else}<UserList users={$data} />{/if}
79
+ * ```
80
+ */
81
+ export declare function useHttp<T>(method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', url: string, options?: UseHttpOptions<T>): UseHttpResult<T>;
82
+ /**
83
+ * GET requests, React's `useGet` in Svelte's idiom.
84
+ *
85
+ * @param url - Request URL to fetch from.
86
+ * @param options - HTTP request options including callbacks and request config.
87
+ * @returns Request state as stores and the controls.
88
+ */
89
+ export declare function useGet<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>;
90
+ /**
91
+ * POST requests, React's `usePost` in Svelte's idiom.
92
+ *
93
+ * @param url - Request URL to post to.
94
+ * @param options - HTTP request options including body data and callbacks.
95
+ * @returns Request state as stores and the controls.
96
+ */
97
+ export declare function usePost<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>;
98
+ /**
99
+ * PUT requests, React's `usePut` in Svelte's idiom.
100
+ *
101
+ * @param url - Request URL to send the PUT request to.
102
+ * @param options - HTTP request options including body data and callbacks.
103
+ * @returns Request state as stores and the controls.
104
+ */
105
+ export declare function usePut<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>;
106
+ /**
107
+ * PATCH requests, React's `usePatch` in Svelte's idiom.
108
+ *
109
+ * @param url - Request URL to send the PATCH request to.
110
+ * @param options - HTTP request options including partial body data and callbacks.
111
+ * @returns Request state as stores and the controls.
112
+ */
113
+ export declare function usePatch<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>;
114
+ /**
115
+ * DELETE requests, React's `useDelete` in Svelte's idiom.
116
+ *
117
+ * @param url - Request URL of the resource to delete.
118
+ * @param options - HTTP request options including callbacks.
119
+ * @returns Request state as stores and the controls.
120
+ */
121
+ export declare function useDelete<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>;
122
+ //# sourceMappingURL=useHttp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useHttp.d.ts","sourceRoot":"","sources":["../../src/hooks/useHttp.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,KAAK,QAAQ,EAAY,MAAM,cAAc,CAAA;AAEtD,OAAO,KAAK,EAAgB,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAMrE,uCAAuC;AACvC,MAAM,WAAW,YAAY,CAAC,CAAC;IAC7B,IAAI,EAAE,CAAC,GAAG,IAAI,CAAA;IACd,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,KAAK,GAAG,IAAI,CAAA;CACpB;AAED,2FAA2F;AAC3F,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,0CAA0C;IAC1C,IAAI,EAAE,QAAQ,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;IACxB,sCAAsC;IACtC,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAA;IAC1B,oCAAoC;IACpC,KAAK,EAAE,QAAQ,CAAC,KAAK,GAAG,IAAI,CAAC,CAAA;IAC7B;;;;;;;OAOG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;IAChC,6DAA6D;IAC7D,KAAK,EAAE,MAAM,IAAI,CAAA;CAClB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,cAAc,CAAC,CAAC,CAAE,SAAQ,aAAa;IACtD,2DAA2D;IAC3D,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,CAAA;IAC7B,sFAAsF;IACtF,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CACjC;AA+BD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,OAAO,CAAC,CAAC,EACvB,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,EACnD,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,GAC1B,aAAa,CAAC,CAAC,CAAC,CA8IlB;AAED;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,CAEpF;AAED;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,CAErF;AAED;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,CAEpF;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,CAEtF;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,CAEvF"}
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Svelte hooks for HTTP requests, porting React's `useHttp` family.
3
+ *
4
+ * @module
5
+ */
6
+ import { onDestroy } from 'svelte';
7
+ import { writable } from 'svelte/store';
8
+ import { t } from '@molecule/app-i18n';
9
+ import { useHttpClient } from '../context.js';
10
+ import { fieldStore } from './live-store.js';
11
+ /** The previous host's lane, alive until its disarm timer runs. */
12
+ let handoff = null;
13
+ /**
14
+ * HTTP requests with state management, React's `useHttp` in Svelte's idiom:
15
+ * call it during component init under `setMoleculeContext({ http })`.
16
+ *
17
+ * The newest request owns the displayed state: an older response answering
18
+ * after a newer `execute` or `reset` cannot touch it (callbacks still report
19
+ * every request's own outcome). A failure resolves `null` — it never rejects
20
+ * to the caller. `reset` takes ownership too, so a request it superseded
21
+ * cannot repopulate the state. `execute` keeps one identity per mount, and its
22
+ * options are read at call time. `immediate` runs its request once per host,
23
+ * on mount only, even when the host re-mounts the hook with new arguments.
24
+ *
25
+ * @param method - HTTP method.
26
+ * @param url - Request URL.
27
+ * @param options - Request options, read at call time.
28
+ * @returns Request state as stores and the controls.
29
+ * @example
30
+ * ```svelte
31
+ * <script>
32
+ * import { useGet } from '@molecule/app-svelte'
33
+ * const { data, loading, error, execute } = useGet('/api/users')
34
+ * </script>
35
+ *
36
+ * {#if $loading}<Spinner />
37
+ * {:else if $error}<p>{$error.message}</p>
38
+ * {:else}<UserList users={$data} />{/if}
39
+ * ```
40
+ */
41
+ export function useHttp(method, url, options) {
42
+ const client = useHttpClient();
43
+ const immediate = options?.immediate ?? false;
44
+ // A mount in the same turn as the previous host's destroy is React's
45
+ // re-render (an args step), not a new component: adopt its lane so the
46
+ // pending request stays armed and `immediate` does not repeat.
47
+ const adopted = handoff;
48
+ handoff = null;
49
+ const lane = adopted ?? {
50
+ latest: 0,
51
+ ranImmediate: false,
52
+ dead: false,
53
+ state: { data: null, loading: false, error: null },
54
+ sink: null,
55
+ };
56
+ if (adopted)
57
+ adopted.dead = false;
58
+ // The displayed state starts from the lane's last published state (what
59
+ // React's single instance kept), or from the initial one; the lane mirrors
60
+ // exactly what the store shows, so a replacing mount reads the same values.
61
+ const initialState = {
62
+ data: adopted ? lane.state.data : null,
63
+ loading: adopted ? lane.state.loading : immediate,
64
+ error: adopted ? lane.state.error : null,
65
+ };
66
+ const state = writable(initialState);
67
+ lane.state = { ...initialState };
68
+ lane.sink = {
69
+ patch: (next) => {
70
+ if (next.data !== undefined) {
71
+ lane.state.data = next.data;
72
+ state.update((current) => ({ ...current, data: next.data }));
73
+ }
74
+ // Read once into locals: the narrowed type is lost inside the updater
75
+ // closure (`state.update` runs later).
76
+ const loading = next.loading;
77
+ if (loading !== undefined) {
78
+ lane.state.loading = loading;
79
+ state.update((current) => ({ ...current, loading }));
80
+ }
81
+ const error = next.error;
82
+ if (error !== undefined) {
83
+ lane.state.error = error;
84
+ state.update((current) => ({ ...current, error }));
85
+ }
86
+ },
87
+ };
88
+ onDestroy(() => {
89
+ lane.sink = null;
90
+ lane.dead = true;
91
+ // Offer the lane to a mount in the same turn (React's re-render); the
92
+ // timer clears it when no replacement adopted, so a mount after a settled
93
+ // teardown starts fresh.
94
+ handoff = lane;
95
+ const offered = lane;
96
+ setTimeout(() => {
97
+ if (handoff === offered)
98
+ handoff = null;
99
+ }, 0);
100
+ });
101
+ const execute = async () => {
102
+ if (lane.dead)
103
+ return null;
104
+ // Options describe the request being sent, read at call time; method/url/
105
+ // client decide WHICH request execute performs.
106
+ const { immediate: _immediate, onSuccess, onError, ...requestConfig } = options ?? {};
107
+ const request = ++lane.latest;
108
+ // Callbacks report THIS request's outcome (a submit's onSuccess still
109
+ // runs); only the newest request may change what the hook shows.
110
+ const ownsState = () => !lane.dead && request === lane.latest;
111
+ lane.sink?.patch({ loading: true, error: null });
112
+ try {
113
+ let response;
114
+ switch (method) {
115
+ case 'GET':
116
+ response = await client.get(url, requestConfig);
117
+ break;
118
+ case 'POST':
119
+ response = await client.post(url, requestConfig.data, requestConfig);
120
+ break;
121
+ case 'PUT':
122
+ response = await client.put(url, requestConfig.data, requestConfig);
123
+ break;
124
+ case 'PATCH':
125
+ response = await client.patch(url, requestConfig.data, requestConfig);
126
+ break;
127
+ case 'DELETE':
128
+ response = await client.delete(url, requestConfig);
129
+ break;
130
+ default:
131
+ throw new Error(t('svelte.error.unsupportedMethod', { method }, {
132
+ defaultValue: 'Unsupported method: {{method}}',
133
+ }));
134
+ }
135
+ if (!lane.dead) {
136
+ if (ownsState())
137
+ lane.sink?.patch({ data: response.data, loading: false, error: null });
138
+ onSuccess?.(response.data);
139
+ }
140
+ return response.data;
141
+ }
142
+ catch (error) {
143
+ const err = error instanceof Error ? error : new Error(String(error));
144
+ if (!lane.dead) {
145
+ if (ownsState())
146
+ lane.sink?.patch({ data: null, loading: false, error: err });
147
+ onError?.(err);
148
+ }
149
+ return null;
150
+ }
151
+ };
152
+ const reset = () => {
153
+ // reset takes ownership: a request it superseded cannot repopulate.
154
+ lane.latest++;
155
+ lane.sink?.patch({ data: null, loading: false, error: null });
156
+ };
157
+ // Execute immediately if requested — mount only, once per host, the option's
158
+ // historical contract.
159
+ if (immediate && !lane.ranImmediate) {
160
+ lane.ranImmediate = true;
161
+ void execute();
162
+ }
163
+ return {
164
+ data: fieldStore(state, 'data'),
165
+ loading: fieldStore(state, 'loading'),
166
+ error: fieldStore(state, 'error'),
167
+ execute,
168
+ reset,
169
+ };
170
+ }
171
+ /**
172
+ * GET requests, React's `useGet` in Svelte's idiom.
173
+ *
174
+ * @param url - Request URL to fetch from.
175
+ * @param options - HTTP request options including callbacks and request config.
176
+ * @returns Request state as stores and the controls.
177
+ */
178
+ export function useGet(url, options) {
179
+ return useHttp('GET', url, options);
180
+ }
181
+ /**
182
+ * POST requests, React's `usePost` in Svelte's idiom.
183
+ *
184
+ * @param url - Request URL to post to.
185
+ * @param options - HTTP request options including body data and callbacks.
186
+ * @returns Request state as stores and the controls.
187
+ */
188
+ export function usePost(url, options) {
189
+ return useHttp('POST', url, options);
190
+ }
191
+ /**
192
+ * PUT requests, React's `usePut` in Svelte's idiom.
193
+ *
194
+ * @param url - Request URL to send the PUT request to.
195
+ * @param options - HTTP request options including body data and callbacks.
196
+ * @returns Request state as stores and the controls.
197
+ */
198
+ export function usePut(url, options) {
199
+ return useHttp('PUT', url, options);
200
+ }
201
+ /**
202
+ * PATCH requests, React's `usePatch` in Svelte's idiom.
203
+ *
204
+ * @param url - Request URL to send the PATCH request to.
205
+ * @param options - HTTP request options including partial body data and callbacks.
206
+ * @returns Request state as stores and the controls.
207
+ */
208
+ export function usePatch(url, options) {
209
+ return useHttp('PATCH', url, options);
210
+ }
211
+ /**
212
+ * DELETE requests, React's `useDelete` in Svelte's idiom.
213
+ *
214
+ * @param url - Request URL of the resource to delete.
215
+ * @param options - HTTP request options including callbacks.
216
+ * @returns Request state as stores and the controls.
217
+ */
218
+ export function useDelete(url, options) {
219
+ return useHttp('DELETE', url, options);
220
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Svelte hooks for logging, porting React's `useLogger` family.
3
+ *
4
+ * @module
5
+ */
6
+ import type { Logger, LoggerConfig } from '@molecule/app-logger';
7
+ /**
8
+ * Gets a logger instance, React's `useLogger` in Svelte's idiom: called during
9
+ * component init under `setMoleculeContext`, it returns the logger itself (a
10
+ * plain object — there is nothing reactive in a logger).
11
+ *
12
+ * @param name - Logger name (usually component or module name).
13
+ * @param config - Optional logger configuration.
14
+ * @returns Logger instance.
15
+ * @throws {Error} If no logger provider has been set in context.
16
+ * @example
17
+ * ```svelte
18
+ * <script>
19
+ * import { useLogger } from '@molecule/app-svelte'
20
+ * const logger = useLogger('UserProfile')
21
+ * logger.info('Component mounted')
22
+ * </script>
23
+ * ```
24
+ */
25
+ export declare function useLogger(name: string, config?: Partial<LoggerConfig>): Logger;
26
+ /**
27
+ * Gets the root logger, React's `useRootLogger` in Svelte's idiom: called
28
+ * during component init under `setMoleculeContext`.
29
+ *
30
+ * @returns Root logger instance.
31
+ * @throws {Error} If no logger provider has been set in context.
32
+ */
33
+ export declare function useRootLogger(): Logger;
34
+ /**
35
+ * Creates a child logger with additional context, React's `useChildLogger` in
36
+ * Svelte's idiom: called during component init under `setMoleculeContext`.
37
+ *
38
+ * @param parentName - Parent logger name.
39
+ * @param context - Additional context to include in logs.
40
+ * @returns Child logger instance.
41
+ * @throws {Error} If no logger provider has been set in context.
42
+ * @example
43
+ * ```svelte
44
+ * <script>
45
+ * import { useChildLogger } from '@molecule/app-svelte'
46
+ * const logger = useChildLogger('UserList', { component: 'UserList' })
47
+ * logger.withContext({ userId }).info('User clicked')
48
+ * </script>
49
+ * ```
50
+ */
51
+ export declare function useChildLogger(parentName: string, context: Record<string, unknown>): Logger;
52
+ //# sourceMappingURL=useLogger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLogger.d.ts","sourceRoot":"","sources":["../../src/hooks/useLogger.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAIhE;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,MAAM,CAM9E;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAGtC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAI3F"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Svelte hooks for logging, porting React's `useLogger` family.
3
+ *
4
+ * @module
5
+ */
6
+ import { useLoggerProvider } from '../context.js';
7
+ /**
8
+ * Gets a logger instance, React's `useLogger` in Svelte's idiom: called during
9
+ * component init under `setMoleculeContext`, it returns the logger itself (a
10
+ * plain object — there is nothing reactive in a logger).
11
+ *
12
+ * @param name - Logger name (usually component or module name).
13
+ * @param config - Optional logger configuration.
14
+ * @returns Logger instance.
15
+ * @throws {Error} If no logger provider has been set in context.
16
+ * @example
17
+ * ```svelte
18
+ * <script>
19
+ * import { useLogger } from '@molecule/app-svelte'
20
+ * const logger = useLogger('UserProfile')
21
+ * logger.info('Component mounted')
22
+ * </script>
23
+ * ```
24
+ */
25
+ export function useLogger(name, config) {
26
+ const provider = useLoggerProvider();
27
+ if (config) {
28
+ return provider.createLogger({ name, ...config });
29
+ }
30
+ return provider.getLogger(name);
31
+ }
32
+ /**
33
+ * Gets the root logger, React's `useRootLogger` in Svelte's idiom: called
34
+ * during component init under `setMoleculeContext`.
35
+ *
36
+ * @returns Root logger instance.
37
+ * @throws {Error} If no logger provider has been set in context.
38
+ */
39
+ export function useRootLogger() {
40
+ const provider = useLoggerProvider();
41
+ return provider.getLogger();
42
+ }
43
+ /**
44
+ * Creates a child logger with additional context, React's `useChildLogger` in
45
+ * Svelte's idiom: called during component init under `setMoleculeContext`.
46
+ *
47
+ * @param parentName - Parent logger name.
48
+ * @param context - Additional context to include in logs.
49
+ * @returns Child logger instance.
50
+ * @throws {Error} If no logger provider has been set in context.
51
+ * @example
52
+ * ```svelte
53
+ * <script>
54
+ * import { useChildLogger } from '@molecule/app-svelte'
55
+ * const logger = useChildLogger('UserList', { component: 'UserList' })
56
+ * logger.withContext({ userId }).info('User clicked')
57
+ * </script>
58
+ * ```
59
+ */
60
+ export function useChildLogger(parentName, context) {
61
+ const provider = useLoggerProvider();
62
+ const parent = provider.getLogger(parentName);
63
+ return parent.withContext(context);
64
+ }