@choosemycompany/lib 0.6.0 → 0.7.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
@@ -1,6 +1,6 @@
1
1
  # @choosemycompany/lib
2
2
 
3
- Composables, stores et types partagés entre les apps front ChooseMyCompany (`commercial`, `workspace`).
3
+ Composables, stores and types shared between the ChooseMyCompany front-end apps (`commercial`, `workspace`).
4
4
 
5
5
  ## Installation
6
6
 
@@ -8,36 +8,41 @@ Composables, stores et types partagés entre les apps front ChooseMyCompany (`co
8
8
  pnpm add @choosemycompany/lib
9
9
  ```
10
10
 
11
- ## Utilisation
11
+ ## Usage
12
12
 
13
13
  ```ts
14
14
  import { useHttp, useStore, type Store, type View } from '@choosemycompany/lib'
15
15
  ```
16
16
 
17
- Un seul entry point, tout est ré-exporté depuis `@choosemycompany/lib`.
17
+ A single entry point: everything is re-exported from `@choosemycompany/lib`.
18
18
 
19
- ## Dépendances
19
+ ## Dependencies
20
20
 
21
- Le package s'attend à être consommé **dans un projet Nuxt 4** avec les peer deps suivantes installées :
21
+ The package expects to be consumed **inside a Nuxt 4 project**, with the following peer deps installed:
22
22
 
23
23
  - `vue`, `vue-i18n`, `vue-router`, `pinia`
24
- - `mande` (client HTTP)
25
- - `h3` (pour `useErrorHandling`)
24
+ - `mande` (HTTP client)
25
+ - `h3` (for `useErrorHandling`)
26
26
  - `@nuxtjs/i18n` (`useLocalePath`)
27
- - `nuxt` (pour `useRuntimeConfig`, `useState`, `showError` importés depuis `nuxt/app`)
27
+ - `nuxt` (for `useRuntimeConfig`, `useState`, `showError`, imported from `nuxt/app`)
28
28
 
29
- Les composables utilisant `useRuntimeConfig()`, `useRoute()`, `useI18n()` doivent être appelés dans un scope Nuxt (setup, plugin, middleware).
29
+ Composables using `useRuntimeConfig()`, `useRoute()` or `useI18n()` must be called inside a Nuxt scope (setup, plugin, middleware).
30
30
 
31
- ## Développement local (HMR via sandbox)
31
+ ## Local development (HMR through the sandbox)
32
32
 
33
33
  ```bash
34
- pnpm install
35
- pnpm --filter sandbox dev # n'existe pas : sandbox est indépendant
36
- # ou
37
34
  cd sandbox && pnpm install && pnpm dev
38
35
  ```
39
36
 
40
- La sandbox utilise un alias Vite `@choosemycompany/lib` → `../src/index.ts`, donc chaque modif des sources de la lib déclenche du HMR immédiat.
37
+ Then <http://localhost:3000>. The sandbox has its own `package.json` and its own lockfile: it is not part of a pnpm workspace, hence the `cd`.
38
+
39
+ The sandbox uses a Vite alias `@choosemycompany/lib` → `../src/index.ts`, so every change to the lib's sources triggers immediate HMR. A mock API is served by Nitro: `/api/philosophers` for `useHttp` + `useStore`, and an authentication backend for the `/auth` page.
40
+
41
+ ### The `/auth` page
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.
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.
41
46
 
42
47
  ## Build & publish
43
48
 
@@ -45,10 +50,10 @@ La sandbox utilise un alias Vite `@choosemycompany/lib` → `../src/index.ts`, d
45
50
  pnpm build # vite build → dist/
46
51
  pnpm typecheck
47
52
  pnpm test
48
- pnpm publish # via CI CircleCI sur push main
53
+ pnpm publish # through CircleCI on a push to main
49
54
  ```
50
55
 
51
- ## Changements d'API notables
56
+ ## Notable API changes
52
57
 
53
- - `useStore` : signature unifiée qui absorbe la variante `workspace` (search, filters, 4ᵉ générique `FilterItem`). Méthode publique : `isPending(key)`. `getViewKey` trie les clés pour garantir un cache déterministe.
54
- - `usePrimaryTypeTranslation(primaryTypes)` : reçoit désormais la liste des primaryTypes en argument au lieu de l'importer depuis `@/entities/form` de commercial.
58
+ - `useStore`: unified signature absorbing the `workspace` variant (search, filters, a fourth `FilterItem` generic). Public method: `isPending(key)`. `getViewKey` sorts keys to guarantee a deterministic cache.
59
+ - `usePrimaryTypeTranslation(primaryTypes)`: now receives the list of primary types as an argument instead of importing it from commercial's `@/entities/form`.
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Base URLs the application declares to the library.
3
+ *
4
+ * `baseUrl` is what {@link useHttp} uses when the caller names no target.
5
+ * `targets` holds the other origins the app talks to, addressed by name.
6
+ */
7
+ export interface HttpConfig {
8
+ /** Base URL used by `useHttp()`. May carry a path prefix. */
9
+ baseUrl: string;
10
+ /** Extra origins, addressed by name: `useHttp('happy')`. */
11
+ targets?: Record<string, string>;
12
+ }
13
+ /**
14
+ * Declares the base URLs the library must use.
15
+ *
16
+ * The app owns its configuration. It reads its own keys — from
17
+ * `runtimeConfig`, from the environment, from anywhere — and it hands the
18
+ * result to the library. The library never reads the configuration of the app,
19
+ * so it imposes no key name and it needs no knowledge of the host framework.
20
+ *
21
+ * Call this once, as early as the app can: a Nuxt plugin, or the entry point of
22
+ * a non-Nuxt host.
23
+ *
24
+ * The key names below belong to the app, and to the app alone. This library
25
+ * names none of them, which is the whole point of the arrangement.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * // app/plugins/00.http.ts
30
+ * const config = useRuntimeConfig()
31
+ *
32
+ * configureHttp({
33
+ * baseUrl: config.public.apiBaseUrl as string,
34
+ * targets: { reporting: config.public.reportingApiUrl as string },
35
+ * })
36
+ * ```
37
+ */
38
+ export declare function configureHttp(config: HttpConfig): void;
39
+ /**
40
+ * Returns the base URL for a target, or the default base URL when `target` is
41
+ * absent.
42
+ *
43
+ * Throws instead of returning `undefined`. A base URL that is missing builds
44
+ * request URLs such as `"undefined/api/v2/…"`, which fail far from their cause
45
+ * and read as a network problem once they do.
46
+ *
47
+ * Internal: the public surface is {@link configureHttp} and {@link useHttp}.
48
+ */
49
+ export declare function resolveBaseUrl(target?: string): string;
50
+ /**
51
+ * Test seam: drops the declaration so a suite can declare again between cases.
52
+ * Not part of the public API.
53
+ */
54
+ export declare function resetHttpConfig(): void;
@@ -1,11 +1,17 @@
1
1
  import { MandeInstance } from 'mande';
2
2
  /**
3
- * Returns a `mande` instance pre-configured against the CMC API base URL,
4
- * along with two helpers to attach/detach the `Authorization` bearer token.
3
+ * Returns a `mande` instance bound to one of the base URLs the app declared
4
+ * through `configureHttp`, along with two helpers to attach/detach the
5
+ * `Authorization` bearer token.
5
6
  *
6
7
  * The returned `http` instance exposes the standard `mande` verbs
7
- * (`get`, `post`, `put`, `patch`, `delete`) and is meant to be the only
8
- * way the lib (and downstream apps) talk to the CMC backend.
8
+ * (`get`, `post`, `put`, `patch`, `delete`) and is meant to be the only way the
9
+ * lib (and downstream apps) talk to an HTTP backend.
10
+ *
11
+ * @param target - Name of a declared target. Omit it for the default base URL,
12
+ * which is what almost every caller wants. Name one to reach
13
+ * another origin the app declared — the call site then holds no
14
+ * URL of its own, and no second HTTP client has to exist.
9
15
  *
10
16
  * @example
11
17
  * ```ts
@@ -15,8 +21,13 @@ import { MandeInstance } from 'mande';
15
21
  * const { item } = await http.get<RetrieveResponse<User>>('/me')
16
22
  * clearToken() // on logout
17
23
  * ```
24
+ *
25
+ * @example Another declared origin
26
+ * ```ts
27
+ * const { http } = useHttp('happy')
28
+ * ```
18
29
  */
19
- export declare function useHttp(): {
30
+ export declare function useHttp(target?: string): {
20
31
  http: MandeInstance;
21
32
  setToken: (token: string) => void;
22
33
  clearToken: () => void;
package/dist/index.d.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  * re-exported here is considered internal and may change without notice.
6
6
  *
7
7
  * Grouped by concern:
8
- * - **HTTP** — {@link useHttp}: thin `mande` wrapper bound to the CMC API base URL.
8
+ * - **HTTP** — {@link configureHttp}: the app declares its base URLs;
9
+ * {@link useHttp}: thin `mande` wrapper bound to one of them.
9
10
  * - **Store** — {@link useStore}, {@link getViewKey}: typed cache for `retrieve` /
10
11
  * `list` workflows with single-flight, per-key errors, and CRUD mutations.
11
12
  * - **i18n** — locale-aware translators for plain strings, country names,
@@ -18,6 +19,7 @@
18
19
  * @packageDocumentation
19
20
  */
20
21
  export { useHttp } from './http/useHttp';
22
+ export { configureHttp, type HttpConfig } from './http/config';
21
23
  export { useStore, getViewKey, CREATE_PENDING_KEY, type Store } from './store/useStore';
22
24
  export { useClickOutside } from './ui/useClickOutside';
23
25
  export { useCountriesTranslation, type CountryCodes } from './i18n/useCountriesTranslation';
package/dist/index.js CHANGED
@@ -1,14 +1,31 @@
1
1
  import { mande as D } from "mande";
2
- import { useRuntimeConfig as L, showError as K, useState as H } from "nuxt/app";
3
- import { ref as M, onMounted as z, onBeforeUnmount as F, computed as N, onUnmounted as O } from "vue";
2
+ import { ref as M, onMounted as L, onBeforeUnmount as N, computed as z, onUnmounted as K } from "vue";
4
3
  import { useI18n as k } from "vue-i18n";
5
- import { createError as q } from "h3";
4
+ import { createError as H } from "h3";
5
+ import { showError as F, useRuntimeConfig as O, useState as q } from "nuxt/app";
6
6
  let w;
7
- function Z() {
8
- return w || (w = L().public.cmcApiUrl, w);
7
+ function ea(a) {
8
+ if (!a.baseUrl)
9
+ throw new Error("@choosemycompany/lib: configureHttp() needs a non-empty baseUrl");
10
+ w = a;
9
11
  }
10
- function ea() {
11
- const a = Z(), i = D(a, {
12
+ function Z(a) {
13
+ if (!w)
14
+ throw new Error(
15
+ "@choosemycompany/lib: useHttp() was called before configureHttp(). Declare the base URLs from an app plugin."
16
+ );
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";
21
+ throw new Error(
22
+ `@choosemycompany/lib: no HTTP target named "${a}". Declared targets: ${e}.`
23
+ );
24
+ }
25
+ return t;
26
+ }
27
+ function na(a) {
28
+ const i = D(Z(a), {
12
29
  headers: {}
13
30
  });
14
31
  function t(e) {
@@ -26,7 +43,7 @@ function T(a) {
26
43
  return Object.entries(a).sort(([i], [t]) => i.localeCompare(t)).map(([i, t]) => `${i}=${t}`).join("|");
27
44
  }
28
45
  const x = "create";
29
- function na(a) {
46
+ function ia(a) {
30
47
  const i = M({}), t = M({}), n = M({}), e = M({}), s = a.getItemId ?? ((r) => {
31
48
  const d = r.id;
32
49
  if (d === void 0)
@@ -58,18 +75,18 @@ function na(a) {
58
75
  const u = e.value[r];
59
76
  if (u)
60
77
  return u;
61
- const f = a.fetchOne, C = (async () => {
78
+ const f = a.fetchOne, A = (async () => {
62
79
  try {
63
- const A = await f(r), h = a.enrichItem ? a.enrichItem(A) : A;
80
+ const C = await f(r), h = a.enrichItem ? a.enrichItem(C) : C;
64
81
  return i.value[r] = h, delete n.value[r], i.value[r];
65
- } catch (A) {
66
- n.value[r] = A;
82
+ } catch (C) {
83
+ n.value[r] = C;
67
84
  return;
68
85
  } finally {
69
86
  delete e.value[r];
70
87
  }
71
88
  })();
72
- return e.value[r] = C, C;
89
+ return e.value[r] = A, A;
73
90
  }
74
91
  function p(r) {
75
92
  const d = T(r), o = t.value[d];
@@ -91,15 +108,15 @@ function na(a) {
91
108
  const f = e.value[o];
92
109
  if (f)
93
110
  return await f, p(r);
94
- const C = a.fetchPage, A = (async () => {
111
+ const A = a.fetchPage, C = (async () => {
95
112
  try {
96
- const h = await C(r), R = [];
97
- for (const E of h.items) {
98
- const y = a.enrichItem ? a.enrichItem(E) : E, P = s(y);
99
- i.value[P] = y, R.push(P);
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);
100
117
  }
101
118
  t.value[o] = {
102
- itemIds: R,
119
+ itemIds: E,
103
120
  total: h.total,
104
121
  hasMore: h.hasMore,
105
122
  page: h.page,
@@ -111,13 +128,13 @@ function na(a) {
111
128
  delete e.value[o];
112
129
  }
113
130
  })();
114
- return e.value[o] = A, await A, p(r);
131
+ return e.value[o] = C, await C, p(r);
115
132
  }
116
133
  async function B(r, d = x) {
117
134
  if (!a.createMutation)
118
135
  throw new Error("useStore.create called but createMutation is not defined in store options");
119
- const o = a.createMutation, u = await l(d, (async () => o(r))()), f = a.enrichItem ? a.enrichItem(u) : u, C = s(f);
120
- return i.value[C] = f, t.value = {}, f;
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;
121
138
  }
122
139
  async function m(r, d) {
123
140
  if (!a.updateMutation)
@@ -143,18 +160,18 @@ function na(a) {
143
160
  }
144
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 };
145
162
  }
146
- function ia(a, i) {
163
+ function ta(a, i) {
147
164
  const t = (n) => {
148
165
  const e = a.value, s = n.target;
149
166
  !e || !s || e.contains(s) || i();
150
167
  };
151
- z(() => {
168
+ L(() => {
152
169
  document.addEventListener("click", t);
153
- }), F(() => {
170
+ }), N(() => {
154
171
  document.removeEventListener("click", t);
155
172
  });
156
173
  }
157
- function ta() {
174
+ function ra() {
158
175
  const { locale: a } = k();
159
176
  function i(t, n = null) {
160
177
  const e = V[t.trim().toUpperCase()];
@@ -308,17 +325,17 @@ const V = {
308
325
  ZA: { en: "South Africa", fr: "Afrique Du Sud", es: "Sudáfrica", de: "Südafrika", it: "Sudafrica", pt: "África Do Sul", da: "Sydafrika" },
309
326
  ZM: { en: "Zambia", fr: "Zambie", es: "Zambia", de: "Sambia", it: "Zambia", pt: "Zâmbia", da: "Zambia" },
310
327
  ZW: { en: "Zimbabwe", fr: "Zimbabwe", es: "Zimbabue", de: "Simbabwe", it: "Zimbabwe", pt: "Zimbábue", da: "Zimbabwe" }
311
- }, ra = ({ code: a, message: i, data: t }) => {
312
- const n = i || "An unexpected error occurred", e = q({
328
+ }, oa = ({ code: a, message: i, data: t }) => {
329
+ const n = i || "An unexpected error occurred", e = H({
313
330
  statusCode: a,
314
331
  statusMessage: n,
315
332
  message: n,
316
333
  data: t
317
334
  });
318
- throw K(e), e;
335
+ throw F(e), e;
319
336
  }, J = "ilcJCL_lmpwcEJfSkKND";
320
- function oa() {
321
- const { gtagId: a } = L().public;
337
+ function sa() {
338
+ const { gtagId: a } = O().public;
322
339
  return { reportConversion: () => {
323
340
  if (typeof window > "u" || typeof window.gtag > "u" || !a)
324
341
  return;
@@ -329,11 +346,11 @@ function oa() {
329
346
  } };
330
347
  }
331
348
  const U = "https://5509641.hs-sites-eu1.com";
332
- function sa() {
349
+ function da() {
333
350
  const { locale: a } = k();
334
- return { contactUrl: N(() => a.value === "fr" ? `${U}/contact` : `${U}/${a.value}/contact`) };
351
+ return { contactUrl: z(() => a.value === "fr" ? `${U}/contact` : `${U}/${a.value}/contact`) };
335
352
  }
336
- function da() {
353
+ function ua() {
337
354
  async function a(n) {
338
355
  await Promise.all(
339
356
  n.map(
@@ -353,7 +370,7 @@ function da() {
353
370
  return async (l) => {
354
371
  n.value = !0;
355
372
  };
356
- const c = H(
373
+ const c = q(
357
374
  `${e}LoadedImageCache`,
358
375
  () => ({})
359
376
  );
@@ -387,7 +404,7 @@ function _(a) {
387
404
  function G(a) {
388
405
  return a.toString().trim().toUpperCase();
389
406
  }
390
- function ua() {
407
+ function la() {
391
408
  function a(i, t) {
392
409
  if (!t.length) return;
393
410
  const n = t.map(G), e = new Set(n), { language: s, region: c } = _(i), l = [];
@@ -401,7 +418,7 @@ function ua() {
401
418
  }
402
419
  return { getRegionFromLocale: a };
403
420
  }
404
- function la() {
421
+ function ca() {
405
422
  const { t: a } = k();
406
423
  function i(t, n) {
407
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), {});
@@ -414,23 +431,23 @@ function la() {
414
431
  }
415
432
  return { parse: i };
416
433
  }
417
- function ca(a, i, t = 768) {
418
- const n = M(t - 1), e = N(
434
+ function pa(a, i, t = 768) {
435
+ const n = M(t - 1), e = z(
419
436
  () => n.value >= t ? i : a
420
437
  );
421
438
  if (import.meta.client) {
422
439
  const s = () => {
423
440
  n.value = window.innerWidth;
424
441
  };
425
- z(() => {
442
+ L(() => {
426
443
  s(), window.addEventListener("resize", s);
427
- }), O(() => {
444
+ }), K(() => {
428
445
  window.removeEventListener("resize", s);
429
446
  });
430
447
  }
431
448
  return { size: e, windowWidth: n };
432
449
  }
433
- function pa() {
450
+ function fa() {
434
451
  const { locale: a } = k();
435
452
  function i(t, n = "fr") {
436
453
  if (!t) return "";
@@ -441,17 +458,18 @@ function pa() {
441
458
  }
442
459
  export {
443
460
  x as CREATE_PENDING_KEY,
461
+ ea as configureHttp,
444
462
  T as getViewKey,
445
- ra as showAndThrowError,
446
- ia as useClickOutside,
447
- ta as useCountriesTranslation,
448
- oa as useGtagConversion,
449
- ea as useHttp,
450
- sa as useHubspotContactUrl,
451
- da as useImageCacheWatcherCallback,
452
- ua as useLocaleHelpers,
453
- la as useParseTranslation,
454
- ca as useResponsiveSize,
455
- na as useStore,
456
- pa as useTranslate
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
457
475
  };
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.6.0",
4
+ "version": "0.7.0",
5
5
  "private": false,
6
6
  "type": "module",
7
7
  "packageManager": "pnpm@10.17.0",