@mercurjs/client 2.0.0-canary.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.
@@ -0,0 +1,59 @@
1
+ import { MedusaResponse } from '@medusajs/framework/http';
2
+
3
+ type DecrementDepth = [never, 0, 1, 2, 3, 4, 5, 6];
4
+ type PrettifyDeep<T, Depth extends number = 4> = Depth extends never ? T : T extends (...args: any[]) => any ? T : T extends Array<infer U> ? Array<PrettifyDeep<U, DecrementDepth[Depth]>> : T extends Date ? T : T extends object ? {
5
+ [K in keyof T]: PrettifyDeep<T[K], DecrementDepth[Depth]>;
6
+ } & {} : T;
7
+ type TypeError<TMessage extends string> = TMessage;
8
+ type InferInput<TRequest> = TRequest extends {
9
+ validatedBody: infer Input;
10
+ } ? Input : void;
11
+ type InferOutput<TResponse> = TResponse extends MedusaResponse<infer Output> ? Output : void;
12
+ type HttpMethod = "GET" | "POST" | "DELETE";
13
+ type ChildKeys<T> = Exclude<keyof T, HttpMethod | "__esModule">;
14
+
15
+ type ClientOptions = {
16
+ baseUrl: string;
17
+ fetchOptions?: RequestInit;
18
+ };
19
+ type AddParamsToFn<Fn, TParams> = keyof TParams extends never ? Fn : Fn extends (input?: infer TInput) => infer TOutput ? (input: (TInput extends Record<string, any> ? Omit<TInput, 'fetchOptions'> : {}) & TParams & {
20
+ fetchOptions?: RequestInit;
21
+ }) => TOutput : Fn extends (input: infer TInput) => infer TOutput ? (input: (TInput extends Record<string, any> ? Omit<TInput, 'fetchOptions'> : {}) & TParams & {
22
+ fetchOptions?: RequestInit;
23
+ }) => TOutput : Fn;
24
+ type InferFetchFn<TRequest, TResponse, TInput = PrettifyDeep<InferInput<TRequest>>, TOutput = PrettifyDeep<InferOutput<TResponse>>> = [TInput] extends [Record<string, any>] ? (input: TInput & {
25
+ fetchOptions?: RequestInit;
26
+ }) => Promise<TOutput> : (input?: {
27
+ fetchOptions?: RequestInit;
28
+ }) => Promise<TOutput>;
29
+ type InferEndpointMethods<TRoutes, TParams> = (TRoutes extends {
30
+ GET: (req: infer TReq, res: infer TRes) => any;
31
+ } ? {
32
+ query: AddParamsToFn<InferFetchFn<TReq, TRes>, TParams>;
33
+ } : {}) & (TRoutes extends {
34
+ POST: (req: infer TReq, res: infer TRes) => any;
35
+ } ? {
36
+ mutate: AddParamsToFn<InferFetchFn<TReq, TRes>, TParams>;
37
+ } : {}) & (TRoutes extends {
38
+ DELETE: (req: infer TReq, res: infer TRes) => any;
39
+ } ? {
40
+ delete: AddParamsToFn<InferFetchFn<TReq, TRes>, TParams>;
41
+ } : {});
42
+ type ProcessRoutes<TRoutes, TParams = {}> = InferEndpointMethods<TRoutes, TParams> & {
43
+ [K in ChildKeys<TRoutes>]: K extends `$${string}` ? ProcessRoutes<TRoutes[K], TParams & {
44
+ [P in K]: string;
45
+ }> : ProcessRoutes<TRoutes[K], TParams>;
46
+ };
47
+ type InferClient<TRoutes> = TRoutes extends Record<string, any> ? ProcessRoutes<TRoutes> : TypeError<`Looks like you forgot to pass the \`Routes\` generic type to the \`createClient\` function.`>;
48
+
49
+ type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
50
+ type InferClientInput<T> = T extends (input: infer I) => any ? PrettifyDeep<DistributiveOmit<I, 'fetchOptions'>> : T extends (input?: infer I) => any ? PrettifyDeep<DistributiveOmit<NonNullable<I>, 'fetchOptions'>> : never;
51
+ type InferClientOutput<T> = T extends (...args: any[]) => Promise<infer O> ? PrettifyDeep<O> : never;
52
+ declare class ClientError extends Error {
53
+ status: number | undefined;
54
+ statusText: string | undefined;
55
+ constructor(message: string, statusText?: string, status?: number);
56
+ }
57
+ declare function createClient(options: ClientOptions): any;
58
+
59
+ export { ClientError, type InferClient, type InferClientInput, type InferClientOutput, createClient };
package/dist/index.mjs ADDED
@@ -0,0 +1,141 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
32
+ var __async = (__this, __arguments, generator) => {
33
+ return new Promise((resolve, reject) => {
34
+ var fulfilled = (value) => {
35
+ try {
36
+ step(generator.next(value));
37
+ } catch (e) {
38
+ reject(e);
39
+ }
40
+ };
41
+ var rejected = (value) => {
42
+ try {
43
+ step(generator.throw(value));
44
+ } catch (e) {
45
+ reject(e);
46
+ }
47
+ };
48
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
+ step((generator = generator.apply(__this, __arguments)).next());
50
+ });
51
+ };
52
+
53
+ // src/index.ts
54
+ import { stringify } from "qs";
55
+
56
+ // src/create-proxy.ts
57
+ function createRecursiveProxy(callback, path = []) {
58
+ return new Proxy(function() {
59
+ }, {
60
+ get(_, prop) {
61
+ if (typeof prop !== "string") {
62
+ return void 0;
63
+ }
64
+ if (prop === "then" || prop === "catch" || prop === "finally") {
65
+ return void 0;
66
+ }
67
+ return createRecursiveProxy(callback, [...path, prop]);
68
+ },
69
+ apply(_, __, args) {
70
+ return callback(path, args);
71
+ }
72
+ });
73
+ }
74
+
75
+ // src/utils.ts
76
+ var kebabCase = (string) => string.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
77
+
78
+ // src/index.ts
79
+ var ClientError = class extends Error {
80
+ constructor(message, statusText, status) {
81
+ super(message);
82
+ this.statusText = statusText;
83
+ this.status = status;
84
+ }
85
+ };
86
+ function createClient(options) {
87
+ const { baseUrl, fetchOptions: defaultFetchOptions } = options;
88
+ return createRecursiveProxy((path, args) => {
89
+ var _a;
90
+ const action = path.pop();
91
+ const input = (_a = args[0]) != null ? _a : {};
92
+ const method = action === "query" ? "GET" : action === "mutate" ? "POST" : action === "delete" ? "DELETE" : null;
93
+ if (!method) {
94
+ throw new Error(`Action '${action}' is not a valid action.`);
95
+ }
96
+ const _b = input, { fetchOptions: inputFetchOptions } = _b, rest = __objRest(_b, ["fetchOptions"]);
97
+ const urlParts = path.map((segment) => {
98
+ if (segment.startsWith("$")) {
99
+ const value = rest[segment];
100
+ delete rest[segment];
101
+ return String(value);
102
+ }
103
+ return kebabCase(segment);
104
+ });
105
+ const urlPath = "/" + urlParts.join("/");
106
+ const base = new URL(baseUrl);
107
+ const fullPath = `${base.pathname.replace(/\/$/, "")}/${urlPath.replace(/^\//, "")}`;
108
+ const url = new URL(fullPath, base.origin);
109
+ let body;
110
+ if (method === "GET" && Object.keys(rest).length > 0) {
111
+ url.search = stringify(rest, { skipNulls: true });
112
+ } else if (method !== "GET" && Object.keys(rest).length > 0) {
113
+ body = JSON.stringify(rest);
114
+ }
115
+ const headers = new Headers(__spreadValues(__spreadValues({
116
+ "Content-Type": "application/json",
117
+ Accept: "application/json"
118
+ }, defaultFetchOptions == null ? void 0 : defaultFetchOptions.headers), inputFetchOptions == null ? void 0 : inputFetchOptions.headers));
119
+ return fetch(url, __spreadProps(__spreadValues(__spreadValues({}, defaultFetchOptions), inputFetchOptions), {
120
+ method,
121
+ body,
122
+ headers
123
+ })).then((response) => __async(null, null, function* () {
124
+ var _a2, _b2;
125
+ if (response.status >= 300) {
126
+ const jsonError = yield response.json().catch(() => ({}));
127
+ throw new ClientError(
128
+ (_a2 = jsonError.message) != null ? _a2 : response.statusText,
129
+ response.statusText,
130
+ response.status
131
+ );
132
+ }
133
+ const isJsonRequest = (_b2 = headers.get("accept")) == null ? void 0 : _b2.includes("application/json");
134
+ return isJsonRequest ? yield response.json() : response;
135
+ }));
136
+ });
137
+ }
138
+ export {
139
+ ClientError,
140
+ createClient
141
+ };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@mercurjs/client",
3
+ "version": "2.0.0-canary.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "https://github.com/mercurjs/mercur",
7
+ "directory": "packages/client"
8
+ },
9
+ "type": "commonjs",
10
+ "author": "MercurJS (https://github.com/mercurjs)",
11
+ "license": "MIT",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.mjs"
22
+ }
23
+ },
24
+ "scripts": {
25
+ "typecheck": "tsc --noEmit",
26
+ "dev": "tsup --watch",
27
+ "build": "tsup"
28
+ },
29
+ "dependencies": {
30
+ "@tanstack/react-query": "^5.64.2",
31
+ "qs": "^6.14.0"
32
+ },
33
+ "devDependencies": {
34
+ "@medusajs/framework": "^2.13.0",
35
+ "@types/qs": "^6.9.18",
36
+ "tsup": "^8.5.0",
37
+ "typescript": "5.9.3"
38
+ },
39
+ "peerDependencies": {
40
+ "typescript": ">=4.8.0"
41
+ }
42
+ }