@eldrajs/sdk 0.1.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -7,6 +7,15 @@ change, naming the contract version when the contract moved. Release-please writ
7
7
  from commit messages and does not describe the SDK. The contract's own history is `CONTRACT.md` in the
8
8
  platform repository.
9
9
 
10
+ ## Unreleased
11
+
12
+ - **Breaking.** The SDK no longer ships response types. The Vite plugin — now `eldra()`, was
13
+ `eldraCms()` — generates `contract.ts` from your gateway's `/api/public/openapi.json` next to the
14
+ CMS types, and it augments the SDK's `EldraContract` so every method is typed against the gateway
15
+ you build against. Without it, responses are `unknown` and request bodies and queries are plain
16
+ objects; name the type at the call site. `ELDRA_CONTRACT_VERSION` moved into the generated file.
17
+ `openapi-typescript` is a dependency of the `./vite` entry.
18
+
10
19
  ## 0.1.0 — 2026-09-15
11
20
 
12
21
  - Contract snapshot 2.4.0. `inventory.availability` items no longer need a `locationId`: `EldraStockAvailabilityInput.locationId` is optional, and an omitted one is answered by the organisation's default inventory location, the same resolution the cart's reservation uses; the response still names the location that answered. A storefront needs no location id in its configuration any more.
package/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # @eldrajs/sdk
2
+
3
+ The client for the Eldra Web Studio public storefront API: CMS, catalog, cart, checkout handoff,
4
+ orders, inventory. Framework-free — plain `fetch`, runs in a browser, in Node, in SSR, at the edge.
5
+
6
+ ```bash
7
+ pnpm add @eldrajs/sdk
8
+ ```
9
+
10
+ ```ts
11
+ import { createEldraClient } from '@eldrajs/sdk';
12
+
13
+ const eldra = createEldraClient({ orgId: 'your-organisation-id' });
14
+ const { data } = await eldra.catalog.listProducts();
15
+ ```
16
+
17
+ ## Types come from your gateway
18
+
19
+ The package ships no response types. Add the Vite plugin and they are generated into your project
20
+ on every dev start and build, from the gateway you point at:
21
+
22
+ ```ts
23
+ import { eldra } from '@eldrajs/sdk/vite';
24
+
25
+ export default defineConfig({
26
+ plugins: [eldra({ orgId: process.env.ELDRA_ORG_ID })],
27
+ });
28
+ ```
29
+
30
+ That writes `.eldra/web-studio/` — your CMS schemas as types, the gateway's API contract as types,
31
+ and a typed client wrapper — and from then on `eldra.cart.get(id)` returns the cart your gateway
32
+ actually returns. Commit the folder; it is what your CI type-checks against, and the diff is how
33
+ you see the API change. Without the plugin, responses are `unknown` and you name the type at the
34
+ call site.
35
+
36
+ The full walkthrough is [docs/getting-started.md](../../docs/getting-started.md).
37
+
38
+ ## What is in the client
39
+
40
+ | Group | Methods |
41
+ | ----------- | ---------------------------------------------------------------------------------------------------------------------- |
42
+ | `catalog` | `listProducts`, `getProduct`, `listCategories`, `listCollections`, `getCollection`, `listCollectionProducts`, `search` |
43
+ | `cms` | `list`, `get`, `getEntryByUniqueField`, `resolveEntryList` |
44
+ | `cart` | `addItem`, `get`, `updateItem`, `removeItem`, `applyDiscount`, `removeDiscount` |
45
+ | `checkout` | `handoffUrl` |
46
+ | `orders` | `get`, `recover` |
47
+ | `inventory` | `availability` |
48
+ | `features` | `getOrganization`, `list`, `isEnabled`, `getCapabilities` |
49
+
50
+ Every failed request throws `EldraHttpError` with `status` and the gateway's problem `code`.
51
+ `createCartSession` and `createOrderAccessTokens` persist the cart id and order tokens without
52
+ throwing where storage is unavailable.
@@ -177,9 +177,10 @@ function createEldraClient(options) {
177
177
  query: localeOptions,
178
178
  body: { code: trimmed }
179
179
  });
180
+ const discountCode = cart.discountCode;
180
181
  return {
181
182
  cart,
182
- applied: typeof cart.discountCode === "string" && cart.discountCode.trim().toUpperCase() === trimmed.toUpperCase()
183
+ applied: typeof discountCode === "string" && discountCode.trim().toUpperCase() === trimmed.toUpperCase()
183
184
  };
184
185
  },
185
186
  removeDiscount: (cartId, localeOptions, context) => request({
package/dist/index.d.ts CHANGED
@@ -1,7 +1,4 @@
1
- import { $ as EldraProductVariant, A as EldraFeature, B as EldraOrdersClient, C as EldraCmsResolveEntryListResponse, D as EldraCollectionListOptions, E as EldraCollectionList, F as EldraInventoryClient, G as EldraPaginated, H as EldraOrganizationFeature, I as EldraLocaleOptions, J as EldraProductListItem, K as EldraProductDetails, L as EldraOrder, M as EldraFeatureClient, N as EldraHttpClient, O as EldraCollectionProductsOptions, P as EldraHttpRequest, Q as EldraProductThumbnail, R as EldraOrderLine, S as EldraCmsResolveEntryListOptions, T as EldraCollection, U as EldraOrganizationOptions, V as EldraOrganizationDetails, W as EldraPageMeta, X as EldraProductOption, Y as EldraProductMediaLink, Z as EldraProductOptionValue, _ as EldraCmsEntryListEntry, a as EldraCartTotals, at as EldraSearchResponse, b as EldraCmsGetOptions, c as EldraCatalogListProductsOptions, ct as EldraStockAvailabilityItem, d as EldraCheckoutHandoffOptions, dt as EldraContractBody, et as EldraRecoveredBasket, f as EldraClient, ft as EldraContractMethod, g as EldraCmsEntryListDisplayMode, gt as paths, h as EldraCmsEntryList, ht as EldraContractResponse, i as EldraCartItem, it as EldraSearchOptions, j as EldraFeatureCapabilities, k as EldraDiscountResult, l as EldraCategory, lt as RuntimeEnv, m as EldraCmsClient, mt as EldraContractQuery, n as EldraCart, nt as EldraRequestContext, o as EldraCatalogClient, ot as EldraStockAvailability, p as EldraClientOptions, pt as EldraContractPath, q as EldraProductList, r as EldraCartClient, rt as EldraRequestOptions, s as EldraCatalogGetProductOptions, st as EldraStockAvailabilityInput, t as EldraAddCartItemInput, tt as EldraRecoveredBasketItem, u as EldraCheckoutClient, ut as RuntimeValue, v as EldraCmsEntryListFilterCriterion, w as EldraCmsResolvedEntryList, x as EldraCmsListOptions, y as EldraCmsGetEntryByUniqueFieldOptions, z as EldraOrderReadOptions } from "./types-DNiJpmSn.js";
2
- //#region src/contract/version.d.ts
3
- export declare const ELDRA_CONTRACT_VERSION = "2.4.0";
4
- //#endregion
1
+ import { $ as EldraProductVariant, A as EldraFeature, B as EldraOrdersClient, C as EldraCmsResolveEntryListResponse, D as EldraCollectionListOptions, E as EldraCollectionList, F as EldraInventoryClient, G as EldraPaginated, H as EldraOrganizationFeature, I as EldraLocaleOptions, J as EldraProductListItem, K as EldraProductDetails, L as EldraOrder, M as EldraFeatureClient, N as EldraHttpClient, O as EldraCollectionProductsOptions, P as EldraHttpRequest, Q as EldraProductThumbnail, R as EldraOrderLine, S as EldraCmsResolveEntryListOptions, T as EldraCollection, U as EldraOrganizationOptions, V as EldraOrganizationDetails, W as EldraPageMeta, X as EldraProductOption, Y as EldraProductMediaLink, Z as EldraProductOptionValue, _ as EldraCmsEntryListEntry, _t as EldraContractProp, a as EldraCartTotals, at as EldraSearchResponse, b as EldraCmsGetOptions, c as EldraCatalogListProductsOptions, ct as EldraStockAvailabilityItem, d as EldraCheckoutHandoffOptions, dt as EldraContract, et as EldraRecoveredBasket, f as EldraClient, ft as EldraContractBody, g as EldraCmsEntryListDisplayMode, gt as EldraContractPaths, h as EldraCmsEntryList, ht as EldraContractPath, i as EldraCartItem, it as EldraSearchOptions, j as EldraFeatureCapabilities, k as EldraDiscountResult, l as EldraCategory, lt as RuntimeEnv, m as EldraCmsClient, mt as EldraContractMethod, n as EldraCart, nt as EldraRequestContext, o as EldraCatalogClient, ot as EldraStockAvailability, p as EldraClientOptions, pt as EldraContractItem, q as EldraProductList, r as EldraCartClient, rt as EldraRequestOptions, s as EldraCatalogGetProductOptions, st as EldraStockAvailabilityInput, t as EldraAddCartItemInput, tt as EldraRecoveredBasketItem, u as EldraCheckoutClient, ut as RuntimeValue, v as EldraCmsEntryListFilterCriterion, vt as EldraContractQuery, w as EldraCmsResolvedEntryList, x as EldraCmsListOptions, y as EldraCmsGetEntryByUniqueFieldOptions, yt as EldraContractResponse, z as EldraOrderReadOptions } from "./types-Bq1jUVcz.js";
5
2
  //#region src/client.d.ts
6
3
  export declare const DEFAULT_ELDRA_API_BASE_URL = "https://web.eldra.app/api";
7
4
  export declare class EldraHttpError extends Error {
@@ -47,4 +44,4 @@ export declare function createCartSession(options?: EldraCartSessionOptions): El
47
44
  */
48
45
  export declare function createOrderAccessTokens(options?: EldraOrderAccessTokenOptions): EldraOrderAccessTokens;
49
46
  //#endregion
50
- export type { EldraAddCartItemInput, EldraCart, EldraCartClient, EldraCartItem, EldraCartSession, EldraCartSessionOptions, EldraCartTotals, EldraCatalogClient, EldraCatalogGetProductOptions, EldraCatalogListProductsOptions, EldraCategory, EldraCheckoutClient, EldraCheckoutHandoffOptions, EldraClient, EldraClientOptions, EldraCmsClient, EldraCmsEntryList, EldraCmsEntryListDisplayMode, EldraCmsEntryListEntry, EldraCmsEntryListFilterCriterion, EldraCmsGetEntryByUniqueFieldOptions, EldraCmsGetOptions, EldraCmsListOptions, EldraCmsResolveEntryListOptions, EldraCmsResolveEntryListResponse, EldraCmsResolvedEntryList, EldraCollection, EldraCollectionList, EldraCollectionListOptions, EldraCollectionProductsOptions, EldraContractBody, EldraContractMethod, EldraContractPath, paths as EldraContractPaths, EldraContractQuery, EldraContractResponse, EldraDiscountResult, EldraFeature, EldraFeatureCapabilities, EldraFeatureClient, EldraHttpClient, EldraHttpRequest, EldraInventoryClient, EldraKeyValueStorage, EldraLocaleOptions, EldraOrder, EldraOrderAccessTokenOptions, EldraOrderAccessTokens, EldraOrderLine, EldraOrderReadOptions, EldraOrdersClient, EldraOrganizationDetails, EldraOrganizationFeature, EldraOrganizationOptions, EldraPageMeta, EldraPaginated, EldraProductDetails, EldraProductList, EldraProductListItem, EldraProductMediaLink, EldraProductOption, EldraProductOptionValue, EldraProductThumbnail, EldraProductVariant, EldraRecoveredBasket, EldraRecoveredBasketItem, EldraRequestContext, EldraRequestOptions, EldraSearchOptions, EldraSearchResponse, EldraStockAvailability, EldraStockAvailabilityInput, EldraStockAvailabilityItem, RuntimeEnv, RuntimeValue };
47
+ export type { EldraAddCartItemInput, EldraCart, EldraCartClient, EldraCartItem, EldraCartSession, EldraCartSessionOptions, EldraCartTotals, EldraCatalogClient, EldraCatalogGetProductOptions, EldraCatalogListProductsOptions, EldraCategory, EldraCheckoutClient, EldraCheckoutHandoffOptions, EldraClient, EldraClientOptions, EldraCmsClient, EldraCmsEntryList, EldraCmsEntryListDisplayMode, EldraCmsEntryListEntry, EldraCmsEntryListFilterCriterion, EldraCmsGetEntryByUniqueFieldOptions, EldraCmsGetOptions, EldraCmsListOptions, EldraCmsResolveEntryListOptions, EldraCmsResolveEntryListResponse, EldraCmsResolvedEntryList, EldraCollection, EldraCollectionList, EldraCollectionListOptions, EldraCollectionProductsOptions, EldraContract, EldraContractBody, EldraContractItem, EldraContractMethod, EldraContractPath, EldraContractPaths, EldraContractProp, EldraContractQuery, EldraContractResponse, EldraDiscountResult, EldraFeature, EldraFeatureCapabilities, EldraFeatureClient, EldraHttpClient, EldraHttpRequest, EldraInventoryClient, EldraKeyValueStorage, EldraLocaleOptions, EldraOrder, EldraOrderAccessTokenOptions, EldraOrderAccessTokens, EldraOrderLine, EldraOrderReadOptions, EldraOrdersClient, EldraOrganizationDetails, EldraOrganizationFeature, EldraOrganizationOptions, EldraPageMeta, EldraPaginated, EldraProductDetails, EldraProductList, EldraProductListItem, EldraProductMediaLink, EldraProductOption, EldraProductOptionValue, EldraProductThumbnail, EldraProductVariant, EldraRecoveredBasket, EldraRecoveredBasketItem, EldraRequestContext, EldraRequestOptions, EldraSearchOptions, EldraSearchResponse, EldraStockAvailability, EldraStockAvailabilityInput, EldraStockAvailabilityItem, RuntimeEnv, RuntimeValue };
package/dist/index.js CHANGED
@@ -1,7 +1,4 @@
1
- import { a as initEldraClient, i as getEldraClient, n as EldraHttpError, r as createEldraClient, t as DEFAULT_ELDRA_API_BASE_URL } from "./client-CP-xWxRN.js";
2
- //#region src/contract/version.ts
3
- const ELDRA_CONTRACT_VERSION = "2.4.0";
4
- //#endregion
1
+ import { a as initEldraClient, i as getEldraClient, n as EldraHttpError, r as createEldraClient, t as DEFAULT_ELDRA_API_BASE_URL } from "./client-BREAy8rQ.js";
5
2
  //#region src/storage.ts
6
3
  const DEFAULT_CART_KEY = "eldra.cartId";
7
4
  const DEFAULT_ORDER_TOKEN_PREFIX = "eldra.orderAccessToken.";
@@ -50,4 +47,4 @@ function createOrderAccessTokens(options = {}) {
50
47
  };
51
48
  }
52
49
  //#endregion
53
- export { DEFAULT_ELDRA_API_BASE_URL, ELDRA_CONTRACT_VERSION, EldraHttpError, createCartSession, createEldraClient, createOrderAccessTokens, getEldraClient, initEldraClient };
50
+ export { DEFAULT_ELDRA_API_BASE_URL, EldraHttpError, createCartSession, createEldraClient, createOrderAccessTokens, getEldraClient, initEldraClient };
@@ -0,0 +1,261 @@
1
+ //#region src/contract.d.ts
2
+ interface EldraContract {}
3
+ type Paths = EldraContract extends {
4
+ paths: infer P;
5
+ } ? P : never;
6
+ type Generated = [Paths] extends [never] ? false : true;
7
+ type EldraContractPaths = Paths;
8
+ type EldraContractPath = Generated extends true ? keyof Paths : string;
9
+ type EldraContractMethod<Path extends EldraContractPath> = Generated extends true ? keyof Paths[Path & keyof Paths] : string;
10
+ type Operation<Path, Method> = Path extends keyof Paths ? Method extends keyof Paths[Path] ? Paths[Path][Method] : never : never;
11
+ type JsonContent<Response> = Response extends {
12
+ content: {
13
+ 'application/json': infer Body;
14
+ };
15
+ } ? Body : never;
16
+ type SuccessResponse<Responses> = Responses extends {
17
+ 200: infer Response;
18
+ } ? JsonContent<Response> : Responses extends {
19
+ 201: infer Response;
20
+ } ? JsonContent<Response> : never;
21
+ type EldraContractResponse<Path extends EldraContractPath, Method extends EldraContractMethod<Path>> = Generated extends true ? Operation<Path, Method> extends {
22
+ responses: infer Responses;
23
+ } ? SuccessResponse<Responses> : never : unknown;
24
+ type EldraContractBody<Path extends EldraContractPath, Method extends EldraContractMethod<Path>> = Generated extends true ? Operation<Path, Method> extends {
25
+ requestBody?: infer Body;
26
+ } ? JsonContent<NonNullable<Body>> : never : Record<string, unknown>;
27
+ type EldraContractQuery<Path extends EldraContractPath, Method extends EldraContractMethod<Path>> = Generated extends true ? Operation<Path, Method> extends {
28
+ parameters: {
29
+ query?: infer Query;
30
+ };
31
+ } ? NonNullable<Query> : never : Record<string, unknown>;
32
+ type EldraContractProp<T, K extends PropertyKey> = T extends object ? K extends keyof T ? NonNullable<T[K]> : unknown : unknown;
33
+ type EldraContractItem<T> = NonNullable<T> extends readonly (infer Item)[] ? Item : unknown;
34
+ //#endregion
35
+ //#region src/types.d.ts
36
+ type RuntimeValue<T> = T | (() => T | undefined) | undefined;
37
+ type RuntimeEnv = Record<string, string | boolean | number | undefined>;
38
+ interface EldraRequestContext {
39
+ orgId?: string;
40
+ headers?: HeadersInit;
41
+ signal?: AbortSignal;
42
+ }
43
+ interface EldraRequestOptions extends EldraRequestContext {
44
+ method?: string;
45
+ path: string;
46
+ query?: object;
47
+ body?: unknown;
48
+ }
49
+ interface EldraHttpRequest {
50
+ url: string;
51
+ method: string;
52
+ headers: Headers;
53
+ body?: BodyInit;
54
+ signal?: AbortSignal;
55
+ }
56
+ type EldraHttpClient = <T = unknown>(request: EldraHttpRequest) => Promise<T>;
57
+ interface EldraClientOptions {
58
+ apiBaseUrl?: RuntimeValue<string>;
59
+ orgId?: RuntimeValue<string>;
60
+ env?: RuntimeValue<RuntimeEnv>;
61
+ headers?: RuntimeValue<HeadersInit>;
62
+ httpClient?: EldraHttpClient;
63
+ fetch?: typeof fetch;
64
+ /** Origin of the hosted checkout app, used by `checkout.handoffUrl`. */
65
+ checkoutUrl?: RuntimeValue<string>;
66
+ }
67
+ interface EldraPaginationOptions {
68
+ page?: number;
69
+ pageSize?: number;
70
+ limit?: number;
71
+ fields?: string[];
72
+ sort?: string[];
73
+ filter?: string[];
74
+ }
75
+ interface EldraCmsListOptions extends EldraPaginationOptions {
76
+ locale?: string;
77
+ depth?: number;
78
+ }
79
+ interface EldraCmsGetOptions {
80
+ locale?: string;
81
+ depth?: number;
82
+ }
83
+ type EldraCmsGetEntryByUniqueFieldOptions = EldraCmsGetOptions;
84
+ type EldraCmsEntryListDisplayMode = 'GRID' | 'ROW' | 'CAROUSEL' | 'MASONRY' | (string & {});
85
+ interface EldraCmsEntryListFilterCriterion {
86
+ schemaId: string;
87
+ fieldId: string;
88
+ operator: string;
89
+ value: unknown;
90
+ }
91
+ interface EldraCmsEntryList {
92
+ schemas?: string[];
93
+ filters?: EldraCmsEntryListFilterCriterion[];
94
+ displayAs?: EldraCmsEntryListDisplayMode;
95
+ orderBy?: string;
96
+ pageSize?: number;
97
+ entries?: unknown;
98
+ }
99
+ interface EldraPageMeta {
100
+ page: number;
101
+ pageSize: number;
102
+ total: number;
103
+ totalPages: number;
104
+ rows: number;
105
+ hasNext: boolean;
106
+ hasPrev: boolean;
107
+ }
108
+ interface EldraPaginated<Entry = unknown> {
109
+ data: Entry[];
110
+ meta: EldraPageMeta;
111
+ }
112
+ type EldraCmsEntryListEntry<List> = List extends {
113
+ entries?: {
114
+ data: Array<infer Entry>;
115
+ };
116
+ } ? Entry : List extends {
117
+ entries?: EldraPaginated<infer Entry>;
118
+ } ? Entry : unknown;
119
+ type EldraCmsResolvedEntryList<List extends EldraCmsEntryList> = Omit<List, 'entries'> & {
120
+ schemas?: string[];
121
+ filters?: EldraCmsEntryListFilterCriterion[];
122
+ displayAs?: EldraCmsEntryListDisplayMode;
123
+ orderBy?: string;
124
+ pageSize?: number;
125
+ entries: EldraPaginated<EldraCmsEntryListEntry<List>>;
126
+ };
127
+ type EldraCmsResolveEntryListResponse<Response, List extends EldraCmsEntryList> = [Response] extends [never] ? EldraCmsResolvedEntryList<List> : Response;
128
+ interface EldraCmsResolveEntryListOptions {
129
+ locale?: string;
130
+ page?: number;
131
+ pageSize?: number;
132
+ limit?: number;
133
+ depth?: number;
134
+ deep?: number;
135
+ }
136
+ type EldraCatalogListProductsOptions = EldraContractQuery<'/catalog/v1/products/list', 'get'>;
137
+ interface EldraCatalogGetProductOptions {
138
+ locale?: string;
139
+ }
140
+ type EldraFeature = 'CMS' | 'ECOMMERCE';
141
+ interface EldraOrganizationFeature {
142
+ feature: EldraFeature | string;
143
+ enabled: boolean;
144
+ }
145
+ interface EldraOrganizationDetails {
146
+ id: string;
147
+ name: string;
148
+ description?: string;
149
+ features?: EldraOrganizationFeature[];
150
+ paymentProviders?: unknown;
151
+ createdAt?: string;
152
+ updatedAt?: string;
153
+ }
154
+ interface EldraOrganizationOptions {
155
+ orgId?: string;
156
+ }
157
+ interface EldraFeatureCapabilities {
158
+ cms: boolean;
159
+ catalog: boolean;
160
+ products: boolean;
161
+ ecommerce: boolean;
162
+ features: Partial<Record<EldraFeature, boolean>>;
163
+ }
164
+ interface EldraCmsClient {
165
+ list<Response = unknown>(schemaApiId: string, options?: EldraCmsListOptions, context?: EldraRequestContext): Promise<Response>;
166
+ get<Response = unknown>(schemaApiId: string, entryId: string, options?: EldraCmsGetOptions, context?: EldraRequestContext): Promise<Response>;
167
+ getEntryByUniqueField<Response = unknown>(schemaApiId: string, fieldId: string, entryIdentifier: string, options?: EldraCmsGetEntryByUniqueFieldOptions, context?: EldraRequestContext): Promise<Response>;
168
+ resolveEntryList<Response = never, List extends EldraCmsEntryList = EldraCmsEntryList>(entryList: List, options?: EldraCmsResolveEntryListOptions, context?: EldraRequestContext): Promise<EldraCmsResolveEntryListResponse<Response, List>>;
169
+ }
170
+ type EldraProductList = EldraContractResponse<'/catalog/v1/products/list', 'get'>;
171
+ type EldraProductListItem = EldraContractItem<EldraContractProp<EldraProductList, 'data'>>;
172
+ type EldraProductDetails = EldraContractResponse<'/catalog/v1/products/{productId}', 'get'>;
173
+ type EldraProductVariant = EldraContractItem<EldraContractProp<EldraProductDetails, 'variants'>>;
174
+ type EldraProductOption = EldraContractItem<EldraContractProp<EldraProductDetails, 'options'>>;
175
+ type EldraProductOptionValue = EldraContractItem<EldraContractProp<EldraProductOption, 'values'>>;
176
+ type EldraProductMediaLink = EldraContractItem<EldraContractProp<EldraProductDetails, 'mediaLinks'>>;
177
+ type EldraProductThumbnail = EldraContractProp<EldraProductListItem, 'thumbnail'>;
178
+ interface EldraCatalogClient {
179
+ listProducts<Response = EldraProductList>(options?: EldraCatalogListProductsOptions, context?: EldraRequestContext): Promise<Response>;
180
+ getProduct<Response = EldraProductDetails>(productId: string, options?: EldraCatalogGetProductOptions, context?: EldraRequestContext): Promise<Response>;
181
+ listCategories(options?: EldraLocaleOptions, context?: EldraRequestContext): Promise<EldraCategory[]>;
182
+ listCollections(options?: EldraCollectionListOptions, context?: EldraRequestContext): Promise<EldraCollectionList>;
183
+ getCollection(slug: string, options?: EldraLocaleOptions, context?: EldraRequestContext): Promise<EldraCollection>;
184
+ listCollectionProducts(slug: string, options?: EldraCollectionProductsOptions, context?: EldraRequestContext): Promise<EldraProductList>;
185
+ search(query: string, options?: EldraSearchOptions, context?: EldraRequestContext): Promise<EldraSearchResponse>;
186
+ }
187
+ interface EldraFeatureClient {
188
+ getOrganization(options?: EldraOrganizationOptions, context?: EldraRequestContext): Promise<EldraOrganizationDetails>;
189
+ list(options?: EldraOrganizationOptions, context?: EldraRequestContext): Promise<EldraOrganizationFeature[]>;
190
+ isEnabled(feature: EldraFeature, options?: EldraOrganizationOptions, context?: EldraRequestContext): Promise<boolean>;
191
+ getCapabilities(options?: EldraOrganizationOptions, context?: EldraRequestContext): Promise<EldraFeatureCapabilities>;
192
+ }
193
+ interface EldraClient {
194
+ request<T = unknown>(options: EldraRequestOptions): Promise<T>;
195
+ cms: EldraCmsClient;
196
+ catalog: EldraCatalogClient;
197
+ features: EldraFeatureClient;
198
+ cart: EldraCartClient;
199
+ orders: EldraOrdersClient;
200
+ checkout: EldraCheckoutClient;
201
+ inventory: EldraInventoryClient;
202
+ }
203
+ interface EldraLocaleOptions {
204
+ locale?: string;
205
+ }
206
+ type EldraCategory = EldraContractItem<EldraContractResponse<'/catalog/v1/categories', 'get'>>;
207
+ type EldraCollectionList = EldraContractResponse<'/catalog/v1/collections', 'get'>;
208
+ type EldraCollection = EldraContractResponse<'/catalog/v1/collections/{slug}', 'get'>;
209
+ type EldraCollectionListOptions = EldraContractQuery<'/catalog/v1/collections', 'get'>;
210
+ type EldraCollectionProductsOptions = EldraContractQuery<'/catalog/v1/collections/{slug}/products', 'get'>;
211
+ type EldraSearchOptions = Omit<EldraContractQuery<'/search/v1', 'get'>, 'q'>;
212
+ type EldraSearchResponse = EldraContractResponse<'/search/v1', 'get'>;
213
+ type EldraCart = EldraContractResponse<'/shopping-cart/v1/cart/{cartID}', 'get'>;
214
+ type EldraCartItem = EldraContractItem<EldraContractProp<EldraCart, 'items'>>;
215
+ type EldraCartTotals = EldraContractProp<EldraCart, 'totals'>;
216
+ type EldraAddCartItemInput = EldraContractBody<'/shopping-cart/v1/cart/items', 'post'>;
217
+ interface EldraDiscountResult {
218
+ cart: EldraCart;
219
+ /** The server drops a code it will not honour, so the returned cart is the verdict. */
220
+ applied: boolean;
221
+ }
222
+ type EldraOrder = EldraContractResponse<'/order/v1/{orderId}', 'get'>;
223
+ type EldraOrderLine = EldraContractItem<EldraContractProp<EldraOrder, 'orderLines'>>;
224
+ type EldraRecoveredBasket = EldraContractResponse<'/order/v1/recover', 'post'>;
225
+ type EldraRecoveredBasketItem = EldraContractItem<EldraContractProp<EldraRecoveredBasket, 'items'>>;
226
+ interface EldraOrderReadOptions {
227
+ /** The one-time token returned when the order was created. Required unless the caller owns the order. */
228
+ accessToken?: string;
229
+ }
230
+ type EldraStockAvailabilityInput = EldraContractItem<EldraContractProp<EldraContractBody<'/inventory/v1/stock/availability', 'post'>, 'items'>>;
231
+ type EldraStockAvailability = EldraContractResponse<'/inventory/v1/stock/availability', 'post'>;
232
+ type EldraStockAvailabilityItem = EldraContractItem<EldraContractProp<EldraStockAvailability, 'items'>>;
233
+ interface EldraCheckoutHandoffOptions {
234
+ cartId: string;
235
+ locale?: string;
236
+ checkoutUrl?: string;
237
+ orgId?: string;
238
+ }
239
+ interface EldraCartClient {
240
+ addItem(input: EldraAddCartItemInput, context?: EldraRequestContext): Promise<EldraCart>;
241
+ get(cartId: string, options?: EldraLocaleOptions, context?: EldraRequestContext): Promise<EldraCart>;
242
+ updateItem(cartId: string, itemId: string, input: {
243
+ quantity: number;
244
+ }, context?: EldraRequestContext): Promise<EldraCart>;
245
+ removeItem(cartId: string, itemId: string, context?: EldraRequestContext): Promise<EldraCart>;
246
+ applyDiscount(cartId: string, code: string, options?: EldraLocaleOptions, context?: EldraRequestContext): Promise<EldraDiscountResult>;
247
+ removeDiscount(cartId: string, options?: EldraLocaleOptions, context?: EldraRequestContext): Promise<EldraCart>;
248
+ }
249
+ interface EldraOrdersClient {
250
+ get(orderId: string, options?: EldraOrderReadOptions, context?: EldraRequestContext): Promise<EldraOrder>;
251
+ recover(token: string, context?: EldraRequestContext): Promise<EldraRecoveredBasket>;
252
+ }
253
+ interface EldraCheckoutClient {
254
+ /** Where a storefront sends the customer: `{checkoutUrl}/checkout/{orgId}/{cartId}`. */
255
+ handoffUrl(options: EldraCheckoutHandoffOptions): string;
256
+ }
257
+ interface EldraInventoryClient {
258
+ availability(items: EldraStockAvailabilityInput[], context?: EldraRequestContext): Promise<EldraStockAvailability>;
259
+ }
260
+ //#endregion
261
+ export { EldraProductVariant as $, EldraFeature as A, EldraOrdersClient as B, EldraCmsResolveEntryListResponse as C, EldraCollectionListOptions as D, EldraCollectionList as E, EldraInventoryClient as F, EldraPaginated as G, EldraOrganizationFeature as H, EldraLocaleOptions as I, EldraProductListItem as J, EldraProductDetails as K, EldraOrder as L, EldraFeatureClient as M, EldraHttpClient as N, EldraCollectionProductsOptions as O, EldraHttpRequest as P, EldraProductThumbnail as Q, EldraOrderLine as R, EldraCmsResolveEntryListOptions as S, EldraCollection as T, EldraOrganizationOptions as U, EldraOrganizationDetails as V, EldraPageMeta as W, EldraProductOption as X, EldraProductMediaLink as Y, EldraProductOptionValue as Z, EldraCmsEntryListEntry as _, EldraContractProp as _t, EldraCartTotals as a, EldraSearchResponse as at, EldraCmsGetOptions as b, EldraCatalogListProductsOptions as c, EldraStockAvailabilityItem as ct, EldraCheckoutHandoffOptions as d, EldraContract as dt, EldraRecoveredBasket as et, EldraClient as f, EldraContractBody as ft, EldraCmsEntryListDisplayMode as g, EldraContractPaths as gt, EldraCmsEntryList as h, EldraContractPath as ht, EldraCartItem as i, EldraSearchOptions as it, EldraFeatureCapabilities as j, EldraDiscountResult as k, EldraCategory as l, RuntimeEnv as lt, EldraCmsClient as m, EldraContractMethod as mt, EldraCart as n, EldraRequestContext as nt, EldraCatalogClient as o, EldraStockAvailability as ot, EldraClientOptions as p, EldraContractItem as pt, EldraProductList as q, EldraCartClient as r, EldraRequestOptions as rt, EldraCatalogGetProductOptions as s, EldraStockAvailabilityInput as st, EldraAddCartItemInput as t, EldraRecoveredBasketItem as tt, EldraCheckoutClient as u, RuntimeValue as ut, EldraCmsEntryListFilterCriterion as v, EldraContractQuery as vt, EldraCmsResolvedEntryList as w, EldraCmsListOptions as x, EldraCmsGetEntryByUniqueFieldOptions as y, EldraContractResponse as yt, EldraOrderReadOptions as z };
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { lt as RuntimeEnv, ut as RuntimeValue } from "./types-DNiJpmSn.js";
1
+ import { lt as RuntimeEnv, ut as RuntimeValue } from "./types-Bq1jUVcz.js";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/vite-plugin.d.ts
4
- export interface EldraCmsVitePluginOptions {
4
+ export interface EldraVitePluginOptions {
5
5
  apiBaseUrl?: RuntimeValue<string>;
6
6
  orgId?: RuntimeValue<string>;
7
7
  env?: RuntimeValue<RuntimeEnv>;
@@ -11,12 +11,19 @@ export interface EldraCmsVitePluginOptions {
11
11
  moduleName?: string;
12
12
  outDir?: string;
13
13
  typesFileName?: string;
14
+ /** Set to `false` to skip the gateway contract; CMS types are still generated. */
15
+ contract?: boolean;
16
+ contractFileName?: string;
14
17
  clientFileName?: string;
15
18
  indexFileName?: string;
16
19
  sdkImport?: string;
17
20
  fetch?: typeof fetch;
18
21
  skipOnMissingConfig?: boolean;
19
22
  }
20
- export declare function eldraCms(options?: EldraCmsVitePluginOptions): Plugin;
21
- export declare function generateEldraCmsFiles(root: string, options: EldraCmsVitePluginOptions, mode?: string): Promise<void>;
23
+ export declare function eldra(options?: EldraVitePluginOptions): Plugin;
24
+ export declare function generateEldraFiles(root: string, options: EldraVitePluginOptions, mode?: string): Promise<void>;
25
+ export declare function createContractSource(document: unknown, options?: {
26
+ sdkImport?: string;
27
+ source?: URL | string;
28
+ }): Promise<string>;
22
29
  //#endregion
package/dist/vite.js CHANGED
@@ -1,10 +1,12 @@
1
- import "./client-CP-xWxRN.js";
2
- import { mkdir, writeFile } from "node:fs/promises";
1
+ import "./client-BREAy8rQ.js";
2
+ import { access, mkdir, writeFile } from "node:fs/promises";
3
3
  import { dirname, resolve } from "node:path";
4
+ import openapiTS, { astToString } from "openapi-typescript";
4
5
  import { loadEnv } from "vite";
5
6
  //#region src/vite-plugin.ts
6
7
  const defaultOutDir = ".eldra/web-studio";
7
8
  const defaultTypesFileName = "cms-types.ts";
9
+ const defaultContractFileName = "contract.ts";
8
10
  const defaultClientFileName = "client.ts";
9
11
  const defaultIndexFileName = "index.ts";
10
12
  const defaultModuleName = "EldraCMS";
@@ -23,11 +25,11 @@ const orgIdEnvKeys = [
23
25
  "NUXT_PUBLIC_ELDRA_ORG_ID",
24
26
  "PUBLIC_ELDRA_ORG_ID"
25
27
  ];
26
- function eldraCms(options = {}) {
28
+ function eldra(options = {}) {
27
29
  let config;
28
30
  let generated = false;
29
31
  return {
30
- name: "eldra-cms",
32
+ name: "eldra",
31
33
  enforce: "pre",
32
34
  configResolved(resolvedConfig) {
33
35
  config = resolvedConfig;
@@ -35,58 +37,104 @@ function eldraCms(options = {}) {
35
37
  async buildStart() {
36
38
  if (generated) return;
37
39
  generated = true;
38
- await generateEldraCmsFiles(config?.root ?? process.cwd(), options, config?.mode);
40
+ await generateEldraFiles(config?.root ?? process.cwd(), options, config?.mode);
39
41
  }
40
42
  };
41
43
  }
42
- async function generateEldraCmsFiles(root, options, mode = process.env.NODE_ENV ?? "development") {
44
+ async function generateEldraFiles(root, options, mode = process.env.NODE_ENV ?? "development") {
43
45
  const env = resolvePluginEnv(root, mode, options);
44
46
  const apiBaseUrl = resolveRuntimeValue(options.apiBaseUrl) ?? readFirstEnvValue(env, apiBaseUrlEnvKeys) ?? "https://web.eldra.app/api";
45
47
  const orgId = resolveRuntimeValue(options.orgId) ?? readFirstEnvValue(env, orgIdEnvKeys);
46
48
  if (!orgId) {
47
49
  if (options.skipOnMissingConfig) return;
48
- throw new Error("Missing Eldra CMS generation config. Set orgId or ELDRA_ORG_ID. Set apiBaseUrl only for staging, local, or test gateways.");
50
+ throw new Error("Missing Eldra generation config. Set orgId or ELDRA_ORG_ID. Set apiBaseUrl only for staging, local, or test gateways.");
49
51
  }
50
52
  const moduleName = options.moduleName ?? defaultModuleName;
53
+ const sdkImport = options.sdkImport ?? defaultSdkImport;
51
54
  const outDir = resolve(root, options.outDir ?? defaultOutDir);
52
55
  const typesFileName = options.typesFileName ?? defaultTypesFileName;
56
+ const contractFileName = options.contractFileName ?? defaultContractFileName;
53
57
  const clientFileName = options.clientFileName ?? defaultClientFileName;
54
58
  const indexFileName = options.indexFileName ?? defaultIndexFileName;
55
- const typesSource = await fetchCmsTypesOrSkip(apiBaseUrl, orgId, {
59
+ const fetchOptions = {
56
60
  fetch: options.fetch,
57
- headers: resolveRuntimeValue(options.headers),
61
+ headers: resolveRuntimeValue(options.headers)
62
+ };
63
+ const typesSource = await orSkip(() => fetchCmsTypes(apiBaseUrl, orgId, {
64
+ ...fetchOptions,
58
65
  maxDepth: options.maxDepth,
59
66
  moduleName,
60
67
  schemas: options.schemas
61
- });
62
- if (!typesSource) return;
63
- await mkdir(outDir, { recursive: true });
64
- await writeGeneratedFile(resolve(outDir, typesFileName), typesSource);
65
- await writeGeneratedFile(resolve(outDir, clientFileName), createGeneratedClientSource({
66
- moduleName,
67
- sdkImport: options.sdkImport ?? defaultSdkImport,
68
- typesImport: `./${stripTSExtension(typesFileName)}`
69
68
  }));
70
- await writeGeneratedFile(resolve(outDir, indexFileName), `export * from './${stripTSExtension(clientFileName)}';\n`);
69
+ const contractSource = options.contract === false ? void 0 : await orSkip(() => fetchContract(apiBaseUrl, orgId, {
70
+ ...fetchOptions,
71
+ sdkImport
72
+ }));
73
+ if (!typesSource && !contractSource) return;
74
+ await mkdir(outDir, { recursive: true });
75
+ if (typesSource) {
76
+ await writeGeneratedFile(resolve(outDir, typesFileName), typesSource);
77
+ await writeGeneratedFile(resolve(outDir, clientFileName), createGeneratedClientSource({
78
+ moduleName,
79
+ sdkImport,
80
+ typesImport: `./${stripTSExtension(typesFileName)}`
81
+ }));
82
+ }
83
+ if (contractSource) await writeGeneratedFile(resolve(outDir, contractFileName), contractSource);
84
+ const hasClient = typesSource !== void 0 || await exists(resolve(outDir, clientFileName));
85
+ const hasContract = contractSource !== void 0 || await exists(resolve(outDir, contractFileName));
86
+ await writeGeneratedFile(resolve(outDir, indexFileName), [hasClient ? `export * from './${stripTSExtension(clientFileName)}';` : void 0, hasContract ? `export * from './${stripTSExtension(contractFileName)}';` : void 0].filter(Boolean).join("\n") + "\n");
71
87
  }
72
88
  async function fetchCmsTypes(apiBaseUrl, orgId, options) {
73
- const url = new URL(`${apiBaseUrl.replace(/\/$/, "")}/cms/v1/typescript-definitions`);
89
+ const url = new URL(`${trimSlash(apiBaseUrl)}/cms/v1/typescript-definitions`);
74
90
  url.searchParams.set("moduleName", options.moduleName);
75
91
  if (options.maxDepth !== void 0) url.searchParams.set("maxDepth", String(options.maxDepth));
76
92
  if (options.schemas && options.schemas.length > 0) url.searchParams.set("schemas", options.schemas.join(","));
93
+ const body = await fetchText(url, orgId, {
94
+ ...options,
95
+ accept: "text/plain"
96
+ });
97
+ return body.endsWith("\n") ? body : `${body}\n`;
98
+ }
99
+ async function fetchContract(apiBaseUrl, orgId, options) {
100
+ const url = new URL(`${trimSlash(apiBaseUrl)}/public/openapi.json`);
101
+ const body = await fetchText(url, orgId, {
102
+ ...options,
103
+ accept: "application/json"
104
+ });
105
+ return createContractSource(JSON.parse(body), {
106
+ sdkImport: options.sdkImport,
107
+ source: url
108
+ });
109
+ }
110
+ async function createContractSource(document, options = {}) {
111
+ const version = readVersion(document);
112
+ const sdkImport = options.sdkImport ?? defaultSdkImport;
113
+ const ast = await openapiTS(document, {
114
+ alphabetize: true,
115
+ exportType: true
116
+ });
117
+ return `// Generated by ${sdkImport}${options.source ? ` from ${options.source.toString()}` : ""} (contract ${version}). Do not edit; it is rewritten on every\n// dev start and build. Commit it so the types exist without a running gateway.\nexport const ELDRA_CONTRACT_VERSION = '${version}';\n\n` + astToString(ast) + `\ndeclare module '${sdkImport}' {\n interface EldraContract {\n paths: paths;\n }\n}\n`;
118
+ }
119
+ function readVersion(document) {
120
+ const version = document?.info?.version;
121
+ if (typeof version !== "string" || !version) throw new Error("The OpenAPI document has no info.version.");
122
+ return version;
123
+ }
124
+ async function fetchText(url, orgId, options) {
77
125
  const headers = new Headers(options.headers);
78
- headers.set("Accept", "text/plain");
126
+ headers.set("Accept", options.accept);
79
127
  headers.set("X-Org-Id", orgId);
80
128
  const fetchImpl = options.fetch ?? globalThis.fetch;
81
- if (!fetchImpl) throw new Error("No fetch implementation is available for Eldra CMS generation.");
129
+ if (!fetchImpl) throw new Error("No fetch implementation is available for Eldra generation.");
82
130
  const response = await fetchImpl(url, { headers });
83
131
  const body = await response.text();
84
- if (!response.ok) throw new Error(`Failed to generate Eldra CMS types: ${response.status} ${response.statusText}\n${body}`);
85
- return body.endsWith("\n") ? body : `${body}\n`;
132
+ if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}\n${body}`);
133
+ return body;
86
134
  }
87
- async function fetchCmsTypesOrSkip(apiBaseUrl, orgId, options) {
135
+ async function orSkip(run) {
88
136
  try {
89
- return await fetchCmsTypes(apiBaseUrl, orgId, options);
137
+ return await run();
90
138
  } catch {
91
139
  return;
92
140
  }
@@ -143,6 +191,17 @@ async function writeGeneratedFile(path, source) {
143
191
  await mkdir(dirname(path), { recursive: true });
144
192
  await writeFile(path, source, "utf8");
145
193
  }
194
+ async function exists(path) {
195
+ try {
196
+ await access(path);
197
+ return true;
198
+ } catch {
199
+ return false;
200
+ }
201
+ }
202
+ function trimSlash(value) {
203
+ return value.replace(/\/$/, "");
204
+ }
146
205
  function stripTSExtension(path) {
147
206
  return path.replace(/\.ts$/, "");
148
207
  }
@@ -150,4 +209,4 @@ function pascalTypeName(value) {
150
209
  return value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
151
210
  }
152
211
  //#endregion
153
- export { eldraCms, generateEldraCmsFiles };
212
+ export { createContractSource, eldra, generateEldraFiles };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@eldrajs/sdk",
3
- "version": "0.1.0",
4
- "description": "Framework-free client for the Eldra Web Studio public storefront API: CMS, catalog, cart, checkout handoff, orders, inventory. Types generated from the versioned public contract.",
3
+ "version": "0.2.0",
4
+ "description": "Framework-free client for the Eldra Web Studio public storefront API: CMS, catalog, cart, checkout handoff, orders, inventory. Types generated from your gateway's OpenAPI document and CMS schemas at build time.",
5
5
  "keywords": [
6
6
  "cms",
7
7
  "commerce",
@@ -40,8 +40,10 @@
40
40
  "access": "public",
41
41
  "provenance": true
42
42
  },
43
+ "dependencies": {
44
+ "openapi-typescript": "^7.13.0"
45
+ },
43
46
  "devDependencies": {
44
- "openapi-typescript": "^7.13.0",
45
47
  "vite": "^8.0.8"
46
48
  },
47
49
  "peerDependencies": {
@@ -57,9 +59,8 @@
57
59
  },
58
60
  "scripts": {
59
61
  "build": "tsdown",
60
- "typecheck": "tsc -p tsconfig.json",
62
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.generated.json",
61
63
  "test": "vitest run",
62
- "contract": "node scripts/contract.mjs",
63
- "contract:check": "node scripts/contract.mjs --check"
64
+ "fixture": "node scripts/fixture.mjs"
64
65
  }
65
66
  }