@fingerly/svelte 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,303 @@
1
- # Temporary Holding Version
1
+ # @fingerly/svelte
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Svelte bindings for the Fingerly SDK. One state per app, held in Svelte's
4
+ context, read as plain reactive properties.
5
+
6
+ Requires Svelte **5**. The state is built with runes, which is what lets a
7
+ component read `fingerly.verdicts` and re-render with no store, no subscription
8
+ and no `$` prefix at the call site.
9
+
10
+ ```
11
+ pnpm add @fingerly/svelte
12
+ ```
13
+
14
+ ## Set it up
15
+
16
+ ```svelte
17
+ <!-- +layout.svelte, or your root component -->
18
+ <script lang="ts">
19
+ import { setupFingerly } from '@fingerly/svelte'
20
+
21
+ // consent: 'granted' only once you have consent (or another lawful basis)
22
+ setupFingerly({ apiKey: 'fly_pk_production_…', consent: 'granted' })
23
+ </script>
24
+
25
+ <slot />
26
+ ```
27
+
28
+ The key is a **public** SDK key from the dashboard, and it belongs in the page —
29
+ it is scoped to the origins you list, which is what makes it safe there. A
30
+ **secret** key is refused if it arrives with an `Origin`, so pasting one here
31
+ does not work by design.
32
+
33
+ Setting up collects nothing. It makes the client reachable and no more; when to
34
+ identify is the page's decision. Like every Svelte context call it has to run
35
+ during component initialisation — a `<script>` block, not an event handler and
36
+ not an `$effect`.
37
+
38
+ Consent defaults to `pending`, and nothing is collected or sent until it is
39
+ `granted`. A page with a consent banner leaves it `pending` and calls
40
+ `setConsent('granted')` once the banner is accepted; see
41
+ [Waiting for consent](#waiting-for-consent).
42
+
43
+ ## Identify
44
+
45
+ ```svelte
46
+ <script lang="ts">
47
+ import { useIdentify } from '@fingerly/svelte'
48
+
49
+ const fingerly = useIdentify()
50
+
51
+ async function submit() {
52
+ await fingerly.identify()
53
+
54
+ if (fingerly.isSuspicious) {
55
+ // step up to MFA, hold for review, add friction
56
+ }
57
+ }
58
+ </script>
59
+
60
+ <button onclick={submit} disabled={fingerly.isLoading}>
61
+ {fingerly.isLoading ? 'Checking…' : 'Continue'}
62
+ </button>
63
+
64
+ {#if fingerly.error}<p>{fingerly.error.message}</p>{/if}
65
+ ```
66
+
67
+ `identify()` collects, scores locally, and submits. It resolves as soon as the
68
+ server has a receipt — IP geolocation and the velocity windows are computed
69
+ after the response, so what comes back is a `requestId` rather than a finished
70
+ event.
71
+
72
+ ### On mount instead
73
+
74
+ ```svelte
75
+ <script lang="ts">
76
+ const fingerly = useIdentify({ immediate: true })
77
+ </script>
78
+ ```
79
+
80
+ `immediate` runs in an `$effect`, which is what makes it **safe under SSR** —
81
+ effects do not run during a server render, so a SvelteKit page using this
82
+ renders on the server and collects on the client with no guard of its own.
83
+
84
+ Pass it in as many components as want it. The state is shared, so the second
85
+ and third callers get the first one's answer rather than starting their own
86
+ submission.
87
+
88
+ ## One identification per page
89
+
90
+ The state lives in context, not in each `useIdentify()` call. Three components
91
+ asking whether the visitor is suspicious produce **one** submission, one
92
+ `requestId`, and one line on your bill:
93
+
94
+ ```svelte
95
+ <!-- Header.svelte, CheckoutForm.svelte, RiskBanner.svelte — all three: -->
96
+ const fingerly = useIdentify({ immediate: true })
97
+ <!-- → one network request, one shared answer -->
98
+ ```
99
+
100
+ Context rather than a module-level singleton, and the reason is the server: a
101
+ module-level state on a SvelteKit server is shared by every request the process
102
+ renders. Context is per component tree, and a component tree is per request.
103
+
104
+ To deliberately identify again — a long-lived app reaching a second checkout:
105
+
106
+ ```svelte
107
+ await fingerly.refresh() // ignores the cached result and collects afresh
108
+ ```
109
+
110
+ ## A single verdict
111
+
112
+ ```svelte
113
+ <script lang="ts">
114
+ import { useVerdict } from '@fingerly/svelte'
115
+
116
+ const automation = useVerdict('automation')
117
+ </script>
118
+
119
+ {#if automation.matched}
120
+ <aside>
121
+ Automated access suspected ({automation.confidence})
122
+ <ul>{#each automation.reasons as reason (reason)}<li>{reason}</li>{/each}</ul>
123
+ </aside>
124
+ {/if}
125
+ ```
126
+
127
+ Names: `incognito` · `tor` · `emulator` · `automation` · `farm`.
128
+
129
+ `matched` requires **medium confidence or better** by default. A
130
+ `low`-confidence verdict is a single weak tell — one removable flag, or one
131
+ countermeasure a privacy-conscious real user might equally be running — and
132
+ acting on it would generate false positives. Raise or lower it explicitly:
133
+
134
+ ```ts
135
+ const tor = useVerdict('tor', { min: 'high' }) // block only when certain
136
+ const tor = useVerdict('tor', { min: 'low' }) // observe everything
137
+ ```
138
+
139
+ Both arguments accept a getter as well as a value, because this is called once
140
+ when the component initialises and its arguments may be props that change after
141
+ that:
142
+
143
+ ```svelte
144
+ const verdict = useVerdict(() => name, { min: () => threshold })
145
+ ```
146
+
147
+ ## A correlation tag
148
+
149
+ Echoed back on the finished event so you can match a submission to whatever the
150
+ page was doing. It accepts a getter, and is read at submission time rather than
151
+ at initialisation:
152
+
153
+ ```ts
154
+ const fingerly = useIdentify({ tag: () => `checkout:${page.params.orderId}` })
155
+ ```
156
+
157
+ ## Collect without submitting
158
+
159
+ For a page that wants the local verdicts and nothing else:
160
+
161
+ ```ts
162
+ setupFingerly({ apiKey: 'fly_pk_production_…', submit: false })
163
+ ```
164
+
165
+ Everything the server decides comes back empty: no `requestId`, no `visitorId`,
166
+ and `suspectScore` is `null` rather than `0`. That is the honest answer rather
167
+ than a gap — nothing was sent, so nobody scored it, and a `0` would read as
168
+ "scored, found nothing".
169
+
170
+ ## Waiting for consent
171
+
172
+ If identifying a visitor needs their consent first, set up with `consent:
173
+ 'pending'`, the default. Until it is `granted` nothing is collected and nothing is sent:
174
+ `useIdentify({ immediate: true })` waits, and the client is not even built.
175
+
176
+ ```ts
177
+ const fingerly = setupFingerly({ apiKey: 'fly_pk_production_…', consent: 'pending' })
178
+ ```
179
+
180
+ Then set it from wherever your consent tool reports the answer:
181
+
182
+ ```ts
183
+ fingerly.setConsent('granted') // from the consent tool's callback
184
+
185
+ const client = await fingerly.client()
186
+ client.setConsent('denied') // the same, on the client itself
187
+ ```
188
+
189
+ - `consent`: `'pending'` (the default), `'granted'` or `'denied'`, an option to
190
+ `setupFingerly()` and `createFingerly()`.
191
+ - `setConsent(state)`: on the object `setupFingerly()`, `useFingerly()` and
192
+ `useIdentify()` return, and on the client. Synchronous, and setting the
193
+ current value again does nothing.
194
+ - `fingerly.consent`: the current state, reactive, for rendering a banner.
195
+
196
+ Setting `granted` starts the identification that was waiting, once. `pending`
197
+ and `denied` behave the same. Withdrawing consent while an identification is
198
+ running stops it before it submits, and it fails with a `ConsentError`.
199
+
200
+ ## What you get back
201
+
202
+ ```ts
203
+ const fingerly = useIdentify()
204
+
205
+ fingerly.requestId // string | null — identifies this submission
206
+ fingerly.visitorId // string | null — who the server decided this is
207
+ fingerly.visitorIsNew // boolean — never seen before
208
+ fingerly.visitorConfidence // number — 0 to 100
209
+ fingerly.identifiable // boolean — false when the signals were too thin
210
+ fingerly.duplicate // boolean — answered before; this is the first answer
211
+ fingerly.state // string | null — the server's disposition
212
+ fingerly.reason // string | null — why, when state needs explaining
213
+ fingerly.suspectScore // number | null — null when nothing scored it
214
+ fingerly.suspectLevel // string | null — low, medium, high
215
+ fingerly.triggers // IdentifyTrigger[] — what the server scored on
216
+ fingerly.verdicts // Verdicts | null — the five local verdicts
217
+ fingerly.report // SignalReport | null — every source, with status and timing
218
+ fingerly.error // Error | null
219
+ fingerly.consent // ConsentState (granted, pending or denied)
220
+ fingerly.isLoading // boolean
221
+ fingerly.isReady // boolean — finished, successfully or not
222
+ fingerly.isSuspicious // boolean — any verdict at medium+
223
+ fingerly.identify() // Promise<IdentifyResult>
224
+ fingerly.refresh() // Promise<IdentifyResult>
225
+ fingerly.setConsent('granted')
226
+ ```
227
+
228
+ Every field is a getter over a rune, so reading one in a template subscribes to
229
+ it and reading one in an event handler gets the current value. None of them is
230
+ settable: the state is shared, so a component that could assign to it would be
231
+ changing what every other component sees.
232
+
233
+ A verdict is `{ value, confidence, reasons }` — `reasons` is ordered strongest
234
+ first, and exists because a boolean that cannot say why it is true is not
235
+ something you can defend to a customer whose user you blocked.
236
+
237
+ These verdicts are **advisory**. The same detectors run again server-side over
238
+ the stored report, where the rules improve without every integration
239
+ redeploying. Treat the client's answer as a hint for the UI and the server's as
240
+ the decision.
241
+
242
+ ## The visitor is never asked for anything
243
+
244
+ No permission prompt, no picker, no dialog, on any browser. Reading a
245
+ permission's *state* prompts nobody and is used freely; requesting is banned
246
+ outright and enforced by a test in `@fingerly/web-js`. The one API that prompts on
247
+ some browsers — canvas readback, which raises a doorhanger in Tor Browser — is
248
+ skipped when the SDK measures a clamped clock.
249
+
250
+ You can drop this into a checkout without it ever interrupting the checkout.
251
+
252
+ ## Errors
253
+
254
+ `identify()` both stores the error and rethrows it, so either style works:
255
+
256
+ ```ts
257
+ try {
258
+ await fingerly.identify()
259
+ } catch (error) {
260
+ // your own handling
261
+ }
262
+ ```
263
+
264
+ ```svelte
265
+ {#if fingerly.error}<p>{fingerly.error.message}</p>{/if}
266
+ ```
267
+
268
+ A failed identification is forgotten rather than remembered, so the next call
269
+ tries again instead of being handed the same rejection.
270
+
271
+ `TransportError` carries a `status`. The two worth branching on are `401` (the
272
+ key is wrong, or was used from an origin it does not list) and `402` (the
273
+ organisation is not accepting traffic) — both are your configuration rather than
274
+ the visitor's.
275
+
276
+ `ConsentError` means consent is not `granted`. It carries `code:
277
+ 'consent_required'` and the `state`, and lands in `error` like any other
278
+ failure. `{ immediate: true }` waits for consent rather than producing one, so
279
+ it only sees this error when consent is withdrawn while it runs.
280
+
281
+ Calling `identify()` during SSR rejects with `FingerlyServerError` and a message
282
+ saying what to do instead. Use `{ immediate: true }`, which already waits for
283
+ the client.
284
+
285
+ ## Running the playground
286
+
287
+ `playground/` is this package's own state and hooks driving the real SDK — no
288
+ mocks — with a `useVerdict()` card per verdict, all sharing one identification.
289
+
290
+ ```
291
+ pnpm --filter @fingerly/svelte playground # http://localhost:4176
292
+ ```
293
+
294
+ Open it twice — an ordinary window and a private one — and watch the incognito
295
+ card change. That pair is the only real test that verdict gets.
296
+
297
+ ## A note on the build
298
+
299
+ The package is emitted by `tsc`, not bundled, and that is a requirement rather
300
+ than a preference. The runes in `*.svelte.js` are compiled by the *app's*
301
+ Svelte plugin, which decides what to compile by the file name — bundling them
302
+ into an `index.js` would hand the app a file full of `$state(…)` that nothing
303
+ compiles, and `$state is not defined` at runtime.
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Putting the state where every component can reach it.
3
+ *
4
+ * Svelte's context rather than a module-level singleton, and the reason is the
5
+ * server. A module-level state on a SvelteKit server is shared by every
6
+ * request the process renders, which is the one way this package could leak
7
+ * one visitor's report into another visitor's page. Context is per component
8
+ * tree, and a component tree is per request.
9
+ */
10
+ import { type Fingerly, type FingerlyOptions } from './state.svelte.js';
11
+ /**
12
+ * The context key.
13
+ *
14
+ * A symbol, so nothing else can collide with it, and exported so an advanced
15
+ * caller can reach the state with `getContext()` directly.
16
+ */
17
+ export declare const FINGERLY_KEY: unique symbol;
18
+ /**
19
+ * Create the state and put it in context. Call it once, high up.
20
+ *
21
+ * ```svelte
22
+ * <!-- +layout.svelte -->
23
+ * <script lang="ts">
24
+ * import { setupFingerly } from '@fingerly/svelte'
25
+ * setupFingerly({ apiKey: 'fly_pk_production_…' })
26
+ * </script>
27
+ * ```
28
+ *
29
+ * Like every Svelte context call, it has to run during component
30
+ * initialisation - not in an event handler, and not in an `$effect`.
31
+ *
32
+ * Nothing is collected here. When to identify stays the page's decision.
33
+ */
34
+ export declare function setupFingerly(options: FingerlyOptions): Fingerly;
35
+ /**
36
+ * The state `setupFingerly()` put in context.
37
+ *
38
+ * The error is worth its length: a missing setup otherwise surfaces as
39
+ * "cannot read properties of undefined" inside a function the caller did not
40
+ * write, and the fix - one call in a layout - is not guessable from that.
41
+ */
42
+ export declare function useFingerly(): Fingerly;
43
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,EAAkB,KAAK,QAAQ,EAAE,KAAK,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAEvF;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,OAAO,MAA2B,CAAA;AAE7D;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,QAAQ,CAIhE;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,IAAI,QAAQ,CAYtC"}
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Putting the state where every component can reach it.
3
+ *
4
+ * Svelte's context rather than a module-level singleton, and the reason is the
5
+ * server. A module-level state on a SvelteKit server is shared by every
6
+ * request the process renders, which is the one way this package could leak
7
+ * one visitor's report into another visitor's page. Context is per component
8
+ * tree, and a component tree is per request.
9
+ */
10
+ import { getContext, hasContext, setContext } from 'svelte';
11
+ import { createFingerly } from './state.svelte.js';
12
+ /**
13
+ * The context key.
14
+ *
15
+ * A symbol, so nothing else can collide with it, and exported so an advanced
16
+ * caller can reach the state with `getContext()` directly.
17
+ */
18
+ export const FINGERLY_KEY = Symbol('fingerly');
19
+ /**
20
+ * Create the state and put it in context. Call it once, high up.
21
+ *
22
+ * ```svelte
23
+ * <!-- +layout.svelte -->
24
+ * <script lang="ts">
25
+ * import { setupFingerly } from '@fingerly/svelte'
26
+ * setupFingerly({ apiKey: 'fly_pk_production_…' })
27
+ * </script>
28
+ * ```
29
+ *
30
+ * Like every Svelte context call, it has to run during component
31
+ * initialisation - not in an event handler, and not in an `$effect`.
32
+ *
33
+ * Nothing is collected here. When to identify stays the page's decision.
34
+ */
35
+ export function setupFingerly(options) {
36
+ const fingerly = createFingerly(options);
37
+ setContext(FINGERLY_KEY, fingerly);
38
+ return fingerly;
39
+ }
40
+ /**
41
+ * The state `setupFingerly()` put in context.
42
+ *
43
+ * The error is worth its length: a missing setup otherwise surfaces as
44
+ * "cannot read properties of undefined" inside a function the caller did not
45
+ * write, and the fix - one call in a layout - is not guessable from that.
46
+ */
47
+ export function useFingerly() {
48
+ if (!hasContext(FINGERLY_KEY)) {
49
+ throw new Error('No Fingerly context. Call setupFingerly() in a component above this one:\n\n' +
50
+ " import { setupFingerly } from '@fingerly/svelte'\n" +
51
+ " setupFingerly({ apiKey: 'fly_pk_production_…' })\n\n" +
52
+ 'It has to run during component initialisation - a <script> block, not an ' +
53
+ 'event handler or an $effect.');
54
+ }
55
+ return getContext(FINGERLY_KEY);
56
+ }
57
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAA;AAE3D,OAAO,EAAE,cAAc,EAAuC,MAAM,mBAAmB,CAAA;AAEvF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAkB,MAAM,CAAC,UAAU,CAAC,CAAA;AAE7D;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,aAAa,CAAC,OAAwB;IACpD,MAAM,QAAQ,GAAG,cAAc,CAAC,OAAO,CAAC,CAAA;IACxC,UAAU,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAA;IAClC,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW;IACzB,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CACb,8EAA8E;YAC5E,sDAAsD;YACtD,wDAAwD;YACxD,2EAA2E;YAC3E,8BAA8B,CACjC,CAAA;IACH,CAAC;IAED,OAAO,UAAU,CAAW,YAAY,CAAC,CAAA;AAC3C,CAAC"}