@andco/sdk-svelte 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 2026 Andco
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 ADDED
@@ -0,0 +1,168 @@
1
+ # `@andco/sdk-svelte`
2
+
3
+ Svelte 5 bindings for `@andco/sdk`, implemented with runes, callback props,
4
+ and Svelte context.
5
+
6
+ Svelte creates and owns the iframe. The package does not wrap a Web Component or
7
+ delegate rendering to a shared DOM function.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ pnpm add @andco/sdk-svelte svelte
13
+ ```
14
+
15
+ ## Configure a subtree
16
+
17
+ `AndcoProvider` either builds the Andco Instance for you from `clientOptions`, or takes an
18
+ instance you already own via `client` (useful when the application builds it with
19
+ `createAndcoInstanceForBrowser` from `@andco/sdk/browser` itself, or on a server-rendered app
20
+ that wants to hand the provider a session resolved ahead of time via `initialSession`):
21
+
22
+ ```svelte
23
+ <script lang="ts">
24
+ import { AndcoProvider } from "@andco/sdk-svelte";
25
+
26
+ import App from "./App.svelte";
27
+
28
+ const clientOptions = {
29
+ clientId: "client_123",
30
+ endpointAuth: "https://auth.example.com",
31
+ endpointApi: "https://api.example.com",
32
+ endpointWidget: "https://widgets.example.com",
33
+ redirectTo: "https://app.example.com/auth/callback",
34
+ initialScopes: ["openid", "email", "profile"],
35
+ locale: "es-CL",
36
+ };
37
+ </script>
38
+
39
+ <AndcoProvider {clientOptions}>
40
+ <App />
41
+ </AndcoProvider>
42
+ ```
43
+
44
+ `clientOptions` is the same `AndcoBrowserOptions` shape `createAndcoInstanceForBrowser` takes
45
+ (everything `AndcoClientOptions` accepts, minus the server-only `presenter`/`source`/`clientSecret`
46
+ fields), so `allowedPopupOrigins`, `apiVersion`, `theme`, `themeMode`, `detectSessionInUrl`, and the
47
+ rest of that type belong here too when needed — there is no separate function or component prop for
48
+ them.
49
+
50
+ ## Hosted sign-in
51
+
52
+ Svelte 5 callback props use lowercase DOM-style names. `AndcoButton` takes its client, endpoints,
53
+ and theme from the `<AndcoProvider>` context, not from props — the only thing a per-render sign-in
54
+ needs to pass is `authorization`, the same request-local options `auth.signIn` accepts (`scopes`,
55
+ `redirectTo`, `orgId`, `authorizationDetails`, `resource`, …):
56
+
57
+ ```svelte
58
+ <script lang="ts">
59
+ import { AndcoButton } from "@andco/sdk-svelte";
60
+ let message = $state<string>();
61
+ </script>
62
+
63
+ <AndcoButton
64
+ authorization={{ scopes: ["openid", "email", "profile"] }}
65
+ oncomplete={() => console.log("Authorized")}
66
+ onerror={(error) => (message = error.message)}
67
+ />
68
+ ```
69
+
70
+ Available callbacks are `onready`, `onactivate`, `oncomplete`, `ondismiss`, and `onerror`. There is
71
+ no `onstatechange` — read `useAndcoSession()` instead if a component needs to react to every state
72
+ change, including a silent token rotation.
73
+
74
+ ## Reactive session
75
+
76
+ ```svelte
77
+ <script lang="ts">
78
+ import { useAndco, useAndcoSession, useAndcoUser } from "@andco/sdk-svelte";
79
+
80
+ const andco = useAndco();
81
+ const session = useAndcoSession();
82
+ const user = useAndcoUser();
83
+ </script>
84
+
85
+ {#if user.current}
86
+ <p>Signed in as {user.current.name ?? user.current.email}</p>
87
+ <button type="button" onclick={() => void andco.current.auth.signOut()}>Sign out</button>
88
+ {/if}
89
+ ```
90
+
91
+ Every hook returns `{ readonly current }` rather than a raw value, because a
92
+ rune's reactivity does not survive being returned by value — read `.current`
93
+ directly from markup and derived runes.
94
+
95
+ `useAndco().current` is `AndcoClient | AndcoClientAuthed` and changes
96
+ reference exactly when the Authorized Identity does — sign-in, sign-out, a
97
+ widened Grant — and stays the same reference across a token rotation, which is
98
+ why an `$effect` reading `andco.current` re-runs on a sign-in but not on a
99
+ silent refresh. `useAndcoAuthed().current` is the same change rule narrowed to
100
+ `AndcoClientAuthed | null`, for the "do this once signed in" path.
101
+
102
+ `useAndcoSession().current` changes on *every* republication, rotations
103
+ included — reach for it when you need the credential as data, such as an
104
+ expiry, or to observe the unresolved-to-anonymous transition `useAndco`
105
+ deliberately hides. `useAndcoUser().current` changes only when the person
106
+ changes — identifier, name, email, or avatar.
107
+
108
+ ## Progressive scopes
109
+
110
+ ```svelte
111
+ {#if session.current && !session.current.scopes.includes("bank_accounts:read")}
112
+ <AndcoButton authorization={{ scopes: ["openid", "email", "profile", "bank_accounts:read"] }} />
113
+ {/if}
114
+ ```
115
+
116
+ ## Intents
117
+
118
+ `andco.intents` is domain-neutral: it only knows how to create, read, execute, and observe an
119
+ Intent generically, regardless of the domain that Intent belongs to. Bind it to the signed-in
120
+ identity once, then use it directly:
121
+
122
+ ```svelte
123
+ <script lang="ts">
124
+ import { useAndcoAuthed } from "@andco/sdk-svelte";
125
+
126
+ const andco = useAndcoAuthed();
127
+ </script>
128
+ ```
129
+
130
+ ```svelte
131
+ <script lang="ts">
132
+ async function topUp() {
133
+ if (!andco.current) return;
134
+ const { data: intent, error } = await andco.current.intents.create(
135
+ "deposit",
136
+ {
137
+ expires_in: "30 minutes",
138
+ amount: { currency: "CLP", suggested: "40000", editable: false },
139
+ note: { suggested: "Wallet top-up", editable: true },
140
+ metadata: { merchant_transaction_id: "deposit_8472" },
141
+ },
142
+ { idempotencyKey: "deposit:8472" },
143
+ );
144
+ if (error) throw error;
145
+ }
146
+ </script>
147
+
148
+ <button type="button" onclick={() => void topUp()}>Top up</button>
149
+ ```
150
+
151
+ `AndcoIntentButton` renders the same hosted iframe as `AndcoButton`, with its `flow` fixed to
152
+ `"intent"` — the Hosted Intent Presentation is the canonical way a person confirms an Intent, and
153
+ its DOM and code stay Andco's, never the Project's. It takes the same props as `AndcoButton`
154
+ (`authorization`, `busy`, `disabled`, `locale`, `release`, `themeMode`, and the `onready` /
155
+ `onactivate` / `oncomplete` / `ondismiss` / `onerror` callbacks); there is currently no prop to
156
+ target a specific, already-created Intent, and `oncomplete` takes no arguments — read the Intent's
157
+ state with `andco.current.intents.get(intentId)` after it fires, or through
158
+ `andco.current.intents.events(intentId)` / `andco.current.intents.subscribe(...)`, rather than
159
+ expecting it on the callback.
160
+
161
+ ```svelte
162
+ <AndcoIntentButton onerror={(error) => console.error(error.message)} />
163
+ ```
164
+
165
+ See [`apps/example-svelte`](../../apps/example-svelte/README.md) for the complete
166
+ session → Grant → resource flow.
167
+
168
+ There is no separate hosted-vs-direct pair of Intent buttons — `AndcoIntentButton` is the only one.
@@ -0,0 +1,97 @@
1
+ <script lang="ts">
2
+ import type { AndcoError } from "@andco/sdk";
3
+ import {
4
+ AndcoButtonController,
5
+ type AndcoButtonControllerOptions,
6
+ type AndcoButtonSnapshot,
7
+ } from "@andco/sdk/browser";
8
+ import type { HTMLIframeAttributes } from "svelte/elements";
9
+ import { andcoContext } from "./context.svelte.js";
10
+
11
+ type Options = AndcoButtonControllerOptions;
12
+ type Props = Omit<HTMLIframeAttributes, "onerror" | "referrerpolicy" | "sandbox" | "src" | "srcdoc"> &
13
+ Pick<Options, "authorization" | "busy" | "disabled" | "flow" | "locale" | "release" | "themeMode"> & {
14
+ onready?: Options["onReady"];
15
+ onactivate?: Options["onActivate"];
16
+ oncomplete?: () => void;
17
+ ondismiss?: () => void;
18
+ onerror?: (error: AndcoError) => void;
19
+ };
20
+
21
+ let {
22
+ authorization,
23
+ busy,
24
+ disabled,
25
+ flow,
26
+ locale,
27
+ release,
28
+ themeMode,
29
+ onready,
30
+ onactivate,
31
+ oncomplete,
32
+ ondismiss,
33
+ onerror,
34
+ title = "Andco",
35
+ ...attributes
36
+ }: Props = $props();
37
+
38
+ // The stable instance, read directly off the context rather than through `useAndco`: the bridge
39
+ // controller must not be rebuilt on sign-in.
40
+ const client = andcoContext().client;
41
+ let iframe = $state<HTMLIFrameElement>();
42
+ let snapshot = $state<AndcoButtonSnapshot>();
43
+ let controller = $state<AndcoButtonController>();
44
+
45
+ $effect(() => {
46
+ const next = new AndcoButtonController({
47
+ client,
48
+ ...(authorization ? { authorization } : {}),
49
+ ...(flow ? { flow } : {}),
50
+ ...(release === undefined ? {} : { release }),
51
+ ...(themeMode ? { themeMode } : {}),
52
+ ...(locale ? { locale } : {}),
53
+ ...(disabled === undefined ? {} : { disabled }),
54
+ ...(busy === undefined ? {} : { busy }),
55
+ onReady: (event) => onready?.(event),
56
+ onActivate: (event) => onactivate?.(event),
57
+ onComplete: () => oncomplete?.(),
58
+ onDismiss: () => ondismiss?.(),
59
+ onError: (error) => onerror?.(error),
60
+ });
61
+ controller = next;
62
+ const stop = next.subscribe((value) => {
63
+ snapshot = value;
64
+ });
65
+ return () => {
66
+ stop();
67
+ next.destroy();
68
+ controller = undefined;
69
+ };
70
+ });
71
+
72
+ // The controller's returned disconnect is the effect's cleanup, which is the whole reason every
73
+ // subscription in this SDK answers with a plain function.
74
+ //
75
+ // It depends on the element and the controller only. Reading the snapshot here would close a
76
+ // cycle, because connecting publishes a new snapshot; the bridge already re-runs its handshake on
77
+ // the iframe's own `load`, so a URL change needs no reconnection from here.
78
+ $effect(() => {
79
+ if (!iframe || !controller) return;
80
+ return controller.connect(iframe);
81
+ });
82
+ </script>
83
+
84
+ <!--
85
+ A bare iframe is 300x150 with a border, and the hosted control fills whatever box it is given, so
86
+ without a default the application sees a bordered grey slab. A `style` on the component wins.
87
+ -->
88
+ <iframe
89
+ style="border:0;display:block;height:3rem;width:18rem"
90
+ {...attributes}
91
+ bind:this={iframe}
92
+ hidden={!snapshot?.ready}
93
+ referrerpolicy="no-referrer"
94
+ sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"
95
+ src={snapshot?.iframeURL}
96
+ {title}
97
+ ></iframe>
@@ -0,0 +1,14 @@
1
+ import type { AndcoError } from "@andco/sdk";
2
+ import { type AndcoButtonControllerOptions } from "@andco/sdk/browser";
3
+ import type { HTMLIframeAttributes } from "svelte/elements";
4
+ type Options = AndcoButtonControllerOptions;
5
+ type Props = Omit<HTMLIframeAttributes, "onerror" | "referrerpolicy" | "sandbox" | "src" | "srcdoc"> & Pick<Options, "authorization" | "busy" | "disabled" | "flow" | "locale" | "release" | "themeMode"> & {
6
+ onready?: Options["onReady"];
7
+ onactivate?: Options["onActivate"];
8
+ oncomplete?: () => void;
9
+ ondismiss?: () => void;
10
+ onerror?: (error: AndcoError) => void;
11
+ };
12
+ declare const AndCoButton: import("svelte").Component<Props, {}, "">;
13
+ type AndCoButton = ReturnType<typeof AndCoButton>;
14
+ export default AndCoButton;
@@ -0,0 +1,9 @@
1
+ <script lang="ts">
2
+ import AndcoButton from "./AndCoButton.svelte";
3
+
4
+ // The same hosted control in its Intent flow, not a parallel implementation. Two implementations
5
+ // of one presentation is what let the previous direct and hosted paths drift apart.
6
+ let props = $props();
7
+ </script>
8
+
9
+ <AndcoButton {...props} flow="intent" />
@@ -0,0 +1,3 @@
1
+ declare const AndCoIntentButton: import("svelte").Component<$$ComponentProps, {}, "">;
2
+ type AndCoIntentButton = ReturnType<typeof AndCoIntentButton>;
3
+ export default AndCoIntentButton;
@@ -0,0 +1,51 @@
1
+ <script lang="ts">
2
+ import type { AndcoClient, AndcoSession } from "@andco/sdk";
3
+ import { type AndcoBrowserOptions, createAndcoInstanceForBrowser } from "@andco/sdk/browser";
4
+ import type { Snippet } from "svelte";
5
+ import { setAndcoContext } from "./context.svelte.js";
6
+
7
+ type Props = {
8
+ children: Snippet;
9
+ clientOptions?: AndcoBrowserOptions;
10
+ /** An instance the application already owns. Wins when both are given. */
11
+ client?: AndcoClient;
12
+ /** A session the server already resolved, so the first frame is real rather than unresolved. */
13
+ initialSession?: AndcoSession | null;
14
+ };
15
+
16
+ let { children, client, clientOptions, initialSession }: Props = $props();
17
+
18
+ // svelte-ignore state_referenced_locally
19
+ //
20
+ // Capturing the initial values is the intent. An Andco Instance is a value identified by its
21
+ // configuration, and its store may already be loading; rebuilding it because a prop changed
22
+ // would throw that away and, on a callback page, discard a single-use authorization code. An
23
+ // application that genuinely needs a different configuration mounts a different provider.
24
+ if (!client && !clientOptions) throw new Error("AndcoProvider requires either clientOptions or client");
25
+
26
+ // svelte-ignore state_referenced_locally
27
+ const instance =
28
+ client ??
29
+ createAndcoInstanceForBrowser({
30
+ ...(clientOptions as AndcoBrowserOptions),
31
+ ...(initialSession === undefined ? {} : { initialSession }),
32
+ });
33
+
34
+ let session = $state<AndcoSession | null | undefined>(instance.session.getSnapshot());
35
+
36
+ // Subscribing is what starts the load, and the returned function is the cleanup.
37
+ $effect(() =>
38
+ instance.session.subscribe(() => {
39
+ session = instance.session.getSnapshot();
40
+ }),
41
+ );
42
+
43
+ setAndcoContext({
44
+ client: instance,
45
+ get session() {
46
+ return session;
47
+ },
48
+ });
49
+ </script>
50
+
51
+ {@render children()}
@@ -0,0 +1,14 @@
1
+ import type { AndcoClient, AndcoSession } from "@andco/sdk";
2
+ import { type AndcoBrowserOptions } from "@andco/sdk/browser";
3
+ import type { Snippet } from "svelte";
4
+ type Props = {
5
+ children: Snippet;
6
+ clientOptions?: AndcoBrowserOptions;
7
+ /** An instance the application already owns. Wins when both are given. */
8
+ client?: AndcoClient;
9
+ /** A session the server already resolved, so the first frame is real rather than unresolved. */
10
+ initialSession?: AndcoSession | null;
11
+ };
12
+ declare const AndCoProvider: import("svelte").Component<Props, {}, "">;
13
+ type AndCoProvider = ReturnType<typeof AndCoProvider>;
14
+ export default AndCoProvider;
@@ -0,0 +1,84 @@
1
+ import { type AndcoClient, type AndcoClientAuthed, type AndcoSession, type AndcoUser } from "@andco/sdk";
2
+ export type AndcoSvelteContext = {
3
+ /** The instance. One reference for the provider's lifetime — never `with(...)` or `authorized()`. */
4
+ readonly client: AndcoClient;
5
+ readonly session: AndcoSession | null | undefined;
6
+ };
7
+ export declare function setAndcoContext(context: AndcoSvelteContext): void;
8
+ /**
9
+ * The raw context: the stable instance plus the raw session.
10
+ *
11
+ * Not exported from the package. It exists for components inside this package — {@link AndCoButton}
12
+ * in particular — that need the stable instance without going through {@link useAndco}, which hands
13
+ * out a new reference on sign-in and would rebuild the bridge for no reason.
14
+ */
15
+ export declare function andcoContext(): AndcoSvelteContext;
16
+ /**
17
+ * Reads the Andco Instance, as a value that changes when the Authorized Identity does.
18
+ *
19
+ * Start here. The instance carries the methods and resolves the token, so this is what an
20
+ * `$effect` or a `$derived` is usually written against, and reading it does what it reads like:
21
+ * the effect re-runs on sign-in, on sign-out, and when granted scopes change. It does *not* re-run
22
+ * on a token rotation, which changes no answer this instance would give.
23
+ *
24
+ * While there is no Authorized Identity — the session is unresolved or anonymous — `current` is the
25
+ * instance itself, `isAuthed === false`, and that reference is stable across the
26
+ * unresolved-to-anonymous transition. An effect that must react to *that* transition reads
27
+ * {@link useAndcoSession} instead, since `useAndco` deliberately does not change reference for it.
28
+ *
29
+ * Behind a getter, because a rune's reactivity does not survive being returned by value. See
30
+ * {@link useAndcoAuthed} for the same change rule narrowed to `null` while signed out, and
31
+ * {@link useAndcoUser} for the person alone.
32
+ *
33
+ * @example
34
+ * ```svelte
35
+ * const andco = useAndco();
36
+ * $effect(() => { void andco.current; loadAccounts(); });
37
+ * ```
38
+ */
39
+ export declare function useAndco(): {
40
+ readonly current: AndcoClient | AndcoClientAuthed;
41
+ };
42
+ /**
43
+ * Reads the authorized arm of the Andco Instance, or `null` while there is no Authorized Identity.
44
+ *
45
+ * Same change rule as {@link useAndco}: a new reference on sign-in, on sign-out, and on a widened
46
+ * Grant, and the same reference across a token rotation. Reach for this instead of `useAndco` when
47
+ * the common "do this once signed in" path should need no guard beyond a null check — `current` is
48
+ * `null` for both the unresolved and the anonymous session, so the distinction between them is not
49
+ * observable here; read {@link useAndcoSession} when it matters.
50
+ *
51
+ * @example
52
+ * ```svelte
53
+ * const andco = useAndcoAuthed();
54
+ * $effect(() => {
55
+ * if (andco.current) loadAccounts(andco.current);
56
+ * });
57
+ * ```
58
+ */
59
+ export declare function useAndcoAuthed(): {
60
+ readonly current: AndcoClientAuthed | null;
61
+ };
62
+ /**
63
+ * The current session, as three distinct states.
64
+ *
65
+ * `undefined` means the store has not finished loading; `null` means signed out. Rendering them the
66
+ * same way flashes a signed-out state on every load. Unlike {@link useAndco}, this changes on
67
+ * *every* republication — including a silent token rotation — because whoever reads it is reading
68
+ * the credential as data, not asking whether the Authorized Identity changed.
69
+ *
70
+ * Returned behind a getter because a rune's reactivity does not survive being returned by value.
71
+ */
72
+ export declare function useAndcoSession(): {
73
+ readonly current: AndcoSession | null | undefined;
74
+ };
75
+ /**
76
+ * The authenticated person, or `null`/`undefined` sharing {@link useAndcoSession}'s three states.
77
+ *
78
+ * Changes reference only when the person changes — identifier, name, email, or avatar — never on a
79
+ * token rotation and never on a widened Grant, so an effect keyed on it does not reload a profile
80
+ * for a change the person did not make. See {@link useAndco} for the client itself.
81
+ */
82
+ export declare function useAndcoUser(): {
83
+ readonly current: AndcoUser | null | undefined;
84
+ };
@@ -0,0 +1,143 @@
1
+ import { sessionIdentityKey, } from "@andco/sdk";
2
+ import { createContext } from "svelte";
3
+ const [get, set] = createContext();
4
+ export function setAndcoContext(context) {
5
+ set(context);
6
+ }
7
+ /**
8
+ * The raw context: the stable instance plus the raw session.
9
+ *
10
+ * Not exported from the package. It exists for components inside this package — {@link AndCoButton}
11
+ * in particular — that need the stable instance without going through {@link useAndco}, which hands
12
+ * out a new reference on sign-in and would rebuild the bridge for no reason.
13
+ */
14
+ export function andcoContext() {
15
+ try {
16
+ return get();
17
+ }
18
+ catch {
19
+ throw new Error("useAndco requires an <AndcoProvider> above it");
20
+ }
21
+ }
22
+ /**
23
+ * Reads the Andco Instance, as a value that changes when the Authorized Identity does.
24
+ *
25
+ * Start here. The instance carries the methods and resolves the token, so this is what an
26
+ * `$effect` or a `$derived` is usually written against, and reading it does what it reads like:
27
+ * the effect re-runs on sign-in, on sign-out, and when granted scopes change. It does *not* re-run
28
+ * on a token rotation, which changes no answer this instance would give.
29
+ *
30
+ * While there is no Authorized Identity — the session is unresolved or anonymous — `current` is the
31
+ * instance itself, `isAuthed === false`, and that reference is stable across the
32
+ * unresolved-to-anonymous transition. An effect that must react to *that* transition reads
33
+ * {@link useAndcoSession} instead, since `useAndco` deliberately does not change reference for it.
34
+ *
35
+ * Behind a getter, because a rune's reactivity does not survive being returned by value. See
36
+ * {@link useAndcoAuthed} for the same change rule narrowed to `null` while signed out, and
37
+ * {@link useAndcoUser} for the person alone.
38
+ *
39
+ * @example
40
+ * ```svelte
41
+ * const andco = useAndco();
42
+ * $effect(() => { void andco.current; loadAccounts(); });
43
+ * ```
44
+ */
45
+ export function useAndco() {
46
+ const value = andcoContext();
47
+ // `$derived` rather than a manually cached getter: Svelte only re-notifies a dependent `$effect`
48
+ // when a derived's *value* changes, so computing the identity as its own derived and the view as
49
+ // a derived over that is what makes a rotation — same identity string, new session object — a
50
+ // no-op for anything reading `current`, instead of merely returning a stable reference to an
51
+ // effect that already reran.
52
+ const identity = $derived(sessionIdentityKey(value.session));
53
+ const view = $derived.by(() => identity === "unresolved" || identity === "anonymous" ? value.client : value.client.authorized());
54
+ return {
55
+ get current() {
56
+ return view;
57
+ },
58
+ };
59
+ }
60
+ /**
61
+ * Reads the authorized arm of the Andco Instance, or `null` while there is no Authorized Identity.
62
+ *
63
+ * Same change rule as {@link useAndco}: a new reference on sign-in, on sign-out, and on a widened
64
+ * Grant, and the same reference across a token rotation. Reach for this instead of `useAndco` when
65
+ * the common "do this once signed in" path should need no guard beyond a null check — `current` is
66
+ * `null` for both the unresolved and the anonymous session, so the distinction between them is not
67
+ * observable here; read {@link useAndcoSession} when it matters.
68
+ *
69
+ * @example
70
+ * ```svelte
71
+ * const andco = useAndcoAuthed();
72
+ * $effect(() => {
73
+ * if (andco.current) loadAccounts(andco.current);
74
+ * });
75
+ * ```
76
+ */
77
+ export function useAndcoAuthed() {
78
+ const value = andcoContext();
79
+ const identity = $derived(sessionIdentityKey(value.session));
80
+ const view = $derived.by(() => identity === "unresolved" || identity === "anonymous" ? null : value.client.authorized());
81
+ return {
82
+ get current() {
83
+ return view;
84
+ },
85
+ };
86
+ }
87
+ /**
88
+ * The current session, as three distinct states.
89
+ *
90
+ * `undefined` means the store has not finished loading; `null` means signed out. Rendering them the
91
+ * same way flashes a signed-out state on every load. Unlike {@link useAndco}, this changes on
92
+ * *every* republication — including a silent token rotation — because whoever reads it is reading
93
+ * the credential as data, not asking whether the Authorized Identity changed.
94
+ *
95
+ * Returned behind a getter because a rune's reactivity does not survive being returned by value.
96
+ */
97
+ export function useAndcoSession() {
98
+ const value = andcoContext();
99
+ return {
100
+ get current() {
101
+ return value.session;
102
+ },
103
+ };
104
+ }
105
+ /**
106
+ * The authenticated person, or `null`/`undefined` sharing {@link useAndcoSession}'s three states.
107
+ *
108
+ * Changes reference only when the person changes — identifier, name, email, or avatar — never on a
109
+ * token rotation and never on a widened Grant, so an effect keyed on it does not reload a profile
110
+ * for a change the person did not make. See {@link useAndco} for the client itself.
111
+ */
112
+ export function useAndcoUser() {
113
+ const value = andcoContext();
114
+ let cached;
115
+ // `$derived.by` for the same reason as `useAndco`: recomputing on every session read is fine, but
116
+ // handing back `cached` unchanged is what stops a dependent `$effect` from re-running on a
117
+ // rotation, since Svelte compares the derived's produced value, not what was read to produce it.
118
+ const user = $derived.by(() => {
119
+ const session = value.session;
120
+ if (session === undefined) {
121
+ cached = undefined;
122
+ return cached;
123
+ }
124
+ if (session === null) {
125
+ cached = null;
126
+ return cached;
127
+ }
128
+ const next = session.user;
129
+ if (!cached ||
130
+ cached.id !== next.id ||
131
+ cached.name !== next.name ||
132
+ cached.email !== next.email ||
133
+ cached.avatarUrl !== next.avatarUrl) {
134
+ cached = next;
135
+ }
136
+ return cached;
137
+ });
138
+ return {
139
+ get current() {
140
+ return user;
141
+ },
142
+ };
143
+ }
@@ -0,0 +1,4 @@
1
+ export { default as AndcoButton } from "./AndCoButton.svelte";
2
+ export { default as AndcoIntentButton } from "./AndCoIntentButton.svelte";
3
+ export { default as AndcoProvider } from "./AndCoProvider.svelte";
4
+ export { type AndcoSvelteContext, setAndcoContext, useAndco, useAndcoAuthed, useAndcoSession, useAndcoUser, } from "./context.svelte.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { default as AndcoButton } from "./AndCoButton.svelte";
2
+ export { default as AndcoIntentButton } from "./AndCoIntentButton.svelte";
3
+ export { default as AndcoProvider } from "./AndCoProvider.svelte";
4
+ export { setAndcoContext, useAndco, useAndcoAuthed, useAndcoSession, useAndcoUser, } from "./context.svelte.js";
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@andco/sdk-svelte",
3
+ "version": "0.0.1",
4
+ "private": false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "sideEffects": false,
10
+ "svelte": "./dist/index.js",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "svelte": "./dist/index.js",
15
+ "import": "./dist/index.js",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "peerDependencies": {
23
+ "svelte": "^5.0.0"
24
+ },
25
+ "dependencies": {
26
+ "@andco/sdk": "0.0.1"
27
+ },
28
+ "devDependencies": {
29
+ "@sveltejs/package": "^2.0.0",
30
+ "@sveltejs/vite-plugin-svelte": "^7.3.0",
31
+ "svelte": "^5.57.1",
32
+ "svelte-check": "^4.0.0",
33
+ "typescript": "^6.0.3",
34
+ "vite": "^8.3.0",
35
+ "vitest": "^5.0.1"
36
+ },
37
+ "license": "Apache-2.0",
38
+ "description": "Svelte bindings for the Andco SDK.",
39
+ "scripts": {
40
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
41
+ "build": "pnpm run clean && svelte-package",
42
+ "dev": "svelte-package --watch",
43
+ "check-types": "svelte-check --tsconfig ./tsconfig.json",
44
+ "lint": "svelte-check --tsconfig ./tsconfig.json",
45
+ "test": "vitest run"
46
+ }
47
+ }