@teamnovu/kit-shopware-api-client 0.0.15 → 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 +16 -0
- package/dist/error.d.ts +16 -56
- package/dist/index.mjs +1142 -273
- package/package.json +12 -3
- package/docs/index.md +0 -161
- package/docs/info.json +0 -3
- package/src/client.ts +0 -236
- package/src/error.ts +0 -42
- package/src/eventEmitter.ts +0 -159
- package/src/index.ts +0 -3
- package/src/query.ts +0 -39
- package/src/types.ts +0 -69
- package/tsconfig.json +0 -12
- package/vite.config.js +0 -27
package/package.json
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teamnovu/kit-shopware-api-client",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "A client for the Shopware API",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist",
|
|
7
|
+
"CHANGELOG.md"
|
|
8
|
+
],
|
|
5
9
|
"main": "dist/index.mjs",
|
|
6
10
|
"module": "dist/index.mjs",
|
|
7
11
|
"types": "dist/index.d.ts",
|
|
@@ -19,11 +23,16 @@
|
|
|
19
23
|
"author": "Elias Bernhaut",
|
|
20
24
|
"homepage": "https://kit.novu.ch/packages/shopware-api-client/",
|
|
21
25
|
"dependencies": {
|
|
22
|
-
"zod": "^
|
|
26
|
+
"zod": "^4.6.7"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"vitest": "^5.1.0"
|
|
23
30
|
},
|
|
24
31
|
"scripts": {
|
|
25
32
|
"build": "vite build",
|
|
26
33
|
"watch": "NODE_ENV=development vite build --watch",
|
|
27
|
-
"lint": "eslint --fix --ignore-pattern 'dist/**' ."
|
|
34
|
+
"lint": "eslint --fix --ignore-pattern 'dist/**' .",
|
|
35
|
+
"typecheck": "vue-tsc --noEmit",
|
|
36
|
+
"test": "vitest run"
|
|
28
37
|
}
|
|
29
38
|
}
|
package/docs/index.md
DELETED
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
# Shopware API Client
|
|
2
|
-
|
|
3
|
-
A TypeScript client for the Shopware Store API with full type safety and event-driven context management.
|
|
4
|
-
|
|
5
|
-
Install with `npm i @teamnovu/kit-shopware-api-client`
|
|
6
|
-
|
|
7
|
-
## Features
|
|
8
|
-
|
|
9
|
-
- ✅ **Type-safe API calls** - Full TypeScript support with operation-based type inference
|
|
10
|
-
- ✅ **Automatic context token management** - Handles authentication tokens automatically
|
|
11
|
-
- ✅ **Event-driven architecture** - Subscribe to context token changes
|
|
12
|
-
- ✅ **URL parameter interpolation** - Dynamic URL path parameters with type safety
|
|
13
|
-
- ✅ **Query parameter support** - Type-safe query string generation
|
|
14
|
-
- ✅ **SEO URLs support** - Optional SEO-friendly URL responses
|
|
15
|
-
- ✅ **Error handling** - Custom error types with response details
|
|
16
|
-
|
|
17
|
-
## Basic Usage
|
|
18
|
-
|
|
19
|
-
```typescript
|
|
20
|
-
import { ShopwareClient } from '@teamnovu/kit-shopware-api-client'
|
|
21
|
-
|
|
22
|
-
// Initialize the client
|
|
23
|
-
const client = new ShopwareClient({
|
|
24
|
-
baseURL: 'https://your-shopware-store.com',
|
|
25
|
-
apiKey: 'your-api-key',
|
|
26
|
-
includeSeoUrls: true,
|
|
27
|
-
language: 'language-id' // optional
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
// Make API calls using operation strings
|
|
31
|
-
const products = await client.query('readProductListing post /product-listing', {
|
|
32
|
-
body: {
|
|
33
|
-
// request body
|
|
34
|
-
}
|
|
35
|
-
})
|
|
36
|
-
|
|
37
|
-
// With URL parameters
|
|
38
|
-
const product = await client.query('readProduct post /product/{productId}', {
|
|
39
|
-
params: {
|
|
40
|
-
productId: 'product-uuid'
|
|
41
|
-
}
|
|
42
|
-
})
|
|
43
|
-
|
|
44
|
-
// With query parameters
|
|
45
|
-
const categories = await client.query('readCategoryList post /category', {
|
|
46
|
-
query: {
|
|
47
|
-
limit: 10,
|
|
48
|
-
page: 1
|
|
49
|
-
}
|
|
50
|
-
})
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
## Client Configuration
|
|
54
|
-
|
|
55
|
-
### ShopwareClientOptions
|
|
56
|
-
|
|
57
|
-
| Option | Type | Required | Default | Description |
|
|
58
|
-
|--------|------|----------|---------|-------------|
|
|
59
|
-
| `baseURL` | `string` | ✅ | - | The base URL of your Shopware store |
|
|
60
|
-
| `apiKey` | `string` | ✅ | - | Your Shopware Store API access key |
|
|
61
|
-
| `language` | `string` | ❌ | `undefined` | Language ID for localized responses |
|
|
62
|
-
| `contextToken` | `string` | ❌ | `undefined` | Initial context token for authenticated requests |
|
|
63
|
-
| `includeSeoUrls` | `boolean` | ❌ | `false` | Include SEO-friendly URLs in responses |
|
|
64
|
-
| `reflectContextToken` | `boolean` | ❌ | `true` | Automatically update context token from responses |
|
|
65
|
-
|
|
66
|
-
## Operation Format
|
|
67
|
-
|
|
68
|
-
Operations follow the pattern: `{operationName} {httpMethod} {urlPath}`
|
|
69
|
-
|
|
70
|
-
Examples:
|
|
71
|
-
- `'readProductListing post /product-listing'`
|
|
72
|
-
- `'readProduct post /product/{productId}'`
|
|
73
|
-
- `'addLineItem patch /checkout/cart/line-item'`
|
|
74
|
-
|
|
75
|
-
## Context Token Management
|
|
76
|
-
|
|
77
|
-
The client automatically manages context tokens for session handling:
|
|
78
|
-
|
|
79
|
-
```typescript
|
|
80
|
-
// Listen for context token changes
|
|
81
|
-
client.on('contextToken', (token) => {
|
|
82
|
-
console.log('New context token:', token)
|
|
83
|
-
// Store token for future requests
|
|
84
|
-
})
|
|
85
|
-
|
|
86
|
-
// Manually set context token
|
|
87
|
-
client.setContextToken('your-context-token')
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
## Error Handling
|
|
91
|
-
|
|
92
|
-
The client throws `ShopwareApiError` for API failures:
|
|
93
|
-
|
|
94
|
-
```typescript
|
|
95
|
-
import { ShopwareApiError } from '@teamnovu/kit-shopware-api-client'
|
|
96
|
-
|
|
97
|
-
try {
|
|
98
|
-
const result = await client.query('someOperation post /some-endpoint')
|
|
99
|
-
} catch (error) {
|
|
100
|
-
if (error instanceof ShopwareApiError) {
|
|
101
|
-
console.error('API Error:', error.message)
|
|
102
|
-
console.error('Status:', error.status)
|
|
103
|
-
console.error('Response:', error.response)
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
## Advanced Usage
|
|
109
|
-
|
|
110
|
-
### Raw Response Access
|
|
111
|
-
|
|
112
|
-
Use `queryRaw()` to access the raw fetch Response:
|
|
113
|
-
|
|
114
|
-
```typescript
|
|
115
|
-
const response = await client.queryRaw('readProduct post /product/{productId}', {
|
|
116
|
-
params: { productId: 'uuid' }
|
|
117
|
-
})
|
|
118
|
-
|
|
119
|
-
const data = await response.json()
|
|
120
|
-
const headers = response.headers
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
### Dynamic Configuration
|
|
124
|
-
|
|
125
|
-
Update client configuration at runtime:
|
|
126
|
-
|
|
127
|
-
```typescript
|
|
128
|
-
client.setBaseURL('https://new-store.com')
|
|
129
|
-
client.setApiKey('new-api-key')
|
|
130
|
-
client.setLanguage('new-language-id')
|
|
131
|
-
client.setIncludeSeoUrls(true)
|
|
132
|
-
client.setReflectContextToken(false)
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
## Type Safety
|
|
136
|
-
|
|
137
|
-
The client provides full TypeScript support when used with generated operation types:
|
|
138
|
-
|
|
139
|
-
```typescript
|
|
140
|
-
type MyOperations = {
|
|
141
|
-
'readProduct post /product/{productId}': {
|
|
142
|
-
body?: { includes?: Record<string, any> }
|
|
143
|
-
response: ProductDetailResponse
|
|
144
|
-
}
|
|
145
|
-
'readProductListing post /product-listing': {
|
|
146
|
-
body: ProductListingCriteria
|
|
147
|
-
response: ProductListingResponse
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
const client = new ShopwareClient<MyOperations>({
|
|
152
|
-
baseURL: 'https://store.com',
|
|
153
|
-
apiKey: 'key'
|
|
154
|
-
})
|
|
155
|
-
|
|
156
|
-
// Now fully type-safe!
|
|
157
|
-
const product = await client.query('readProduct post /product/{productId}', {
|
|
158
|
-
params: { productId: 'uuid' } // TypeScript enforces this
|
|
159
|
-
})
|
|
160
|
-
// product is typed as ProductDetailResponse
|
|
161
|
-
```
|
package/docs/info.json
DELETED
package/src/client.ts
DELETED
|
@@ -1,236 +0,0 @@
|
|
|
1
|
-
import { ShopwareApiError } from './error'
|
|
2
|
-
import { EventEmitter } from './eventEmitter'
|
|
3
|
-
import { createQueryParams } from './query'
|
|
4
|
-
import type {
|
|
5
|
-
OperationOptions,
|
|
6
|
-
OperationProp,
|
|
7
|
-
ShopwareClientOptions,
|
|
8
|
-
} from './types'
|
|
9
|
-
|
|
10
|
-
const operationRegex = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i
|
|
11
|
-
|
|
12
|
-
// This **Must** stay an interface and the response **must** be branded.
|
|
13
|
-
// This is to ensure that the response type is not already resolved when the
|
|
14
|
-
// library is built so we can still use module augmentation to override operations.
|
|
15
|
-
export interface ResponseType<TKey> {
|
|
16
|
-
__response?: TKey
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export type BrandedResponse<Operations, OperationKey extends (keyof Operations) & string> =
|
|
20
|
-
ResponseType<OperationKey> & OperationProp<Operations, OperationKey, 'response'> & { __brand: string }
|
|
21
|
-
|
|
22
|
-
export class ShopwareClient<Operations> extends EventEmitter {
|
|
23
|
-
private options: ShopwareClientOptions = {
|
|
24
|
-
baseURL: '',
|
|
25
|
-
apiKey: '',
|
|
26
|
-
language: '',
|
|
27
|
-
contextToken: '',
|
|
28
|
-
includeSeoUrls: false,
|
|
29
|
-
reflectContextToken: true,
|
|
30
|
-
headers: {},
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
constructor(options: ShopwareClientOptions) {
|
|
34
|
-
super()
|
|
35
|
-
|
|
36
|
-
this.requestInitDefaults = options.requestInitDefaults
|
|
37
|
-
this.baseURL = options.baseURL ?? this.options.baseURL
|
|
38
|
-
this.apiKey = options.apiKey ?? this.options.apiKey
|
|
39
|
-
this.language = options.language ?? this.options.language
|
|
40
|
-
this.contextToken = options.contextToken ?? this.options.contextToken
|
|
41
|
-
this.includeSeoUrls = options.includeSeoUrls ?? this.options.includeSeoUrls
|
|
42
|
-
this.reflectContextToken = options.reflectContextToken ?? this.options.reflectContextToken
|
|
43
|
-
this.headers = options.headers ?? this.options.headers
|
|
44
|
-
this.queryClientId = options.queryClientId ?? this.options.queryClientId
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
set requestInitDefaults(defaults: RequestInit | undefined) {
|
|
48
|
-
this.options.requestInitDefaults = defaults
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
get requestInitDefaults() {
|
|
52
|
-
return this.options.requestInitDefaults
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
set baseURL(baseURL: string) {
|
|
56
|
-
if (typeof baseURL !== 'string') {
|
|
57
|
-
throw new Error('Invalid baseURL: It must be a string.')
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
this.options.baseURL = baseURL
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
get baseURL() {
|
|
64
|
-
return this.options.baseURL
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
set apiKey(apiKey: string) {
|
|
68
|
-
if (typeof apiKey !== 'string') {
|
|
69
|
-
throw new Error('Invalid apiKey: It must be a string.')
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
this.options.apiKey = apiKey
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
get apiKey() {
|
|
76
|
-
return this.options.apiKey
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
set language(language: string | undefined) {
|
|
80
|
-
if (language && typeof language !== 'string') {
|
|
81
|
-
throw new Error('Invalid language: If provided, it must be a string.')
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
this.options.language = language
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
get language() {
|
|
88
|
-
return this.options.language
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
set contextToken(contextToken: string | undefined) {
|
|
92
|
-
if (contextToken && typeof contextToken !== 'string') {
|
|
93
|
-
throw new Error('Invalid contextToken: If provided, it must be a string.')
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
this.options.contextToken = contextToken
|
|
97
|
-
this.emit('contextToken', contextToken)
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
get contextToken() {
|
|
101
|
-
return this.options.contextToken
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
set includeSeoUrls(includeSeoUrls: boolean | undefined) {
|
|
105
|
-
this.options.includeSeoUrls = includeSeoUrls
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
get includeSeoUrls() {
|
|
109
|
-
return this.options.includeSeoUrls
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
set reflectContextToken(reflectContextToken: boolean | undefined) {
|
|
113
|
-
this.options.reflectContextToken = reflectContextToken
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
get reflectContextToken() {
|
|
117
|
-
return this.options.reflectContextToken
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
set headers(headers: HeadersInit | undefined) {
|
|
121
|
-
this.options.headers = headers
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
get headers() {
|
|
125
|
-
return this.options.headers
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
set queryClientId(queryClientId: string | undefined) {
|
|
129
|
-
if (queryClientId && typeof queryClientId !== 'string') {
|
|
130
|
-
throw new Error('Invalid queryClientId: If provided, it must be a string.')
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
this.options.queryClientId = queryClientId
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
get queryClientId() {
|
|
137
|
-
return this.options.queryClientId
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
private parseOperation(operation: keyof Operations & string): {
|
|
141
|
-
name: string
|
|
142
|
-
method: string
|
|
143
|
-
url: string
|
|
144
|
-
} {
|
|
145
|
-
const match = operationRegex.exec(operation)
|
|
146
|
-
if (!match?.groups) {
|
|
147
|
-
throw new Error('Invalid operation format')
|
|
148
|
-
}
|
|
149
|
-
return {
|
|
150
|
-
name: match.groups.name,
|
|
151
|
-
method: match.groups.method.toUpperCase(),
|
|
152
|
-
url: match.groups.url,
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
private interpolateUrl(url: string, params: Record<string, string>): string {
|
|
157
|
-
return url.replace(/{([^}]+?)}/g, (_, param) => {
|
|
158
|
-
if (!(param in params)) {
|
|
159
|
-
throw new Error(`Missing required URL parameter: ${param}`)
|
|
160
|
-
}
|
|
161
|
-
return params[param]
|
|
162
|
-
})
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async queryRaw<OperationKey extends (keyof Operations) & string>(
|
|
166
|
-
operation: OperationKey,
|
|
167
|
-
options?: OperationOptions<Operations, OperationKey>,
|
|
168
|
-
): Promise<Response> {
|
|
169
|
-
let response: Response
|
|
170
|
-
|
|
171
|
-
try {
|
|
172
|
-
const { method, url } = this.parseOperation(operation)
|
|
173
|
-
|
|
174
|
-
const interpolatedUrl = this.interpolateUrl(url, options?.params ?? {})
|
|
175
|
-
|
|
176
|
-
const query = options?.query ? `?${createQueryParams(options.query)}` : ''
|
|
177
|
-
|
|
178
|
-
response = await fetch(`${this.baseURL}/store-api${interpolatedUrl}${query}`, {
|
|
179
|
-
...this.requestInitDefaults,
|
|
180
|
-
...options,
|
|
181
|
-
method,
|
|
182
|
-
headers: {
|
|
183
|
-
'Content-Type': 'application/json',
|
|
184
|
-
'sw-access-key': this.apiKey,
|
|
185
|
-
...this.requestInitDefaults?.headers,
|
|
186
|
-
...(this.contextToken && { 'sw-context-token': this.contextToken }),
|
|
187
|
-
...(this.includeSeoUrls && { 'sw-include-seo-urls': 'true' }),
|
|
188
|
-
...(this.language && { 'sw-language-id': this.language }),
|
|
189
|
-
...this.headers,
|
|
190
|
-
...options?.headers,
|
|
191
|
-
},
|
|
192
|
-
body: options?.body ? JSON.stringify(options.body) : undefined,
|
|
193
|
-
})
|
|
194
|
-
} catch (error) {
|
|
195
|
-
const shopwareError = new ShopwareApiError(
|
|
196
|
-
'Failed to communicate with Shopware API',
|
|
197
|
-
500,
|
|
198
|
-
error instanceof Error ? error.message : undefined,
|
|
199
|
-
)
|
|
200
|
-
|
|
201
|
-
this.emit('error', shopwareError)
|
|
202
|
-
|
|
203
|
-
throw shopwareError
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
if (!response.ok) {
|
|
207
|
-
const error = new ShopwareApiError(
|
|
208
|
-
`Shopware API request failed: ${response.statusText}`,
|
|
209
|
-
response.status,
|
|
210
|
-
await response.json().catch(() => undefined),
|
|
211
|
-
)
|
|
212
|
-
|
|
213
|
-
this.emit('error', error)
|
|
214
|
-
|
|
215
|
-
throw error
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
if (this.options.reflectContextToken) {
|
|
219
|
-
const contextToken = response.headers.get('sw-context-token')
|
|
220
|
-
if (contextToken) {
|
|
221
|
-
this.contextToken = contextToken
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
return response
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
async query<OperationKey extends (keyof Operations) & string>(
|
|
229
|
-
operation: OperationKey,
|
|
230
|
-
options?: OperationOptions<Operations, OperationKey>,
|
|
231
|
-
): Promise<BrandedResponse<Operations, OperationKey>> {
|
|
232
|
-
const response = await this.queryRaw(operation, options)
|
|
233
|
-
|
|
234
|
-
return response.json().catch(() => undefined)
|
|
235
|
-
}
|
|
236
|
-
}
|
package/src/error.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod'
|
|
2
|
-
|
|
3
|
-
const shopwareErrorSchema = z.object({
|
|
4
|
-
status: z.string(),
|
|
5
|
-
code: z.string(),
|
|
6
|
-
title: z.string().optional(),
|
|
7
|
-
detail: z.string().optional(),
|
|
8
|
-
meta: z.record(z.unknown()).optional(),
|
|
9
|
-
source: z.object({
|
|
10
|
-
pointer: z.string().optional(),
|
|
11
|
-
}).optional(),
|
|
12
|
-
trace: z.array(
|
|
13
|
-
z.object({
|
|
14
|
-
file: z.string(),
|
|
15
|
-
line: z.number(),
|
|
16
|
-
function: z.string(),
|
|
17
|
-
}),
|
|
18
|
-
).optional(),
|
|
19
|
-
})
|
|
20
|
-
|
|
21
|
-
const shopwareErrorResponseSchema = z.object({
|
|
22
|
-
errors: z.array(shopwareErrorSchema),
|
|
23
|
-
})
|
|
24
|
-
|
|
25
|
-
export type ShopwareError = z.infer<typeof shopwareErrorSchema>
|
|
26
|
-
|
|
27
|
-
export class ShopwareApiError extends Error {
|
|
28
|
-
errors: ShopwareError[]
|
|
29
|
-
|
|
30
|
-
constructor(
|
|
31
|
-
message: string,
|
|
32
|
-
public readonly status: number,
|
|
33
|
-
public readonly response?: unknown,
|
|
34
|
-
) {
|
|
35
|
-
super(message)
|
|
36
|
-
this.name = 'ShopwareApiError'
|
|
37
|
-
|
|
38
|
-
const { success, data } = shopwareErrorResponseSchema.safeParse(response)
|
|
39
|
-
|
|
40
|
-
this.errors = success ? data.errors : []
|
|
41
|
-
}
|
|
42
|
-
}
|
package/src/eventEmitter.ts
DELETED
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
// TODO: Move naming to hooks - deprecate event emitter
|
|
2
|
-
|
|
3
|
-
interface EventListenerEntry {
|
|
4
|
-
listener: EventListenerOrEventListenerObject
|
|
5
|
-
options: AddEventListenerOptions
|
|
6
|
-
signal?: AbortSignal
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export class EventEmitter implements EventTarget {
|
|
10
|
-
private listeners = new Map<string, EventListenerEntry[]>()
|
|
11
|
-
|
|
12
|
-
addEventListener(
|
|
13
|
-
type: string,
|
|
14
|
-
listener: EventListenerOrEventListenerObject | null,
|
|
15
|
-
options?: boolean | AddEventListenerOptions,
|
|
16
|
-
): void {
|
|
17
|
-
if (!listener) return
|
|
18
|
-
|
|
19
|
-
const listenerOptions = this.normalizeOptions(options)
|
|
20
|
-
const entry: EventListenerEntry = {
|
|
21
|
-
listener,
|
|
22
|
-
options: listenerOptions,
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
if (listenerOptions.signal) {
|
|
26
|
-
if (listenerOptions.signal.aborted) return
|
|
27
|
-
|
|
28
|
-
entry.signal = listenerOptions.signal
|
|
29
|
-
listenerOptions.signal.addEventListener('abort', () => {
|
|
30
|
-
this.removeEventListener(type, listener, options)
|
|
31
|
-
}, { once: true })
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
if (!this.listeners.has(type)) {
|
|
35
|
-
this.listeners.set(type, [])
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
this.listeners.get(type)!.push(entry)
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
removeEventListener(
|
|
42
|
-
type: string,
|
|
43
|
-
listener: EventListenerOrEventListenerObject | null,
|
|
44
|
-
options?: boolean | EventListenerOptions,
|
|
45
|
-
): void {
|
|
46
|
-
if (!listener) return
|
|
47
|
-
|
|
48
|
-
const entries = this.listeners.get(type)
|
|
49
|
-
if (!entries) return
|
|
50
|
-
|
|
51
|
-
const listenerOptions = this.normalizeOptions(options)
|
|
52
|
-
const index = entries.findIndex(entry =>
|
|
53
|
-
entry.listener === listener
|
|
54
|
-
&& this.optionsMatch(entry.options, listenerOptions))
|
|
55
|
-
|
|
56
|
-
if (index !== -1) {
|
|
57
|
-
entries.splice(index, 1)
|
|
58
|
-
if (entries.length === 0) {
|
|
59
|
-
this.listeners.delete(type)
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
dispatchEvent(event: Event): boolean {
|
|
65
|
-
const entries = this.listeners.get(event.type)
|
|
66
|
-
if (!entries || entries.length === 0) return true
|
|
67
|
-
|
|
68
|
-
const entriesCopy = [...entries]
|
|
69
|
-
|
|
70
|
-
for (const entry of entriesCopy) {
|
|
71
|
-
if (entry.signal?.aborted) continue
|
|
72
|
-
|
|
73
|
-
if (typeof entry.listener === 'function') {
|
|
74
|
-
entry.listener.call(this, event)
|
|
75
|
-
} else {
|
|
76
|
-
entry.listener.handleEvent(event)
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// Remove if 'once' option was set
|
|
80
|
-
if (entry.options.once) {
|
|
81
|
-
this.removeEventListener(event.type, entry.listener, entry.options)
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Stop if event propagation was stopped
|
|
85
|
-
if (event.cancelBubble) break
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
return !event.defaultPrevented
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
private normalizeOptions(
|
|
92
|
-
options?: boolean | AddEventListenerOptions | EventListenerOptions,
|
|
93
|
-
): AddEventListenerOptions {
|
|
94
|
-
if (typeof options === 'boolean') {
|
|
95
|
-
return { capture: options }
|
|
96
|
-
}
|
|
97
|
-
return {
|
|
98
|
-
capture: false,
|
|
99
|
-
once: false,
|
|
100
|
-
passive: false,
|
|
101
|
-
...options,
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
private optionsMatch(a: AddEventListenerOptions, b: AddEventListenerOptions): boolean {
|
|
106
|
-
return a.capture === b.capture
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// Utility methods for easier usage
|
|
110
|
-
on(
|
|
111
|
-
type: string,
|
|
112
|
-
listener: EventListenerOrEventListenerObject,
|
|
113
|
-
options?: boolean | AddEventListenerOptions,
|
|
114
|
-
): void {
|
|
115
|
-
this.addEventListener(type, listener, options)
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
off(
|
|
119
|
-
type: string,
|
|
120
|
-
listener: EventListenerOrEventListenerObject,
|
|
121
|
-
options?: boolean | EventListenerOptions,
|
|
122
|
-
): void {
|
|
123
|
-
this.removeEventListener(type, listener, options)
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
once(
|
|
127
|
-
type: string,
|
|
128
|
-
listener: EventListenerOrEventListenerObject,
|
|
129
|
-
options?: boolean | AddEventListenerOptions,
|
|
130
|
-
): void {
|
|
131
|
-
const onceOptions = typeof options === 'boolean'
|
|
132
|
-
? {
|
|
133
|
-
capture: options,
|
|
134
|
-
once: true,
|
|
135
|
-
}
|
|
136
|
-
: {
|
|
137
|
-
...options,
|
|
138
|
-
once: true,
|
|
139
|
-
}
|
|
140
|
-
this.addEventListener(type, listener, onceOptions)
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
emit(type: string, detail?: unknown): boolean {
|
|
144
|
-
const event = new CustomEvent(type, { detail })
|
|
145
|
-
return this.dispatchEvent(event)
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
getEventTypes(): string[] {
|
|
149
|
-
return Array.from(this.listeners.keys())
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
removeAllListeners(type?: string): void {
|
|
153
|
-
if (type) {
|
|
154
|
-
this.listeners.delete(type)
|
|
155
|
-
} else {
|
|
156
|
-
this.listeners.clear()
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
package/src/index.ts
DELETED
package/src/query.ts
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
const isIgnored = (value: unknown) =>
|
|
2
|
-
value === undefined
|
|
3
|
-
|| value === null
|
|
4
|
-
|| (typeof value === 'number' && isNaN(value as number))
|
|
5
|
-
|| typeof value === 'function'
|
|
6
|
-
|
|
7
|
-
export function createQueryParams(params: Record<string, unknown>) {
|
|
8
|
-
const queryParams = new URLSearchParams()
|
|
9
|
-
|
|
10
|
-
const appendNested = (key: string, value: unknown) => {
|
|
11
|
-
if (isIgnored(value)) {
|
|
12
|
-
return
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
if (typeof value === 'object') {
|
|
16
|
-
queryParams.append(key, JSON.stringify(value))
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
queryParams.append(key, String(value))
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
for (const [key, value] of Object.entries(params)) {
|
|
23
|
-
if (isIgnored(value)) {
|
|
24
|
-
continue
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (typeof value === 'string') {
|
|
28
|
-
queryParams.append(key, String(value))
|
|
29
|
-
} else if (Array.isArray(value)) {
|
|
30
|
-
for (const item of value) {
|
|
31
|
-
appendNested(`${key}[]`, item)
|
|
32
|
-
}
|
|
33
|
-
} else {
|
|
34
|
-
appendNested(key, value)
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
return queryParams
|
|
39
|
-
}
|