@stancer/stancer 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/.editorconfig +14 -0
  2. package/.gitlab-ci.yml +159 -0
  3. package/.prettierignore +3 -0
  4. package/CHANGELOG.md +14 -0
  5. package/LICENSE +19 -0
  6. package/README.md +166 -2
  7. package/eslint.config.js +14 -0
  8. package/package.json +58 -3
  9. package/pnpm-workspace.yaml +19 -0
  10. package/prettier.config.js +3 -0
  11. package/src/address/api-endpoint.ts +30 -0
  12. package/src/address/model.ts +79 -0
  13. package/src/address/repository.ts +18 -0
  14. package/src/address/validator.ts +34 -0
  15. package/src/api-endpoint/abstract-api-endpoint.ts +310 -0
  16. package/src/api-endpoint/configuration.ts +125 -0
  17. package/src/api-endpoint/http/fetch-http-client.ts +29 -0
  18. package/src/api-endpoint/http/http.ts +75 -0
  19. package/src/api-endpoint/http/index.ts +2 -0
  20. package/src/api-endpoint/version.ts +4 -0
  21. package/src/card/api-endpoint.ts +39 -0
  22. package/src/card/enum/funding.ts +11 -0
  23. package/src/card/enum/nature.ts +7 -0
  24. package/src/card/enum/network.ts +16 -0
  25. package/src/card/model.ts +139 -0
  26. package/src/card/repository.ts +11 -0
  27. package/src/card/validator.ts +79 -0
  28. package/src/core/abstract-model.ts +126 -0
  29. package/src/core/abstract-repository.ts +201 -0
  30. package/src/core/common/branded-type.ts +15 -0
  31. package/src/core/common/handler/date-handler.ts +31 -0
  32. package/src/core/common/handler/enum-handler.ts +18 -0
  33. package/src/core/common/handler/handler.ts +64 -0
  34. package/src/core/common/handler/id-handler.ts +27 -0
  35. package/src/core/common/id-validator.ts +23 -0
  36. package/src/core/common/mutation-tracked-object.ts +49 -0
  37. package/src/core/endpoint-interface.ts +43 -0
  38. package/src/core/error/base-error.ts +1 -0
  39. package/src/core/error/endpoint/api/api-conflict-error.ts +7 -0
  40. package/src/core/error/endpoint/api/api-error.ts +10 -0
  41. package/src/core/error/endpoint/api/api-not-found-error.ts +7 -0
  42. package/src/core/error/endpoint/api/api-unauthorized-error.ts +7 -0
  43. package/src/core/error/endpoint/api/api-unknown-error.ts +7 -0
  44. package/src/core/error/endpoint/api/api-validation-error.ts +13 -0
  45. package/src/core/error/endpoint/api/index.ts +6 -0
  46. package/src/core/error/endpoint/route-inaccessible-error.ts +8 -0
  47. package/src/core/error/unpopulated-error.ts +3 -0
  48. package/src/core/error/unsendable-error.ts +3 -0
  49. package/src/core/error/validation-error.ts +3 -0
  50. package/src/core/validator.ts +129 -0
  51. package/src/customer/api-endpoint.ts +29 -0
  52. package/src/customer/model.ts +113 -0
  53. package/src/customer/repository.ts +14 -0
  54. package/src/customer/validator.ts +26 -0
  55. package/src/payment/api-endpoint.ts +118 -0
  56. package/src/payment/enum/currency.ts +14 -0
  57. package/src/payment/enum/method.ts +2 -0
  58. package/src/payment/enum/status.ts +21 -0
  59. package/src/payment/model.ts +378 -0
  60. package/src/payment/repository.ts +73 -0
  61. package/src/payment/validator.ts +96 -0
  62. package/src/payment-intent/api-endpoint.ts +123 -0
  63. package/src/payment-intent/enum/status.ts +21 -0
  64. package/src/payment-intent/enum/threeds.ts +2 -0
  65. package/src/payment-intent/model.ts +266 -0
  66. package/src/payment-intent/repository.ts +85 -0
  67. package/src/payment-intent/validator.ts +45 -0
  68. package/src/payout/model.ts +8 -0
  69. package/src/refund/api-endpoint.ts +33 -0
  70. package/src/refund/enum/refund-status.ts +11 -0
  71. package/src/refund/model.ts +90 -0
  72. package/src/refund/repository.ts +14 -0
  73. package/src/refund/validator.ts +44 -0
  74. package/src/sepa/api-endpoint.ts +26 -0
  75. package/src/sepa/model.ts +80 -0
  76. package/src/sepa/repository.ts +11 -0
  77. package/src/sepa/validator.ts +56 -0
  78. package/test/fixtures/endpoint.stub.ts +22 -0
  79. package/test/fixtures/list-endpoint.stub.ts +33 -0
  80. package/test/fixtures/list-model.stub.ts +24 -0
  81. package/test/fixtures/model.stub.ts +12 -0
  82. package/test/functional/address.test.ts +126 -0
  83. package/test/functional/card.test.ts +175 -0
  84. package/test/functional/customer.test.ts +174 -0
  85. package/test/functional/payment-intent.test.ts +215 -0
  86. package/test/functional/payment.test.ts +206 -0
  87. package/test/functional/refund.test.ts +112 -0
  88. package/test/functional/sepa.test.ts +136 -0
  89. package/test/integration/stub-integration.test.ts +88 -0
  90. package/test/stub/stub-endpoint.ts +42 -0
  91. package/test/stub/stub-model.ts +82 -0
  92. package/test/stub/stub-repository.ts +11 -0
  93. package/test/test-helper.ts +133 -0
  94. package/test/unit/address/api-endpoint.test.ts +134 -0
  95. package/test/unit/address/fixtures.ts +60 -0
  96. package/test/unit/address/model.test.ts +75 -0
  97. package/test/unit/address/repository.test.ts +148 -0
  98. package/test/unit/address/validator.test.ts +49 -0
  99. package/test/unit/api-endpoint/http/fetch-http-client.test.ts +44 -0
  100. package/test/unit/api-endpoint/http/http.test.ts +152 -0
  101. package/test/unit/card/api-endpoint.test.ts +170 -0
  102. package/test/unit/card/card-helper.ts +116 -0
  103. package/test/unit/card/fixtures.ts +87 -0
  104. package/test/unit/card/model.test.ts +167 -0
  105. package/test/unit/card/repository.test.ts +146 -0
  106. package/test/unit/card/validator.test.ts +96 -0
  107. package/test/unit/core/common/mutation-tracked-object.test.ts +24 -0
  108. package/test/unit/customer/api-endpoint.test.ts +143 -0
  109. package/test/unit/customer/fixtures.ts +73 -0
  110. package/test/unit/customer/model.test.ts +90 -0
  111. package/test/unit/customer/repository.test.ts +148 -0
  112. package/test/unit/customer/validator.test.ts +62 -0
  113. package/test/unit/payment/api-endpoint.test.ts +188 -0
  114. package/test/unit/payment/fixtures.ts +116 -0
  115. package/test/unit/payment/model.test.ts +240 -0
  116. package/test/unit/payment/repository.test.ts +270 -0
  117. package/test/unit/payment/validator.test.ts +137 -0
  118. package/test/unit/payment-intent/api-endpoint.test.ts +142 -0
  119. package/test/unit/payment-intent/fixtures.ts +94 -0
  120. package/test/unit/payment-intent/model.test.ts +157 -0
  121. package/test/unit/payment-intent/repository.test.ts +263 -0
  122. package/test/unit/payment-intent/validator.test.ts +136 -0
  123. package/test/unit/refund/api-endpoint.test.ts +129 -0
  124. package/test/unit/refund/fixtures.ts +58 -0
  125. package/test/unit/refund/model.test.ts +89 -0
  126. package/test/unit/refund/repository.test.ts +157 -0
  127. package/test/unit/refund/validator.test.ts +89 -0
  128. package/test/unit/sepa/api-endpoint.test.ts +170 -0
  129. package/test/unit/sepa/fixture.ts +62 -0
  130. package/test/unit/sepa/model.test.ts +86 -0
  131. package/test/unit/sepa/repository.test.ts +149 -0
  132. package/test/unit/sepa/sepa-helper.ts +71 -0
  133. package/test/unit/sepa/validator.test.ts +58 -0
  134. package/test/unit/stub/stub-endpoint.test.ts +236 -0
  135. package/test/unit/stub/stub-list-endpoint.test.ts +86 -0
  136. package/test/unit/stub/stub-model.test.ts +111 -0
  137. package/test/unit/stub/stub-repository.test.ts +144 -0
  138. package/tsconfig.json +50 -0
  139. package/vitest.config.ts +20 -0
@@ -0,0 +1,310 @@
1
+ import type { ModelData, ModelType } from '#core/abstract-model.js';
2
+ import type { IdValue } from '#core/common/branded-type.js';
3
+ import { timestampHandler } from '#core/common/handler/date-handler.js';
4
+ import { type Handler, defaultHandler } from '#core/common/handler/handler.js';
5
+ import type { EndpointInterface, ListParams } from '#core/endpoint-interface.js';
6
+ import { StancerError } from '#core/error/base-error.js';
7
+ import { StancerRouteInaccessibleError } from '#error/endpoint/route-inaccessible-error.js';
8
+ import { UnsendableError } from '#error/unsendable-error.js';
9
+
10
+ import { Configuration } from './configuration.js';
11
+ import { Http } from './http/index.js';
12
+
13
+ export interface Restriction {
14
+ postable?: boolean;
15
+ patchable?: boolean;
16
+ listable?: boolean;
17
+ deletable?: boolean;
18
+ }
19
+
20
+ export const baseHandler = (
21
+ payloadName: string = 'createdAt',
22
+ ): { [Property in keyof ModelData]: Handler<ModelData[Property]> } => {
23
+ return {
24
+ createdAt: { ...timestampHandler({ patchable: false, postable: false }), payloadName },
25
+ deleted: defaultHandler<boolean>('boolean', { postable: false, patchable: false }),
26
+ };
27
+ };
28
+ interface Config<Data> extends Restriction {
29
+ name: string;
30
+ deserializeResource: (resource: Record<string, unknown>) => Partial<Data>;
31
+ postObjectSerializer: (obj: Partial<Data>) => object;
32
+ patchObjectSerializer: (obj: Partial<Data>) => object;
33
+ }
34
+ type Handlers<T> = {
35
+ [Property in keyof T]: Handler<T[Property]>;
36
+ };
37
+
38
+ export type ConfigParameter = {
39
+ name: string;
40
+ } & Restriction;
41
+
42
+ type RangeParam = { start: number; end: number; limit: number; count: number; has_more: boolean };
43
+ type Range<Data> = { range: RangeParam } & {
44
+ [_key: string]: Partial<Data>[];
45
+ };
46
+
47
+ export const camelCaseTo_snake_case = (key: string): string =>
48
+ key.replaceAll(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
49
+
50
+ export abstract class ApiEndpoint<Data extends ModelType> implements EndpointInterface<Data> {
51
+ //#region constructor & property
52
+ protected abstract _handler: Handlers<Data>;
53
+
54
+ // All the property in our Data has the same name (cased in camelCase) as our API property, if not we specify a payloadName
55
+ private _payloadKey = (key: keyof Data & string) => this._handler[key]?.payloadName ?? camelCaseTo_snake_case(key);
56
+
57
+ private config: Config<Data> = {
58
+ name: '',
59
+ patchable: true,
60
+ postable: true,
61
+ listable: true,
62
+ deletable: true,
63
+
64
+ //Deserializer take an unknown resource and make it a Data from a specific model of our library
65
+ deserializeResource: (resource: Record<string, unknown>): Partial<Data> => {
66
+ // By definition Object.keys(specificArray) return array<keyof specificArray>
67
+ const keys = Object.keys(this._handler) as Array<keyof Data & string>;
68
+ return Object.fromEntries(
69
+ keys
70
+ .filter((key) => {
71
+ return this._handler[key].gettable && resource[this._payloadKey(key)] !== undefined;
72
+ })
73
+ .map((key) => {
74
+ return [key, this._handler[key].deserialize(resource[this._payloadKey(key)])];
75
+ }),
76
+ ) as Partial<Data>;
77
+ },
78
+ //Serializers take our model and make it readable by an external resource (api ...)
79
+ postObjectSerializer: (data: Partial<Data>): Record<string, unknown> => {
80
+ // By definition Object.keys(specificArray) return array<keyof specificArray>
81
+ const keys = Object.keys(this._handler) as Array<keyof Data & string>;
82
+
83
+ const partiallyRequired = keys.filter((key) => this._handler[key].postRequired === 'partial');
84
+ const partialFullfilled = partiallyRequired.filter((key) => data[key] !== undefined);
85
+ if (!partialFullfilled.length && partiallyRequired.length) {
86
+ throw new UnsendableError(`one of the partially required data ( ${partiallyRequired.join(' or ')})`);
87
+ }
88
+ return Object.fromEntries(
89
+ keys
90
+ .filter((key) => {
91
+ if (this._handler[key].postRequired === true && data[key] === undefined) {
92
+ throw new UnsendableError(key);
93
+ }
94
+ return this._handler[key].postable && data[key] !== undefined;
95
+ })
96
+ .map((key) => [this._payloadKey(key), this._handler[key].serialize(data[key] as Data[keyof Data & string])]),
97
+ );
98
+ },
99
+ patchObjectSerializer: (data: Partial<Data>): Record<string, unknown> => {
100
+ // By definition Object.keys(specificArray) return array<keyof specificArray>
101
+ const keys = Object.keys(this._handler) as Array<keyof Data & string>;
102
+
103
+ const partiallyRequired = keys.filter((key) => this._handler[key].patchRequired === 'partial');
104
+ const partialFullfilled = partiallyRequired.filter((key) => data[key] !== undefined);
105
+ if (!partialFullfilled.length && partiallyRequired.length) {
106
+ throw new UnsendableError(`one of the partially required data (${partiallyRequired.join(' or ')}) `);
107
+ }
108
+ return Object.fromEntries(
109
+ keys
110
+ .filter((key) => {
111
+ if (this._handler[key].patchRequired === true && data[key] === undefined) {
112
+ throw new UnsendableError(key);
113
+ }
114
+ return this._handler[key].patchable && data[key] !== undefined;
115
+ })
116
+ .map((key) => [this._payloadKey(key), this._handler[key].serialize(data[key] as Data[keyof Data & string])]),
117
+ );
118
+ },
119
+ };
120
+
121
+ constructor(config: ConfigParameter) {
122
+ this.config.name = config.name;
123
+ this.config.patchable = config.patchable ?? true;
124
+ this.config.postable = config.postable ?? true;
125
+ this.config.listable = config.listable ?? true;
126
+ this.config.deletable = config.deletable ?? true;
127
+ }
128
+
129
+ //#endregion
130
+ //#region endpoint interface
131
+
132
+ public delete(id: IdValue) {
133
+ if (!this.deletable) {
134
+ throw new StancerRouteInaccessibleError('DELETE', this.config.name);
135
+ }
136
+ return this._httpClient
137
+ .makeRequest(
138
+ Http.createRequest({
139
+ url: this._getResourceUri(id),
140
+ method: 'DELETE',
141
+ authenticated: true,
142
+ }),
143
+ )
144
+ .then(Http.transformResponseToData<Record<string, unknown>>)
145
+ .then(this.deserializeResource);
146
+ }
147
+
148
+ public get(id: IdValue): Promise<Partial<Data>> /*Gettable resources*/ {
149
+ return this._httpClient
150
+ .makeRequest(
151
+ Http.createRequest({
152
+ url: this._getResourceUri(id),
153
+ method: 'GET',
154
+ authenticated: true,
155
+ }),
156
+ )
157
+ .then(Http.transformResponseToData<Record<string, unknown>>)
158
+ .then(this.deserializeResource);
159
+ }
160
+
161
+ public send(id: IdValue | undefined, mutations: Partial<Data>): Promise<Partial<Data>> {
162
+ if (!mutations || Object.keys(mutations).length === 0) {
163
+ throw new StancerError('You cannot send a model whithout modification');
164
+ }
165
+ if (id) {
166
+ return this.patch(id, mutations);
167
+ }
168
+ return this.post(mutations);
169
+ }
170
+
171
+ //#endregion
172
+
173
+ public list({
174
+ start = 0,
175
+ limit = 100,
176
+ end = 1000,
177
+ filters = {},
178
+ }: Partial<ListParams>): AsyncGenerator<Partial<Data>, void, Partial<Data>> {
179
+ if (!this.listable) {
180
+ throw new StancerRouteInaccessibleError('LIST', this.config.name);
181
+ }
182
+ return this.listGenerator({ start, limit, end, filters });
183
+ }
184
+
185
+ private createListUrl(endpoint: string, { start, limit, filters }: Omit<ListParams, 'end'>) {
186
+ const url = new URL(endpoint + '/');
187
+ url.searchParams.append('start', start.toString());
188
+ url.searchParams.append('limit', limit.toString());
189
+ for (const [key, value] of Object.entries(filters)) {
190
+ url.searchParams.append(key, String(value));
191
+ }
192
+ return url;
193
+ }
194
+
195
+ private async *listGenerator(
196
+ { start, limit, end, filters }: ListParams,
197
+ endpoint = this._endpointBaseUrl,
198
+ ): AsyncGenerator<Partial<Data>, void, Partial<Data>> {
199
+ if (limit <= 0) {
200
+ return;
201
+ }
202
+ for (let currentStart = start; currentStart - start < end; currentStart = currentStart + limit) {
203
+ const url = this.createListUrl(endpoint, { start: currentStart, limit, filters });
204
+ const endpointName = this.config.name;
205
+
206
+ const data = await this._httpClient
207
+ .makeRequest(
208
+ Http.createRequest({
209
+ url: url.toString(),
210
+ method: 'GET',
211
+ authenticated: true,
212
+ }),
213
+ )
214
+ .then(Http.transformResponseToData<Range<Data>>)
215
+ .then((result) => {
216
+ if (!Array.isArray(result[endpointName])) {
217
+ return;
218
+ }
219
+ const serializedData = result[endpointName].map((data) => this.deserializeResource(data)) ?? [];
220
+
221
+ return { [endpointName]: serializedData, range: result.range };
222
+ });
223
+
224
+ if (!data || !Array.isArray(data[endpointName])) {
225
+ return;
226
+ }
227
+
228
+ yield* data[endpointName];
229
+
230
+ if (!data.range?.has_more) {
231
+ return;
232
+ }
233
+ }
234
+ }
235
+
236
+ //#endregion
237
+ //#region method
238
+
239
+ private sendRequest(method: 'PATCH' | 'POST', url: string, data: object): Promise<Partial<Data>> {
240
+ return this._httpClient
241
+ .makeRequest(
242
+ Http.createRequest({
243
+ url,
244
+ method,
245
+ authenticated: true,
246
+ headers: {
247
+ 'content-type': 'application/json',
248
+ },
249
+ body: JSON.stringify(data),
250
+ }),
251
+ )
252
+ .then(Http.transformResponseToData<Record<string, unknown>>)
253
+ .then(this.deserializeResource);
254
+ }
255
+
256
+ public patch(id: IdValue, data: Partial<Data>) {
257
+ if (!this.patchable) {
258
+ throw new StancerRouteInaccessibleError('PATCH', this.config.name);
259
+ }
260
+ return this.sendRequest('PATCH', this._getResourceUri(id), this.patchObjectSerializer(data));
261
+ }
262
+
263
+ public post(data: Partial<Data>): Promise<Partial<Data>> {
264
+ if (!this.postable) {
265
+ throw new StancerRouteInaccessibleError('POST', this.config.name);
266
+ }
267
+ return this.sendRequest('POST', this._getResourceUri(), this.postObjectSerializer(data));
268
+ }
269
+ //#endregion
270
+
271
+ //#region getter
272
+
273
+ protected get _endpointBaseUrl() {
274
+ return `${Configuration.baseUrl}/${this.config.name}`;
275
+ }
276
+ protected _getResourceUri(id?: IdValue) {
277
+ return id ? `${this._endpointBaseUrl}/${id}` : `${this._endpointBaseUrl}/`;
278
+ }
279
+
280
+ protected get _httpClient() {
281
+ return Configuration.httpClient;
282
+ }
283
+ get deletable() {
284
+ return this.config.deletable;
285
+ }
286
+ get patchable() {
287
+ return this.config.patchable;
288
+ }
289
+
290
+ get postable() {
291
+ return this.config.postable;
292
+ }
293
+
294
+ get listable() {
295
+ return this.config.listable;
296
+ }
297
+
298
+ get deserializeResource() {
299
+ return this.config.deserializeResource;
300
+ }
301
+
302
+ get postObjectSerializer() {
303
+ return this.config.postObjectSerializer;
304
+ }
305
+
306
+ get patchObjectSerializer() {
307
+ return this.config.patchObjectSerializer;
308
+ }
309
+ //#endregion
310
+ }
@@ -0,0 +1,125 @@
1
+ import { StancerError } from '#error/base-error.js';
2
+
3
+ import pkg from './../../package.json' with { type: 'json' };
4
+ import { httpClient } from './http/fetch-http-client.js';
5
+ import { type Http } from './http/index.js';
6
+ import { ApiVersion } from './version.js';
7
+
8
+ export class _Configuration {
9
+ //#region Properties
10
+
11
+ private _apiVersion: ApiVersion = ApiVersion.Default;
12
+ // Host is not publicly settable. It already point to the API.
13
+ private _host: string = 'api.stancer.com';
14
+ private _httpClient: Http.Client = httpClient;
15
+ private _httpUserAgent: string = `libstancer-ts/${pkg.version} node-fetch`;
16
+ private _keys: {
17
+ privateLiveKey: string | null;
18
+ privateTestKey: string | null;
19
+ } = {
20
+ privateLiveKey: null,
21
+ privateTestKey: null,
22
+ };
23
+
24
+ private _mode: 'prod' | 'test' = 'test';
25
+ public port?: number;
26
+ //#endregion
27
+
28
+ //#region Getters
29
+
30
+ private get _privateKey(): string | null {
31
+ switch (this._mode) {
32
+ case 'prod':
33
+ return this._keys.privateLiveKey;
34
+ case 'test':
35
+ return this._keys.privateTestKey;
36
+ default:
37
+ return null;
38
+ }
39
+ }
40
+
41
+ get apiVersion(): string {
42
+ return this._apiVersion;
43
+ }
44
+
45
+ get baseUrl(): string {
46
+ return this.port
47
+ ? `https://${this.host}:${this.port}/${this.apiVersion}`
48
+ : `https://${this.host}/${this.apiVersion}`;
49
+ }
50
+
51
+ get defaultHttpHeaders(): Record<string, string> {
52
+ return {
53
+ 'user-agent': this.httpUserAgent,
54
+ };
55
+ }
56
+
57
+ get host(): string {
58
+ return this._host;
59
+ }
60
+
61
+ get httpBasicAuthHeader() {
62
+ if (!this._privateKey) {
63
+ return {};
64
+ }
65
+ return {
66
+ // This api only run in node env if private key is malformed we get an unauthorized error.
67
+ authorization: `Basic ${Buffer.from(`${this._privateKey}:`).toString('base64')}`,
68
+ };
69
+ }
70
+
71
+ get httpClient(): Http.Client {
72
+ return this._httpClient;
73
+ }
74
+
75
+ get httpUserAgent(): string {
76
+ return this._httpUserAgent;
77
+ }
78
+
79
+ public get mode(): 'prod' | 'test' {
80
+ return this._mode;
81
+ }
82
+
83
+ //#endregion
84
+
85
+ //#region Methods
86
+
87
+ init({ keys, mode }: { keys: Partial<_Configuration['_keys']>; mode: _Configuration['mode'] }) {
88
+ if (mode !== 'prod' && mode !== 'test') {
89
+ throw new StancerError(`Invalid mode: ${mode}. Must be 'prod' or 'test'`);
90
+ }
91
+ if (mode === 'prod' && !keys.privateLiveKey) {
92
+ throw new StancerError(`Prod key is required for production mode`);
93
+ }
94
+ if (mode === 'test' && !keys.privateTestKey) {
95
+ throw new StancerError(`Test key is required for test mode`);
96
+ }
97
+ this._keys = Object.assign({}, this._keys, keys);
98
+ this._mode = mode;
99
+ return this;
100
+ }
101
+
102
+ setApiVersion(apiVersion: ApiVersion) {
103
+ this._apiVersion = apiVersion;
104
+ }
105
+
106
+ setKey(keys: Partial<_Configuration['_keys']>) {
107
+ this._keys = Object.assign({}, this._keys, keys);
108
+ }
109
+
110
+ setMode(mode: 'test' | 'prod') {
111
+ if ((mode === 'prod' && this._keys.privateLiveKey) || (mode === 'test' && this._keys.privateTestKey)) {
112
+ this._mode = mode;
113
+ return;
114
+ }
115
+ throw new StancerError(`key matching mode ${mode} is necessary to set it`);
116
+ }
117
+
118
+ setUserAgent(userAgent: string) {
119
+ this._httpUserAgent = userAgent;
120
+ }
121
+
122
+ //#endregion
123
+ }
124
+
125
+ export const Configuration = new _Configuration();
@@ -0,0 +1,29 @@
1
+ import { StancerApiUnknownError } from '#error/endpoint/api/api-unknown-error.js';
2
+
3
+ import { Http } from './index.js';
4
+
5
+ export const httpClient: Http.Client = {
6
+ makeRequest: async (request: Http.Request): Promise<Http.Response> => {
7
+ const headers = {
8
+ ...(request.headers ?? {}),
9
+ };
10
+ if (!headers['user-agent']) {
11
+ headers['user-agent'] = 'Stancer fetch';
12
+ }
13
+ const partialRequest = {
14
+ method: request.method,
15
+ headers,
16
+ };
17
+ const completeRequest = request.body ? { ...partialRequest, body: request.body } : partialRequest;
18
+ try {
19
+ const response = await fetch(request.url, completeRequest);
20
+
21
+ return {
22
+ status: response.status,
23
+ json: async <T>() => (await response.json()) as T,
24
+ };
25
+ } catch (e) {
26
+ throw new StancerApiUnknownError(0, e instanceof Error ? e.message : 'Network error');
27
+ }
28
+ },
29
+ };
@@ -0,0 +1,75 @@
1
+ import {
2
+ StancerApiConflictError,
3
+ StancerApiError,
4
+ StancerApiNotFoundError,
5
+ StancerApiUnauthorizedError,
6
+ StancerApiUnknownError,
7
+ StancerApiValidationError,
8
+ type StancerApiValidationErrorDetails,
9
+ } from '#error/endpoint/api/index.js';
10
+
11
+ import { Configuration } from '../configuration.js';
12
+
13
+ //#region interfaces
14
+ export interface Client {
15
+ makeRequest: (request: Request) => Promise<Response>;
16
+ }
17
+
18
+ export interface Request {
19
+ url: string;
20
+ method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
21
+ headers?: Record<string, string>;
22
+ body?: string;
23
+ authenticated?: boolean;
24
+ }
25
+
26
+ export interface Response {
27
+ status: number;
28
+ json<T>(): Promise<T>;
29
+ }
30
+ //#endregion
31
+
32
+ //#region implementation
33
+ export const createRequest = (req: Request): Request => {
34
+ return {
35
+ ...req,
36
+ headers: {
37
+ ...(req.authenticated ? Configuration.httpBasicAuthHeader : {}),
38
+ ...Configuration.defaultHttpHeaders,
39
+ ...req.headers,
40
+ },
41
+ };
42
+ };
43
+
44
+ export const handleHttpResponseErrors = async (response: Response) => {
45
+ if (response.status >= 200 && response.status < 300) {
46
+ return response;
47
+ }
48
+ try {
49
+ const data = await response.json<{ error: string | object; detail: StancerApiValidationErrorDetails[] }>();
50
+ const stringifyError = (error: string | object) => (typeof error === 'string' ? error : JSON.stringify(error));
51
+ switch (response.status) {
52
+ case 401:
53
+ throw new StancerApiUnauthorizedError(stringifyError(data.error));
54
+ case 422:
55
+ throw new StancerApiValidationError(data.detail);
56
+ case 404:
57
+ throw new StancerApiNotFoundError(stringifyError(data.error));
58
+ case 409:
59
+ throw new StancerApiConflictError(stringifyError(data.error));
60
+ default:
61
+ throw new StancerApiUnknownError(response.status, stringifyError(data.error) ?? `${response.status} error`);
62
+ }
63
+ } catch (e) {
64
+ if (e instanceof StancerApiError) {
65
+ throw e;
66
+ }
67
+ throw new StancerApiUnknownError(response.status, `HTTP Error ${response.status}`);
68
+ }
69
+ };
70
+
71
+ export const transformResponseToData = async <T>(response: Response) => {
72
+ await handleHttpResponseErrors(response);
73
+ return response.json<T>();
74
+ };
75
+ //#endregion
@@ -0,0 +1,2 @@
1
+ export * as Http from './http.js';
2
+ export * as FetchHttpClient from './fetch-http-client.js';
@@ -0,0 +1,4 @@
1
+ export enum ApiVersion {
2
+ V2 = 'v2',
3
+ Default = ApiVersion.V2,
4
+ }
@@ -0,0 +1,39 @@
1
+ import { ApiEndpoint, baseHandler } from '#api/abstract-api-endpoint.js';
2
+ import { enumHandler } from '#core/common/handler/enum-handler.js';
3
+ import { defaultHandler } from '#core/common/handler/handler.js';
4
+ import { IdHandler } from '#core/common/handler/id-handler.js';
5
+
6
+ import { CustomerModel, type IdCustomer } from '../customer/model.js';
7
+ import { FundingCardEnum } from './enum/funding.js';
8
+ import { NatureCardEnum } from './enum/nature.js';
9
+ import { NetworkCardEnum, PreferredNetworkCardEnum } from './enum/network.js';
10
+ import { type CardData, CardModel, type IdCard } from './model.js';
11
+
12
+ export class CardApiEndpoint extends ApiEndpoint<CardData> {
13
+ public _handler = {
14
+ ...baseHandler('created'),
15
+ id: IdHandler<IdCard>(CardModel.regex),
16
+ brand: defaultHandler<CardData['brand']>('string', { patchable: false, postable: false }),
17
+ country: defaultHandler<CardData['country']>('string', { patchable: false, postable: false }),
18
+ customer: IdHandler<IdCustomer>(CustomerModel.regex, { patchable: false }),
19
+ cvc: defaultHandler<CardData['cvc']>('string', { gettable: false, patchable: false }),
20
+ expMonth: defaultHandler<CardData['expMonth']>('number', { postRequired: true }),
21
+ expYear: defaultHandler<CardData['expYear']>('number', { postRequired: true }),
22
+ externalId: defaultHandler<CardData['externalId']>('string'),
23
+ funding: enumHandler(FundingCardEnum, { patchable: false, postable: false }),
24
+ last4: defaultHandler<CardData['last4']>('string', { postable: false, patchable: false }),
25
+ name: defaultHandler<CardData['name']>('string', { patchable: false }),
26
+ nature: enumHandler(NatureCardEnum, { patchable: false, postable: false }),
27
+ network: enumHandler(NetworkCardEnum, { postable: false, patchable: false }),
28
+ number: defaultHandler<CardData['number']>('string', { gettable: false, patchable: false, postRequired: true }),
29
+ preferredNetwork: enumHandler(PreferredNetworkCardEnum, { patchable: false }),
30
+ tokenize: defaultHandler<CardData['tokenize']>('boolean', { gettable: false, patchable: false }),
31
+ zipCode: defaultHandler<CardData['zipCode']>('string'),
32
+ };
33
+
34
+ constructor() {
35
+ super({
36
+ name: 'cards',
37
+ });
38
+ }
39
+ }
@@ -0,0 +1,11 @@
1
+ export const FundingCardEnum = [
2
+ 'credit',
3
+ 'debit',
4
+ 'prepaid',
5
+ 'universal',
6
+ 'charge',
7
+ 'deferred',
8
+ 'unknown',
9
+ ] as const;
10
+
11
+ export type FundingCard = (typeof FundingCardEnum)[number];
@@ -0,0 +1,7 @@
1
+ export const NatureCardEnum = [
2
+ 'personal',
3
+ 'corporate',
4
+ 'unknown',
5
+ ] as const;
6
+
7
+ export type NatureCard = (typeof NatureCardEnum)[number];
@@ -0,0 +1,16 @@
1
+ export const NetworkCardEnum = [
2
+ 'national',
3
+ 'visa',
4
+ 'mastercard',
5
+ 'unknown',
6
+ ] as const;
7
+
8
+ export type NetworkCard = (typeof NetworkCardEnum)[number];
9
+
10
+ export const PreferredNetworkCardEnum = [
11
+ 'national',
12
+ 'visa',
13
+ 'mastercard',
14
+ ] as const;
15
+
16
+ export type PreferredNetworkCard = (typeof PreferredNetworkCardEnum)[number];