@laconius/core 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 (90) hide show
  1. package/LICENSE +73 -0
  2. package/README.md +31 -0
  3. package/lib/module/auth.js +182 -0
  4. package/lib/module/auth.js.map +1 -0
  5. package/lib/module/client.js +99 -0
  6. package/lib/module/client.js.map +1 -0
  7. package/lib/module/config.js +72 -0
  8. package/lib/module/config.js.map +1 -0
  9. package/lib/module/converters.js +31 -0
  10. package/lib/module/converters.js.map +1 -0
  11. package/lib/module/create-config.js +36 -0
  12. package/lib/module/create-config.js.map +1 -0
  13. package/lib/module/endpoints.js +89 -0
  14. package/lib/module/endpoints.js.map +1 -0
  15. package/lib/module/errors.js +76 -0
  16. package/lib/module/errors.js.map +1 -0
  17. package/lib/module/i18n.js +84 -0
  18. package/lib/module/i18n.js.map +1 -0
  19. package/lib/module/index.js +18 -0
  20. package/lib/module/index.js.map +1 -0
  21. package/lib/module/media.js +182 -0
  22. package/lib/module/media.js.map +1 -0
  23. package/lib/module/models.js +2 -0
  24. package/lib/module/models.js.map +1 -0
  25. package/lib/module/package.json +1 -0
  26. package/lib/module/provider.js +182 -0
  27. package/lib/module/provider.js.map +1 -0
  28. package/lib/module/runtime.js +43 -0
  29. package/lib/module/runtime.js.map +1 -0
  30. package/lib/module/single-flight.js +23 -0
  31. package/lib/module/single-flight.js.map +1 -0
  32. package/lib/module/site-context.js +74 -0
  33. package/lib/module/site-context.js.map +1 -0
  34. package/lib/module/stores.js +66 -0
  35. package/lib/module/stores.js.map +1 -0
  36. package/lib/module/translations.js +42 -0
  37. package/lib/module/translations.js.map +1 -0
  38. package/lib/typescript/package.json +1 -0
  39. package/lib/typescript/src/auth.d.ts +31 -0
  40. package/lib/typescript/src/auth.d.ts.map +1 -0
  41. package/lib/typescript/src/client.d.ts +31 -0
  42. package/lib/typescript/src/client.d.ts.map +1 -0
  43. package/lib/typescript/src/config.d.ts +150 -0
  44. package/lib/typescript/src/config.d.ts.map +1 -0
  45. package/lib/typescript/src/converters.d.ts +17 -0
  46. package/lib/typescript/src/converters.d.ts.map +1 -0
  47. package/lib/typescript/src/create-config.d.ts +11 -0
  48. package/lib/typescript/src/create-config.d.ts.map +1 -0
  49. package/lib/typescript/src/endpoints.d.ts +36 -0
  50. package/lib/typescript/src/endpoints.d.ts.map +1 -0
  51. package/lib/typescript/src/errors.d.ts +43 -0
  52. package/lib/typescript/src/errors.d.ts.map +1 -0
  53. package/lib/typescript/src/i18n.d.ts +20 -0
  54. package/lib/typescript/src/i18n.d.ts.map +1 -0
  55. package/lib/typescript/src/index.d.ts +17 -0
  56. package/lib/typescript/src/index.d.ts.map +1 -0
  57. package/lib/typescript/src/media.d.ts +81 -0
  58. package/lib/typescript/src/media.d.ts.map +1 -0
  59. package/lib/typescript/src/models.d.ts +327 -0
  60. package/lib/typescript/src/models.d.ts.map +1 -0
  61. package/lib/typescript/src/provider.d.ts +37 -0
  62. package/lib/typescript/src/provider.d.ts.map +1 -0
  63. package/lib/typescript/src/runtime.d.ts +26 -0
  64. package/lib/typescript/src/runtime.d.ts.map +1 -0
  65. package/lib/typescript/src/single-flight.d.ts +7 -0
  66. package/lib/typescript/src/single-flight.d.ts.map +1 -0
  67. package/lib/typescript/src/site-context.d.ts +28 -0
  68. package/lib/typescript/src/site-context.d.ts.map +1 -0
  69. package/lib/typescript/src/stores.d.ts +54 -0
  70. package/lib/typescript/src/stores.d.ts.map +1 -0
  71. package/lib/typescript/src/translations.d.ts +40 -0
  72. package/lib/typescript/src/translations.d.ts.map +1 -0
  73. package/package.json +77 -0
  74. package/src/auth.ts +223 -0
  75. package/src/client.ts +133 -0
  76. package/src/config.ts +191 -0
  77. package/src/converters.ts +47 -0
  78. package/src/create-config.ts +29 -0
  79. package/src/endpoints.ts +133 -0
  80. package/src/errors.ts +104 -0
  81. package/src/i18n.ts +108 -0
  82. package/src/index.ts +123 -0
  83. package/src/media.ts +209 -0
  84. package/src/models.ts +384 -0
  85. package/src/provider.tsx +229 -0
  86. package/src/runtime.ts +57 -0
  87. package/src/single-flight.ts +23 -0
  88. package/src/site-context.ts +77 -0
  89. package/src/stores.ts +94 -0
  90. package/src/translations.ts +40 -0
package/LICENSE ADDED
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @laconius/core
2
+
3
+ The foundation every Laconius package peers on: configuration, the OCC HTTP client, auth, state,
4
+ converters, media and i18n. No React Native UI — just the runtime.
5
+
6
+ ## Public API
7
+
8
+ - **Config**: `createLaconiusConfig(app, chunks)` deep-merges the app's config over the feature
9
+ defaults (`defaultCartConfig`, …). Arrays replace, objects merge, nothing self-registers.
10
+ - **Provider**: `<LaconiusProvider config={…}>` wires TanStack Query, hydrates the stored
11
+ session, and exposes `useLaconius()`, `useLaconiusConfig()`, `useIsLoggedIn()`,
12
+ `useIsOnline()`, `useLogout()`, `useSiteContext()`, `useTranslation()`.
13
+ - **HTTP**: `createHttpClient` — endpoint resolution with `${param}` templates and query-string
14
+ merging, `lang` / `curr` appended, `Authorization` attached (never on `basesites`, never
15
+ overwriting a caller's), proactive + single-flight token refresh, and the OCC `errors[]`
16
+ envelope parsed into `LaconiusHttpError`. `getErrorMessage(error, t)` turns any error into a
17
+ translated sentence.
18
+ - **Auth**: Authorization Code + PKCE via `expo-auth-session`; refresh token in
19
+ `expo-secure-store`, access token in memory ([ADR-0003](../../docs/adr/0003-refresh-token-in-the-keychain.md)).
20
+ `auth.tokenProvider` is the slot for CDC or a legacy auth server.
21
+ - **State**: `useSessionStore`, `useSiteContextStore` (Zustand); `userId` is derived, never
22
+ stored. `laconiusQueryKey(feature, …)` builds the `['laconius', feature, {ctx}, …]` keys.
23
+ - **Converters**: `Converter<S, T>` — the Spartacus populator signature as a plain function —
24
+ registered under typed string keys, applied by adapters.
25
+ - **Media**: `normalizeImages`, `resolveMediaCandidates`, `getPrimaryImage`, `absolutizeMedia` —
26
+ format-based candidate sets for `expo-image`.
27
+ - **i18n**: ~40 lines — key lookup, `{{param}}` interpolation, `Intl.PluralRules`. Apps with an
28
+ existing runtime set `i18n.translate`.
29
+ - **Models**: the shared domain types (`Product`, `Price`, `Address`, `User`, …).
30
+
31
+ See the [spec](../../docs/spec/) — chapters 02–05, 08 and 09 are this package.
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+
3
+ import * as AuthSession from 'expo-auth-session';
4
+ import * as SecureStore from 'expo-secure-store';
5
+ import { singleFlight } from "./single-flight.js";
6
+ import { selectUserId, useSessionStore } from "./stores.js";
7
+ const REFRESH_TOKEN_KEY = 'laconius.refreshToken';
8
+
9
+ /** Refresh-token storage failed. Treated as "no stored session", never as a crash. */
10
+ export class SecureStorageError extends Error {
11
+ constructor(operation, cause) {
12
+ super(`[laconius] Secure storage ${operation} failed.`);
13
+ this.name = 'SecureStorageError';
14
+ this.cause = cause;
15
+ }
16
+ }
17
+ /**
18
+ * Built from config, never from the server's discovery document: that document is wrong about
19
+ * its own server (it never advertises `none` for token endpoint auth, which demonstrably works).
20
+ */
21
+ export function createDiscovery(authServerUrl) {
22
+ const base = authServerUrl.replace(/\/$/, '');
23
+ return {
24
+ authorizationEndpoint: `${base}/oauth/authorize`,
25
+ tokenEndpoint: `${base}/oauth/token`,
26
+ revocationEndpoint: `${base}/oauth/revoke`
27
+ };
28
+ }
29
+ const EXPIRY_SKEW_MS = 60_000;
30
+ export function createAuthClient(config) {
31
+ const auth = config.auth;
32
+ const discovery = createDiscovery(auth.authServerUrl);
33
+ const report = error => config.onError?.(error, {});
34
+ const storeRefreshToken = async token => {
35
+ try {
36
+ if (token === undefined) {
37
+ await SecureStore.deleteItemAsync(REFRESH_TOKEN_KEY);
38
+ } else {
39
+ await SecureStore.setItemAsync(REFRESH_TOKEN_KEY, token, {
40
+ requireAuthentication: auth.requireBiometricUnlock ?? false
41
+ });
42
+ }
43
+ } catch (error) {
44
+ report(new SecureStorageError('write', error));
45
+ }
46
+ };
47
+ const readRefreshToken = async () => {
48
+ try {
49
+ return (await SecureStore.getItemAsync(REFRESH_TOKEN_KEY)) ?? undefined;
50
+ } catch (error) {
51
+ // Biometric re-enrolment invalidates the key: that is "no stored session".
52
+ report(new SecureStorageError('read', error));
53
+ return undefined;
54
+ }
55
+ };
56
+ const adopt = async tokens => {
57
+ useSessionStore.getState().setSession({
58
+ accessToken: tokens.accessToken,
59
+ refreshToken: tokens.refreshToken,
60
+ expiresAt: tokens.expiresAt
61
+ });
62
+ if (tokens.refreshToken) await storeRefreshToken(tokens.refreshToken);
63
+ return tokens;
64
+ };
65
+ const fromTokenResponse = response => ({
66
+ accessToken: response.accessToken,
67
+ refreshToken: response.refreshToken,
68
+ expiresAt: response.expiresIn ? (response.issuedAt + response.expiresIn) * 1000 : undefined
69
+ });
70
+ const fromTokenProvider = async () => {
71
+ if (!auth.tokenProvider) return undefined;
72
+ const token = await auth.tokenProvider();
73
+ return {
74
+ accessToken: token.access_token,
75
+ refreshToken: token.refresh_token,
76
+ expiresAt: Date.now() + token.expires_in * 1000
77
+ };
78
+ };
79
+ const expire = async () => {
80
+ useSessionStore.getState().clearSession();
81
+ await storeRefreshToken(undefined);
82
+ auth.onAuthExpired?.();
83
+ };
84
+ const refresh = singleFlight(async () => {
85
+ const refreshToken = useSessionStore.getState().refreshToken;
86
+ try {
87
+ if (refreshToken) {
88
+ const response = await AuthSession.refreshAsync({
89
+ clientId: auth.clientId,
90
+ refreshToken
91
+ }, discovery);
92
+ return await adopt(fromTokenResponse(response));
93
+ }
94
+ const provided = await fromTokenProvider();
95
+ if (provided) return await adopt(provided);
96
+ } catch (error) {
97
+ report(error);
98
+ }
99
+ await expire();
100
+ return undefined;
101
+ });
102
+ return {
103
+ refresh,
104
+ async login() {
105
+ const provided = await fromTokenProvider();
106
+ if (provided) return adopt(provided);
107
+
108
+ // Imperative API, never `useAuthRequest`: refresh must be callable outside React.
109
+ const request = await AuthSession.loadAsync({
110
+ clientId: auth.clientId,
111
+ redirectUri: auth.redirectUri,
112
+ responseType: AuthSession.ResponseType.Code,
113
+ usePKCE: true,
114
+ scopes: []
115
+ }, discovery);
116
+ const result = await request.promptAsync(discovery);
117
+ if (result.type !== 'success') return undefined;
118
+ const response = await AuthSession.exchangeCodeAsync({
119
+ clientId: auth.clientId,
120
+ redirectUri: auth.redirectUri,
121
+ code: result.params['code'] ?? '',
122
+ extraParams: request.codeVerifier ? {
123
+ code_verifier: request.codeVerifier
124
+ } : {}
125
+ }, discovery);
126
+ return adopt(fromTokenResponse(response));
127
+ },
128
+ async logout() {
129
+ const {
130
+ accessToken,
131
+ refreshToken
132
+ } = useSessionStore.getState();
133
+ const token = refreshToken ?? accessToken;
134
+ if (token && discovery.revocationEndpoint) {
135
+ try {
136
+ // No Authorization header: the rebuilt authorization server reads one as *client*
137
+ // authentication, and a PKCE public client has no secret — the request comes back
138
+ // `invalid_client` and the token stays alive. Unauthenticated, revoke returns 200 and
139
+ // the refresh token is dead (verified live, ticket 23).
140
+ await fetch(discovery.revocationEndpoint, {
141
+ method: 'POST',
142
+ headers: {
143
+ 'Content-Type': 'application/x-www-form-urlencoded'
144
+ },
145
+ body: `token=${encodeURIComponent(token)}&token_type_hint=${refreshToken ? 'refresh_token' : 'access_token'}&client_id=${encodeURIComponent(auth.clientId)}`
146
+ });
147
+ } catch (error) {
148
+ // A failed revoke still logs out locally.
149
+ report(error);
150
+ }
151
+ }
152
+ useSessionStore.getState().clearSession();
153
+ await storeRefreshToken(undefined);
154
+ },
155
+ async hydrate() {
156
+ const stored = await readRefreshToken();
157
+ if (!stored) return undefined;
158
+ useSessionStore.getState().setSession({
159
+ refreshToken: stored
160
+ });
161
+ return refresh();
162
+ },
163
+ async getAccessToken() {
164
+ const {
165
+ accessToken,
166
+ expiresAt
167
+ } = useSessionStore.getState();
168
+ if (accessToken && (!expiresAt || Date.now() < expiresAt - EXPIRY_SKEW_MS)) {
169
+ return accessToken;
170
+ }
171
+ if (!accessToken && !useSessionStore.getState().refreshToken) {
172
+ return undefined;
173
+ }
174
+ return (await refresh())?.accessToken;
175
+ },
176
+ getUserId() {
177
+ const userId = selectUserId(useSessionStore.getState());
178
+ return auth.decorateUserId?.(userId, config.backend.occ.baseSite) ?? userId;
179
+ }
180
+ };
181
+ }
182
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["AuthSession","SecureStore","singleFlight","selectUserId","useSessionStore","REFRESH_TOKEN_KEY","SecureStorageError","Error","constructor","operation","cause","name","createDiscovery","authServerUrl","base","replace","authorizationEndpoint","tokenEndpoint","revocationEndpoint","EXPIRY_SKEW_MS","createAuthClient","config","auth","discovery","report","error","onError","storeRefreshToken","token","undefined","deleteItemAsync","setItemAsync","requireAuthentication","requireBiometricUnlock","readRefreshToken","getItemAsync","adopt","tokens","getState","setSession","accessToken","refreshToken","expiresAt","fromTokenResponse","response","expiresIn","issuedAt","fromTokenProvider","tokenProvider","access_token","refresh_token","Date","now","expires_in","expire","clearSession","onAuthExpired","refresh","refreshAsync","clientId","provided","login","request","loadAsync","redirectUri","responseType","ResponseType","Code","usePKCE","scopes","result","promptAsync","type","exchangeCodeAsync","code","params","extraParams","codeVerifier","code_verifier","logout","fetch","method","headers","body","encodeURIComponent","hydrate","stored","getAccessToken","getUserId","userId","decorateUserId","backend","occ","baseSite"],"sourceRoot":"../../src","sources":["auth.ts"],"mappings":";;AAAA,OAAO,KAAKA,WAAW,MAAM,mBAAmB;AAChD,OAAO,KAAKC,WAAW,MAAM,mBAAmB;AAGhD,SAASC,YAAY,QAAQ,oBAAiB;AAC9C,SAASC,YAAY,EAAEC,eAAe,QAAQ,aAAU;AAExD,MAAMC,iBAAiB,GAAG,uBAAuB;;AAEjD;AACA,OAAO,MAAMC,kBAAkB,SAASC,KAAK,CAAC;EAC5CC,WAAWA,CAACC,SAAiB,EAAEC,KAAc,EAAE;IAC7C,KAAK,CAAC,6BAA6BD,SAAS,UAAU,CAAC;IACvD,IAAI,CAACE,IAAI,GAAG,oBAAoB;IAChC,IAAI,CAACD,KAAK,GAAGA,KAAK;EACpB;AACF;AASA;AACA;AACA;AACA;AACA,OAAO,SAASE,eAAeA,CAC7BC,aAAqB,EACU;EAC/B,MAAMC,IAAI,GAAGD,aAAa,CAACE,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;EAC7C,OAAO;IACLC,qBAAqB,EAAE,GAAGF,IAAI,kBAAkB;IAChDG,aAAa,EAAE,GAAGH,IAAI,cAAc;IACpCI,kBAAkB,EAAE,GAAGJ,IAAI;EAC7B,CAAC;AACH;AAeA,MAAMK,cAAc,GAAG,MAAM;AAE7B,OAAO,SAASC,gBAAgBA,CAACC,MAAsB,EAAc;EACnE,MAAMC,IAAwB,GAAGD,MAAM,CAACC,IAAI;EAC5C,MAAMC,SAAS,GAAGX,eAAe,CAACU,IAAI,CAACT,aAAa,CAAC;EACrD,MAAMW,MAAM,GAAIC,KAAc,IAAKJ,MAAM,CAACK,OAAO,GAAGD,KAAK,EAAE,CAAC,CAAC,CAAC;EAE9D,MAAME,iBAAiB,GAAG,MAAOC,KAAyB,IAAK;IAC7D,IAAI;MACF,IAAIA,KAAK,KAAKC,SAAS,EAAE;QAC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AEDgD,SAASA,CAAA,EAAG;MACV,MAAMC,MAAM,GAAGtF,YAAY,CAACC,eAAe,CAACkC,QAAQ,CAAC,CAAC,CAAC;MACvD,OACEhB,IAAI,CAACoE,cAAc,GAAGD,MAAM,EAAEpE,MAAM,CAACsE,OAAO,CAACC,GAAG,CAACC,QAAQ,CAAC,IAAIJ,MAAM;IAExE;EACF,CAAC;AACH","ignoreList":[]}
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+
3
+ import { createEndpointResolver } from "./endpoints.js";
4
+ import { LaconiusHttpError, parseOccErrors } from "./errors.js";
5
+ import { resolveCurrency, resolveLanguage } from "./stores.js";
6
+
7
+ /** Endpoints that must never carry an `Authorization` header. */
8
+ const ANONYMOUS_ENDPOINTS = new Set(['baseSites']);
9
+ /**
10
+ * Lives outside React so refresh and session reads work from anywhere.
11
+ *
12
+ * `lang` and `curr` are appended here rather than by adapters — the same division Spartacus
13
+ * draws with an interceptor.
14
+ */
15
+ export function createHttpClient(config, auth) {
16
+ const endpoints = createEndpointResolver(config);
17
+ async function send(options, retrying) {
18
+ const anonymous = options.anonymous || ANONYMOUS_ENDPOINTS.has(options.endpoint);
19
+ const url = endpoints.getEndpoint(options.endpoint, {
20
+ urlParams: {
21
+ userId: auth.getUserId(),
22
+ ...options.urlParams
23
+ },
24
+ queryParams: {
25
+ lang: resolveLanguage(config),
26
+ curr: resolveCurrency(config),
27
+ ...options.queryParams
28
+ }
29
+ }, options.scope);
30
+ const headers = {
31
+ Accept: 'application/json'
32
+ };
33
+ if (options.form) {
34
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
35
+ } else if (options.body !== undefined) {
36
+ headers['Content-Type'] = 'application/json';
37
+ }
38
+ if (!anonymous) {
39
+ const token = await auth.getAccessToken();
40
+ if (token) headers['Authorization'] = `Bearer ${token}`;
41
+ }
42
+ // Never overwrite a header the caller set.
43
+ Object.assign(headers, options.headers);
44
+ let response;
45
+ try {
46
+ response = await fetch(url, {
47
+ method: options.method ?? 'GET',
48
+ headers,
49
+ body: options.form ? new URLSearchParams(options.form).toString() : options.body !== undefined ? JSON.stringify(options.body) : undefined,
50
+ signal: options.signal
51
+ });
52
+ } catch (cause) {
53
+ const error = new LaconiusHttpError({
54
+ status: 0,
55
+ url,
56
+ message: cause instanceof Error ? cause.message : 'Network request failed'
57
+ });
58
+ config.onError?.(error, {
59
+ url
60
+ });
61
+ throw error;
62
+ }
63
+ const payload = await readPayload(response);
64
+ if (!response.ok) {
65
+ if (response.status === 401 && !anonymous && !retrying) {
66
+ const refreshed = await auth.refresh();
67
+ if (refreshed) return send(options, true);
68
+ }
69
+ const error = new LaconiusHttpError({
70
+ status: response.status,
71
+ url,
72
+ occErrors: parseOccErrors(payload),
73
+ body: payload
74
+ });
75
+ config.onError?.(error, {
76
+ url
77
+ });
78
+ throw error;
79
+ }
80
+ return payload;
81
+ }
82
+ return {
83
+ endpoints,
84
+ request(options) {
85
+ return send(options, false);
86
+ }
87
+ };
88
+ }
89
+ async function readPayload(response) {
90
+ if (response.status === 204) return undefined;
91
+ const text = await response.text();
92
+ if (!text) return undefined;
93
+ try {
94
+ return JSON.parse(text);
95
+ } catch {
96
+ return text;
97
+ }
98
+ }
99
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["createEndpointResolver","LaconiusHttpError","parseOccErrors","resolveCurrency","resolveLanguage","ANONYMOUS_ENDPOINTS","Set","createHttpClient","config","auth","endpoints","send","options","retrying","anonymous","has","endpoint","url","getEndpoint","urlParams","userId","getUserId","queryParams","lang","curr","scope","headers","Accept","form","body","undefined","token","getAccessToken","Object","assign","response","fetch","method","URLSearchParams","toString","JSON","stringify","signal","cause","error","status","message","Error","onError","payload","readPayload","ok","refreshed","refresh","occErrors","request","text","parse"],"sourceRoot":"../../src","sources":["client.ts"],"mappings":";;AAEA,SAASA,sBAAsB,QAA+B,gBAAa;AAC3E,SAASC,iBAAiB,EAAEC,cAAc,QAAQ,aAAU;AAC5D,SAASC,eAAe,E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MAAM;QACvB5B,GAAG;QACHqC,SAAS,EAAEpD,cAAc,CAAC+C,OAAO,CAAC;QAClCpB,IAAI,EAAEoB;MACR,CAAC,CAAC;MACFzC,MAAM,CAACwC,OAAO,GAAGJ,KAAK,EAAE;QAAE3B;MAAI,CAAC,CAAC;MAChC,MAAM2B,KAAK;IACb;IAEA,OAAOK,OAAO;EAChB;EAEA,OAAO;IACLvC,SAAS;IACT6C,OAAOA,CAAC3C,OAAO,EAAE;MACf,OAAOD,IAAI,CAACC,OAAO,EAAE,KAAK,CAAC;IAC7B;EACF,CAAC;AACH;AAEA,eAAesC,WAAWA,CAACf,QAAkB,EAAoB;EAC/D,IAAIA,QAAQ,CAACU,MAAM,KAAK,GAAG,EAAE,OAAOf,SAAS;EAC7C,MAAM0B,IAAI,GAAG,MAAMrB,QAAQ,CAACqB,IAAI,CAAC,CAAC;EAClC,IAAI,CAACA,IAAI,EAAE,OAAO1B,SAAS;EAC3B,IAAI;IACF,OAAOU,IAAI,CAACiB,KAAK,CAACD,IAAI,CAAC;EACzB,CAAC,CAAC,MAAM;IACN,OAAOA,IAAI;EACb;AACF","ignoreList":[]}
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * An endpoint value is a URL template, optionally split into named scopes.
5
+ * Values carry their own query string (`fields=…`); the builder merges caller params into it.
6
+ */
7
+
8
+ /**
9
+ * Endpoint keys. Feature packages add their own by declaration merging:
10
+ *
11
+ * ```ts
12
+ * declare module '@laconius/core' {
13
+ * interface LaconiusEndpoints { productSearch: string | Record<'default' | 'carousel', string> }
14
+ * }
15
+ * ```
16
+ */
17
+
18
+ /** Converter keys, extended by declaration merging exactly like endpoint keys. */
19
+
20
+ /** Adapter slots, extended by declaration merging. Replacing one is the route to a non-OCC backend. */
21
+
22
+ /** Extended by `@laconius/ui` with themes, components and colour scheme. */
23
+
24
+ /** Extended by `@laconius/cms` with the component registry and layout config. */
25
+
26
+ /** What a feature package exports as `defaultProductConfig` and friends. */
27
+
28
+ /** The app's own chunk. `backend.occ` and `auth` are what the provider refuses to start without. */
29
+
30
+ export const DEFAULT_OCC_PREFIX = '/occ/v2';
31
+ export const defaultCapabilities = {
32
+ jsonVouchers: true,
33
+ productAvailabilities: true,
34
+ userScopedCms: true
35
+ };
36
+ function isPlainObject(value) {
37
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
38
+ }
39
+
40
+ /**
41
+ * Objects deep-merge, arrays are replaced, `undefined` is ignored.
42
+ *
43
+ * Arrays are never concatenated: a default you cannot remove is a bug. Everything that would
44
+ * want concatenation exports a `default*` array the app spreads explicitly.
45
+ */
46
+ export function deepMerge(base, override) {
47
+ if (override === undefined) return base;
48
+ if (!isPlainObject(base) || !isPlainObject(override)) return override;
49
+ const result = {
50
+ ...base
51
+ };
52
+ for (const key of Object.keys(override)) {
53
+ const next = override[key];
54
+ if (next === undefined) continue;
55
+ result[key] = isPlainObject(result[key]) ? deepMerge(result[key], next) : next;
56
+ }
57
+ return result;
58
+ }
59
+
60
+ /** @internal Use `createLaconiusConfig`, which seeds core's own defaults first. */
61
+ export function createLaconiusConfigInternal(app, chunks) {
62
+ const merged = chunks.reduce((acc, chunk) => deepMerge(acc, chunk), {});
63
+ const config = deepMerge(merged, app);
64
+ return {
65
+ ...config,
66
+ capabilities: {
67
+ ...defaultCapabilities,
68
+ ...config.capabilities
69
+ }
70
+ };
71
+ }
72
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["DEFAULT_OCC_PREFIX","defaultCapabilities","jsonVouchers","productAvailabilities","userScopedCms","isPlainObject","value","Array","isArray","Object","getPrototypeOf","prototype","deepMerge","base","override","undefined","result","key","keys","next","createLaconiusConfigInternal","app","chunks","merged","reduce","acc","chunk","config","capabilities"],"sourceRoot":"../../src","sources":["config.ts"],"mappings":";;AAKA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA;;AASA;;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EAAEC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;EAChF,MAAMC,MAAM,GAAGf,SAAS,CAACW,MAAM,EAAEF,GAAG,CAAmB;EACvD,OAAO;IACL,GAAGM,MAAM;IACTC,YAAY,EAAE;MAAE,GAAG3B,mBAAmB;MAAE,GAAG0B,MAAM,CAACC;IAAa;EACjE,CAAC;AACH","ignoreList":[]}
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+
3
+ /** Spartacus' populator pattern with dependency injection removed. */
4
+
5
+ /**
6
+ * Reduces a converter stack so each converter enriches the previous one's partial target.
7
+ *
8
+ * The seed is explicit because it is easy to re-derive wrong: an empty stack returns the source
9
+ * unchanged, and otherwise the first converter is called with `target === undefined`.
10
+ */
11
+ export function applyConverters(source, converters) {
12
+ if (!converters || converters.length === 0) {
13
+ return source;
14
+ }
15
+ return converters.reduce((target, convert) => convert(source, target), undefined);
16
+ }
17
+ /** Converters are registered by explicit spread of a feature's exported defaults. */
18
+ export function createConverterRegistry(config) {
19
+ const registered = config.converters ?? {};
20
+ const stackFor = key => registered[key];
21
+ return {
22
+ convert(source, key) {
23
+ return applyConverters(source, stackFor(key));
24
+ },
25
+ convertAll(sources, key) {
26
+ const converters = stackFor(key);
27
+ return (sources ?? []).map(source => applyConverters(source, converters));
28
+ }
29
+ };
30
+ }
31
+ //# sourceMappingURL=converters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["applyConverters","source","converters","length","reduce","target","convert","undefined","createConverterRegistry","config","registered","stackFor","key","convertAll","sources","map"],"sourceRoot":"../../src","sources":["converters.ts"],"mappings":";;AAEA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,eAAeA,CAC7BC,MAAS,EACTC,UAAkD,EAC/C;EACH,IAAI,CAACA,UAAU,IAAIA,UAAU,CAACC,MAAM,KAAK,CAAC,EAAE;IAC1C,OAAOF,MAAM;EACf;EACA,OAAOC,UAAU,CAACE,MAAM,CACtB,CAACC,MAAM,EAAEC,OAAO,KAAKA,OAAO,CAACL,MAAM,EAAEI,MAAM,CAAC,EAC5CE,SACF,CAAC;AACH;AAOA;AACA,OAAO,SAASC,uBAAuBA,CACrCC,MAAsB,EACH;EACnB,MAAMC,UAAU,GAAGD,MAAM,CAACP,UAAU,IAAI,CAAC,CAAC;EAC1C,MAAMS,QAAQ,GAAUC,GAA6B,IACnDF,UAAU,CAACE,GAAG,CAA2C;EAE3D,OAAO;IACLN,OAAOA,CAAOL,MAAS,EAAEW,GAA6B,EAAE;MACtD,OAAOZ,eAAe,CAAOC,MAAM,EAAEU,QAAQ,CAAOC,GAAG,CAAC,CAAC;IAC3D,CAAC;IACDC,UAAUA,CAAOC,OAAwB,EAAEF,GAA6B,EAAE;MACxE,MAAMV,UAAU,GAAGS,QAAQ,CAAOC,GAAG,CAAC;MACtC,OAAO,CAACE,OAAO,IAAI,EAAE,EAAEC,GAAG,CAAEd,MAAM,IAAKD,eAAe,CAAOC,MAAM,EAAEC,UAAU,CAAC,CAAC;IACnF;EACF,CAAC;AACH","ignoreList":[]}
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+
3
+ import { createLaconiusConfigInternal } from "./config.js";
4
+ import { defaultCoreEndpoints } from "./endpoints.js";
5
+ import { defaultMediaFormats, defaultMediaRoles } from "./media.js";
6
+ import { defaultCoreTranslations } from "./translations.js";
7
+
8
+ /** What core contributes before any feature chunk: its endpoints, media table and strings. */
9
+ export const coreDefaults = {
10
+ backend: {
11
+ occ: {
12
+ endpoints: defaultCoreEndpoints
13
+ }
14
+ },
15
+ ui: {
16
+ media: {
17
+ formats: defaultMediaFormats,
18
+ roles: defaultMediaRoles
19
+ }
20
+ },
21
+ i18n: {
22
+ fallbackLanguage: 'en',
23
+ translations: defaultCoreTranslations
24
+ }
25
+ };
26
+
27
+ /**
28
+ * Deep-merges core's defaults, then the feature chunks in order, then the app chunk last, so an
29
+ * override is written where the reader expects it.
30
+ *
31
+ * Objects deep-merge, arrays are replaced, `undefined` is ignored.
32
+ */
33
+ export function createLaconiusConfig(app, featureChunks = []) {
34
+ return createLaconiusConfigInternal(app, [coreDefaults, ...featureChunks]);
35
+ }
36
+ //# sourceMappingURL=create-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["createLaconiusConfigInternal","defaultCoreEndpoints","defaultMediaFormats","defaultMediaRoles","defaultCoreTranslations","coreDefaults","backend","occ","endpoints","ui","media","formats","roles","i18n","fallbackLanguage","translations","createLaconiusConfig","app","featureChunks"],"sourceRoot":"../../src","sources":["create-config.ts"],"mappings":";;AAAA,SACEA,4BAA4B,QAIvB,aAAU;AACjB,SAASC,oBAAoB,QAAQ,gBAAa;AAClD,SAASC,mBAAmB,EAAEC,iBAAiB,QAAQ,YAAS;AAChE,SAASC,uBAAuB,QAAQ,mBAAgB;;AAExD;AACA,OAAO,MAAMC,YAAiC,GAAG;EAC/CC,OAAO,EAAE;IAAEC,GAAG,EAAE;MAAEC,SAAS,EAAEP;IAAqB;EAAE,CAAC;EACrDQ,EAAE,EAAE;IAAEC,KAAK,EAAE;MAAEC,OAAO,EAAET,mBAAmB;MAAEU,KAAK,EAAET;IAAkB;EAAE,CAAC;EACzEU,IAAI,EAAE;IAAEC,gBAAgB,EAAE,IAAI;IAAEC,YAAY,EAAEX;EAAwB;AACxE,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASY,oBAAoBA,CAClCC,GAAsB,EACtBC,aAAoC,GAAG,EAAE,EACzB;EAChB,OAAOlB,4BAA4B,CAACiB,GAAG,EAAE,CAACZ,YAAY,EAAE,GAAGa,aAAa,CAAC,CAAC;AAC5E","ignoreList":[]}