@01.software/sdk 0.0.1-260102065059 → 0.1.0-dev.260119.0a66443

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/dist/index.js CHANGED
@@ -1,3 +1,1043 @@
1
- import {SignJWT}from'jose';import {stringify}from'qs-esm';import {isServer,useQuery,keepPreviousData,useInfiniteQuery,QueryClient,defaultShouldDehydrateQuery}from'@tanstack/react-query';import se from'react';import {RichText,LinkJSXConverter,defaultJSXConverters}from'@payloadcms/richtext-lexical/react';var z=Object.defineProperty,L=Object.defineProperties;var M=Object.getOwnPropertyDescriptors;var w=Object.getOwnPropertySymbols;var $=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var B=(n,e,t)=>e in n?z(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t,c=(n,e)=>{for(var t in e||(e={}))$.call(e,t)&&B(n,t,e[t]);if(w)for(var t of w(e))F.call(e,t)&&B(n,t,e[t]);return n},y=(n,e)=>L(n,M(e));var P=(n,e)=>{var t={};for(var r in n)$.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&w)for(var r of w(n))e.indexOf(r)<0&&F.call(n,r)&&(t[r]=n[r]);return t};var i=(n,e,t)=>new Promise((r,o)=>{var s=l=>{try{p(t.next(l));}catch(m){o(m);}},a=l=>{try{p(t.throw(l));}catch(m){o(m);}},p=l=>l.done?r(l.value):Promise.resolve(l.value).then(s,a);p((t=t.apply(n,e)).next());});var g=class n extends Error{constructor(e,t,r,o){super(t),this.name="SDKError",this.code=e,this.status=r,this.details=o,Error.captureStackTrace&&Error.captureStackTrace(this,n);}toJSON(){return {name:this.name,code:this.code,message:this.message,status:this.status,details:this.details}}},h=class extends g{constructor(e,t,r){super("NETWORK_ERROR",e,t,r),this.name="NetworkError";}},K=class extends g{constructor(e,t){super("VALIDATION_ERROR",e,400,t),this.name="ValidationError";}},q=class extends g{constructor(e,t,r){super("API_ERROR",e,t,r),this.name="ApiError";}};var C=class extends g{constructor(e="\uC694\uCCAD\uC774 \uC2DC\uAC04 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.",t){super("TIMEOUT_ERROR",e,408,t),this.name="TimeoutError";}};var S=(n,e,t)=>new h(n,e,t),W=(n,e)=>new K(n,e),_=(n,e,t)=>new q(n,e,t);var V="https://01.software",X=(n,e)=>i(null,null,function*(){if(!n||!e)throw new Error("clientKey\uC640 secretKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");let t=new TextEncoder().encode(e);return yield new SignJWT({clientKey:n}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime("1h").sign(t)}),d=(n,e)=>i(null,null,function*(){let b=e||{},{clientKey:t,secretKey:r,timeout:o=3e4,baseUrl:s=V}=b,a=P(b,["clientKey","secretKey","timeout","baseUrl"]),p=new Headers(a.headers);if(t&&p.set("X-Client-Key",t),r&&t){let u=yield X(t,r);p.set("Authorization",`Bearer ${u}`);}!p.has("Content-Type")&&a.body&&p.set("Content-Type","application/json");let l=new AbortController,m=setTimeout(()=>l.abort(),o);try{let u=yield fetch(`${s}${n}`,y(c({},a),{headers:p,signal:l.signal}));if(clearTimeout(m),!u.ok)throw S(`HTTP ${u.status}: ${u.statusText}`,u.status,{url:n,method:a.method||"GET"});return u}catch(u){throw clearTimeout(m),u instanceof Error&&u.name==="AbortError"?new C(`\uC694\uCCAD\uC774 ${o}ms \uD6C4 \uD0C0\uC784\uC544\uC6C3\uB418\uC5C8\uC2B5\uB2C8\uB2E4.`,{url:n,timeout:o}):u instanceof TypeError?S("\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4. \uC778\uD130\uB137 \uC5F0\uACB0\uC744 \uD655\uC778\uD574\uC8FC\uC138\uC694.",void 0,{url:n,originalError:u.message}):u instanceof h||u instanceof C?u:S(u instanceof Error?u.message:"\uC54C \uC218 \uC5C6\uB294 \uB124\uD2B8\uC6CC\uD06C \uC5D0\uB7EC\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.",void 0,{url:n,originalError:u})}});var T=class{constructor(e,t){this.api=e;this.collection=t;}find(e){return i(this,null,function*(){return this.api.requestGet(`/api/${String(this.collection)}`,e)})}findById(e,t){return i(this,null,function*(){return this.api.requestGet(`/api/${String(this.collection)}/${String(e)}`,t)})}create(e){return i(this,null,function*(){return this.api.requestPost(`/api/${String(this.collection)}`,e)})}update(e,t){return i(this,null,function*(){return this.api.requestPatch(`/api/${String(this.collection)}/${String(e)}`,t)})}remove(e){return i(this,null,function*(){return this.api.requestDelete(`/api/${String(this.collection)}/${String(e)}`)})}};var E=class{constructor(e,t,r){if(!e)throw W("clientKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");this.clientKey=e,this.secretKey=t,this.baseUrl=r,this.defaultOptions={clientKey:e,secretKey:t,baseUrl:r};}get(e,t){return i(this,null,function*(){let r=this.buildUrl(e,t),o=yield d(r,y(c({},this.defaultOptions),{method:"GET"}));return this.parseResponse(o)})}post(e,t,r){return i(this,null,function*(){let o=yield d(e,y(c(c({},this.defaultOptions),r),{method:"POST",body:t?JSON.stringify(t):void 0}));return this.parseResponse(o)})}patch(e,t,r){return i(this,null,function*(){let o=yield d(e,y(c(c({},this.defaultOptions),r),{method:"PATCH",body:t?JSON.stringify(t):void 0}));return this.parseResponse(o)})}delete(e,t){return i(this,null,function*(){let r=yield d(e,y(c(c({},this.defaultOptions),t),{method:"DELETE"}));return this.parseResponse(r)})}buildUrl(e,t){if(!t)return e;let r=stringify(t,{addQueryPrefix:true});return r?`${e}${r}`:e}parseResponse(e){return i(this,null,function*(){let t=e.headers.get("content-type");try{if(t&&t.includes("application/json")){let o=yield e.json();if(o.docs!==void 0){let s={page:o.page||1,limit:o.limit||20,totalDocs:o.totalDocs||0,totalPages:o.totalPages||0,hasNextPage:o.hasNextPage||!1,hasPrevPage:o.hasPrevPage||!1};return {data:o.docs,success:!0,pagination:s}}return {data:o,success:!0}}return {data:yield e.text(),success:!0}}catch(r){throw _("\uC751\uB2F5 \uD30C\uC2F1\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",e.status,{contentType:t,error:r instanceof Error?r.message:r})}})}};var f=class extends E{constructor(e,t,r){super(e,t,r);}from(e){return new T(this,e)}requestGet(e,t){return this.get(e,t)}requestPost(e,t){return this.post(e,t)}requestPatch(e,t){return this.patch(e,t)}requestDelete(e){return this.delete(e)}};var Y=["brands","brand-logos","brand-og-images","brand-settings","brand-secret-keys","products","product-variants","product-options","product-categories","product-tags","product-images","orders","order-products","returns","return-products","transactions","links","link-images","playlists","playlist-images","musics","posts","post-categories","post-tags","post-images","documents","document-images","entities","entity-categories","entity-tags","entity-images","nodes","galleries","gallery-images","forms"];function j(){return new QueryClient({defaultOptions:{queries:{staleTime:Number.POSITIVE_INFINITY,refetchOnWindowFocus:false},dehydrate:{shouldDehydrateQuery:n=>defaultShouldDehydrateQuery(n)||n.state.status==="pending",shouldRedactErrors:n=>false}}})}var k;function J(){return isServer?j():(k||(k=j()),k)}var v=class{constructor(e,t){this.queryClient=e,this.collectionsApi=new f((t==null?void 0:t.brandKey)||"",t==null?void 0:t.brandSecret,t==null?void 0:t.baseUrl);}useCollection(e,t,r){let o=t;return useQuery({queryKey:[e,"list",o],queryFn:()=>i(this,null,function*(){return (yield this.collectionsApi.from(e).find(o)).data}),placeholderData:r!=null&&r.keepPreviousData?keepPreviousData:void 0})}useCollectionSingle(e,t,r){let o=t;return useQuery({queryKey:[e,"detail",o],queryFn:()=>i(this,null,function*(){var p;let a=yield this.collectionsApi.from(e).find(o);return a.data.length===0?null:(p=a.data[0])!=null?p:null}),placeholderData:r!=null&&r.keepPreviousData?keepPreviousData:void 0})}useCollectionInfinite(e,t,r){let o=t,s=[e,"list","infinite",o],a=(o==null?void 0:o.limit)||20;return useInfiniteQuery({queryKey:s,queryFn:l=>i(this,[l],function*({pageParam:p=1}){let m=y(c({},o),{page:p,limit:a});return (yield this.collectionsApi.from(e).find(m)).data}),initialPageParam:1,getNextPageParam:(p,l,m)=>!Array.isArray(p)||p.length<a?null:m+1,select:p=>p.pages.flatMap(l=>l),placeholderData:r!=null&&r.keepPreviousData?keepPreviousData:void 0})}useById(e,t,r,o){return useQuery({queryKey:[e,"detail",t],queryFn:()=>i(this,null,function*(){var p;return (p=(yield this.collectionsApi.from(e).findById(t,r)).data)!=null?p:null}),placeholderData:o!=null&&o.keepPreviousData?keepPreviousData:void 0})}prefetchCollection(e,t){return i(this,null,function*(){let r=t,o=[e,"list",r];return this.queryClient.prefetchQuery({queryKey:o,queryFn:()=>i(this,null,function*(){return (yield this.collectionsApi.from(e).find(r)).data})})})}prefetchCollectionSingle(e,t){return i(this,null,function*(){let r=t,o=[e,"detail",r];return this.queryClient.prefetchQuery({queryKey:o,queryFn:()=>i(this,null,function*(){let s=yield this.collectionsApi.from(e).find(r);return s.data.length===0?null:s.data[0]})})})}prefetchCollectionInfinite(e,t){return i(this,null,function*(){let r=t,o=[e,"list","infinite",r],s=(r==null?void 0:r.limit)||20;return this.queryClient.prefetchInfiniteQuery({queryKey:o,queryFn:p=>i(this,[p],function*({pageParam:a=1}){let l=y(c({},r),{page:a,limit:s});return (yield this.collectionsApi.from(e).find(l)).data}),initialPageParam:1,getNextPageParam:(a,p,l)=>!Array.isArray(a)||a.length<s?null:l+1,pages:2})})}prefetchById(e,t,r){return i(this,null,function*(){let o=[e,"detail",t];return this.queryClient.prefetchQuery({queryKey:o,queryFn:()=>i(this,null,function*(){var a;return (a=(yield this.collectionsApi.from(e).findById(t,r)).data)!=null?a:null})})})}invalidateQueries(e,t){let r=t?[e,t]:[e];return this.queryClient.invalidateQueries({queryKey:r})}getQueryData(e,t,...r){let o=[e,t,...r.filter(s=>s!==void 0)];return this.queryClient.getQueryData(o)}setQueryData(e,t,r,...o){let s=[e,t,...o.filter(a=>a!==void 0)];return this.queryClient.setQueryData(s,r)}};var x=class{constructor(e){var r;if(!e.clientKey)throw new Error("clientKey is required.");this.config=c({},e);let t={timestamp:Date.now(),userAgent:typeof window!="undefined"?(r=window.navigator)==null?void 0:r.userAgent:"Node.js"};this.state={metadata:t},this.fetch=d,this.queryClient=J(),this.query=new v(this.queryClient,{brandKey:this.config.clientKey,baseUrl:this.config.baseUrl}),this.collections=new f(this.config.clientKey,void 0,this.config.baseUrl);}getSettings(){return i(this,null,function*(){let{data:e}=yield this.from("brand-settings").find({where:{"brand.clientKey":{equals:this.config.clientKey}}});return e.length>0?e[0]:null})}from(e){return this.collections.from(e)}getState(){return c({},this.state)}},ne=n=>new x(n);var Q=m=>i(null,[m],function*({paymentId:n,orderNumber:e,orderProducts:t,email:r,shippingAddress:o,totalAmount:s,secretKey:a,clientKey:p,baseUrl:l}){return (yield d("/api/orders/create",{method:"POST",baseUrl:l,clientKey:p,secretKey:a,body:JSON.stringify({paymentId:n,orderNumber:e,orderProducts:t,email:r,shippingAddress:o,totalAmount:s})})).json()});var D=s=>i(null,[s],function*({orderNumber:n,status:e,secretKey:t,clientKey:r,baseUrl:o}){return (yield d("/api/orders/update",{method:"POST",baseUrl:o,clientKey:r,secretKey:t,body:JSON.stringify({orderNumber:n,status:e})})).json()});var U=p=>i(null,[p],function*({paymentId:n,status:e,paymentMethod:t,receiptUrl:r,secretKey:o,clientKey:s,baseUrl:a}){return (yield d("/api/transactions/update",{method:"POST",baseUrl:a,clientKey:s,secretKey:o,body:JSON.stringify({paymentId:n,status:e,paymentMethod:t,receiptUrl:r})})).json()});var O=class{constructor(e){if(!e.clientKey)throw new Error("clientKey is required.");if(!e.secretKey)throw new Error("secretKey is required.");this.clientKey=e.clientKey,this.secretKey=e.secretKey,this.baseUrl=e.baseUrl;}getCommonOptions(){return {clientKey:this.clientKey,secretKey:this.secretKey,baseUrl:this.baseUrl}}createOrder(e){return Q(c(c({},e),this.getCommonOptions()))}updateOrder(e){return D(c(c({},e),this.getCommonOptions()))}updateTransaction(e){return U(c(c({},e),this.getCommonOptions()))}};var A=class{constructor(e){var r;if(!e.clientKey)throw new Error("clientKey is required.");if(!e.secretKey)throw new Error("secretKey is required.");this.config=c({},e);let t={timestamp:Date.now(),userAgent:typeof window!="undefined"?(r=window.navigator)==null?void 0:r.userAgent:"Node.js"};this.state={metadata:t},this.fetch=d,this.api=new O({clientKey:this.config.clientKey,secretKey:this.config.secretKey,baseUrl:this.config.baseUrl}),this.collections=new f(this.config.clientKey,this.config.secretKey,this.config.baseUrl);}getSettings(){return i(this,null,function*(){let{data:e}=yield this.from("brand-settings").find({where:{"brand.clientKey":{equals:this.config.clientKey}}});return e.length>0?e[0]:null})}from(e){return this.collections.from(e)}getState(){return c({},this.state)}getConfig(){let r=this.config,{secretKey:e}=r;return P(r,["secretKey"])}},oe=n=>new A(n);function wt(n,e){return i(this,null,function*(){try{let t=yield n.json();return ie(t)?(yield e(t),new Response(JSON.stringify({success:!0,message:"Webhook processed"}),{status:200,headers:{"Content-Type":"application/json"}})):new Response(JSON.stringify({error:"Invalid webhook event format"}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){return console.error("Webhook processing error:",t),new Response(JSON.stringify({error:"Internal server error",message:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}})}function ie(n){return typeof n=="object"&&n!==null&&typeof n.collection=="string"&&(n.operation==="create"||n.operation==="update")&&typeof n.data=="object"&&n.data!==null}function Pt(n,e){return t=>i(null,null,function*(){if(t.collection!==n)throw new Error(`Expected collection "${n}", got "${t.collection}"`);return e(t)})}var Rt=()=>{let n=new Date().getFullYear().toString().slice(-2),e=new Date().getMonth().toString().padStart(2,"0"),t=new Date().getDate().toString().padStart(2,"0"),r=Math.floor(Math.random()*1e6).toString().padStart(6,"0");return `${n}${e}${t}${r}`};var I=n=>typeof n=="number"?null:n;var kt=n=>{var t,r,o,s;let e=n.length;return e===1?((r=I((t=n==null?void 0:n[0])==null?void 0:t.product))==null?void 0:r.title)||"":`${(s=I((o=n.at(0))==null?void 0:o.product))==null?void 0:s.title} \uC678 ${e-1}\uAC74`};function It({data:n,className:e,internalDocToHref:t,blocks:r}){return se.createElement(RichText,{data:n,className:e,converters:y(c(c({},defaultJSXConverters),LinkJSXConverter({internalDocToHref:t})),{blocks:r||void 0})})}
2
- export{O as ApiClient,x as BrowserClient,Y as COLLECTIONS,T as CollectionQueryBuilder,f as CollectionsApi,It as RichTextContent,A as ServerClient,v as UnifiedQueryClient,ne as createBrowserClient,Q as createOrder,oe as createServerClient,Pt as createTypedWebhookHandler,kt as formatOrderName,Rt as generateOrderNumber,J as getQueryClient,wt as handleWebhook,ie as isValidWebhookEvent,I as objectFor,D as updateOrder,U as updateTransaction};//# sourceMappingURL=index.js.map
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 __pow = Math.pow;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21
+ var __objRest = (source, exclude) => {
22
+ var target = {};
23
+ for (var prop in source)
24
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
25
+ target[prop] = source[prop];
26
+ if (source != null && __getOwnPropSymbols)
27
+ for (var prop of __getOwnPropSymbols(source)) {
28
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
29
+ target[prop] = source[prop];
30
+ }
31
+ return target;
32
+ };
33
+ var __async = (__this, __arguments, generator) => {
34
+ return new Promise((resolve, reject) => {
35
+ var fulfilled = (value) => {
36
+ try {
37
+ step(generator.next(value));
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ };
42
+ var rejected = (value) => {
43
+ try {
44
+ step(generator.throw(value));
45
+ } catch (e) {
46
+ reject(e);
47
+ }
48
+ };
49
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
50
+ step((generator = generator.apply(__this, __arguments)).next());
51
+ });
52
+ };
53
+
54
+ // src/core/collection/query-builder.ts
55
+ var CollectionQueryBuilder = class {
56
+ constructor(api, collection) {
57
+ this.api = api;
58
+ this.collection = collection;
59
+ }
60
+ find(options) {
61
+ return __async(this, null, function* () {
62
+ return this.api.requestGet(
63
+ `/api/${String(this.collection)}`,
64
+ options
65
+ );
66
+ });
67
+ }
68
+ findById(id, options) {
69
+ return __async(this, null, function* () {
70
+ return this.api.requestGet(
71
+ `/api/${String(this.collection)}/${String(id)}`,
72
+ options
73
+ );
74
+ });
75
+ }
76
+ create(data) {
77
+ return __async(this, null, function* () {
78
+ return this.api.requestPost(
79
+ `/api/${String(this.collection)}`,
80
+ data
81
+ );
82
+ });
83
+ }
84
+ update(id, data) {
85
+ return __async(this, null, function* () {
86
+ return this.api.requestPatch(
87
+ `/api/${String(this.collection)}/${String(id)}`,
88
+ data
89
+ );
90
+ });
91
+ }
92
+ remove(id) {
93
+ return __async(this, null, function* () {
94
+ return this.api.requestDelete(
95
+ `/api/${String(this.collection)}/${String(id)}`
96
+ );
97
+ });
98
+ }
99
+ };
100
+
101
+ // src/core/collection/base.ts
102
+ import { stringify } from "qs-esm";
103
+
104
+ // src/core/internal/utils/index.ts
105
+ import { SignJWT, jwtVerify, decodeJwt } from "jose";
106
+
107
+ // src/core/internal/errors/index.ts
108
+ var SDKError = class _SDKError extends Error {
109
+ constructor(code, message, status, details, userMessage, suggestion) {
110
+ super(message);
111
+ this.name = "SDKError";
112
+ this.code = code;
113
+ this.status = status;
114
+ this.details = details;
115
+ this.userMessage = userMessage;
116
+ this.suggestion = suggestion;
117
+ if (Error.captureStackTrace) {
118
+ Error.captureStackTrace(this, _SDKError);
119
+ }
120
+ }
121
+ getUserMessage() {
122
+ return this.userMessage || this.message;
123
+ }
124
+ toJSON() {
125
+ return {
126
+ name: this.name,
127
+ code: this.code,
128
+ message: this.message,
129
+ status: this.status,
130
+ details: this.details,
131
+ userMessage: this.userMessage,
132
+ suggestion: this.suggestion
133
+ };
134
+ }
135
+ };
136
+ var NetworkError = class extends SDKError {
137
+ constructor(message, status, details, userMessage, suggestion) {
138
+ super("NETWORK_ERROR", message, status, details, userMessage, suggestion);
139
+ this.name = "NetworkError";
140
+ }
141
+ };
142
+ var ValidationError = class extends SDKError {
143
+ constructor(message, details, userMessage, suggestion) {
144
+ super("VALIDATION_ERROR", message, 400, details, userMessage, suggestion);
145
+ this.name = "ValidationError";
146
+ }
147
+ };
148
+ var ApiError = class extends SDKError {
149
+ constructor(message, status, details, userMessage, suggestion) {
150
+ super("API_ERROR", message, status, details, userMessage, suggestion);
151
+ this.name = "ApiError";
152
+ }
153
+ };
154
+ var ConfigError = class extends SDKError {
155
+ constructor(message, details, userMessage, suggestion) {
156
+ super("CONFIG_ERROR", message, void 0, details, userMessage, suggestion);
157
+ this.name = "ConfigError";
158
+ }
159
+ };
160
+ var TimeoutError = class extends SDKError {
161
+ constructor(message = "\uC694\uCCAD\uC774 \uC2DC\uAC04 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.", details, userMessage, suggestion) {
162
+ super("TIMEOUT_ERROR", message, 408, details, userMessage, suggestion);
163
+ this.name = "TimeoutError";
164
+ }
165
+ };
166
+ function isSDKError(error) {
167
+ return error instanceof SDKError;
168
+ }
169
+ function isNetworkError(error) {
170
+ return error instanceof NetworkError;
171
+ }
172
+ function isValidationError(error) {
173
+ return error instanceof ValidationError;
174
+ }
175
+ function isApiError(error) {
176
+ return error instanceof ApiError;
177
+ }
178
+ function isConfigError(error) {
179
+ return error instanceof ConfigError;
180
+ }
181
+ function isTimeoutError(error) {
182
+ return error instanceof TimeoutError;
183
+ }
184
+ var createNetworkError = (message, status, details, userMessage, suggestion) => new NetworkError(message, status, details, userMessage, suggestion);
185
+ var createValidationError = (message, details, userMessage, suggestion) => new ValidationError(message, details, userMessage, suggestion);
186
+ var createApiError = (message, status, details, userMessage, suggestion) => new ApiError(message, status, details, userMessage, suggestion);
187
+
188
+ // src/core/client/types.ts
189
+ var API_URLS = {
190
+ local: "http://localhost:3000",
191
+ development: "https://dev.01.software",
192
+ staging: "https://stg.01.software",
193
+ production: "https://api.01.software"
194
+ };
195
+ function resolveApiUrl(config) {
196
+ if (config == null ? void 0 : config.baseUrl) {
197
+ return config.baseUrl.replace(/\/$/, "");
198
+ }
199
+ const envUrl = process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL;
200
+ if (envUrl) {
201
+ return envUrl.replace(/\/$/, "");
202
+ }
203
+ if (config == null ? void 0 : config.environment) {
204
+ return API_URLS[config.environment];
205
+ }
206
+ return API_URLS.production;
207
+ }
208
+ function isSuccessResponse(response) {
209
+ return response.success === true;
210
+ }
211
+ function isErrorResponse(response) {
212
+ return response.success === false;
213
+ }
214
+
215
+ // src/core/internal/utils/index.ts
216
+ var DEFAULT_TIMEOUT = 3e4;
217
+ var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
218
+ function createServerToken(clientKey, secretKey, expiresIn = "1h") {
219
+ return __async(this, null, function* () {
220
+ if (!clientKey || !secretKey) {
221
+ throw new Error("clientKey\uC640 secretKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
222
+ }
223
+ const secret = new TextEncoder().encode(secretKey);
224
+ return new SignJWT({ clientKey }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(secret);
225
+ });
226
+ }
227
+ function verifyServerToken(token, secretKey) {
228
+ return __async(this, null, function* () {
229
+ if (!token || !secretKey) {
230
+ throw new Error("token\uACFC secretKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
231
+ }
232
+ const secret = new TextEncoder().encode(secretKey);
233
+ const { payload } = yield jwtVerify(token, secret, {
234
+ algorithms: ["HS256"]
235
+ });
236
+ if (!payload.clientKey || typeof payload.clientKey !== "string") {
237
+ throw new Error("Invalid token payload: clientKey is missing");
238
+ }
239
+ return {
240
+ clientKey: payload.clientKey,
241
+ iat: payload.iat,
242
+ exp: payload.exp
243
+ };
244
+ });
245
+ }
246
+ function decodeServerToken(token) {
247
+ if (!token) {
248
+ throw new Error("token\uC740 \uD544\uC218\uC785\uB2C8\uB2E4.");
249
+ }
250
+ const payload = decodeJwt(token);
251
+ if (!payload.clientKey || typeof payload.clientKey !== "string") {
252
+ throw new Error("Invalid token payload: clientKey is missing");
253
+ }
254
+ return {
255
+ clientKey: payload.clientKey,
256
+ iat: payload.iat,
257
+ exp: payload.exp
258
+ };
259
+ }
260
+ function createApiKey(clientKey, secretKey) {
261
+ if (!clientKey || !secretKey) {
262
+ throw new Error("clientKey\uC640 secretKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
263
+ }
264
+ if (typeof Buffer !== "undefined") {
265
+ return Buffer.from(`${clientKey}:${secretKey}`).toString("base64");
266
+ }
267
+ return btoa(`${clientKey}:${secretKey}`);
268
+ }
269
+ function parseApiKey(apiKey) {
270
+ if (!apiKey) {
271
+ throw new Error("apiKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
272
+ }
273
+ try {
274
+ let decoded;
275
+ if (typeof Buffer !== "undefined") {
276
+ decoded = Buffer.from(apiKey, "base64").toString("utf-8");
277
+ } else {
278
+ decoded = atob(apiKey);
279
+ }
280
+ const colonIndex = decoded.indexOf(":");
281
+ if (colonIndex === -1) {
282
+ throw new Error("Invalid format");
283
+ }
284
+ const clientKey = decoded.substring(0, colonIndex);
285
+ const secretKey = decoded.substring(colonIndex + 1);
286
+ if (!clientKey || !secretKey) {
287
+ throw new Error("Invalid format");
288
+ }
289
+ return { clientKey, secretKey };
290
+ } catch (e) {
291
+ throw new Error('Invalid API key. Expected Base64 encoded "clientKey:secretKey"');
292
+ }
293
+ }
294
+ function debugLog(debug, type, message, data) {
295
+ if (!debug) return;
296
+ const shouldLog = debug === true || type === "request" && debug.logRequests || type === "response" && debug.logResponses || type === "error" && debug.logErrors;
297
+ if (shouldLog) {
298
+ console.group(`[SDK ${type.toUpperCase()}] ${message}`);
299
+ if (data) console.log(data);
300
+ console.groupEnd();
301
+ }
302
+ }
303
+ function getErrorSuggestion(status) {
304
+ if (status === 401) return "\uC778\uC99D \uC815\uBCF4\uB97C \uD655\uC778\uD574\uC8FC\uC138\uC694.";
305
+ if (status === 404) return "\uC694\uCCAD\uD55C \uB9AC\uC18C\uC2A4\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.";
306
+ if (status >= 500)
307
+ return "\uC11C\uBC84 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4. \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694.";
308
+ return void 0;
309
+ }
310
+ function delay(ms) {
311
+ return __async(this, null, function* () {
312
+ return new Promise((resolve) => setTimeout(resolve, ms));
313
+ });
314
+ }
315
+ function _fetch(url, options) {
316
+ return __async(this, null, function* () {
317
+ var _b, _c, _d;
318
+ const _a = options || {}, {
319
+ clientKey,
320
+ secretKey,
321
+ timeout = DEFAULT_TIMEOUT,
322
+ baseUrl = API_URLS.production,
323
+ debug,
324
+ retry
325
+ } = _a, requestInit = __objRest(_a, [
326
+ "clientKey",
327
+ "secretKey",
328
+ "timeout",
329
+ "baseUrl",
330
+ "debug",
331
+ "retry"
332
+ ]);
333
+ const retryConfig = {
334
+ maxRetries: (_b = retry == null ? void 0 : retry.maxRetries) != null ? _b : 3,
335
+ retryableStatuses: (_c = retry == null ? void 0 : retry.retryableStatuses) != null ? _c : DEFAULT_RETRYABLE_STATUSES,
336
+ retryDelay: (_d = retry == null ? void 0 : retry.retryDelay) != null ? _d : ((attempt) => Math.min(1e3 * __pow(2, attempt), 1e4))
337
+ };
338
+ let lastError;
339
+ for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
340
+ try {
341
+ const headers = new Headers(requestInit.headers);
342
+ if (clientKey) {
343
+ headers.set("X-Client-Key", clientKey);
344
+ }
345
+ if (secretKey && clientKey) {
346
+ const token = yield createServerToken(clientKey, secretKey);
347
+ headers.set("Authorization", `Bearer ${token}`);
348
+ }
349
+ if (!headers.has("Content-Type") && requestInit.body) {
350
+ headers.set("Content-Type", "application/json");
351
+ }
352
+ debugLog(debug, "request", url, {
353
+ method: requestInit.method || "GET",
354
+ headers: Object.fromEntries(headers.entries()),
355
+ attempt: attempt + 1
356
+ });
357
+ const controller = new AbortController();
358
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
359
+ const response = yield fetch(`${baseUrl}${url}`, __spreadProps(__spreadValues({}, requestInit), {
360
+ headers,
361
+ signal: controller.signal
362
+ }));
363
+ clearTimeout(timeoutId);
364
+ debugLog(debug, "response", url, {
365
+ status: response.status,
366
+ statusText: response.statusText,
367
+ headers: Object.fromEntries(response.headers.entries())
368
+ });
369
+ if (!response.ok) {
370
+ const error = createNetworkError(
371
+ `HTTP ${response.status}: ${response.statusText}`,
372
+ response.status,
373
+ { url, method: requestInit.method || "GET", attempt: attempt + 1 },
374
+ `\uC694\uCCAD\uC774 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4 (\uC0C1\uD0DC \uCF54\uB4DC: ${response.status})`,
375
+ getErrorSuggestion(response.status)
376
+ );
377
+ if (attempt < retryConfig.maxRetries && retryConfig.retryableStatuses.includes(response.status)) {
378
+ lastError = error;
379
+ const retryDelay = retryConfig.retryDelay(attempt);
380
+ debugLog(debug, "error", `\uC7AC\uC2DC\uB3C4 \uB300\uAE30 \uC911... (${retryDelay}ms)`, error);
381
+ yield delay(retryDelay);
382
+ continue;
383
+ }
384
+ throw error;
385
+ }
386
+ return response;
387
+ } catch (error) {
388
+ debugLog(debug, "error", url, error);
389
+ if (error instanceof Error && error.name === "AbortError") {
390
+ const timeoutError = new TimeoutError(
391
+ `\uC694\uCCAD\uC774 ${timeout}ms \uD6C4 \uD0C0\uC784\uC544\uC6C3\uB418\uC5C8\uC2B5\uB2C8\uB2E4.`,
392
+ { url, timeout, attempt: attempt + 1 },
393
+ "\uC694\uCCAD \uC2DC\uAC04\uC774 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.",
394
+ "\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uAC70\uB098 \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694."
395
+ );
396
+ if (attempt < retryConfig.maxRetries) {
397
+ lastError = timeoutError;
398
+ yield delay(retryConfig.retryDelay(attempt));
399
+ continue;
400
+ }
401
+ throw timeoutError;
402
+ }
403
+ if (error instanceof TypeError) {
404
+ const networkError = createNetworkError(
405
+ "\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
406
+ void 0,
407
+ { url, originalError: error.message, attempt: attempt + 1 },
408
+ "\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
409
+ "\uC778\uD130\uB137 \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uACE0 \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694."
410
+ );
411
+ if (attempt < retryConfig.maxRetries) {
412
+ lastError = networkError;
413
+ yield delay(retryConfig.retryDelay(attempt));
414
+ continue;
415
+ }
416
+ throw networkError;
417
+ }
418
+ if (error instanceof NetworkError || error instanceof TimeoutError) {
419
+ if (attempt < retryConfig.maxRetries && error.status && retryConfig.retryableStatuses.includes(error.status)) {
420
+ lastError = error;
421
+ yield delay(retryConfig.retryDelay(attempt));
422
+ continue;
423
+ }
424
+ throw error;
425
+ }
426
+ const unknownError = createNetworkError(
427
+ error instanceof Error ? error.message : "\uC54C \uC218 \uC5C6\uB294 \uB124\uD2B8\uC6CC\uD06C \uC5D0\uB7EC\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.",
428
+ void 0,
429
+ { url, originalError: error, attempt: attempt + 1 },
430
+ "\uC54C \uC218 \uC5C6\uB294 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.",
431
+ "\uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694."
432
+ );
433
+ if (attempt < retryConfig.maxRetries) {
434
+ lastError = unknownError;
435
+ yield delay(retryConfig.retryDelay(attempt));
436
+ continue;
437
+ }
438
+ throw unknownError;
439
+ }
440
+ }
441
+ throw lastError;
442
+ });
443
+ }
444
+
445
+ // src/core/collection/base.ts
446
+ var BaseApiClient = class {
447
+ constructor(clientKey, secretKey, baseUrl) {
448
+ if (!clientKey) {
449
+ throw createValidationError("clientKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
450
+ }
451
+ this.clientKey = clientKey;
452
+ this.secretKey = secretKey;
453
+ this.baseUrl = baseUrl;
454
+ this.defaultOptions = { clientKey, secretKey, baseUrl };
455
+ }
456
+ get(endpoint, options) {
457
+ return __async(this, null, function* () {
458
+ const url = this.buildUrl(endpoint, options);
459
+ const response = yield _fetch(url, __spreadProps(__spreadValues({}, this.defaultOptions), { method: "GET" }));
460
+ return this.parseResponse(response);
461
+ });
462
+ }
463
+ post(endpoint, data, options) {
464
+ return __async(this, null, function* () {
465
+ const response = yield _fetch(endpoint, __spreadProps(__spreadValues(__spreadValues({}, this.defaultOptions), options), {
466
+ method: "POST",
467
+ body: data ? JSON.stringify(data) : void 0
468
+ }));
469
+ return this.parseResponse(response);
470
+ });
471
+ }
472
+ patch(endpoint, data, options) {
473
+ return __async(this, null, function* () {
474
+ const response = yield _fetch(endpoint, __spreadProps(__spreadValues(__spreadValues({}, this.defaultOptions), options), {
475
+ method: "PATCH",
476
+ body: data ? JSON.stringify(data) : void 0
477
+ }));
478
+ return this.parseResponse(response);
479
+ });
480
+ }
481
+ delete(endpoint, options) {
482
+ return __async(this, null, function* () {
483
+ const response = yield _fetch(endpoint, __spreadProps(__spreadValues(__spreadValues({}, this.defaultOptions), options), {
484
+ method: "DELETE"
485
+ }));
486
+ return this.parseResponse(response);
487
+ });
488
+ }
489
+ buildUrl(endpoint, options) {
490
+ if (!options) return endpoint;
491
+ const queryString = stringify(options, { addQueryPrefix: true });
492
+ return queryString ? `${endpoint}${queryString}` : endpoint;
493
+ }
494
+ parseResponse(response) {
495
+ return __async(this, null, function* () {
496
+ const contentType = response.headers.get("content-type");
497
+ try {
498
+ if (contentType == null ? void 0 : contentType.includes("application/json")) {
499
+ const jsonData = yield response.json();
500
+ if (jsonData.docs !== void 0) {
501
+ const pagination = {
502
+ page: jsonData.page || 1,
503
+ limit: jsonData.limit || 20,
504
+ totalDocs: jsonData.totalDocs || 0,
505
+ totalPages: jsonData.totalPages || 0,
506
+ hasNextPage: jsonData.hasNextPage || false,
507
+ hasPrevPage: jsonData.hasPrevPage || false
508
+ };
509
+ return { data: jsonData.docs, success: true, pagination };
510
+ }
511
+ return { data: jsonData, success: true };
512
+ }
513
+ const textData = yield response.text();
514
+ return { data: textData, success: true };
515
+ } catch (error) {
516
+ throw createApiError("\uC751\uB2F5 \uD30C\uC2F1\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.", response.status, {
517
+ contentType,
518
+ error: error instanceof Error ? error.message : error
519
+ });
520
+ }
521
+ });
522
+ }
523
+ };
524
+
525
+ // src/core/collection/collections-api.ts
526
+ var CollectionsApi = class extends BaseApiClient {
527
+ constructor(clientKey, secretKey, baseUrl) {
528
+ super(clientKey, secretKey, baseUrl);
529
+ }
530
+ from(collection) {
531
+ return new CollectionQueryBuilder(this, collection);
532
+ }
533
+ requestGet(endpoint, options) {
534
+ return this.get(endpoint, options);
535
+ }
536
+ requestPost(endpoint, data) {
537
+ return this.post(endpoint, data);
538
+ }
539
+ requestPatch(endpoint, data) {
540
+ return this.patch(endpoint, data);
541
+ }
542
+ requestDelete(endpoint) {
543
+ return this.delete(endpoint);
544
+ }
545
+ };
546
+
547
+ // src/core/collection/const.ts
548
+ var COLLECTIONS = [
549
+ "tenants",
550
+ "tenant-metadata",
551
+ "tenant-logos",
552
+ "tenant-og-images",
553
+ "products",
554
+ "product-variants",
555
+ "product-options",
556
+ "product-categories",
557
+ "product-tags",
558
+ "product-images",
559
+ "brands",
560
+ "brand-logos",
561
+ "orders",
562
+ "order-products",
563
+ "returns",
564
+ "return-products",
565
+ "transactions",
566
+ "documents",
567
+ "document-categories",
568
+ "document-images",
569
+ "posts",
570
+ "post-categories",
571
+ "post-tags",
572
+ "post-images",
573
+ "playlists",
574
+ "playlist-images",
575
+ "musics",
576
+ "galleries",
577
+ "gallery-images",
578
+ "forms",
579
+ "form-submissions",
580
+ "media"
581
+ ];
582
+
583
+ // src/core/query/get-query-client.ts
584
+ import { isServer, QueryClient, defaultShouldDehydrateQuery } from "@tanstack/react-query";
585
+ function makeQueryClient() {
586
+ return new QueryClient({
587
+ defaultOptions: {
588
+ queries: {
589
+ staleTime: Number.POSITIVE_INFINITY,
590
+ refetchOnWindowFocus: false
591
+ },
592
+ dehydrate: {
593
+ shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === "pending",
594
+ shouldRedactErrors: () => false
595
+ }
596
+ }
597
+ });
598
+ }
599
+ var browserQueryClient;
600
+ function getQueryClient() {
601
+ if (isServer) {
602
+ return makeQueryClient();
603
+ }
604
+ if (!browserQueryClient) {
605
+ browserQueryClient = makeQueryClient();
606
+ }
607
+ return browserQueryClient;
608
+ }
609
+
610
+ // src/core/query/UnifiedQuery.ts
611
+ import {
612
+ useQuery as useQueryOriginal,
613
+ useSuspenseQuery as useSuspenseQueryOriginal,
614
+ useInfiniteQuery as useInfiniteQueryOriginal,
615
+ useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal
616
+ } from "@tanstack/react-query";
617
+ function collectionKeys(collection) {
618
+ return {
619
+ all: [collection],
620
+ lists: () => [collection, "list"],
621
+ list: (options) => [collection, "list", options],
622
+ details: () => [collection, "detail"],
623
+ detail: (id, options) => [collection, "detail", id, options],
624
+ infinites: () => [collection, "infinite"],
625
+ infinite: (options) => [collection, "infinite", options]
626
+ };
627
+ }
628
+ var DEFAULT_PAGE_SIZE = 20;
629
+ var UnifiedQueryClient = class {
630
+ constructor(queryClient, options) {
631
+ this.queryClient = queryClient;
632
+ this.collectionsApi = new CollectionsApi((options == null ? void 0 : options.clientKey) || "", void 0, options == null ? void 0 : options.baseUrl);
633
+ }
634
+ // ===== useQuery =====
635
+ useQuery(params, options) {
636
+ const { collection, options: queryOptions } = params;
637
+ return useQueryOriginal(__spreadValues({
638
+ queryKey: collectionKeys(collection).list(queryOptions),
639
+ queryFn: () => __async(this, null, function* () {
640
+ var _a;
641
+ const response = yield this.collectionsApi.from(collection).find(queryOptions);
642
+ return (_a = response.data) != null ? _a : [];
643
+ })
644
+ }, options));
645
+ }
646
+ // ===== useSuspenseQuery =====
647
+ useSuspenseQuery(params, options) {
648
+ const { collection, options: queryOptions } = params;
649
+ return useSuspenseQueryOriginal(__spreadValues({
650
+ queryKey: collectionKeys(collection).list(queryOptions),
651
+ queryFn: () => __async(this, null, function* () {
652
+ var _a;
653
+ const response = yield this.collectionsApi.from(collection).find(queryOptions);
654
+ return (_a = response.data) != null ? _a : [];
655
+ })
656
+ }, options));
657
+ }
658
+ // ===== useQueryById =====
659
+ useQueryById(params, options) {
660
+ const { collection, id, options: queryOptions } = params;
661
+ return useQueryOriginal(__spreadValues({
662
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
663
+ queryFn: () => __async(this, null, function* () {
664
+ var _a;
665
+ const response = yield this.collectionsApi.from(collection).findById(id, queryOptions);
666
+ return (_a = response.data) != null ? _a : null;
667
+ })
668
+ }, options));
669
+ }
670
+ // ===== useSuspenseQueryById =====
671
+ useSuspenseQueryById(params, options) {
672
+ const { collection, id, options: queryOptions } = params;
673
+ return useSuspenseQueryOriginal(__spreadValues({
674
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
675
+ queryFn: () => __async(this, null, function* () {
676
+ var _a;
677
+ const response = yield this.collectionsApi.from(collection).findById(id, queryOptions);
678
+ return (_a = response.data) != null ? _a : null;
679
+ })
680
+ }, options));
681
+ }
682
+ // ===== useInfiniteQuery =====
683
+ useInfiniteQuery(params, options) {
684
+ const { collection, options: queryOptions, pageSize = DEFAULT_PAGE_SIZE } = params;
685
+ return useInfiniteQueryOriginal(__spreadValues({
686
+ queryKey: collectionKeys(collection).infinite(queryOptions),
687
+ queryFn: (_0) => __async(this, [_0], function* ({ pageParam }) {
688
+ var _a;
689
+ const response = yield this.collectionsApi.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
690
+ return (_a = response.data) != null ? _a : [];
691
+ }),
692
+ initialPageParam: 1,
693
+ getNextPageParam: (lastPage, _allPages, lastPageParam) => {
694
+ if (!Array.isArray(lastPage) || lastPage.length < pageSize) return void 0;
695
+ return lastPageParam + 1;
696
+ }
697
+ }, options));
698
+ }
699
+ // ===== useSuspenseInfiniteQuery =====
700
+ useSuspenseInfiniteQuery(params, options) {
701
+ const { collection, options: queryOptions, pageSize = DEFAULT_PAGE_SIZE } = params;
702
+ return useSuspenseInfiniteQueryOriginal(__spreadValues({
703
+ queryKey: collectionKeys(collection).infinite(queryOptions),
704
+ queryFn: (_0) => __async(this, [_0], function* ({ pageParam }) {
705
+ var _a;
706
+ const response = yield this.collectionsApi.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
707
+ return (_a = response.data) != null ? _a : [];
708
+ }),
709
+ initialPageParam: 1,
710
+ getNextPageParam: (lastPage, _allPages, lastPageParam) => {
711
+ if (!Array.isArray(lastPage) || lastPage.length < pageSize) return void 0;
712
+ return lastPageParam + 1;
713
+ }
714
+ }, options));
715
+ }
716
+ // ===== prefetchQuery =====
717
+ prefetchQuery(params, options) {
718
+ return __async(this, null, function* () {
719
+ const { collection, options: queryOptions } = params;
720
+ return this.queryClient.prefetchQuery(__spreadValues({
721
+ queryKey: collectionKeys(collection).list(queryOptions),
722
+ queryFn: () => __async(this, null, function* () {
723
+ var _a;
724
+ const response = yield this.collectionsApi.from(collection).find(queryOptions);
725
+ return (_a = response.data) != null ? _a : [];
726
+ })
727
+ }, options));
728
+ });
729
+ }
730
+ // ===== prefetchQueryById =====
731
+ prefetchQueryById(params, options) {
732
+ return __async(this, null, function* () {
733
+ const { collection, id, options: queryOptions } = params;
734
+ return this.queryClient.prefetchQuery(__spreadValues({
735
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
736
+ queryFn: () => __async(this, null, function* () {
737
+ var _a;
738
+ const response = yield this.collectionsApi.from(collection).findById(id, queryOptions);
739
+ return (_a = response.data) != null ? _a : null;
740
+ })
741
+ }, options));
742
+ });
743
+ }
744
+ // ===== prefetchInfiniteQuery =====
745
+ prefetchInfiniteQuery(params, options) {
746
+ return __async(this, null, function* () {
747
+ var _a;
748
+ const { collection, options: queryOptions, pageSize = DEFAULT_PAGE_SIZE } = params;
749
+ return this.queryClient.prefetchInfiniteQuery({
750
+ queryKey: collectionKeys(collection).infinite(queryOptions),
751
+ queryFn: (_0) => __async(this, [_0], function* ({ pageParam }) {
752
+ var _a2;
753
+ const response = yield this.collectionsApi.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
754
+ return (_a2 = response.data) != null ? _a2 : [];
755
+ }),
756
+ initialPageParam: 1,
757
+ getNextPageParam: (lastPage, _allPages, lastPageParam) => {
758
+ if (!Array.isArray(lastPage) || lastPage.length < pageSize) return void 0;
759
+ return lastPageParam + 1;
760
+ },
761
+ pages: (_a = options == null ? void 0 : options.pages) != null ? _a : 1,
762
+ staleTime: options == null ? void 0 : options.staleTime
763
+ });
764
+ });
765
+ }
766
+ // ===== Cache Utilities =====
767
+ invalidateQueries(collection, type) {
768
+ const queryKey = type ? [collection, type] : [collection];
769
+ return this.queryClient.invalidateQueries({ queryKey });
770
+ }
771
+ getQueryData(collection, type, idOrOptions, options) {
772
+ if (type === "list") {
773
+ return this.queryClient.getQueryData(collectionKeys(collection).list(idOrOptions));
774
+ }
775
+ return this.queryClient.getQueryData(collectionKeys(collection).detail(idOrOptions, options));
776
+ }
777
+ setQueryData(collection, type, dataOrId, dataOrOptions, options) {
778
+ if (type === "list") {
779
+ this.queryClient.setQueryData(
780
+ collectionKeys(collection).list(dataOrOptions),
781
+ dataOrId
782
+ );
783
+ } else {
784
+ this.queryClient.setQueryData(
785
+ collectionKeys(collection).detail(dataOrId, options),
786
+ dataOrOptions
787
+ );
788
+ }
789
+ }
790
+ };
791
+
792
+ // src/core/client/client.ts
793
+ var BrowserClient = class {
794
+ constructor(options) {
795
+ var _a;
796
+ if (!options.clientKey) {
797
+ throw new Error("clientKey is required.");
798
+ }
799
+ this.config = __spreadValues({}, options);
800
+ this.baseUrl = resolveApiUrl(options);
801
+ const metadata = {
802
+ timestamp: Date.now(),
803
+ userAgent: typeof window !== "undefined" ? (_a = window.navigator) == null ? void 0 : _a.userAgent : "Node.js"
804
+ };
805
+ this.state = { metadata };
806
+ this.queryClient = getQueryClient();
807
+ this.query = new UnifiedQueryClient(this.queryClient, {
808
+ clientKey: this.config.clientKey,
809
+ baseUrl: this.baseUrl
810
+ });
811
+ this.collections = new CollectionsApi(this.config.clientKey, void 0, this.baseUrl);
812
+ }
813
+ from(collection) {
814
+ return this.collections.from(collection);
815
+ }
816
+ getState() {
817
+ return __spreadValues({}, this.state);
818
+ }
819
+ };
820
+ function createBrowserClient(options) {
821
+ return new BrowserClient(options);
822
+ }
823
+
824
+ // src/core/api/api-client.ts
825
+ var ApiClient = class {
826
+ constructor(options) {
827
+ if (!options.clientKey) {
828
+ throw new Error("clientKey is required.");
829
+ }
830
+ if (!options.secretKey) {
831
+ throw new Error("secretKey is required.");
832
+ }
833
+ this.clientKey = options.clientKey;
834
+ this.secretKey = options.secretKey;
835
+ this.baseUrl = options.baseUrl;
836
+ }
837
+ request(endpoint, body) {
838
+ return __async(this, null, function* () {
839
+ const response = yield _fetch(endpoint, {
840
+ method: "POST",
841
+ clientKey: this.clientKey,
842
+ secretKey: this.secretKey,
843
+ baseUrl: this.baseUrl,
844
+ body: JSON.stringify(body)
845
+ });
846
+ const data = yield response.json();
847
+ if (data.error) {
848
+ throw createApiError(
849
+ data.error,
850
+ response.status,
851
+ data,
852
+ data.error,
853
+ "\uC694\uCCAD \uCC98\uB9AC \uC911 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4."
854
+ );
855
+ }
856
+ return data;
857
+ });
858
+ }
859
+ createOrder(params) {
860
+ return this.request("/api/orders/create", params);
861
+ }
862
+ updateOrder(params) {
863
+ return this.request("/api/orders/update", params);
864
+ }
865
+ updateTransaction(params) {
866
+ return this.request("/api/transactions/update", params);
867
+ }
868
+ };
869
+
870
+ // src/core/client/client.server.ts
871
+ var ServerClient = class {
872
+ constructor(options) {
873
+ var _a;
874
+ if (!options.clientKey) {
875
+ throw new Error("clientKey is required.");
876
+ }
877
+ if (!options.secretKey) {
878
+ throw new Error("secretKey is required.");
879
+ }
880
+ this.config = __spreadValues({}, options);
881
+ this.baseUrl = resolveApiUrl(options);
882
+ const metadata = {
883
+ timestamp: Date.now(),
884
+ userAgent: typeof window !== "undefined" ? (_a = window.navigator) == null ? void 0 : _a.userAgent : "Node.js"
885
+ };
886
+ this.state = { metadata };
887
+ this.api = new ApiClient({
888
+ clientKey: this.config.clientKey,
889
+ secretKey: this.config.secretKey,
890
+ baseUrl: this.baseUrl
891
+ });
892
+ this.collections = new CollectionsApi(
893
+ this.config.clientKey,
894
+ this.config.secretKey,
895
+ this.baseUrl
896
+ );
897
+ }
898
+ from(collection) {
899
+ return this.collections.from(collection);
900
+ }
901
+ getState() {
902
+ return __spreadValues({}, this.state);
903
+ }
904
+ getConfig() {
905
+ const _a = this.config, { secretKey: _ } = _a, safeConfig = __objRest(_a, ["secretKey"]);
906
+ return safeConfig;
907
+ }
908
+ };
909
+ function createServerClient(options) {
910
+ return new ServerClient(options);
911
+ }
912
+
913
+ // src/core/webhook/index.tsx
914
+ function isValidWebhookEvent(data) {
915
+ if (typeof data !== "object" || data === null) return false;
916
+ const obj = data;
917
+ return typeof obj.collection === "string" && (obj.operation === "create" || obj.operation === "update") && typeof obj.data === "object" && obj.data !== null;
918
+ }
919
+ function handleWebhook(request, handler) {
920
+ return __async(this, null, function* () {
921
+ try {
922
+ const body = yield request.json();
923
+ if (!isValidWebhookEvent(body)) {
924
+ return new Response(
925
+ JSON.stringify({ error: "Invalid webhook event format" }),
926
+ { status: 400, headers: { "Content-Type": "application/json" } }
927
+ );
928
+ }
929
+ yield handler(body);
930
+ return new Response(
931
+ JSON.stringify({ success: true, message: "Webhook processed" }),
932
+ { status: 200, headers: { "Content-Type": "application/json" } }
933
+ );
934
+ } catch (error) {
935
+ console.error("Webhook processing error:", error);
936
+ return new Response(
937
+ JSON.stringify({
938
+ error: "Internal server error",
939
+ message: error instanceof Error ? error.message : "Unknown error"
940
+ }),
941
+ { status: 500, headers: { "Content-Type": "application/json" } }
942
+ );
943
+ }
944
+ });
945
+ }
946
+ function createTypedWebhookHandler(collection, handler) {
947
+ return (event) => __async(null, null, function* () {
948
+ if (event.collection !== collection) {
949
+ throw new Error(`Expected collection "${collection}", got "${event.collection}"`);
950
+ }
951
+ return handler(event);
952
+ });
953
+ }
954
+
955
+ // src/utils/order/generateOrderNumber.ts
956
+ var generateOrderNumber = () => {
957
+ const year = (/* @__PURE__ */ new Date()).getFullYear().toString().slice(-2);
958
+ const month = (/* @__PURE__ */ new Date()).getMonth().toString().padStart(2, "0");
959
+ const day = (/* @__PURE__ */ new Date()).getDate().toString().padStart(2, "0");
960
+ const random = Math.floor(Math.random() * 1e6).toString().padStart(6, "0");
961
+ return `${year}${month}${day}${random}`;
962
+ };
963
+
964
+ // src/utils/types.ts
965
+ var objectFor = (data) => {
966
+ if (typeof data === "number") {
967
+ return null;
968
+ }
969
+ return data;
970
+ };
971
+
972
+ // src/utils/order/formatOrderName.ts
973
+ var formatOrderName = (options) => {
974
+ var _a, _b, _c, _d;
975
+ const optionLength = options.length;
976
+ return optionLength === 1 ? ((_b = objectFor((_a = options == null ? void 0 : options[0]) == null ? void 0 : _a.product)) == null ? void 0 : _b.title) || "" : `${(_d = objectFor((_c = options.at(0)) == null ? void 0 : _c.product)) == null ? void 0 : _d.title} \uC678 ${optionLength - 1}\uAC74`;
977
+ };
978
+
979
+ // src/components/RichTextContent/index.tsx
980
+ import React from "react";
981
+ import {
982
+ defaultJSXConverters,
983
+ LinkJSXConverter,
984
+ RichText
985
+ } from "@payloadcms/richtext-lexical/react";
986
+ function RichTextContent({
987
+ data,
988
+ className,
989
+ internalDocToHref,
990
+ blocks
991
+ }) {
992
+ return /* @__PURE__ */ React.createElement(
993
+ RichText,
994
+ {
995
+ data,
996
+ className,
997
+ converters: __spreadProps(__spreadValues(__spreadValues({}, defaultJSXConverters), LinkJSXConverter({
998
+ internalDocToHref
999
+ })), {
1000
+ blocks: blocks ? blocks : void 0
1001
+ })
1002
+ }
1003
+ );
1004
+ }
1005
+ export {
1006
+ ApiClient,
1007
+ ApiError,
1008
+ BrowserClient,
1009
+ COLLECTIONS,
1010
+ CollectionQueryBuilder,
1011
+ CollectionsApi,
1012
+ ConfigError,
1013
+ NetworkError,
1014
+ RichTextContent,
1015
+ ServerClient,
1016
+ TimeoutError,
1017
+ UnifiedQueryClient,
1018
+ ValidationError,
1019
+ collectionKeys,
1020
+ createApiKey,
1021
+ createBrowserClient,
1022
+ createServerClient,
1023
+ createServerToken,
1024
+ createTypedWebhookHandler,
1025
+ decodeServerToken,
1026
+ formatOrderName,
1027
+ generateOrderNumber,
1028
+ getQueryClient,
1029
+ handleWebhook,
1030
+ isApiError,
1031
+ isConfigError,
1032
+ isErrorResponse,
1033
+ isNetworkError,
1034
+ isSDKError,
1035
+ isSuccessResponse,
1036
+ isTimeoutError,
1037
+ isValidWebhookEvent,
1038
+ isValidationError,
1039
+ objectFor,
1040
+ parseApiKey,
1041
+ verifyServerToken
1042
+ };
3
1043
  //# sourceMappingURL=index.js.map