@choosemycompany/lib 0.7.0 → 0.8.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/README.md CHANGED
@@ -40,9 +40,11 @@ The sandbox uses a Vite alias `@choosemycompany/lib` → `../src/index.ts`, so e
40
40
 
41
41
  ### The `/auth` page
42
42
 
43
- It reproduces a session that expires, against a mocked auth backend: `POST /auth/api/v2/login`, `POST /auth/api/v2/login/token/refresh` and `POST /auth/api/v2/logout` served at the **origin** like the real auth-api, a protected resource under `/api/session/protected`, and `POST /api/session/simulate` to age the session without waiting 4 h.
43
+ It exercises `useAuthSession` against a mocked auth backend: `POST /auth/api/v2/login`, `POST /auth/api/v2/login/token/refresh` and `POST /auth/api/v2/logout` served at the **origin** like the real auth-api, a protected resource under `/api/session/protected`, and `POST /api/session/simulate` to age the session without waiting 4 h.
44
44
 
45
- The scenario: sign in, call the protected API, expire the token, call again. The network trace shows what the lib does — or does not do — between the app's call and the response.
45
+ The scenario: sign in, call the protected API, expire the token, call again. The app writes a single `http.get` and the trace shows three calls — the `401`, the renewal, the replay.
46
+
47
+ Known limitation: production runs a cross-site guard, `RejectCrossSiteCookieAuthenticatedRequest`, which answers `403` to an unsafe request that is authenticated by cookie, carries no `Authorization` header, and comes from another site. The sandbox has no equivalent, so the lib's `403` path cannot be exercised here.
46
48
 
47
49
  ## Build & publish
48
50
 
@@ -16,7 +16,7 @@ declare global {
16
16
  * The function is a **safe no-op** in three situations:
17
17
  * - running on the server (no `window`)
18
18
  * - the gtag snippet is not loaded (`window.gtag` undefined)
19
- * - `gtagId` is empty in `runtimeConfig` (e.g. preview / staging environments)
19
+ * - `gtagId` is empty in `runtimeConfig` (no tag configured for this deployment)
20
20
  *
21
21
  * That way consumer code can call `reportConversion()` unconditionally without
22
22
  * branching for the environment.
@@ -0,0 +1,14 @@
1
+ /** Why a session ended. Lets the consuming app tailor its exit message. */
2
+ export type SessionExpiryReason =
3
+ /** The refresh endpoint refused the refresh token of an open session. */
4
+ 'refresh-rejected'
5
+ /**
6
+ * The renewal found no session to renew: the visitor is anonymous. Reached
7
+ * only on a session that was never open, so it is the "never signed in" case,
8
+ * not the "signed out" one — an app showing an expiry message must skip it.
9
+ */
10
+ | 'no-session'
11
+ /** The refresh call itself could not complete (network, CORS, 5xx). */
12
+ | 'refresh-unreachable'
13
+ /** The app cleared the session on purpose (logout). */
14
+ | 'logout';
@@ -0,0 +1,74 @@
1
+ import { SessionExpiryReason } from './types';
2
+ /**
3
+ * Refresh endpoint of the CMC API, resolved against the **origin** of the
4
+ * declared base URL, never appended to it: that base URL may carry a path
5
+ * prefix, while the auth API always sits at this path on the origin. Internal.
6
+ */
7
+ export declare const REFRESH_URI = "/auth/api/v2/login/token/refresh";
8
+ /**
9
+ * Path prefix of the auth API. A call to it is never renewed and replayed: it
10
+ * speaks *about* the session rather than relying on it, so a `401` from `login`
11
+ * is a wrong password, one from `refresh` is a dead refresh token, and one from
12
+ * `logout` is nothing worth replaying. Internal.
13
+ */
14
+ export declare const AUTH_API_PREFIX = "/auth/api/v2/";
15
+ /**
16
+ * Name of the Web Locks entry that serialises the refresh across tabs. Namespaced
17
+ * so it cannot collide with a lock the application takes. Internal.
18
+ */
19
+ export declare const REFRESH_LOCK = "cmc-auth-session-refresh";
20
+ /**
21
+ * Shared session store: whether a session is open, and how to renew it when a
22
+ * call comes back `401`.
23
+ *
24
+ * The store holds **no token**. The access token lives in a cookie that the
25
+ * browser attaches to every same-site request on its own, so the store has
26
+ * nothing to read, carry, or put on a header. What it tracks is the one thing
27
+ * the app cannot get from the cookie jar: whether the session is still usable,
28
+ * and why it stopped being so.
29
+ *
30
+ * That the store reads no token is what lets the cookies become `httpOnly`
31
+ * without touching this code. The refresh cookie already is; the access cookie
32
+ * follows when the backend flips it.
33
+ *
34
+ * Paired with {@link useHttp}'s `401` interceptor: a refused call triggers one
35
+ * renewal and one replay. The app watches {@link isExpired} and decides where
36
+ * to send the user.
37
+ *
38
+ * Renewal is **reactive only** — no timer renews ahead of expiry. A timer would
39
+ * buy one faster request every four hours and would not even cover the case it
40
+ * looks like it covers: `setTimeout` does not fire while the laptop sleeps.
41
+ *
42
+ * See `docs/useAuthSession.md` for the wiring and the guarantees.
43
+ */
44
+ export declare const useAuthSession: import('pinia').StoreDefinition<"cmc-auth-session", Pick<{
45
+ isOpen: import('vue').Ref<boolean, boolean>;
46
+ isExpired: import('vue').Ref<boolean, boolean>;
47
+ expiryReason: import('vue').Ref<SessionExpiryReason | undefined, SessionExpiryReason | undefined>;
48
+ isAuthenticated: import('vue').ComputedRef<boolean>;
49
+ open: () => void;
50
+ expire: (reason: SessionExpiryReason) => void;
51
+ clear: () => void;
52
+ logout: () => void;
53
+ refresh: () => Promise<void>;
54
+ }, "isOpen" | "isExpired" | "expiryReason">, Pick<{
55
+ isOpen: import('vue').Ref<boolean, boolean>;
56
+ isExpired: import('vue').Ref<boolean, boolean>;
57
+ expiryReason: import('vue').Ref<SessionExpiryReason | undefined, SessionExpiryReason | undefined>;
58
+ isAuthenticated: import('vue').ComputedRef<boolean>;
59
+ open: () => void;
60
+ expire: (reason: SessionExpiryReason) => void;
61
+ clear: () => void;
62
+ logout: () => void;
63
+ refresh: () => Promise<void>;
64
+ }, "isAuthenticated">, Pick<{
65
+ isOpen: import('vue').Ref<boolean, boolean>;
66
+ isExpired: import('vue').Ref<boolean, boolean>;
67
+ expiryReason: import('vue').Ref<SessionExpiryReason | undefined, SessionExpiryReason | undefined>;
68
+ isAuthenticated: import('vue').ComputedRef<boolean>;
69
+ open: () => void;
70
+ expire: (reason: SessionExpiryReason) => void;
71
+ clear: () => void;
72
+ logout: () => void;
73
+ refresh: () => Promise<void>;
74
+ }, "logout" | "open" | "expire" | "clear" | "refresh">>;
package/dist/env.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Runtime environment flags, shared by the domains that need to behave
3
+ * differently under SSR. Internal — not exported from `src/index.ts`.
4
+ */
5
+ /**
6
+ * True when there is no browser behind the current code path.
7
+ *
8
+ * Two things depend on this. Cookies: Node holds no jar, so a request that
9
+ * relies on one comes back refused and says nothing about the real state.
10
+ * Timers: one armed on the Nitro server outlives the response it belongs to
11
+ * and fires against a request nobody is waiting for.
12
+ *
13
+ * `import.meta.server` is the Nuxt-side answer; the `document` check keeps the
14
+ * guard honest anywhere the flag is not injected, and makes it testable.
15
+ */
16
+ export declare function isServerSide(): boolean;
@@ -8,6 +8,8 @@ import { MandeInstance } from 'mande';
8
8
  * (`get`, `post`, `put`, `patch`, `delete`) and is meant to be the only way the
9
9
  * lib (and downstream apps) talk to an HTTP backend.
10
10
  *
11
+ * Every instance renews the session on its own — see {@link createAuthFetch}.
12
+ *
11
13
  * @param target - Name of a declared target. Omit it for the default base URL,
12
14
  * which is what almost every caller wants. Name one to reach
13
15
  * another origin the app declared — the call site then holds no
@@ -15,16 +17,16 @@ import { MandeInstance } from 'mande';
15
17
  *
16
18
  * @example
17
19
  * ```ts
18
- * const { http, setToken, clearToken } = useHttp()
20
+ * const { http } = useHttp()
19
21
  *
20
- * setToken(accessToken)
21
22
  * const { item } = await http.get<RetrieveResponse<User>>('/me')
22
- * clearToken() // on logout
23
23
  * ```
24
24
  *
25
- * @example Another declared origin
25
+ * @example Another declared origin, authenticated by hand
26
26
  * ```ts
27
- * const { http } = useHttp('happy')
27
+ * const { http, setToken } = useHttp('happy')
28
+ *
29
+ * setToken(tokenForThatOrigin)
28
30
  * ```
29
31
  */
30
32
  export declare function useHttp(target?: string): {
@@ -1,10 +1,10 @@
1
1
  /**
2
- * Public i18n types shared by every composable in this folder. Reflect the
3
- * languages actually supported by ChooseMyCompany apps as of today; add a new
4
- * locale here and downstream code (translations maps, country dictionaries,
5
- * etc.) will get a compile-time error to keep them in sync.
2
+ * Public i18n types shared by every composable in this folder. Reflect the set
3
+ * of languages the library supports; add a new locale here and downstream code
4
+ * (translations maps, country dictionaries, etc.) will get a compile-time error
5
+ * to keep them in sync.
6
6
  */
7
- /** Languages currently shipped by ChooseMyCompany apps (ISO 639-1 codes). */
7
+ /** Languages the library ships translations for (ISO 639-1 codes). */
8
8
  export type Language = 'en' | 'fr' | 'de' | 'es' | 'it' | 'da' | 'pt';
9
9
  /**
10
10
  * A translation bundle: a partial map from `Language` to its translated string.
package/dist/index.d.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  * region resolution, and rich tagged messages.
14
14
  * - **UI** — small DOM / window-aware helpers: outside-click detection, responsive
15
15
  * sizing, image-cache watcher.
16
+ * - **Auth** — {@link useAuthSession}: shared session store (open/expired state, single-flight refresh).
16
17
  * - **Errors** — {@link showAndThrowError}: Nuxt error trigger shorthand.
17
18
  * - **Analytics** — gtag conversion + Hubspot contact URL helpers.
18
19
  *
@@ -20,6 +21,7 @@
20
21
  */
21
22
  export { useHttp } from './http/useHttp';
22
23
  export { configureHttp, type HttpConfig } from './http/config';
24
+ export { useAuthSession } from './auth/useAuthSession';
23
25
  export { useStore, getViewKey, CREATE_PENDING_KEY, type Store } from './store/useStore';
24
26
  export { useClickOutside } from './ui/useClickOutside';
25
27
  export { useCountriesTranslation, type CountryCodes } from './i18n/useCountriesTranslation';
@@ -33,4 +35,5 @@ export { useResponsiveSize } from './ui/useResponsiveSize';
33
35
  export { useTranslate } from './i18n/useTranslate';
34
36
  export type { StoreOptions, RetrieveOptions, ListOptions, ViewKeyParams, View, ViewOptions, } from './store/types';
35
37
  export type { PaginatedQuery, Pagination, ListResponse, RetrieveResponse, HttpResponse, RequestOptions, ErrorItem, MandeError, MandeErrorBody, } from './http/types';
38
+ export type { SessionExpiryReason } from './auth/types';
36
39
  export type { Language, Translation, InternationalizedRoute, } from './i18n/types';
package/dist/index.js CHANGED
@@ -1,193 +1,280 @@
1
- import { mande as D } from "mande";
2
- import { ref as M, onMounted as L, onBeforeUnmount as N, computed as z, onUnmounted as K } from "vue";
1
+ import { mande as N } from "mande";
2
+ import { ref as w, computed as E, onMounted as z, onBeforeUnmount as K, onUnmounted as H } from "vue";
3
+ import { defineStore as F } from "pinia";
3
4
  import { useI18n as k } from "vue-i18n";
4
- import { createError as H } from "h3";
5
- import { showError as F, useRuntimeConfig as O, useState as q } from "nuxt/app";
6
- let w;
7
- function ea(a) {
8
- if (!a.baseUrl)
5
+ import { createError as O } from "h3";
6
+ import { showError as x, useRuntimeConfig as q, useState as Z } from "nuxt/app";
7
+ let I;
8
+ function le(e) {
9
+ if (!e.baseUrl)
9
10
  throw new Error("@choosemycompany/lib: configureHttp() needs a non-empty baseUrl");
10
- w = a;
11
+ I = e;
11
12
  }
12
- function Z(a) {
13
- if (!w)
13
+ function D(e) {
14
+ if (!I)
14
15
  throw new Error(
15
16
  "@choosemycompany/lib: useHttp() was called before configureHttp(). Declare the base URLs from an app plugin."
16
17
  );
17
- if (a === void 0) return w.baseUrl;
18
- const i = w.targets ?? {}, t = Object.hasOwn(i, a) ? i[a] : void 0;
19
- if (typeof t != "string" || !t) {
20
- const n = Object.keys(i), e = n.length > 0 ? n.join(", ") : "none";
18
+ if (e === void 0) return I.baseUrl;
19
+ const a = I.targets ?? {}, n = Object.hasOwn(a, e) ? a[e] : void 0;
20
+ if (typeof n != "string" || !n) {
21
+ const t = Object.keys(a), i = t.length > 0 ? t.join(", ") : "none";
21
22
  throw new Error(
22
- `@choosemycompany/lib: no HTTP target named "${a}". Declared targets: ${e}.`
23
+ `@choosemycompany/lib: no HTTP target named "${e}". Declared targets: ${i}.`
23
24
  );
24
25
  }
25
- return t;
26
+ return n;
26
27
  }
27
- function na(a) {
28
- const i = D(Z(a), {
28
+ const V = "/auth/api/v2/login/token/refresh", J = "/auth/api/v2/", j = "cmc-auth-session-refresh", _ = F("cmc-auth-session", () => {
29
+ const e = w(!1), a = w(!1), n = w(void 0);
30
+ let t, i = 0;
31
+ const s = E(() => e.value && !a.value);
32
+ function d() {
33
+ e.value = !0, a.value = !1, n.value = void 0;
34
+ }
35
+ function l() {
36
+ i += 1, e.value = !1, a.value = !1, n.value = void 0;
37
+ }
38
+ function p() {
39
+ i += 1, e.value = !1, a.value = !0, n.value = "logout";
40
+ }
41
+ function c(h) {
42
+ i += 1, e.value = !1, a.value = !0, n.value = h;
43
+ }
44
+ async function m() {
45
+ if (a.value)
46
+ throw new Error("Session is expired: no refresh will be attempted");
47
+ return t ??= v(g).finally(() => {
48
+ t = void 0;
49
+ }), t;
50
+ }
51
+ async function v(h) {
52
+ const b = globalThis.navigator?.locks;
53
+ if (!b) return h();
54
+ await b.request(j, h);
55
+ }
56
+ async function g() {
57
+ const h = i, b = () => h !== i, r = new URL(V, D()).href;
58
+ let u;
59
+ try {
60
+ u = await fetch(r, {
61
+ method: "POST",
62
+ credentials: "include"
63
+ });
64
+ } catch (o) {
65
+ throw b() || C(), o;
66
+ }
67
+ if (!u.ok)
68
+ throw b() || (u.status === 401 ? c(e.value ? "refresh-rejected" : "no-session") : C()), new Error(`Token refresh failed with status ${u.status}`);
69
+ if (b())
70
+ throw new Error("Session was dropped while the refresh was in flight");
71
+ d();
72
+ }
73
+ function C() {
74
+ n.value = "refresh-unreachable";
75
+ }
76
+ return {
77
+ isOpen: e,
78
+ isExpired: a,
79
+ expiryReason: n,
80
+ isAuthenticated: s,
81
+ open: d,
82
+ expire: c,
83
+ clear: l,
84
+ logout: p,
85
+ refresh: m
86
+ };
87
+ });
88
+ function $() {
89
+ return import.meta.server || typeof document > "u";
90
+ }
91
+ function W(e) {
92
+ return (typeof e == "string" ? e : e instanceof URL ? e.href : e.url).includes(J);
93
+ }
94
+ function Q() {
95
+ return async (e, a) => {
96
+ if ($()) return fetch(e, a);
97
+ const n = await fetch(e, a);
98
+ if (n.status !== 401 || W(e) || new Headers(a?.headers).has("Authorization")) return n;
99
+ let t;
100
+ try {
101
+ t = _();
102
+ } catch {
103
+ return n;
104
+ }
105
+ if (t.isExpired) return n;
106
+ try {
107
+ await t.refresh();
108
+ } catch (i) {
109
+ return t.isExpired || console.warn("[cmc-lib] token refresh failed, returning the original 401", i), n;
110
+ }
111
+ return fetch(e, a);
112
+ };
113
+ }
114
+ function ce(e) {
115
+ const a = N(D(e), {
29
116
  headers: {}
30
- });
31
- function t(e) {
32
- i.options.headers = {
33
- ...i.options.headers ?? {},
34
- Authorization: `Bearer ${e}`
117
+ }, Q());
118
+ function n(i) {
119
+ a.options.headers = {
120
+ ...a.options.headers ?? {},
121
+ Authorization: `Bearer ${i}`
35
122
  };
36
123
  }
37
- function n() {
38
- i.options.headers && delete i.options.headers.Authorization;
124
+ function t() {
125
+ a.options.headers && delete a.options.headers.Authorization;
39
126
  }
40
- return { http: i, setToken: t, clearToken: n };
127
+ return { http: a, setToken: n, clearToken: t };
41
128
  }
42
- function T(a) {
43
- return Object.entries(a).sort(([i], [t]) => i.localeCompare(t)).map(([i, t]) => `${i}=${t}`).join("|");
129
+ function U(e) {
130
+ return Object.entries(e).sort(([a], [n]) => a.localeCompare(n)).map(([a, n]) => `${a}=${n}`).join("|");
44
131
  }
45
- const x = "create";
46
- function ia(a) {
47
- const i = M({}), t = M({}), n = M({}), e = M({}), s = a.getItemId ?? ((r) => {
48
- const d = r.id;
49
- if (d === void 0)
132
+ const Y = "create";
133
+ function fe(e) {
134
+ const a = w({}), n = w({}), t = w({}), i = w({}), s = e.getItemId ?? ((r) => {
135
+ const u = r.id;
136
+ if (u === void 0)
50
137
  throw new Error(
51
138
  "useStore: no `getItemId` option provided and item has no `id` property. Either pass `getItemId` in the store options, or expose an `id` field on your items."
52
139
  );
53
- return d;
140
+ return u;
54
141
  });
55
- function c(r) {
56
- return !!e.value[r];
142
+ function d(r) {
143
+ return !!i.value[r];
57
144
  }
58
- async function l(r, d) {
59
- e.value[r] = d;
145
+ async function l(r, u) {
146
+ i.value[r] = u;
60
147
  try {
61
- const o = await d;
62
- return delete n.value[r], o;
148
+ const o = await u;
149
+ return delete t.value[r], o;
63
150
  } catch (o) {
64
- throw n.value[r] = o, o;
151
+ throw t.value[r] = o, o;
65
152
  } finally {
66
- e.value[r] === d && delete e.value[r];
153
+ i.value[r] === u && delete i.value[r];
67
154
  }
68
155
  }
69
- async function g(r, d = {}) {
70
- if (!a.fetchOne)
156
+ async function p(r, u = {}) {
157
+ if (!e.fetchOne)
71
158
  throw new Error("useStore.retrieve called but fetchOne is not defined in store options");
72
- const { force: o = !1 } = d;
73
- if (i.value[r] && !o)
74
- return i.value[r];
75
- const u = e.value[r];
76
- if (u)
77
- return u;
78
- const f = a.fetchOne, A = (async () => {
159
+ const { force: o = !1 } = u;
160
+ if (a.value[r] && !o)
161
+ return a.value[r];
162
+ const f = i.value[r];
163
+ if (f)
164
+ return f;
165
+ const B = e.fetchOne, S = (async () => {
79
166
  try {
80
- const C = await f(r), h = a.enrichItem ? a.enrichItem(C) : C;
81
- return i.value[r] = h, delete n.value[r], i.value[r];
82
- } catch (C) {
83
- n.value[r] = C;
167
+ const M = await B(r), A = e.enrichItem ? e.enrichItem(M) : M;
168
+ return a.value[r] = A, delete t.value[r], a.value[r];
169
+ } catch (M) {
170
+ t.value[r] = M;
84
171
  return;
85
172
  } finally {
86
- delete e.value[r];
173
+ delete i.value[r];
87
174
  }
88
175
  })();
89
- return e.value[r] = A, A;
176
+ return i.value[r] = S, S;
90
177
  }
91
- function p(r) {
92
- const d = T(r), o = t.value[d];
178
+ function c(r) {
179
+ const u = U(r), o = n.value[u];
93
180
  if (o)
94
181
  return {
95
- items: o.itemIds.map((u) => i.value[u]).filter((u) => u !== void 0),
182
+ items: o.itemIds.map((f) => a.value[f]).filter((f) => f !== void 0),
96
183
  total: o.total,
97
184
  hasMore: o.hasMore,
98
185
  page: o.page,
99
186
  limit: o.limit
100
187
  };
101
188
  }
102
- async function b(r, d = {}) {
103
- if (!a.fetchPage)
189
+ async function m(r, u = {}) {
190
+ if (!e.fetchPage)
104
191
  throw new Error("useStore.list called but fetchPage is not defined in store options");
105
- const o = T(r), { force: u = !1 } = d;
106
- if (t.value[o] && !u)
107
- return p(r);
108
- const f = e.value[o];
109
- if (f)
110
- return await f, p(r);
111
- const A = a.fetchPage, C = (async () => {
192
+ const o = U(r), { force: f = !1 } = u;
193
+ if (n.value[o] && !f)
194
+ return c(r);
195
+ const B = i.value[o];
196
+ if (B)
197
+ return await B, c(r);
198
+ const S = e.fetchPage, M = (async () => {
112
199
  try {
113
- const h = await A(r), E = [];
114
- for (const R of h.items) {
115
- const y = a.enrichItem ? a.enrichItem(R) : R, P = s(y);
116
- i.value[P] = y, E.push(P);
200
+ const A = await S(r), R = [];
201
+ for (const y of A.items) {
202
+ const P = e.enrichItem ? e.enrichItem(y) : y, T = s(P);
203
+ a.value[T] = P, R.push(T);
117
204
  }
118
- t.value[o] = {
119
- itemIds: E,
120
- total: h.total,
121
- hasMore: h.hasMore,
122
- page: h.page,
123
- limit: h.limit
124
- }, delete n.value[o];
125
- } catch (h) {
126
- n.value[o] = h;
205
+ n.value[o] = {
206
+ itemIds: R,
207
+ total: A.total,
208
+ hasMore: A.hasMore,
209
+ page: A.page,
210
+ limit: A.limit
211
+ }, delete t.value[o];
212
+ } catch (A) {
213
+ t.value[o] = A;
127
214
  } finally {
128
- delete e.value[o];
215
+ delete i.value[o];
129
216
  }
130
217
  })();
131
- return e.value[o] = C, await C, p(r);
218
+ return i.value[o] = M, await M, c(r);
132
219
  }
133
- async function B(r, d = x) {
134
- if (!a.createMutation)
220
+ async function v(r, u = Y) {
221
+ if (!e.createMutation)
135
222
  throw new Error("useStore.create called but createMutation is not defined in store options");
136
- const o = a.createMutation, u = await l(d, (async () => o(r))()), f = a.enrichItem ? a.enrichItem(u) : u, A = s(f);
137
- return i.value[A] = f, t.value = {}, f;
223
+ const o = e.createMutation, f = await l(u, (async () => o(r))()), B = e.enrichItem ? e.enrichItem(f) : f, S = s(B);
224
+ return a.value[S] = B, n.value = {}, B;
138
225
  }
139
- async function m(r, d) {
140
- if (!a.updateMutation)
226
+ async function g(r, u) {
227
+ if (!e.updateMutation)
141
228
  throw new Error("useStore.update called but updateMutation is not defined in store options");
142
- const o = a.updateMutation, u = await l(r, (async () => o(r, d))()), f = a.enrichItem ? a.enrichItem(u) : u;
143
- return i.value[r] = f, f;
229
+ const o = e.updateMutation, f = await l(r, (async () => o(r, u))()), B = e.enrichItem ? e.enrichItem(f) : f;
230
+ return a.value[r] = B, B;
144
231
  }
145
- async function v(r) {
146
- if (!a.removeMutation)
232
+ async function C(r) {
233
+ if (!e.removeMutation)
147
234
  throw new Error("useStore.remove called but removeMutation is not defined in store options");
148
- const d = a.removeMutation;
149
- await l(r, (async () => d(r))()), delete i.value[r];
150
- for (const o of Object.values(t.value)) {
151
- const u = o.itemIds.indexOf(r);
152
- u !== -1 && (o.itemIds.splice(u, 1), o.total = Math.max(0, o.total - 1));
235
+ const u = e.removeMutation;
236
+ await l(r, (async () => u(r))()), delete a.value[r];
237
+ for (const o of Object.values(n.value)) {
238
+ const f = o.itemIds.indexOf(r);
239
+ f !== -1 && (o.itemIds.splice(f, 1), o.total = Math.max(0, o.total - 1));
153
240
  }
154
241
  }
155
- function I() {
156
- n.value = {};
242
+ function h() {
243
+ t.value = {};
157
244
  }
158
- function S() {
159
- i.value = {}, t.value = {}, n.value = {}, e.value = {};
245
+ function b() {
246
+ a.value = {}, n.value = {}, t.value = {}, i.value = {};
160
247
  }
161
- return { items: i, views: t, errors: n, isPending: c, list: b, reset: S, retrieve: g, getView: p, withPending: l, create: B, update: m, remove: v, clearErrors: I };
248
+ return { items: a, views: n, errors: t, isPending: d, list: m, reset: b, retrieve: p, getView: c, withPending: l, create: v, update: g, remove: C, clearErrors: h };
162
249
  }
163
- function ta(a, i) {
164
- const t = (n) => {
165
- const e = a.value, s = n.target;
166
- !e || !s || e.contains(s) || i();
250
+ function pe(e, a) {
251
+ const n = (t) => {
252
+ const i = e.value, s = t.target;
253
+ !i || !s || i.contains(s) || a();
167
254
  };
168
- L(() => {
169
- document.addEventListener("click", t);
170
- }), N(() => {
171
- document.removeEventListener("click", t);
255
+ z(() => {
256
+ document.addEventListener("click", n);
257
+ }), K(() => {
258
+ document.removeEventListener("click", n);
172
259
  });
173
260
  }
174
- function ra() {
175
- const { locale: a } = k();
176
- function i(t, n = null) {
177
- const e = V[t.trim().toUpperCase()];
178
- if (!e)
179
- throw new Error(`Unknown country code: ${t}`);
180
- if (n && e[n])
181
- return e[n];
182
- if (e[a.value])
183
- return e[a.value];
184
- if (a.value !== "en" && e.en)
185
- return e.en;
186
- throw new Error(`Unknown country code: ${t}`);
261
+ function ge() {
262
+ const { locale: e } = k();
263
+ function a(n, t = null) {
264
+ const i = X[n.trim().toUpperCase()];
265
+ if (!i)
266
+ throw new Error(`Unknown country code: ${n}`);
267
+ if (t && i[t])
268
+ return i[t];
269
+ if (i[e.value])
270
+ return i[e.value];
271
+ if (e.value !== "en" && i.en)
272
+ return i.en;
273
+ throw new Error(`Unknown country code: ${n}`);
187
274
  }
188
- return i;
275
+ return a;
189
276
  }
190
- const V = {
277
+ const X = {
191
278
  AD: { en: "Andorra", fr: "Andorre", es: "Andorra", de: "Andorra", it: "Andorra", pt: "Andorra", da: "Andorra" },
192
279
  AE: { en: "United Arab Emirates", fr: "Émirats arabes unis", es: "Emiratos Árabes Unidos", de: "Vereinigte Arabische Emirate", it: "Emirati Arabi Uniti", pt: "Emirados Árabes Unidos", da: "De Forenede Arabiske Emirater" },
193
280
  AF: { en: "Afghanistan", fr: "Afghanistan", es: "Afganistán", de: "Afghanistan", it: "Afghanistan", pt: "Afeganistão", da: "Afghanistan" },
@@ -325,151 +412,152 @@ const V = {
325
412
  ZA: { en: "South Africa", fr: "Afrique Du Sud", es: "Sudáfrica", de: "Südafrika", it: "Sudafrica", pt: "África Do Sul", da: "Sydafrika" },
326
413
  ZM: { en: "Zambia", fr: "Zambie", es: "Zambia", de: "Sambia", it: "Zambia", pt: "Zâmbia", da: "Zambia" },
327
414
  ZW: { en: "Zimbabwe", fr: "Zimbabwe", es: "Zimbabue", de: "Simbabwe", it: "Zimbabwe", pt: "Zimbábue", da: "Zimbabwe" }
328
- }, oa = ({ code: a, message: i, data: t }) => {
329
- const n = i || "An unexpected error occurred", e = H({
330
- statusCode: a,
331
- statusMessage: n,
332
- message: n,
333
- data: t
415
+ }, me = ({ code: e, message: a, data: n }) => {
416
+ const t = a || "An unexpected error occurred", i = O({
417
+ statusCode: e,
418
+ statusMessage: t,
419
+ message: t,
420
+ data: n
334
421
  });
335
- throw F(e), e;
336
- }, J = "ilcJCL_lmpwcEJfSkKND";
337
- function sa() {
338
- const { gtagId: a } = O().public;
422
+ throw x(i), i;
423
+ }, ee = "ilcJCL_lmpwcEJfSkKND";
424
+ function he() {
425
+ const { gtagId: e } = q().public;
339
426
  return { reportConversion: () => {
340
- if (typeof window > "u" || typeof window.gtag > "u" || !a)
427
+ if (typeof window > "u" || typeof window.gtag > "u" || !e)
341
428
  return;
342
- const t = `${a}/${J}`;
429
+ const n = `${e}/${ee}`;
343
430
  window.gtag("event", "conversion", {
344
- send_to: t
431
+ send_to: n
345
432
  });
346
433
  } };
347
434
  }
348
- const U = "https://5509641.hs-sites-eu1.com";
349
- function da() {
350
- const { locale: a } = k();
351
- return { contactUrl: z(() => a.value === "fr" ? `${U}/contact` : `${U}/${a.value}/contact`) };
435
+ const L = "https://5509641.hs-sites-eu1.com";
436
+ function be() {
437
+ const { locale: e } = k();
438
+ return { contactUrl: E(() => e.value === "fr" ? `${L}/contact` : `${L}/${e.value}/contact`) };
352
439
  }
353
- function ua() {
354
- async function a(n) {
440
+ function Be() {
441
+ async function e(t) {
355
442
  await Promise.all(
356
- n.map(
357
- (e) => new Promise((s) => {
358
- if (!e) return s(null);
359
- const c = new Image();
360
- c.onload = () => s(null), c.onerror = () => s(null), c.src = e;
443
+ t.map(
444
+ (i) => new Promise((s) => {
445
+ if (!i) return s(null);
446
+ const d = new Image();
447
+ d.onload = () => s(null), d.onerror = () => s(null), d.src = i;
361
448
  })
362
449
  )
363
450
  );
364
451
  }
365
- function i(n, e) {
366
- return e.split(".").reduce((s, c) => s && typeof s == "object" && c in s ? s[c] : "", n) ?? "";
452
+ function a(t, i) {
453
+ return i.split(".").reduce((s, d) => s && typeof s == "object" && d in s ? s[d] : "", t) ?? "";
367
454
  }
368
- function t(n, e, s) {
455
+ function n(t, i, s) {
369
456
  if (import.meta.server)
370
457
  return async (l) => {
371
- n.value = !0;
458
+ t.value = !0;
372
459
  };
373
- const c = q(
374
- `${e}LoadedImageCache`,
460
+ const d = Z(
461
+ `${i}LoadedImageCache`,
375
462
  () => ({})
376
463
  );
377
464
  return async (l) => {
378
465
  if (!l) {
379
- n.value = !1;
466
+ t.value = !1;
380
467
  return;
381
468
  }
382
- const g = s.map((B) => i(l, B)), p = `${e}|${g.join("|")}`;
383
- if (c.value[p]) {
384
- n.value = !0;
469
+ const p = s.map((v) => a(l, v)), c = `${i}|${p.join("|")}`;
470
+ if (d.value[c]) {
471
+ t.value = !0;
385
472
  return;
386
473
  }
387
- n.value = !1;
388
- const b = g.filter(Boolean).map(String);
389
- await a(b), c.value[p] = !0, n.value = !0;
474
+ t.value = !1;
475
+ const m = p.filter(Boolean).map(String);
476
+ await e(m), d.value[c] = !0, t.value = !0;
390
477
  };
391
478
  }
392
- return t;
479
+ return n;
393
480
  }
394
- const j = {
481
+ const ae = {
395
482
  en: ["US", "UK"]
396
- }, $ = "FR";
397
- function _(a) {
398
- const i = a.trim().replace("_", "-"), [t, n] = i.split("-");
483
+ }, ne = "FR";
484
+ function ie(e) {
485
+ const a = e.trim().replace("_", "-"), [n, t] = a.split("-");
399
486
  return {
400
- language: t?.toLowerCase() ?? "",
401
- region: n?.toUpperCase() ?? ""
487
+ language: n?.toLowerCase() ?? "",
488
+ region: t?.toUpperCase() ?? ""
402
489
  };
403
490
  }
404
- function G(a) {
405
- return a.toString().trim().toUpperCase();
491
+ function G(e) {
492
+ return e.toString().trim().toUpperCase();
406
493
  }
407
- function la() {
408
- function a(i, t) {
409
- if (!t.length) return;
410
- const n = t.map(G), e = new Set(n), { language: s, region: c } = _(i), l = [];
411
- c && l.push(c);
412
- const g = j[s];
413
- g?.length && l.push(...g.map(G)), s && l.push(s.toUpperCase()), l.push($);
414
- for (const p of l)
415
- if (e.has(p))
416
- return p;
417
- return n[0];
494
+ function ve() {
495
+ function e(a, n) {
496
+ if (!n.length) return;
497
+ const t = n.map(G), i = new Set(t), { language: s, region: d } = ie(a), l = [];
498
+ d && l.push(d);
499
+ const p = ae[s];
500
+ p?.length && l.push(...p.map(G)), s && l.push(s.toUpperCase()), l.push(ne);
501
+ for (const c of l)
502
+ if (i.has(c))
503
+ return c;
504
+ return t[0];
418
505
  }
419
- return { getRegionFromLocale: a };
506
+ return { getRegionFromLocale: e };
420
507
  }
421
- function ca() {
422
- const { t: a } = k();
423
- function i(t, n) {
424
- const e = a(t), s = [], l = n.map((m) => m.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), g = new RegExp(`\\[(${l})\\]([\\s\\S]*?)\\[\\/\\1\\]`, "g"), p = n.reduce((m, v) => (m[v] = !1, m), {});
425
- let b = 0, B = g.exec(e);
426
- for (; B; ) {
427
- const { index: m, 0: v, 1: I, 2: S } = B;
428
- m > b && s.push({ text: e.slice(b, m), ...p }), S && I && s.push({ text: S, ...p, [I]: !0 }), b = m + v.length, B = g.exec(e);
508
+ function Ae() {
509
+ const { t: e } = k();
510
+ function a(n, t) {
511
+ const i = e(n), s = [], l = t.map((g) => g.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), p = new RegExp(`\\[(${l})\\]([\\s\\S]*?)\\[\\/\\1\\]`, "g"), c = t.reduce((g, C) => (g[C] = !1, g), {});
512
+ let m = 0, v = p.exec(i);
513
+ for (; v; ) {
514
+ const { index: g, 0: C, 1: h, 2: b } = v;
515
+ g > m && s.push({ text: i.slice(m, g), ...c }), b && h && s.push({ text: b, ...c, [h]: !0 }), m = g + C.length, v = p.exec(i);
429
516
  }
430
- return b < e.length && s.push({ text: e.slice(b), ...p }), s;
517
+ return m < i.length && s.push({ text: i.slice(m), ...c }), s;
431
518
  }
432
- return { parse: i };
519
+ return { parse: a };
433
520
  }
434
- function pa(a, i, t = 768) {
435
- const n = M(t - 1), e = z(
436
- () => n.value >= t ? i : a
521
+ function Ce(e, a, n = 768) {
522
+ const t = w(n - 1), i = E(
523
+ () => t.value >= n ? a : e
437
524
  );
438
525
  if (import.meta.client) {
439
526
  const s = () => {
440
- n.value = window.innerWidth;
527
+ t.value = window.innerWidth;
441
528
  };
442
- L(() => {
529
+ z(() => {
443
530
  s(), window.addEventListener("resize", s);
444
- }), K(() => {
531
+ }), H(() => {
445
532
  window.removeEventListener("resize", s);
446
533
  });
447
534
  }
448
- return { size: e, windowWidth: n };
535
+ return { size: i, windowWidth: t };
449
536
  }
450
- function fa() {
451
- const { locale: a } = k();
452
- function i(t, n = "fr") {
453
- if (!t) return "";
454
- const e = a.value;
455
- return t[e] ?? t[n] ?? "";
537
+ function we() {
538
+ const { locale: e } = k();
539
+ function a(n, t = "fr") {
540
+ if (!n) return "";
541
+ const i = e.value;
542
+ return n[i] ?? n[t] ?? "";
456
543
  }
457
- return i;
544
+ return a;
458
545
  }
459
546
  export {
460
- x as CREATE_PENDING_KEY,
461
- ea as configureHttp,
462
- T as getViewKey,
463
- oa as showAndThrowError,
464
- ta as useClickOutside,
465
- ra as useCountriesTranslation,
466
- sa as useGtagConversion,
467
- na as useHttp,
468
- da as useHubspotContactUrl,
469
- ua as useImageCacheWatcherCallback,
470
- la as useLocaleHelpers,
471
- ca as useParseTranslation,
472
- pa as useResponsiveSize,
473
- ia as useStore,
474
- fa as useTranslate
547
+ Y as CREATE_PENDING_KEY,
548
+ le as configureHttp,
549
+ U as getViewKey,
550
+ me as showAndThrowError,
551
+ _ as useAuthSession,
552
+ pe as useClickOutside,
553
+ ge as useCountriesTranslation,
554
+ he as useGtagConversion,
555
+ ce as useHttp,
556
+ be as useHubspotContactUrl,
557
+ Be as useImageCacheWatcherCallback,
558
+ ve as useLocaleHelpers,
559
+ Ae as useParseTranslation,
560
+ Ce as useResponsiveSize,
561
+ fe as useStore,
562
+ we as useTranslate
475
563
  };
@@ -26,8 +26,8 @@ export type View<Item> = ViewKeyParams & {
26
26
  hasMore: boolean;
27
27
  };
28
28
  /**
29
- * Reserved for future "infinite scroll vs. paginated" switching. Currently
30
- * unused by the implementation — declared here to lock the public surface.
29
+ * Reserved for "infinite scroll vs. paginated" switching. Not read by the
30
+ * implementation — declared here to lock the public surface.
31
31
  */
32
32
  export type ViewOptions = {
33
33
  infinite?: boolean;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@choosemycompany/lib",
3
3
  "description": "Shared composables, stores and types for ChooseMyCompany front apps",
4
- "version": "0.7.0",
4
+ "version": "0.8.0",
5
5
  "private": false,
6
6
  "type": "module",
7
7
  "packageManager": "pnpm@10.17.0",
@@ -31,7 +31,7 @@
31
31
  "peerDependencies": {
32
32
  "@nuxtjs/i18n": "^10.0.0",
33
33
  "h3": "^1.0.0",
34
- "mande": "^2.0.0",
34
+ "mande": "^2.0.10",
35
35
  "nuxt": "^4.0.0",
36
36
  "pinia": "^3.0.0",
37
37
  "ufo": "^1.0.0",
@@ -49,7 +49,7 @@
49
49
  "h3": "^1.13.0",
50
50
  "happy-dom": "^18.0.1",
51
51
  "jiti": "^2.6.0",
52
- "mande": "^2.0.9",
52
+ "mande": "^2.0.10",
53
53
  "pinia": "^3.0.3",
54
54
  "typescript": "^5.9.2",
55
55
  "typescript-eslint": "^8.44.1",