@taggor/component 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.
Files changed (169) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +67 -2
  3. package/assets.d.ts +35 -0
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/assets.d.ts +26 -0
  6. package/dist/assets.d.ts.map +1 -0
  7. package/dist/assets.js +14 -0
  8. package/dist/assets.js.map +1 -0
  9. package/dist/bounded-json.d.ts +21 -0
  10. package/dist/bounded-json.d.ts.map +1 -0
  11. package/dist/bounded-json.js +55 -0
  12. package/dist/bounded-json.js.map +1 -0
  13. package/dist/build/check-messages.d.ts +41 -0
  14. package/dist/build/check-messages.d.ts.map +1 -0
  15. package/dist/build/check-messages.js +142 -0
  16. package/dist/build/check-messages.js.map +1 -0
  17. package/dist/build/extract-manifest.d.ts +48 -0
  18. package/dist/build/extract-manifest.d.ts.map +1 -0
  19. package/dist/build/extract-manifest.js +81 -0
  20. package/dist/build/extract-manifest.js.map +1 -0
  21. package/dist/build/extract-styles.d.ts +36 -0
  22. package/dist/build/extract-styles.d.ts.map +1 -0
  23. package/dist/build/extract-styles.js +48 -0
  24. package/dist/build/extract-styles.js.map +1 -0
  25. package/dist/build/find-definition.d.ts +14 -0
  26. package/dist/build/find-definition.d.ts.map +1 -0
  27. package/dist/build/find-definition.js +23 -0
  28. package/dist/build/find-definition.js.map +1 -0
  29. package/dist/build/index.d.ts +10 -0
  30. package/dist/build/index.d.ts.map +1 -0
  31. package/dist/build/index.js +10 -0
  32. package/dist/build/index.js.map +1 -0
  33. package/dist/consent.d.ts +100 -0
  34. package/dist/consent.d.ts.map +1 -0
  35. package/dist/consent.js +147 -0
  36. package/dist/consent.js.map +1 -0
  37. package/dist/data-client.d.ts +34 -0
  38. package/dist/data-client.d.ts.map +1 -0
  39. package/dist/data-client.js +78 -0
  40. package/dist/data-client.js.map +1 -0
  41. package/dist/data-declaration.d.ts +59 -0
  42. package/dist/data-declaration.d.ts.map +1 -0
  43. package/dist/data-declaration.js +2 -0
  44. package/dist/data-declaration.js.map +1 -0
  45. package/dist/data-errors.d.ts +33 -0
  46. package/dist/data-errors.d.ts.map +1 -0
  47. package/dist/data-errors.js +73 -0
  48. package/dist/data-errors.js.map +1 -0
  49. package/dist/data-transport.d.ts +73 -0
  50. package/dist/data-transport.d.ts.map +1 -0
  51. package/dist/data-transport.js +2 -0
  52. package/dist/data-transport.js.map +1 -0
  53. package/dist/debug.d.ts +14 -0
  54. package/dist/debug.d.ts.map +1 -0
  55. package/dist/debug.js +11 -0
  56. package/dist/debug.js.map +1 -0
  57. package/dist/define-component.d.ts +162 -0
  58. package/dist/define-component.d.ts.map +1 -0
  59. package/dist/define-component.js +79 -0
  60. package/dist/define-component.js.map +1 -0
  61. package/dist/define-library.d.ts +24 -0
  62. package/dist/define-library.d.ts.map +1 -0
  63. package/dist/define-library.js +24 -0
  64. package/dist/define-library.js.map +1 -0
  65. package/dist/edge-transport.d.ts +25 -0
  66. package/dist/edge-transport.d.ts.map +1 -0
  67. package/dist/edge-transport.js +94 -0
  68. package/dist/edge-transport.js.map +1 -0
  69. package/dist/events.d.ts +50 -0
  70. package/dist/events.d.ts.map +1 -0
  71. package/dist/events.js +2 -0
  72. package/dist/events.js.map +1 -0
  73. package/dist/form-field.d.ts +59 -0
  74. package/dist/form-field.d.ts.map +1 -0
  75. package/dist/form-field.js +114 -0
  76. package/dist/form-field.js.map +1 -0
  77. package/dist/host.d.ts +45 -0
  78. package/dist/host.d.ts.map +1 -0
  79. package/dist/host.js +30 -0
  80. package/dist/host.js.map +1 -0
  81. package/dist/index.d.ts +46 -0
  82. package/dist/index.d.ts.map +1 -0
  83. package/dist/index.js +38 -0
  84. package/dist/index.js.map +1 -0
  85. package/dist/intl-format.d.ts +37 -0
  86. package/dist/intl-format.d.ts.map +1 -0
  87. package/dist/intl-format.js +56 -0
  88. package/dist/intl-format.js.map +1 -0
  89. package/dist/issued-proofs.d.ts +19 -0
  90. package/dist/issued-proofs.d.ts.map +1 -0
  91. package/dist/issued-proofs.js +19 -0
  92. package/dist/issued-proofs.js.map +1 -0
  93. package/dist/locale.d.ts +28 -0
  94. package/dist/locale.d.ts.map +1 -0
  95. package/dist/locale.js +62 -0
  96. package/dist/locale.js.map +1 -0
  97. package/dist/memory-transport.d.ts +39 -0
  98. package/dist/memory-transport.d.ts.map +1 -0
  99. package/dist/memory-transport.js +34 -0
  100. package/dist/memory-transport.js.map +1 -0
  101. package/dist/messages.d.ts +34 -0
  102. package/dist/messages.d.ts.map +1 -0
  103. package/dist/messages.js +54 -0
  104. package/dist/messages.js.map +1 -0
  105. package/dist/none.d.ts +7 -0
  106. package/dist/none.d.ts.map +1 -0
  107. package/dist/none.js +6 -0
  108. package/dist/none.js.map +1 -0
  109. package/dist/props.d.ts +89 -0
  110. package/dist/props.d.ts.map +1 -0
  111. package/dist/props.js +25 -0
  112. package/dist/props.js.map +1 -0
  113. package/dist/slots.d.ts +26 -0
  114. package/dist/slots.d.ts.map +1 -0
  115. package/dist/slots.js +70 -0
  116. package/dist/slots.js.map +1 -0
  117. package/dist/submit-result.d.ts +19 -0
  118. package/dist/submit-result.d.ts.map +1 -0
  119. package/dist/submit-result.js +58 -0
  120. package/dist/submit-result.js.map +1 -0
  121. package/dist/testing/form-internals.d.ts +59 -0
  122. package/dist/testing/form-internals.d.ts.map +1 -0
  123. package/dist/testing/form-internals.js +150 -0
  124. package/dist/testing/form-internals.js.map +1 -0
  125. package/dist/testing/index.d.ts +15 -0
  126. package/dist/testing/index.d.ts.map +1 -0
  127. package/dist/testing/index.js +14 -0
  128. package/dist/testing/index.js.map +1 -0
  129. package/dist/testing/mount-component.d.ts +105 -0
  130. package/dist/testing/mount-component.d.ts.map +1 -0
  131. package/dist/testing/mount-component.js +270 -0
  132. package/dist/testing/mount-component.js.map +1 -0
  133. package/dist/testing/visitor.d.ts +23 -0
  134. package/dist/testing/visitor.d.ts.map +1 -0
  135. package/dist/testing/visitor.js +34 -0
  136. package/dist/testing/visitor.js.map +1 -0
  137. package/dist/theming.d.ts +42 -0
  138. package/dist/theming.d.ts.map +1 -0
  139. package/dist/theming.js +19 -0
  140. package/dist/theming.js.map +1 -0
  141. package/dist/turnstile.d.ts +60 -0
  142. package/dist/turnstile.d.ts.map +1 -0
  143. package/dist/turnstile.js +179 -0
  144. package/dist/turnstile.js.map +1 -0
  145. package/dist/use-font.d.ts +65 -0
  146. package/dist/use-font.d.ts.map +1 -0
  147. package/dist/use-font.js +145 -0
  148. package/dist/use-font.js.map +1 -0
  149. package/dist/use-locale.d.ts +46 -0
  150. package/dist/use-locale.d.ts.map +1 -0
  151. package/dist/use-locale.js +57 -0
  152. package/dist/use-locale.js.map +1 -0
  153. package/dist/use-taggor-data.d.ts +72 -0
  154. package/dist/use-taggor-data.d.ts.map +1 -0
  155. package/dist/use-taggor-data.js +179 -0
  156. package/dist/use-taggor-data.js.map +1 -0
  157. package/dist/use-track.d.ts +17 -0
  158. package/dist/use-track.d.ts.map +1 -0
  159. package/dist/use-track.js +64 -0
  160. package/dist/use-track.js.map +1 -0
  161. package/dist/value-types.d.ts +69 -0
  162. package/dist/value-types.d.ts.map +1 -0
  163. package/dist/value-types.js +15 -0
  164. package/dist/value-types.js.map +1 -0
  165. package/dist/visitor-action.d.ts +49 -0
  166. package/dist/visitor-action.d.ts.map +1 -0
  167. package/dist/visitor-action.js +77 -0
  168. package/dist/visitor-action.js.map +1 -0
  169. package/package.json +71 -3
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The Turnstile client (TAG-709): loads Cloudflare's script on demand and solves one challenge
3
+ * per submission, in the invisible way, for the data transport (`data-client.ts`). Nothing here
4
+ * runs at import and nothing is loaded until the first `token()` call: a page whose components never
5
+ * submit never contacts `challenges.cloudflare.com` (golden rule 6), and the base loader never
6
+ * pulls this module (it is the lazy data module, `docs/agentes/runtime.md` §2.19).
7
+ *
8
+ * Where the challenge lives (the spike's decision, runtime.md §2.19): in a dedicated `<div>` the
9
+ * client appends to `<body>`, out of every component, with its own closed shadow root holding the
10
+ * container Turnstile renders into. `appearance: "interaction-only"` makes a managed key behave
11
+ * as invisible until Cloudflare needs the visitor, and only then (`before-interactive-callback`)
12
+ * is the box shown, fixed at the bottom right; an invisible-type key never shows it. The host is
13
+ * removed as soon as the token (or a failure) is known, so nothing stays in the page.
14
+ *
15
+ * TAG-310: under a strict CSP the injected script carries the page's nonce and, when the page
16
+ * requires Trusted Types, a `TrustedScriptURL` from the loader's `taggor` policy (see
17
+ * `docs/guias/csp-e-taggor.md`).
18
+ *
19
+ * Golden rule 2: `token()` never rejects and never throws; a script that does not load, a
20
+ * Turnstile error, a timeout, a missing `turnstile` global or an abort all resolve to `undefined`
21
+ * (the caller reports `captcha_failed` and the component shows its friendly message).
22
+ */
23
+ /** Cloudflare's script, in explicit render mode (no implicit `.cf-turnstile` scan of the page). */
24
+ const SCRIPT_URL = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
25
+ /** The origin of `SCRIPT_URL`, what the Trusted Types policy checks the URL against (TAG-310). */
26
+ const SCRIPT_ORIGIN = "https://challenges.cloudflare.com";
27
+ /** Longest a script load or one challenge may take before it counts as failed. */
28
+ const TIMEOUT_MS = 30_000;
29
+ /** The script load in flight (or done) per document, shared by all clients of the page. */
30
+ const loads = new WeakMap();
31
+ /** The `turnstile` global the script defines, if it did. */
32
+ function apiOf(doc) {
33
+ const view = doc.defaultView;
34
+ const api = view?.turnstile;
35
+ return typeof api?.render === "function" && typeof api.execute === "function" ? api : undefined;
36
+ }
37
+ /**
38
+ * Creates the Turnstile client of one site.
39
+ *
40
+ * Inputs: `TurnstileOptions`. Output: a `Turnstile`. Errors: none. Side effects: none until
41
+ * `token()`; then one `<script>` in `<head>` (once per client; a failed load is tried again by
42
+ * the next call) and, for the length of a challenge, one host `<div>` in `<body>`. Turnstile
43
+ * itself talks to Cloudflare; this code reads no cookie and writes no storage.
44
+ */
45
+ export function createTurnstile(options) {
46
+ const doc = options.document ?? document;
47
+ const timeoutMs = options.timeoutMs ?? TIMEOUT_MS;
48
+ let loading;
49
+ const load = () => {
50
+ const ready = apiOf(doc);
51
+ if (ready !== undefined)
52
+ return Promise.resolve(ready);
53
+ // One load per document, shared by every client (every component with data has its own): a
54
+ // second `api.js` makes Cloudflare warn and behave undefined.
55
+ const shared = loads.get(doc);
56
+ if (shared !== undefined)
57
+ return shared;
58
+ const started = new Promise((resolve) => {
59
+ const pending = doc.querySelector(`script[src="${SCRIPT_URL}"]`);
60
+ const script = pending ?? doc.createElement("script");
61
+ const finish = () => {
62
+ clearTimeout(timer);
63
+ const api = apiOf(doc);
64
+ if (api === undefined) {
65
+ // A failed script is dropped so the next attempt injects a fresh one.
66
+ script.remove();
67
+ }
68
+ resolve(api);
69
+ };
70
+ const timer = setTimeout(finish, timeoutMs);
71
+ script.addEventListener("load", finish, { once: true });
72
+ script.addEventListener("error", finish, { once: true });
73
+ if (pending === null) {
74
+ if (options.nonce)
75
+ script.nonce = options.nonce;
76
+ // A TrustedScriptURL where the page requires one; `src` is typed string-only in the DOM lib.
77
+ try {
78
+ script.src = (options.scriptUrl?.(SCRIPT_URL, SCRIPT_ORIGIN) ?? SCRIPT_URL);
79
+ }
80
+ catch {
81
+ // The page's Trusted Types policy refused the URL (TAG-610): settle now; the cache
82
+ // entry below is dropped as soon as a load resolves without an API.
83
+ finish();
84
+ return;
85
+ }
86
+ script.async = true;
87
+ script.referrerPolicy = "no-referrer";
88
+ (doc.head ?? doc.documentElement).appendChild(script);
89
+ }
90
+ });
91
+ loads.set(doc, started);
92
+ // The executor ran synchronously, so a refused URL settled before this entry existed.
93
+ void started.then((api) => api === undefined && loads.delete(doc));
94
+ return started;
95
+ };
96
+ const solve = (api, signal) => new Promise((resolve) => {
97
+ const host = doc.createElement("div");
98
+ host.setAttribute("data-taggor-turnstile", "");
99
+ host.style.cssText = "position:fixed;left:-9999px;top:0;width:0;height:0;overflow:hidden";
100
+ const container = doc.createElement("div");
101
+ host.attachShadow({ mode: "closed" }).appendChild(container);
102
+ let componentId;
103
+ const done = (token) => {
104
+ clearTimeout(timer);
105
+ signal?.removeEventListener("abort", onAbort);
106
+ try {
107
+ if (componentId !== undefined)
108
+ api.remove(componentId);
109
+ }
110
+ catch {
111
+ // Turnstile already dropped it.
112
+ }
113
+ host.remove();
114
+ resolve(token);
115
+ };
116
+ const onAbort = () => {
117
+ done(undefined);
118
+ };
119
+ const timer = setTimeout(onAbort, timeoutMs);
120
+ if (signal?.aborted === true) {
121
+ onAbort();
122
+ return;
123
+ }
124
+ signal?.addEventListener("abort", onAbort, { once: true });
125
+ try {
126
+ (doc.body ?? doc.documentElement).appendChild(host);
127
+ componentId = api.render(container, {
128
+ sitekey: options.siteKey,
129
+ execution: "execute",
130
+ appearance: "interaction-only",
131
+ retry: "never",
132
+ "refresh-expired": "never",
133
+ callback: (token) => {
134
+ done(typeof token === "string" && token !== "" ? token : undefined);
135
+ },
136
+ // Returning true tells Turnstile the error was handled (no console noise).
137
+ "error-callback": () => {
138
+ done(undefined);
139
+ return true;
140
+ },
141
+ "timeout-callback": () => {
142
+ done(undefined);
143
+ },
144
+ "expired-callback": () => {
145
+ done(undefined);
146
+ },
147
+ "before-interactive-callback": () => {
148
+ host.style.cssText =
149
+ "position:fixed;right:16px;bottom:16px;z-index:2147483647;width:auto;height:auto";
150
+ },
151
+ });
152
+ if (componentId === undefined)
153
+ done(undefined);
154
+ else
155
+ api.execute(container);
156
+ }
157
+ catch {
158
+ done(undefined);
159
+ }
160
+ });
161
+ return {
162
+ token: async (signal) => {
163
+ try {
164
+ loading ??= load();
165
+ const api = await loading;
166
+ if (api === undefined) {
167
+ loading = undefined;
168
+ return undefined;
169
+ }
170
+ return await solve(api, signal);
171
+ }
172
+ catch {
173
+ loading = undefined;
174
+ return undefined;
175
+ }
176
+ },
177
+ };
178
+ }
179
+ //# sourceMappingURL=turnstile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turnstile.js","sourceRoot":"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,CAAC;YACH,IAAI,WAAW,KAAK,SAAS;gBAAE,IAAI,CAAC,SAAS,CAAC,CAAC;;gBAC1C,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAC9B,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,CAAC,SAAS,CAAC,CAAC;QAClB,CAAC;IACH,CAAC,CAAC,CAAC;IAEL,OAAO;QACL,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YACtB,IAAI,CAAC;gBACH,OAAO,KAAK,IAAI,EAAE,CAAC;gBACnB,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC;gBAC1B,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;oBACtB,OAAO,GAAG,SAAS,CAAC;oBACpB,OAAO,SAAS,CAAC;gBACnB,CAAC;gBACD,OAAO,MAAM,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YAClC,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,GAAG,SAAS,CAAC;gBACpB,OAAO,SAAS,CAAC;YACnB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,65 @@
1
+ import type { FontUrl } from "./assets.js";
2
+ /** One font face a component renders with: the arguments of `useFont` and `fontFamily`. */
3
+ export interface FontDeclaration {
4
+ /**
5
+ * A readable name, 1 to 4 words of letters, digits, `_` or `-`, each starting with a letter and
6
+ * at most 32 characters (`"Inter"`, `"Brand Sans"`). It is only the start of the registered
7
+ * name, which `useFont` returns.
8
+ */
9
+ readonly family: string;
10
+ /** A `.woff2` import (`import inter from "./inter.woff2"`), never a written URL. */
11
+ readonly src: FontUrl;
12
+ /**
13
+ * The CSS `font-weight` the file covers: `400`, `"700"`, `"normal"`, `"bold"` or, for a variable
14
+ * font, a range such as `"100 900"`. Defaults to `"normal"`.
15
+ */
16
+ readonly weight?: number | string | undefined;
17
+ /** `"normal"` (default) or `"italic"`. */
18
+ readonly style?: "normal" | "italic" | undefined;
19
+ }
20
+ /**
21
+ * The CSS `font-family` value of a font, for the component's `styles`.
22
+ *
23
+ * Inputs: a `FontDeclaration`. Output: the registered name, quoted (`"Inter tg1a2b3c4d5e6f"`);
24
+ * put fallbacks after it (`${fontFamily(inter)}, system-ui, sans-serif`). A declaration `useFont`
25
+ * would refuse (bad family, weight, style or a `src` that is not a `.woff2` asset URL) gives
26
+ * `"taggor-font-unavailable"`, a name no font has, so the fallbacks apply. Errors: never throws.
27
+ * Side effects: none (call it at module level, next to `defineTaggorComponent`).
28
+ */
29
+ export declare function fontFamily(font: FontDeclaration): string;
30
+ /** What `registerFont` needs from the browser; both absent where there is no Font Loading API. */
31
+ export interface FontTarget {
32
+ readonly fonts?: FontFaceSet | undefined;
33
+ readonly FontFace?: typeof FontFace | undefined;
34
+ }
35
+ /**
36
+ * Adds a font to the document unless an equal one is there.
37
+ *
38
+ * Inputs: the document's `fonts` and the window's `FontFace` constructor, the declaration (each
39
+ * field read once, so a getter cannot answer one value for the name and another for the URL), the URL
40
+ * of the component's bundle (`import.meta.url`; its origin is the only one `src` may have) and a
41
+ * `warn` for what is refused or fails. Output: none. Errors: never throws. Side effects: at most
42
+ * one `FontFace` added to `fonts`, unless one with the same registered name, weight and style
43
+ * (compared as the browser normalizes them) is already there; the browser loads it when text
44
+ * needs it. `warn` is called for a refused declaration, a missing API, a constructor that throws
45
+ * and a font that fails to load (the rejection is handled, so the page never sees it); a declaration
46
+ * whose getter throws is warned about too. The first face registered under a name wins: an equal
47
+ * one already in `document.fonts` (put there by the page or another script of the realm, maybe
48
+ * with another file) is kept, since its `src` cannot be read back (threat T-113, accepted).
49
+ */
50
+ export declare function registerFont(target: FontTarget, font: FontDeclaration, bundleUrl: unknown, warn: (message: string) => void): void;
51
+ /**
52
+ * Makes a font available to the component's text and returns its CSS `font-family` value.
53
+ *
54
+ * Inputs: a `FontDeclaration` (`useFont({ family: "Inter", src: inter, weight: "100 900" })`).
55
+ * Output: the same value as `fontFamily(font)`; use it in an inline style or, computed with
56
+ * `fontFamily` at module level, in `styles`. Errors: throws outside a component mounted by the runtime
57
+ * (or by `@taggor/component/testing`), like `useHost`, and when a getter of the declaration throws
58
+ * (the error boundary shows the fallback); nothing else. Each field of the declaration is read
59
+ * once per render. Side effects: once per mount and declaration, `registerFont` on the element's
60
+ * document (see there); a refused declaration or a font that fails to load is a `console.warn` in
61
+ * debug mode only. The font stays registered after
62
+ * the component leaves the page (other components may share it).
63
+ */
64
+ export declare function useFont(font: FontDeclaration): string;
65
+ //# sourceMappingURL=use-font.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-font.d.ts","sourceRoot":"","sources":["../src/use-font.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAI3C,2FAA2F;AAC3F,MAAM,WAAW,eAAe;IAC9B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,oFAAoF;IACpF,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;IACtB;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IAC9C,0CAA0C;IAC1C,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,GAAG,QAAQ,GAAG,SAAS,CAAC;CAClD;AAgCD;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,eAAe,GAAG,MAAM,CAGxD;AAED,kGAAkG;AAClG,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;IACzC,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,QAAQ,GAAG,SAAS,CAAC;CACjD;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,eAAe,EACrB,SAAS,EAAE,OAAO,EAClB,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC9B,IAAI,CAwCN;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,eAAe,GAAG,MAAM,CAkBrD"}
@@ -0,0 +1,145 @@
1
+ /**
2
+ * `useFont` (TAG-213): the hook a component uses to render text in its own typeface. A `@font-face`
3
+ * inside a shadow root is ignored (Chrome) or not applied in every browser, so the font has to be
4
+ * known to the document; the hook adds it to `document.fonts` with the CSS Font Loading API
5
+ * (`new FontFace(…)`), which every shadow root of the page uses.
6
+ *
7
+ * This is the one exception to "no component CSS in the document" (TAG-308, docs/agentes/runtime.md
8
+ * rule 16), and it is kept minimal on purpose:
9
+ * - no `<style>`, no CSS text and no selector reach the document: a `FontFace` object only
10
+ * describes a font, so it cannot style anything, and the page's CSP `style-src` does not apply
11
+ * (only `font-src`, for the CDN origin);
12
+ * - the source is only an asset URL served next to the component's own bundle,
13
+ * `<origin of import.meta.url>/a/<sha256>.woff2` (`checkAssetUrl` of the contract), never a URL
14
+ * from the page, a prop or another host: no third-party font service learns about the visitor
15
+ * (golden rule 6);
16
+ * - the family is registered under a name that carries the file's hash (`Inter tg1a2b3c4d5e6f`),
17
+ * never the name the author gave, so a component can never replace a font the page uses (golden
18
+ * rule 2); `useFont` returns that name, quoted, for the component's CSS;
19
+ * - `font-display: swap` (the descriptor `display`), so text shows in the fallback font at once;
20
+ * - one `FontFace` per name, weight and style on the whole page: a second component (with its own
21
+ * copy of the SDK) or a second instance finds the first in `document.fonts` and adds nothing.
22
+ *
23
+ * Nothing of this reaches a component that does not import `useFont` (tree-shaking; `bundle.test.ts`).
24
+ */
25
+ import { checkAssetUrl } from "@taggor/contract/zod-free";
26
+ import { useContext, useMemo } from "preact/hooks";
27
+ import { debugWarn } from "./debug.js";
28
+ import { HostContext } from "./host.js";
29
+ /** `family`: up to four words of up to 32 characters, each starting with a letter. */
30
+ const FAMILY_PATTERN = /^[A-Za-z][\w-]{0,31}(?: [A-Za-z][\w-]{0,31}){0,3}$/;
31
+ /** `weight`: a keyword, a weight from 1 to 1000, or a range of two. */
32
+ const WEIGHT_PATTERN = /^(?:normal|bold|(?:[1-9]\d{0,2}|1000)(?: (?:[1-9]\d{0,2}|1000))?)$/;
33
+ /** Hex digits of the file's hash in the registered name: 48 bits, enough to never collide. */
34
+ const NAME_HASH_DIGITS = 12;
35
+ /** The name `fontFamily` gives a declaration it cannot register; no font ever has it. */
36
+ const UNAVAILABLE = '"taggor-font-unavailable"';
37
+ /** The registered name (unquoted) of a valid declaration, or `undefined`. */
38
+ function registeredName(font) {
39
+ // Untyped component code may pass anything: every field is checked as unknown.
40
+ const { family, src, weight = "normal", style = "normal", } = font;
41
+ // The URL checked against its own origin: only its shape matters for the name, so the name is
42
+ // the same in a test (file: bundle URL) and on the CDN.
43
+ const hash = checkAssetUrl(src, "woff2", src)?.hash;
44
+ return typeof family === "string" &&
45
+ FAMILY_PATTERN.test(family) &&
46
+ WEIGHT_PATTERN.test(String(weight)) &&
47
+ (style === "normal" || style === "italic") &&
48
+ hash !== undefined
49
+ ? `${family} tg${hash.slice(0, NAME_HASH_DIGITS)}`
50
+ : undefined;
51
+ }
52
+ /**
53
+ * The CSS `font-family` value of a font, for the component's `styles`.
54
+ *
55
+ * Inputs: a `FontDeclaration`. Output: the registered name, quoted (`"Inter tg1a2b3c4d5e6f"`);
56
+ * put fallbacks after it (`${fontFamily(inter)}, system-ui, sans-serif`). A declaration `useFont`
57
+ * would refuse (bad family, weight, style or a `src` that is not a `.woff2` asset URL) gives
58
+ * `"taggor-font-unavailable"`, a name no font has, so the fallbacks apply. Errors: never throws.
59
+ * Side effects: none (call it at module level, next to `defineTaggorComponent`).
60
+ */
61
+ export function fontFamily(font) {
62
+ const name = registeredName(font);
63
+ return name === undefined ? UNAVAILABLE : `"${name}"`;
64
+ }
65
+ /**
66
+ * Adds a font to the document unless an equal one is there.
67
+ *
68
+ * Inputs: the document's `fonts` and the window's `FontFace` constructor, the declaration (each
69
+ * field read once, so a getter cannot answer one value for the name and another for the URL), the URL
70
+ * of the component's bundle (`import.meta.url`; its origin is the only one `src` may have) and a
71
+ * `warn` for what is refused or fails. Output: none. Errors: never throws. Side effects: at most
72
+ * one `FontFace` added to `fonts`, unless one with the same registered name, weight and style
73
+ * (compared as the browser normalizes them) is already there; the browser loads it when text
74
+ * needs it. `warn` is called for a refused declaration, a missing API, a constructor that throws
75
+ * and a font that fails to load (the rejection is handled, so the page never sees it); a declaration
76
+ * whose getter throws is warned about too. The first face registered under a name wins: an equal
77
+ * one already in `document.fonts` (put there by the page or another script of the realm, maybe
78
+ * with another file) is kept, since its `src` cannot be read back (threat T-113, accepted).
79
+ */
80
+ export function registerFont(target, font, bundleUrl, warn) {
81
+ const { fonts, FontFace: Face } = target;
82
+ try {
83
+ // One read of each field (security review of TAG-213, L1): a getter that answered differently
84
+ // on a second read could name the font after one file and load another.
85
+ const { family, src, weight = "normal", style = "normal" } = font;
86
+ const name = registeredName({ family, src, weight, style });
87
+ const checked = checkAssetUrl(src, "woff2", bundleUrl);
88
+ if (name === undefined || checked === undefined) {
89
+ warn("useFont ignored a font: it needs a family name, a weight, a style and a .woff2 import served next to the component");
90
+ return;
91
+ }
92
+ if (fonts === undefined || Face === undefined) {
93
+ warn("useFont: this browser has no FontFace API, the fallback fonts apply");
94
+ return;
95
+ }
96
+ const face = new Face(name, `url("${checked.url}")`, {
97
+ weight: String(weight),
98
+ style,
99
+ display: "swap",
100
+ });
101
+ for (const other of fonts) {
102
+ if (other.family === face.family &&
103
+ other.weight === face.weight &&
104
+ other.style === face.style) {
105
+ return;
106
+ }
107
+ }
108
+ fonts.add(face);
109
+ face.loaded.catch(() => {
110
+ warn("useFont: the font could not be loaded, the fallback fonts apply");
111
+ });
112
+ }
113
+ catch {
114
+ // A getter of the declaration that throws, or the browser refusing the face.
115
+ warn("useFont: the font was refused");
116
+ }
117
+ }
118
+ /**
119
+ * Makes a font available to the component's text and returns its CSS `font-family` value.
120
+ *
121
+ * Inputs: a `FontDeclaration` (`useFont({ family: "Inter", src: inter, weight: "100 900" })`).
122
+ * Output: the same value as `fontFamily(font)`; use it in an inline style or, computed with
123
+ * `fontFamily` at module level, in `styles`. Errors: throws outside a component mounted by the runtime
124
+ * (or by `@taggor/component/testing`), like `useHost`, and when a getter of the declaration throws
125
+ * (the error boundary shows the fallback); nothing else. Each field of the declaration is read
126
+ * once per render. Side effects: once per mount and declaration, `registerFont` on the element's
127
+ * document (see there); a refused declaration or a font that fails to load is a `console.warn` in
128
+ * debug mode only. The font stays registered after
129
+ * the component leaves the page (other components may share it).
130
+ */
131
+ export function useFont(font) {
132
+ const host = useContext(HostContext);
133
+ // Outside a component there is no host: reading `element` throws, like `useHost`.
134
+ const page = host.element.ownerDocument;
135
+ const { family, src, weight, style } = font;
136
+ const declared = { family, src, weight, style };
137
+ useMemo(() => {
138
+ registerFont({ fonts: page.fonts, FontFace: page.defaultView?.FontFace }, declared, import.meta.url, (message) => {
139
+ debugWarn(host, message);
140
+ });
141
+ // The declaration's fields are the identity; a new object with the same fields is the same font.
142
+ }, [page, family, src, weight, style]);
143
+ return fontFamily(declared);
144
+ }
145
+ //# sourceMappingURL=use-font.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-font.js","sourceRoot":"","sources":["../src/use-font.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAGnD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,WAAW,EAAsB,MAAM,WAAW,CAAC;AAqB5D,sFAAsF;AACtF,MAAM,cAAc,GAAG,oDAAoD,CAAC;AAC5E,uEAAuE;AACvE,MAAM,cAAc,GAAG,oEAAoE,CAAC;AAC5F,8FAA8F;AAC9F,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,yFAAyF;AACzF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AI,GAAG,UAAU,CAAC,WAAW,CAAkB,CAAC;IACtD,kFAAkF;IAClF,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC;IACxC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;IAC5C,MAAM,QAAQ,GAAoB,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IACjE,OAAO,CAAC,GAAG,EAAE;QACX,YAAY,CACV,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE,EAC3D,QAAQ,EACR,MAAM,CAAC,IAAI,CAAC,GAAG,EACf,CAAC,OAAO,EAAE,EAAE;YACV,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC3B,CAAC,CACF,CAAC;QACF,iGAAiG;IACnG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;IACvC,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { type MessagesDeclaration, type Translate } from "./messages.js";
2
+ /**
3
+ * The `locales` an author writes in `defineTaggorComponent`: the catalogs by language tag and the default.
4
+ * The builder's `extractManifest` turns it into the contract's `{ supported, default }`
5
+ * (`supported` = the keys of `messages`, in order); the catalogs stay in the bundle.
6
+ */
7
+ export interface LocalesDraft<M> {
8
+ /** The language used when no candidate of the page matches; one of the keys of `messages`. */
9
+ readonly default: keyof M & string;
10
+ /** One flat catalog per language tag (`{ "pt-BR": ptBR, en }`), usually imported JSON. */
11
+ readonly messages: M;
12
+ }
13
+ /**
14
+ * What `useLocale` needs from the render context: the manifest with its `locales`, typed by the
15
+ * catalogs `M`. `RenderContext` is one.
16
+ */
17
+ export interface LocaleAnchor<M> {
18
+ readonly manifest: {
19
+ readonly locales?: LocalesDraft<M> | undefined;
20
+ };
21
+ }
22
+ /** The component's language and its messages. */
23
+ export interface Locale<M> {
24
+ /**
25
+ * The chosen tag, one of the keys of `messages` (`"pt-BR"`); pass it to `formatNumber`,
26
+ * `formatCurrency` and `formatDate`, and to `lang` where the component renders text.
27
+ */
28
+ readonly locale: keyof M & string;
29
+ /** The message of a key in the chosen language (default language, then the key, if missing). */
30
+ readonly t: Translate<M>;
31
+ }
32
+ /**
33
+ * Gives the component its language and `t`.
34
+ *
35
+ * Inputs: the render context (`render`'s second argument), whose manifest declares
36
+ * `locales: { default, messages }`; its type makes `t` accept only keys of the catalogs. Output: a
37
+ * `Locale`, new on each render; with no `locales` (untyped code), the tag is `"en"` and `t`
38
+ * returns the key. Errors: throws outside a component mounted by the runtime (or by
39
+ * `@taggor/component/testing`), like `useHost`; nothing else: missing keys fall back (`checkMessages`
40
+ * warns about them at build time). Side effects: reads the element's attributes, the `lang` of its ancestors and of `<html>`
41
+ * and `navigator.language`; while mounted, a `MutationObserver` on the element (`locale`, `lang`)
42
+ * and on `<html>` (`lang`), disconnected on unmount, which re-renders the component when the language
43
+ * changes.
44
+ */
45
+ export declare function useLocale<M extends MessagesDeclaration>(context: LocaleAnchor<M>): Locale<M>;
46
+ //# sourceMappingURL=use-locale.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-locale.d.ts","sourceRoot":"","sources":["../src/use-locale.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAmB,KAAK,mBAAmB,EAAE,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1F;;;;GAIG;AACH,MAAM,WAAW,YAAY,CAAC,CAAC;IAC7B,8FAA8F;IAC9F,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,GAAG,MAAM,CAAC;IACnC,0FAA0F;IAC1F,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC;CACtB;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY,CAAC,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE;QAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,SAAS,CAAA;KAAE,CAAC;CACvE;AAED,iDAAiD;AACjD,MAAM,WAAW,MAAM,CAAC,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAAC;IAClC,gGAAgG;IAChG,QAAQ,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;CAC1B;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,mBAAmB,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CA4B5F"}
@@ -0,0 +1,57 @@
1
+ /**
2
+ * `useLocale` (TAG-211): the hook a component uses to speak the visitor's language. It picks one of
3
+ * the languages of the component's catalogs (`locale.ts`, in the contract's order: `locale`
4
+ * attribute, nearest `lang` and `<html lang>`, `navigator.language`, the declared default) and
5
+ * returns it with `t`. The `Intl` helpers (`intl-format.ts`) are separate exports that take the
6
+ * tag, so a component only pays for the ones it calls.
7
+ *
8
+ * The `locale` attribute is read here, in the component's own copy of the SDK, not by the runtime:
9
+ * a `MutationObserver` on the element (`locale`, `lang`) and on `<html>` (`lang`) re-renders the
10
+ * component when the page switches language, and nothing of this reaches a component that does not
11
+ * import it (tree-shaking; `bundle.test.ts`). The runtime observes only declared props, and the
12
+ * contract refuses a prop named `locale` next to `locales`, so the two never compete for the
13
+ * attribute.
14
+ */
15
+ import { LOCALE_ATTRIBUTE } from "@taggor/contract/zod-free";
16
+ import { useContext, useEffect, useState } from "preact/hooks";
17
+ import { HostContext } from "./host.js";
18
+ import { localeCandidates, resolveLocale } from "./locale.js";
19
+ import { createTranslate } from "./messages.js";
20
+ /**
21
+ * Gives the component its language and `t`.
22
+ *
23
+ * Inputs: the render context (`render`'s second argument), whose manifest declares
24
+ * `locales: { default, messages }`; its type makes `t` accept only keys of the catalogs. Output: a
25
+ * `Locale`, new on each render; with no `locales` (untyped code), the tag is `"en"` and `t`
26
+ * returns the key. Errors: throws outside a component mounted by the runtime (or by
27
+ * `@taggor/component/testing`), like `useHost`; nothing else: missing keys fall back (`checkMessages`
28
+ * warns about them at build time). Side effects: reads the element's attributes, the `lang` of its ancestors and of `<html>`
29
+ * and `navigator.language`; while mounted, a `MutationObserver` on the element (`locale`, `lang`)
30
+ * and on `<html>` (`lang`), disconnected on unmount, which re-renders the component when the language
31
+ * changes.
32
+ */
33
+ export function useLocale(context) {
34
+ // Outside a component mounted by the runtime there is no host: reading `element` throws, like
35
+ // `useHost`, and the runtime's error boundary shows the fallback.
36
+ const { element } = useContext(HostContext);
37
+ const { messages, default: fallback = "en" } = context.manifest.locales ?? {};
38
+ const pick = () => resolveLocale(localeCandidates(element), Object.keys(messages ?? {}), fallback);
39
+ const [locale, setLocale] = useState(pick);
40
+ useEffect(() => {
41
+ const update = () => {
42
+ setLocale(pick());
43
+ };
44
+ // The page may have switched language between the first render and this effect (an attribute
45
+ // set right after insertion, a translation script changing <html lang>): read again first.
46
+ update();
47
+ const observer = new MutationObserver(update);
48
+ observer.observe(element, { attributeFilter: [LOCALE_ATTRIBUTE, "lang"] });
49
+ observer.observe(document.documentElement, { attributeFilter: ["lang"] });
50
+ return () => {
51
+ observer.disconnect();
52
+ };
53
+ // `pick` reads only the element and the frozen manifest, both fixed while mounted.
54
+ }, [element]);
55
+ return { locale, t: createTranslate(locale, messages, fallback) };
56
+ }
57
+ //# sourceMappingURL=use-locale.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-locale.js","sourceRoot":"","sources":["../src/use-locale.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;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CAAC,CAAC;QACF,mFAAmF;IACrF,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAEd,OAAO,EAAE,MAAM,EAAE,CAAC,EAAE,eAAe,CAAC,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC;AACpE,CAAC"}
@@ -0,0 +1,72 @@
1
+ import type { ConsentProof } from "@taggor/contract";
2
+ import type { CollectionName, DataAnchor, SubmitValues } from "./data-declaration.js";
3
+ import type { SubmitErrorCode } from "./data-transport.js";
4
+ /** Where a component's submission is: before the first one, sending, accepted or failed. */
5
+ export type SubmitStatus = "idle" | "submitting" | "success" | "error";
6
+ /** Per-field messages from the server, by field path (`email`); first message per field. */
7
+ export type FieldErrors = Readonly<Record<string, string>>;
8
+ /** A failed submission: the code and its friendly message in the page's language. */
9
+ export interface SubmitError {
10
+ readonly code: SubmitErrorCode;
11
+ readonly message: string;
12
+ }
13
+ /** Extra inputs of one submission. */
14
+ export interface SubmitOptions {
15
+ /**
16
+ * A Turnstile token of this submission, if the component has one. Normally absent: the data module
17
+ * (`data-client.ts`, TAG-709) solves a challenge for every attempt itself.
18
+ */
19
+ readonly turnstileToken?: string | undefined;
20
+ /** The value of a hidden honeypot field: humans leave it empty, bots fill it. */
21
+ readonly honeypot?: string | undefined;
22
+ /**
23
+ * The visitor's consent (TAG-212): `useConsent(...).proof`. Required when the manifest declares
24
+ * `data.personal`; without it, nothing is sent and the outcome is `consent_required`.
25
+ */
26
+ readonly consent?: ConsentProof | undefined;
27
+ }
28
+ /** What `submit` resolves to (it never rejects). */
29
+ export type SubmitOutcome = {
30
+ readonly ok: true;
31
+ } | {
32
+ readonly ok: false;
33
+ readonly error: SubmitError;
34
+ readonly fieldErrors: FieldErrors;
35
+ };
36
+ /** What `useTaggorData` returns. */
37
+ export interface TaggorData<V> {
38
+ readonly status: SubmitStatus;
39
+ /** Set when `status` is `error`. */
40
+ readonly error: SubmitError | undefined;
41
+ /** Per-field server messages of the last failed submission (empty otherwise). */
42
+ readonly fieldErrors: FieldErrors;
43
+ /** Sends `values`; while one submission is in flight, returns that one's promise. */
44
+ readonly submit: (values: V, options?: SubmitOptions) => Promise<SubmitOutcome>;
45
+ /** Back to `idle` with no errors (ignored while submitting). */
46
+ readonly reset: () => void;
47
+ }
48
+ /**
49
+ * Submits to one declared collection of the component.
50
+ *
51
+ * Inputs: the render context (`render`'s second argument; its type carries the component's `data`
52
+ * declaration) and the name of a collection declared in `data.collections` — an undeclared name
53
+ * is a compile error. Output: `TaggorData` with `status`, `error`, `fieldErrors`, `submit(values,
54
+ * { turnstileToken, honeypot })` and `reset()`; `values` are typed from the collection's fields
55
+ * (required ones mandatory). Errors: none; every failure is an outcome: `unavailable` without a
56
+ * transport, `collection_not_found` (sent nowhere, debug warning) for a collection the manifest
57
+ * does not declare, `consent_required` (sent nowhere) for a component with `data.personal` when
58
+ * `options.consent` is not a proof `useConsent` issued for this component (TAG-212; a proof built by
59
+ * hand is refused, TAG-237), `network_error`, or the server's code with
60
+ * its field messages; a given `consent` travels in the body. A `consent_required` answer that blames
61
+ * a `consent.*` field (the site has no privacy policy URL saved, or the page's differs from it) comes
62
+ * out as `consent_unverifiable` (TAG-728): the visitor is told the form is not available, the debug
63
+ * console says how to fix it. Side effects:
64
+ * one transport `submit` per accepted call; the idempotency key is kept only to retry the same
65
+ * values after a `network_error` (the server may have received them) and dropped once the server
66
+ * answers or the values change. TAG-317: the host's `signal` goes to the transport, so unmounting
67
+ * the component cancels a submission in flight; it resolves to `network_error` and, the component
68
+ * being gone, no state is shown. Whatever the transport resolves to is normalized (unknown codes
69
+ * and malformed results become `network_error`).
70
+ */
71
+ export declare function useTaggorData<D, C extends CollectionName<D>>(context: DataAnchor<D>, collection: C): TaggorData<SubmitValues<D, C>>;
72
+ //# sourceMappingURL=use-taggor-data.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-taggor-data.d.ts","sourceRoot":"","sources":["../src/use-taggor-data.ts"],"names":[],"mappings":"AAgB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