pingen2-sdk-js 0.1.2 → 0.3.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.
Files changed (225) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.mts +845 -0
  3. package/dist/index.d.ts +845 -12
  4. package/dist/index.js +1222 -59
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +1137 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/package.json +16 -3
  9. package/dist/client.d.ts +0 -30
  10. package/dist/client.d.ts.map +0 -1
  11. package/dist/client.js +0 -72
  12. package/dist/client.js.map +0 -1
  13. package/dist/common/enums/address-position.d.ts +0 -5
  14. package/dist/common/enums/address-position.d.ts.map +0 -1
  15. package/dist/common/enums/address-position.js +0 -9
  16. package/dist/common/enums/address-position.js.map +0 -1
  17. package/dist/common/enums/delivery-product.d.ts +0 -8
  18. package/dist/common/enums/delivery-product.d.ts.map +0 -1
  19. package/dist/common/enums/delivery-product.js +0 -12
  20. package/dist/common/enums/delivery-product.js.map +0 -1
  21. package/dist/common/enums/index.d.ts +0 -6
  22. package/dist/common/enums/index.d.ts.map +0 -1
  23. package/dist/common/enums/index.js +0 -14
  24. package/dist/common/enums/index.js.map +0 -1
  25. package/dist/common/enums/paper-type.d.ts +0 -7
  26. package/dist/common/enums/paper-type.d.ts.map +0 -1
  27. package/dist/common/enums/paper-type.js +0 -11
  28. package/dist/common/enums/paper-type.js.map +0 -1
  29. package/dist/common/enums/print-mode.d.ts +0 -5
  30. package/dist/common/enums/print-mode.d.ts.map +0 -1
  31. package/dist/common/enums/print-mode.js +0 -9
  32. package/dist/common/enums/print-mode.js.map +0 -1
  33. package/dist/common/enums/print-spectrum.d.ts +0 -5
  34. package/dist/common/enums/print-spectrum.d.ts.map +0 -1
  35. package/dist/common/enums/print-spectrum.js +0 -9
  36. package/dist/common/enums/print-spectrum.js.map +0 -1
  37. package/dist/common/index.d.ts +0 -8
  38. package/dist/common/index.d.ts.map +0 -1
  39. package/dist/common/index.js +0 -24
  40. package/dist/common/index.js.map +0 -1
  41. package/dist/common/json-api.d.ts +0 -37
  42. package/dist/common/json-api.d.ts.map +0 -1
  43. package/dist/common/json-api.js +0 -3
  44. package/dist/common/json-api.js.map +0 -1
  45. package/dist/common/preset.d.ts +0 -13
  46. package/dist/common/preset.d.ts.map +0 -1
  47. package/dist/common/preset.js +0 -20
  48. package/dist/common/preset.js.map +0 -1
  49. package/dist/common/relationships.d.ts +0 -20
  50. package/dist/common/relationships.d.ts.map +0 -1
  51. package/dist/common/relationships.js +0 -3
  52. package/dist/common/relationships.js.map +0 -1
  53. package/dist/common/response.d.ts +0 -12
  54. package/dist/common/response.d.ts.map +0 -1
  55. package/dist/common/response.js +0 -77
  56. package/dist/common/response.js.map +0 -1
  57. package/dist/common/typed-response.d.ts +0 -29
  58. package/dist/common/typed-response.d.ts.map +0 -1
  59. package/dist/common/typed-response.js +0 -3
  60. package/dist/common/typed-response.js.map +0 -1
  61. package/dist/common/webhook-event.d.ts +0 -34
  62. package/dist/common/webhook-event.d.ts.map +0 -1
  63. package/dist/common/webhook-event.js +0 -3
  64. package/dist/common/webhook-event.js.map +0 -1
  65. package/dist/constants.d.ts +0 -10
  66. package/dist/constants.d.ts.map +0 -1
  67. package/dist/constants.js +0 -16
  68. package/dist/constants.js.map +0 -1
  69. package/dist/errors.d.ts +0 -50
  70. package/dist/errors.d.ts.map +0 -1
  71. package/dist/errors.js +0 -115
  72. package/dist/errors.js.map +0 -1
  73. package/dist/index.d.ts.map +0 -1
  74. package/dist/oauth.d.ts +0 -17
  75. package/dist/oauth.d.ts.map +0 -1
  76. package/dist/oauth.js +0 -68
  77. package/dist/oauth.js.map +0 -1
  78. package/dist/requestor.d.ts +0 -28
  79. package/dist/requestor.d.ts.map +0 -1
  80. package/dist/requestor.js +0 -163
  81. package/dist/requestor.js.map +0 -1
  82. package/dist/resources/base.d.ts +0 -19
  83. package/dist/resources/base.d.ts.map +0 -1
  84. package/dist/resources/base.js +0 -40
  85. package/dist/resources/base.js.map +0 -1
  86. package/dist/resources/batches/batches.d.ts +0 -15
  87. package/dist/resources/batches/batches.d.ts.map +0 -1
  88. package/dist/resources/batches/batches.js +0 -68
  89. package/dist/resources/batches/batches.js.map +0 -1
  90. package/dist/resources/batches/enums.d.ts +0 -39
  91. package/dist/resources/batches/enums.d.ts.map +0 -1
  92. package/dist/resources/batches/enums.js +0 -44
  93. package/dist/resources/batches/enums.js.map +0 -1
  94. package/dist/resources/batches/response.d.ts +0 -27
  95. package/dist/resources/batches/response.d.ts.map +0 -1
  96. package/dist/resources/batches/response.js +0 -3
  97. package/dist/resources/batches/response.js.map +0 -1
  98. package/dist/resources/batches/types.d.ts +0 -41
  99. package/dist/resources/batches/types.d.ts.map +0 -1
  100. package/dist/resources/batches/types.js +0 -3
  101. package/dist/resources/batches/types.js.map +0 -1
  102. package/dist/resources/ebills/ebills.d.ts +0 -13
  103. package/dist/resources/ebills/ebills.d.ts.map +0 -1
  104. package/dist/resources/ebills/ebills.js +0 -38
  105. package/dist/resources/ebills/ebills.js.map +0 -1
  106. package/dist/resources/ebills/response.d.ts +0 -27
  107. package/dist/resources/ebills/response.d.ts.map +0 -1
  108. package/dist/resources/ebills/response.js +0 -3
  109. package/dist/resources/ebills/response.js.map +0 -1
  110. package/dist/resources/ebills/types.d.ts +0 -23
  111. package/dist/resources/ebills/types.d.ts.map +0 -1
  112. package/dist/resources/ebills/types.js +0 -3
  113. package/dist/resources/ebills/types.js.map +0 -1
  114. package/dist/resources/emails/emails.d.ts +0 -13
  115. package/dist/resources/emails/emails.d.ts.map +0 -1
  116. package/dist/resources/emails/emails.js +0 -38
  117. package/dist/resources/emails/emails.js.map +0 -1
  118. package/dist/resources/emails/response.d.ts +0 -24
  119. package/dist/resources/emails/response.d.ts.map +0 -1
  120. package/dist/resources/emails/response.js +0 -3
  121. package/dist/resources/emails/response.js.map +0 -1
  122. package/dist/resources/emails/types.d.ts +0 -26
  123. package/dist/resources/emails/types.d.ts.map +0 -1
  124. package/dist/resources/emails/types.js +0 -3
  125. package/dist/resources/emails/types.js.map +0 -1
  126. package/dist/resources/events/batch-events.d.ts +0 -6
  127. package/dist/resources/events/batch-events.d.ts.map +0 -1
  128. package/dist/resources/events/batch-events.js +0 -11
  129. package/dist/resources/events/batch-events.js.map +0 -1
  130. package/dist/resources/events/ebill-events.d.ts +0 -6
  131. package/dist/resources/events/ebill-events.d.ts.map +0 -1
  132. package/dist/resources/events/ebill-events.js +0 -11
  133. package/dist/resources/events/ebill-events.js.map +0 -1
  134. package/dist/resources/events/email-events.d.ts +0 -6
  135. package/dist/resources/events/email-events.d.ts.map +0 -1
  136. package/dist/resources/events/email-events.js +0 -11
  137. package/dist/resources/events/email-events.js.map +0 -1
  138. package/dist/resources/events/letter-events.d.ts +0 -11
  139. package/dist/resources/events/letter-events.d.ts.map +0 -1
  140. package/dist/resources/events/letter-events.js +0 -26
  141. package/dist/resources/events/letter-events.js.map +0 -1
  142. package/dist/resources/events/response.d.ts +0 -20
  143. package/dist/resources/events/response.d.ts.map +0 -1
  144. package/dist/resources/events/response.js +0 -3
  145. package/dist/resources/events/response.js.map +0 -1
  146. package/dist/resources/file-upload.d.ts +0 -17
  147. package/dist/resources/file-upload.d.ts.map +0 -1
  148. package/dist/resources/file-upload.js +0 -24
  149. package/dist/resources/file-upload.js.map +0 -1
  150. package/dist/resources/index.d.ts +0 -30
  151. package/dist/resources/index.d.ts.map +0 -1
  152. package/dist/resources/index.js +0 -58
  153. package/dist/resources/index.js.map +0 -1
  154. package/dist/resources/letters/letters.d.ts +0 -18
  155. package/dist/resources/letters/letters.d.ts.map +0 -1
  156. package/dist/resources/letters/letters.js +0 -88
  157. package/dist/resources/letters/letters.js.map +0 -1
  158. package/dist/resources/letters/response.d.ts +0 -35
  159. package/dist/resources/letters/response.d.ts.map +0 -1
  160. package/dist/resources/letters/response.js +0 -3
  161. package/dist/resources/letters/response.js.map +0 -1
  162. package/dist/resources/letters/types.d.ts +0 -61
  163. package/dist/resources/letters/types.d.ts.map +0 -1
  164. package/dist/resources/letters/types.js +0 -3
  165. package/dist/resources/letters/types.js.map +0 -1
  166. package/dist/resources/organisations/organisations.d.ts +0 -7
  167. package/dist/resources/organisations/organisations.d.ts.map +0 -1
  168. package/dist/resources/organisations/organisations.js +0 -14
  169. package/dist/resources/organisations/organisations.js.map +0 -1
  170. package/dist/resources/organisations/response.d.ts +0 -24
  171. package/dist/resources/organisations/response.d.ts.map +0 -1
  172. package/dist/resources/organisations/response.js +0 -3
  173. package/dist/resources/organisations/response.js.map +0 -1
  174. package/dist/resources/users/response.d.ts +0 -21
  175. package/dist/resources/users/response.d.ts.map +0 -1
  176. package/dist/resources/users/response.js +0 -3
  177. package/dist/resources/users/response.js.map +0 -1
  178. package/dist/resources/users/user-associations.d.ts +0 -6
  179. package/dist/resources/users/user-associations.d.ts.map +0 -1
  180. package/dist/resources/users/user-associations.js +0 -11
  181. package/dist/resources/users/user-associations.js.map +0 -1
  182. package/dist/resources/users/users.d.ts +0 -6
  183. package/dist/resources/users/users.d.ts.map +0 -1
  184. package/dist/resources/users/users.js +0 -11
  185. package/dist/resources/users/users.js.map +0 -1
  186. package/dist/resources/webhooks/enums.d.ts +0 -8
  187. package/dist/resources/webhooks/enums.d.ts.map +0 -1
  188. package/dist/resources/webhooks/enums.js +0 -12
  189. package/dist/resources/webhooks/enums.js.map +0 -1
  190. package/dist/resources/webhooks/response.d.ts +0 -8
  191. package/dist/resources/webhooks/response.d.ts.map +0 -1
  192. package/dist/resources/webhooks/response.js +0 -3
  193. package/dist/resources/webhooks/response.js.map +0 -1
  194. package/dist/resources/webhooks/types.d.ts +0 -7
  195. package/dist/resources/webhooks/types.d.ts.map +0 -1
  196. package/dist/resources/webhooks/types.js +0 -3
  197. package/dist/resources/webhooks/types.js.map +0 -1
  198. package/dist/resources/webhooks/webhooks.d.ts +0 -10
  199. package/dist/resources/webhooks/webhooks.d.ts.map +0 -1
  200. package/dist/resources/webhooks/webhooks.js +0 -24
  201. package/dist/resources/webhooks/webhooks.js.map +0 -1
  202. package/dist/utils/headers.d.ts +0 -2
  203. package/dist/utils/headers.d.ts.map +0 -1
  204. package/dist/utils/headers.js +0 -13
  205. package/dist/utils/headers.js.map +0 -1
  206. package/dist/utils/idempotency.d.ts +0 -2
  207. package/dist/utils/idempotency.d.ts.map +0 -1
  208. package/dist/utils/idempotency.js +0 -8
  209. package/dist/utils/idempotency.js.map +0 -1
  210. package/dist/utils/object.d.ts +0 -2
  211. package/dist/utils/object.d.ts.map +0 -1
  212. package/dist/utils/object.js +0 -17
  213. package/dist/utils/object.js.map +0 -1
  214. package/dist/utils/payload.d.ts +0 -8
  215. package/dist/utils/payload.d.ts.map +0 -1
  216. package/dist/utils/payload.js +0 -20
  217. package/dist/utils/payload.js.map +0 -1
  218. package/dist/utils/retry.d.ts +0 -6
  219. package/dist/utils/retry.d.ts.map +0 -1
  220. package/dist/utils/retry.js +0 -45
  221. package/dist/utils/retry.js.map +0 -1
  222. package/dist/webhook.d.ts +0 -7
  223. package/dist/webhook.d.ts.map +0 -1
  224. package/dist/webhook.js +0 -25
  225. package/dist/webhook.js.map +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,1137 @@
1
+ // src/requestor.ts
2
+ import { promises as fs } from "fs";
3
+
4
+ // src/errors.ts
5
+ var PingenError = class extends Error {
6
+ constructor(message, status, body = null, requestId, retryAfterMs) {
7
+ super(message);
8
+ this.name = this.constructor.name;
9
+ this.status = status;
10
+ this.body = body;
11
+ this.requestId = requestId;
12
+ this.retryAfterMs = retryAfterMs;
13
+ }
14
+ };
15
+ var PingenBadRequestError = class extends PingenError {
16
+ };
17
+ var PingenUnauthorizedError = class extends PingenError {
18
+ };
19
+ var PingenForbiddenError = class extends PingenError {
20
+ };
21
+ var PingenNotFoundError = class extends PingenError {
22
+ };
23
+ var PingenMethodNotAllowedError = class extends PingenError {
24
+ };
25
+ var PingenNotAcceptableError = class extends PingenError {
26
+ };
27
+ var PingenConflictError = class extends PingenError {
28
+ };
29
+ var PingenGoneError = class extends PingenError {
30
+ };
31
+ var PingenUnsupportedMediaError = class extends PingenError {
32
+ };
33
+ var PingenUnprocessableEntityError = class extends PingenError {
34
+ };
35
+ var PingenDependencyError = class extends PingenError {
36
+ };
37
+ var PingenRateLimitError = class extends PingenError {
38
+ };
39
+ var PingenServerError = class extends PingenError {
40
+ };
41
+ var PingenServiceUnavailableError = class extends PingenError {
42
+ };
43
+ var PingenTimeoutError = class extends PingenError {
44
+ };
45
+ var AuthenticationError = class extends PingenError {
46
+ constructor(message) {
47
+ super(message, 0);
48
+ }
49
+ };
50
+ var ValidationError = class extends PingenError {
51
+ constructor(field, message) {
52
+ super(message, 0);
53
+ this.field = field;
54
+ }
55
+ };
56
+ var WebhookSignatureError = class extends PingenError {
57
+ constructor(message) {
58
+ super(message, 0);
59
+ }
60
+ };
61
+ var HTTP_ERROR_BY_STATUS = {
62
+ 400: PingenBadRequestError,
63
+ 401: PingenUnauthorizedError,
64
+ 403: PingenForbiddenError,
65
+ 404: PingenNotFoundError,
66
+ 405: PingenMethodNotAllowedError,
67
+ 406: PingenNotAcceptableError,
68
+ 409: PingenConflictError,
69
+ 410: PingenGoneError,
70
+ 415: PingenUnsupportedMediaError,
71
+ 422: PingenUnprocessableEntityError,
72
+ 424: PingenDependencyError,
73
+ 429: PingenRateLimitError,
74
+ 500: PingenServerError,
75
+ 503: PingenServiceUnavailableError
76
+ };
77
+ function createPingenError(message, status, body = null, requestId, retryAfterMs) {
78
+ const ErrorClass = HTTP_ERROR_BY_STATUS[status] ?? PingenError;
79
+ return new ErrorClass(message, status, body, requestId, retryAfterMs);
80
+ }
81
+ function isAbortOrTimeoutError(error) {
82
+ const matchesAbortName = (candidate) => candidate instanceof Error && (candidate.name === "TimeoutError" || candidate.name === "AbortError");
83
+ if (matchesAbortName(error)) {
84
+ return true;
85
+ }
86
+ const cause = error instanceof Error ? error.cause : void 0;
87
+ return matchesAbortName(cause);
88
+ }
89
+ function classifyFetchError(context, error) {
90
+ if (isAbortOrTimeoutError(error)) {
91
+ return new PingenTimeoutError(`${context} timed out.`, 0);
92
+ }
93
+ return new PingenError(`${context} failed unexpectedly.`, 0, error);
94
+ }
95
+
96
+ // src/common/response.ts
97
+ var PingenResponse = class {
98
+ constructor(body, statusCode, headers) {
99
+ this.body = body;
100
+ this.statusCode = statusCode;
101
+ this.headers = headers;
102
+ this.data = body ? safeParse(body) : null;
103
+ }
104
+ get requestId() {
105
+ return this.headers["x-request-id"] ?? null;
106
+ }
107
+ toResource() {
108
+ const raw = this.data;
109
+ if (!isJsonApiResource(raw)) {
110
+ throw new PingenError("Response body is not a JSON:API resource document.", this.statusCode, raw);
111
+ }
112
+ return {
113
+ id: raw.data.id,
114
+ resourceType: raw.data.type,
115
+ attributes: raw.data.attributes,
116
+ relationships: raw.data.relationships,
117
+ links: raw.data.links,
118
+ meta: raw.data.meta,
119
+ included: raw.included ?? [],
120
+ statusCode: this.statusCode,
121
+ headers: this.headers
122
+ };
123
+ }
124
+ toCollection() {
125
+ const raw = this.data;
126
+ if (!isJsonApiCollection(raw)) {
127
+ throw new PingenError("Response body is not a JSON:API collection document.", this.statusCode, raw);
128
+ }
129
+ const items = raw.data.map((obj) => ({
130
+ id: obj.id,
131
+ resourceType: obj.type,
132
+ attributes: obj.attributes,
133
+ relationships: obj.relationships,
134
+ links: obj.links,
135
+ meta: obj.meta
136
+ }));
137
+ return {
138
+ data: items,
139
+ links: raw.links,
140
+ meta: raw.meta,
141
+ included: raw.included ?? [],
142
+ statusCode: this.statusCode,
143
+ headers: this.headers
144
+ };
145
+ }
146
+ };
147
+ function isObject(v) {
148
+ return typeof v === "object" && v !== null && !Array.isArray(v);
149
+ }
150
+ function isJsonApiResource(v) {
151
+ if (!isObject(v)) {
152
+ return false;
153
+ }
154
+ const data = v.data;
155
+ return isObject(data) && typeof data.type === "string";
156
+ }
157
+ function isJsonApiCollection(v) {
158
+ return isObject(v) && Array.isArray(v.data);
159
+ }
160
+ function safeParse(body) {
161
+ try {
162
+ return JSON.parse(body);
163
+ } catch {
164
+ return body;
165
+ }
166
+ }
167
+
168
+ // src/common/list-params.ts
169
+ function serializeListParams(params) {
170
+ if (!params) {
171
+ return void 0;
172
+ }
173
+ const out = {};
174
+ if (params.page?.number !== void 0) {
175
+ out["page[number]"] = String(params.page.number);
176
+ }
177
+ if (params.page?.limit !== void 0) {
178
+ out["page[limit]"] = String(params.page.limit);
179
+ }
180
+ if (params.sort !== void 0) {
181
+ out["sort"] = params.sort;
182
+ }
183
+ if (params.q !== void 0) {
184
+ out["q"] = params.q;
185
+ }
186
+ if (params.include !== void 0) {
187
+ out["include"] = params.include;
188
+ }
189
+ if (params.fields) {
190
+ for (const [type, value] of Object.entries(params.fields)) {
191
+ out[`fields[${type}]`] = value;
192
+ }
193
+ }
194
+ return Object.keys(out).length ? out : void 0;
195
+ }
196
+
197
+ // src/constants.ts
198
+ var API_PRODUCTION = "https://api.pingen.com";
199
+ var API_STAGING = "https://api-staging.pingen.com";
200
+ var USER_AGENT = "PINGEN.SDK.NODE";
201
+ var DEFAULT_TIMEOUT_MS = 2e4;
202
+ var UPLOAD_TIMEOUT_MS = 6e4;
203
+ var MAX_RETRY_ATTEMPTS = 3;
204
+ var TOKEN_EXPIRY_BUFFER_SEC = 60;
205
+ var MAX_RETRY_AFTER_MS = 1e4;
206
+ var BASE_BACKOFF_MS = 250;
207
+
208
+ // src/utils/idempotency.ts
209
+ import { randomUUID } from "crypto";
210
+ function newIdempotencyKey() {
211
+ return randomUUID();
212
+ }
213
+
214
+ // src/utils/retry.ts
215
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "PUT", "DELETE"]);
216
+ var MUTATION_METHODS = /* @__PURE__ */ new Set(["POST", "PATCH"]);
217
+ function isRetryableStatus(method, status) {
218
+ if (status === 429) {
219
+ return true;
220
+ }
221
+ if (status >= 500 && status < 600) {
222
+ return IDEMPOTENT_METHODS.has(method) || MUTATION_METHODS.has(method);
223
+ }
224
+ return false;
225
+ }
226
+ function shouldAttachIdempotencyKey(method) {
227
+ return MUTATION_METHODS.has(method);
228
+ }
229
+ function computeBackoffMs(retryAfterHeader, attempt) {
230
+ const base = Math.max(parseRetryAfterMs(retryAfterHeader), BASE_BACKOFF_MS * 2 ** attempt);
231
+ return Math.round(base * (0.8 + Math.random() * 0.4));
232
+ }
233
+ function parseRetryAfterMs(v) {
234
+ if (typeof v !== "string") {
235
+ return 0;
236
+ }
237
+ const seconds = parseInt(v, 10);
238
+ if (!Number.isFinite(seconds) || seconds <= 0) {
239
+ return 0;
240
+ }
241
+ return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS);
242
+ }
243
+ function sleep(ms) {
244
+ return new Promise((resolve) => setTimeout(resolve, ms));
245
+ }
246
+
247
+ // src/utils/headers.ts
248
+ function headersToRecord(headers) {
249
+ const rec = {};
250
+ headers.forEach((v, k) => {
251
+ rec[k] = v;
252
+ });
253
+ return rec;
254
+ }
255
+
256
+ // src/requestor.ts
257
+ function safeParseJson(body) {
258
+ if (!body) {
259
+ return null;
260
+ }
261
+ try {
262
+ return JSON.parse(body);
263
+ } catch {
264
+ return body;
265
+ }
266
+ }
267
+ function parseRetryAfterMs2(value) {
268
+ if (!value) {
269
+ return void 0;
270
+ }
271
+ const seconds = parseInt(value, 10);
272
+ if (!Number.isFinite(seconds) || seconds <= 0) {
273
+ return void 0;
274
+ }
275
+ return seconds * 1e3;
276
+ }
277
+ var ApiRequestor = class {
278
+ constructor(accessToken, options = {}) {
279
+ this.accessToken = accessToken;
280
+ this.apiBase = options.useStaging ? API_STAGING : API_PRODUCTION;
281
+ this.maxAttempts = options.maxAttempts ?? MAX_RETRY_ATTEMPTS;
282
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
283
+ this.uploadTimeoutMs = options.uploadTimeoutMs ?? UPLOAD_TIMEOUT_MS;
284
+ this.on401 = options.on401;
285
+ }
286
+ setAccessToken(accessToken) {
287
+ this.accessToken = accessToken;
288
+ }
289
+ get(path, params, extraHeaders) {
290
+ return this.execute("GET", this.buildUrl(path, params), void 0, extraHeaders);
291
+ }
292
+ post(path, payload, extraHeaders) {
293
+ return this.execute("POST", this.apiBase + path, payload, extraHeaders);
294
+ }
295
+ patch(path, payload, extraHeaders) {
296
+ return this.execute("PATCH", this.apiBase + path, payload, extraHeaders);
297
+ }
298
+ delete(path) {
299
+ return this.execute("DELETE", this.apiBase + path, void 0);
300
+ }
301
+ async put(url, filePath) {
302
+ const fileBuffer = await fs.readFile(filePath);
303
+ let res;
304
+ try {
305
+ res = await fetch(url, {
306
+ method: "PUT",
307
+ body: fileBuffer,
308
+ signal: AbortSignal.timeout(this.uploadTimeoutMs)
309
+ });
310
+ } catch (e) {
311
+ throw classifyFetchError("File upload to signed URL", e);
312
+ }
313
+ if (!res.ok) {
314
+ const respBody = await res.text();
315
+ const respHeaders = headersToRecord(res.headers);
316
+ throw createPingenError(
317
+ `File upload to signed URL failed (status ${res.status}).`,
318
+ res.status,
319
+ safeParseJson(respBody),
320
+ respHeaders["x-request-id"],
321
+ parseRetryAfterMs2(respHeaders["retry-after"])
322
+ );
323
+ }
324
+ }
325
+ async stream(path) {
326
+ let res;
327
+ try {
328
+ res = await fetch(this.buildUrl(path), {
329
+ headers: this.defaultHeaders(false),
330
+ signal: AbortSignal.timeout(this.uploadTimeoutMs)
331
+ });
332
+ } catch (e) {
333
+ throw classifyFetchError("File download", e);
334
+ }
335
+ const body = await res.text();
336
+ if (!res.ok) {
337
+ const respHeaders = headersToRecord(res.headers);
338
+ throw createPingenError(
339
+ `File download failed (status ${res.status}).`,
340
+ res.status,
341
+ safeParseJson(body),
342
+ respHeaders["x-request-id"],
343
+ parseRetryAfterMs2(respHeaders["retry-after"])
344
+ );
345
+ }
346
+ return body;
347
+ }
348
+ buildUrl(path, params) {
349
+ const url = new URL(this.apiBase + path);
350
+ const query = serializeListParams(params);
351
+ if (query) {
352
+ for (const [name, value] of Object.entries(query)) url.searchParams.set(name, value);
353
+ }
354
+ return url.toString();
355
+ }
356
+ defaultHeaders(hasBody, extra = {}) {
357
+ const headers = {
358
+ "User-Agent": USER_AGENT,
359
+ Accept: "application/vnd.api+json",
360
+ ...extra
361
+ };
362
+ if (hasBody) {
363
+ headers["Content-Type"] = "application/vnd.api+json";
364
+ }
365
+ if (this.accessToken) {
366
+ headers.Authorization = `Bearer ${this.accessToken}`;
367
+ }
368
+ return headers;
369
+ }
370
+ async execute(method, url, body, extra) {
371
+ const idempotencyKey = shouldAttachIdempotencyKey(method) ? newIdempotencyKey() : void 0;
372
+ let refreshed = false;
373
+ let attempt = 0;
374
+ for (; ; ) {
375
+ const headers = this.defaultHeaders(body !== void 0, extra);
376
+ if (idempotencyKey && !headers["Idempotency-Key"]) {
377
+ headers["Idempotency-Key"] = idempotencyKey;
378
+ }
379
+ let res;
380
+ try {
381
+ res = await fetch(url, {
382
+ method,
383
+ headers,
384
+ body,
385
+ signal: AbortSignal.timeout(this.timeoutMs)
386
+ });
387
+ } catch (e) {
388
+ throw classifyFetchError(`Pingen API ${method} ${url}`, e);
389
+ }
390
+ const respBody = await res.text();
391
+ const respHeaders = headersToRecord(res.headers);
392
+ if (res.status >= 200 && res.status < 300) {
393
+ return new PingenResponse(respBody, res.status, respHeaders);
394
+ }
395
+ if (res.status === 401 && !refreshed && this.on401) {
396
+ const fresh = await this.on401();
397
+ refreshed = true;
398
+ if (fresh) {
399
+ this.accessToken = fresh;
400
+ continue;
401
+ }
402
+ }
403
+ const lastAttempt = attempt >= this.maxAttempts - 1;
404
+ if (lastAttempt || !isRetryableStatus(method, res.status)) {
405
+ throw createPingenError(
406
+ `Pingen API returned ${res.status}.`,
407
+ res.status,
408
+ safeParseJson(respBody),
409
+ respHeaders["x-request-id"],
410
+ parseRetryAfterMs2(respHeaders["retry-after"])
411
+ );
412
+ }
413
+ await sleep(computeBackoffMs(respHeaders["retry-after"], attempt));
414
+ attempt++;
415
+ }
416
+ }
417
+ };
418
+
419
+ // src/oauth.ts
420
+ var OAuth = class {
421
+ constructor(config) {
422
+ this.cachedToken = null;
423
+ this.pendingRequest = null;
424
+ if (!config.clientId || !config.clientSecret) {
425
+ throw new AuthenticationError("OAuth requires clientId and clientSecret.");
426
+ }
427
+ this.clientId = config.clientId;
428
+ this.clientSecret = config.clientSecret;
429
+ this.useStaging = config.useStaging ?? false;
430
+ }
431
+ async getAccessToken() {
432
+ if (this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
433
+ return this.cachedToken.accessToken;
434
+ }
435
+ if (this.pendingRequest) {
436
+ return this.pendingRequest;
437
+ }
438
+ this.pendingRequest = this.fetchToken().finally(() => {
439
+ this.pendingRequest = null;
440
+ });
441
+ return this.pendingRequest;
442
+ }
443
+ invalidate() {
444
+ this.cachedToken = null;
445
+ }
446
+ async fetchToken() {
447
+ const base = this.useStaging ? API_STAGING : API_PRODUCTION;
448
+ const body = new URLSearchParams({
449
+ client_id: this.clientId,
450
+ client_secret: this.clientSecret,
451
+ grant_type: "client_credentials"
452
+ }).toString();
453
+ let res;
454
+ try {
455
+ res = await fetch(`${base}/auth/access-tokens`, {
456
+ method: "POST",
457
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
458
+ body,
459
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS)
460
+ });
461
+ } catch (e) {
462
+ throw classifyFetchError("Pingen auth request", e);
463
+ }
464
+ if (!res.ok) {
465
+ const text = await res.text();
466
+ throw createPingenError(`Pingen auth endpoint returned ${res.status}: ${text || res.statusText}`, res.status);
467
+ }
468
+ let response;
469
+ try {
470
+ response = await res.json();
471
+ } catch {
472
+ throw new PingenError("Pingen auth endpoint returned non-JSON body.", res.status);
473
+ }
474
+ const ttlMs = Math.max(0, response.expires_in - TOKEN_EXPIRY_BUFFER_SEC) * 1e3;
475
+ this.cachedToken = { accessToken: response.access_token, expiresAt: Date.now() + ttlMs };
476
+ return response.access_token;
477
+ }
478
+ };
479
+
480
+ // src/resources/file-upload.ts
481
+ var FileUpload = class {
482
+ constructor(requestor) {
483
+ this.requestor = requestor;
484
+ }
485
+ async requestFileUpload() {
486
+ const res = await this.requestor.get("/file-upload");
487
+ const { url, url_signature } = res.toResource().attributes;
488
+ if (!url || !url_signature) {
489
+ throw new PingenError(
490
+ "Pingen /file-upload returned a response missing url or url_signature.",
491
+ res.statusCode,
492
+ res.data
493
+ );
494
+ }
495
+ return { url, signature: url_signature };
496
+ }
497
+ putFile(filePath, fileUrl) {
498
+ return this.requestor.put(fileUrl, filePath);
499
+ }
500
+ };
501
+
502
+ // src/resources/base.ts
503
+ var BaseResource = class {
504
+ constructor(requestor) {
505
+ this.requestor = requestor;
506
+ }
507
+ };
508
+ var OrgResource = class {
509
+ constructor(orgId, requestor) {
510
+ this.orgId = orgId;
511
+ this.requestor = requestor;
512
+ }
513
+ // Shared upload flow used by Letters/Batches/Ebills/Emails. Requests a signed URL, PUTs the
514
+ // file to it, and returns the URL + signature so the caller can attach them to its create()
515
+ // call. Throws if the signed-URL upload fails (see ApiRequestor.put).
516
+ uploadFile(filePath) {
517
+ const fu = new FileUpload(this.requestor);
518
+ return fu.requestFileUpload().then(async (signed) => {
519
+ await fu.putFile(filePath, signed.url);
520
+ return signed;
521
+ });
522
+ }
523
+ // Shared "upload then create" flow: takes upload options containing `filePath`, runs the
524
+ // signed-URL upload, then forwards the rest to the resource-specific `create` step with
525
+ // fileUrl/fileSignature attached. Each resource keeps its own typed Create/Upload pair —
526
+ // this helper just removes the four-line boilerplate that used to live in every subclass.
527
+ async uploadAndCall(opts, create) {
528
+ const { url, signature } = await this.uploadFile(opts.filePath);
529
+ const { filePath: _filePath, ...rest } = opts;
530
+ return create({ ...rest, fileUrl: url, fileSignature: signature });
531
+ }
532
+ };
533
+
534
+ // src/utils/payload.ts
535
+ function buildJsonApi(env) {
536
+ const data = { type: env.type };
537
+ if (env.id !== void 0) {
538
+ data.id = env.id;
539
+ }
540
+ if (env.attributes !== void 0) {
541
+ data.attributes = env.attributes;
542
+ }
543
+ if (env.relationships !== void 0) {
544
+ data.relationships = env.relationships;
545
+ }
546
+ return JSON.stringify({ data });
547
+ }
548
+
549
+ // src/utils/object.ts
550
+ function definedOnly(input) {
551
+ const result = {};
552
+ for (const key of Object.keys(input)) {
553
+ if (input[key] !== void 0) {
554
+ result[key] = input[key];
555
+ }
556
+ }
557
+ return result;
558
+ }
559
+
560
+ // src/resources/letters/letters.ts
561
+ function validateAutoSend(opts) {
562
+ if (!opts.autoSend) {
563
+ return;
564
+ }
565
+ if (!opts.deliveryProduct) {
566
+ throw new ValidationError("deliveryProduct", "deliveryProduct is required when autoSend is true");
567
+ }
568
+ if (!opts.printMode) {
569
+ throw new ValidationError("printMode", "printMode is required when autoSend is true");
570
+ }
571
+ if (!opts.printSpectrum) {
572
+ throw new ValidationError("printSpectrum", "printSpectrum is required when autoSend is true");
573
+ }
574
+ }
575
+ var Letters = class extends OrgResource {
576
+ getDetails(letterId, params) {
577
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/letters/${letterId}`, params);
578
+ }
579
+ getCollection(params) {
580
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/letters`, params);
581
+ }
582
+ uploadAndCreate(opts) {
583
+ validateAutoSend(opts);
584
+ return this.uploadAndCall(opts, (rest) => this.createValidated(rest));
585
+ }
586
+ create(opts) {
587
+ validateAutoSend(opts);
588
+ return this.createValidated(opts);
589
+ }
590
+ createValidated(opts) {
591
+ const attributes = definedOnly({
592
+ file_original_name: opts.fileOriginalName,
593
+ file_url: opts.fileUrl,
594
+ file_url_signature: opts.fileSignature,
595
+ address_position: opts.addressPosition,
596
+ auto_send: opts.autoSend,
597
+ delivery_product: opts.deliveryProduct,
598
+ print_mode: opts.printMode,
599
+ print_spectrum: opts.printSpectrum,
600
+ meta_data: opts.metaData
601
+ });
602
+ return this.requestor.post(
603
+ `/organisations/${this.orgId}/deliveries/letters`,
604
+ buildJsonApi({ type: "letters", attributes, relationships: opts.preset?.toValue() })
605
+ );
606
+ }
607
+ send(opts) {
608
+ return this.requestor.patch(
609
+ `/organisations/${this.orgId}/deliveries/letters/${opts.letterId}/send`,
610
+ buildJsonApi({
611
+ type: "letters",
612
+ id: opts.letterId,
613
+ attributes: {
614
+ delivery_product: opts.deliveryProduct,
615
+ print_mode: opts.printMode,
616
+ print_spectrum: opts.printSpectrum
617
+ }
618
+ })
619
+ );
620
+ }
621
+ cancel(letterId) {
622
+ return this.requestor.patch(`/organisations/${this.orgId}/deliveries/letters/${letterId}/cancel`);
623
+ }
624
+ delete(letterId) {
625
+ return this.requestor.delete(`/organisations/${this.orgId}/deliveries/letters/${letterId}`);
626
+ }
627
+ edit(letterId, paperTypes) {
628
+ return this.requestor.patch(
629
+ `/organisations/${this.orgId}/deliveries/letters/${letterId}`,
630
+ buildJsonApi({ type: "letters", id: letterId, attributes: { paper_types: paperTypes } })
631
+ );
632
+ }
633
+ getFile(letterId) {
634
+ return this.requestor.stream(`/organisations/${this.orgId}/deliveries/letters/${letterId}/file`);
635
+ }
636
+ calculatePrice(opts) {
637
+ return this.requestor.post(
638
+ `/organisations/${this.orgId}/deliveries/letters/price-calculator`,
639
+ buildJsonApi({
640
+ type: "letter_price_calculator",
641
+ attributes: {
642
+ country: opts.country,
643
+ paper_types: opts.paperTypes,
644
+ print_mode: opts.printMode,
645
+ print_spectrum: opts.printSpectrum,
646
+ delivery_product: opts.deliveryProduct
647
+ }
648
+ })
649
+ );
650
+ }
651
+ };
652
+
653
+ // src/resources/batches/batches.ts
654
+ var BATCH_NAME_MIN = 5;
655
+ var BATCH_NAME_MAX = 100;
656
+ var Batches = class extends OrgResource {
657
+ getDetails(batchId, params) {
658
+ return this.requestor.get(`/organisations/${this.orgId}/batches/${batchId}`, params);
659
+ }
660
+ getCollection(params) {
661
+ return this.requestor.get(`/organisations/${this.orgId}/batches`, params);
662
+ }
663
+ uploadAndCreate(opts) {
664
+ return this.uploadAndCall(opts, (rest) => this.create(rest));
665
+ }
666
+ create(opts) {
667
+ const attributes = definedOnly({
668
+ file_url: opts.fileUrl,
669
+ file_url_signature: opts.fileSignature,
670
+ name: opts.name,
671
+ icon: opts.icon,
672
+ file_original_name: opts.fileOriginalName,
673
+ address_position: opts.addressPosition,
674
+ grouping_type: opts.groupingType,
675
+ grouping_options_split_type: opts.splitType,
676
+ grouping_options_split_size: opts.splitSize,
677
+ grouping_options_split_separator: opts.splitSeparator,
678
+ grouping_options_split_position: opts.splitPosition
679
+ });
680
+ return this.requestor.post(
681
+ `/organisations/${this.orgId}/batches`,
682
+ buildJsonApi({ type: "batches", attributes, relationships: opts.preset?.toValue() })
683
+ );
684
+ }
685
+ send(opts) {
686
+ return this.requestor.patch(
687
+ `/organisations/${this.orgId}/batches/${opts.batchId}/send`,
688
+ buildJsonApi({
689
+ type: "batches",
690
+ id: opts.batchId,
691
+ attributes: {
692
+ delivery_products: opts.deliveryProducts,
693
+ print_mode: opts.printMode,
694
+ print_spectrum: opts.printSpectrum
695
+ }
696
+ })
697
+ );
698
+ }
699
+ cancel(batchId) {
700
+ return this.requestor.patch(`/organisations/${this.orgId}/batches/${batchId}/cancel`);
701
+ }
702
+ delete(batchId) {
703
+ return this.requestor.delete(`/organisations/${this.orgId}/batches/${batchId}`);
704
+ }
705
+ edit(batchId, opts) {
706
+ if (opts.name !== void 0 && (opts.name.length < BATCH_NAME_MIN || opts.name.length > BATCH_NAME_MAX)) {
707
+ throw new ValidationError("name", `name must be between ${BATCH_NAME_MIN} and ${BATCH_NAME_MAX} characters`);
708
+ }
709
+ return this.requestor.patch(
710
+ `/organisations/${this.orgId}/batches/${batchId}`,
711
+ buildJsonApi({
712
+ type: "batches",
713
+ id: batchId,
714
+ attributes: definedOnly({ name: opts.name, icon: opts.icon })
715
+ })
716
+ );
717
+ }
718
+ getStatistics(batchId) {
719
+ return this.requestor.get(`/organisations/${this.orgId}/batches/${batchId}/statistics`);
720
+ }
721
+ };
722
+
723
+ // src/resources/batches/enums.ts
724
+ var BatchIcon = /* @__PURE__ */ ((BatchIcon2) => {
725
+ BatchIcon2["Campaign"] = "campaign";
726
+ BatchIcon2["Megaphone"] = "megaphone";
727
+ BatchIcon2["WaveHand"] = "wave-hand";
728
+ BatchIcon2["Flash"] = "flash";
729
+ BatchIcon2["Rocket"] = "rocket";
730
+ BatchIcon2["Bell"] = "bell";
731
+ BatchIcon2["PercentTag"] = "percent-tag";
732
+ BatchIcon2["PercentBadge"] = "percent-badge";
733
+ BatchIcon2["Present"] = "present";
734
+ BatchIcon2["Receipt"] = "receipt";
735
+ BatchIcon2["Document"] = "document";
736
+ BatchIcon2["Information"] = "information";
737
+ BatchIcon2["Calendar"] = "calendar";
738
+ BatchIcon2["Newspaper"] = "newspaper";
739
+ BatchIcon2["Crown"] = "crown";
740
+ BatchIcon2["Virus"] = "virus";
741
+ return BatchIcon2;
742
+ })(BatchIcon || {});
743
+ var GroupingType = /* @__PURE__ */ ((GroupingType2) => {
744
+ GroupingType2["Merge"] = "merge";
745
+ GroupingType2["Zip"] = "zip";
746
+ return GroupingType2;
747
+ })(GroupingType || {});
748
+ var SplitType = /* @__PURE__ */ ((SplitType2) => {
749
+ SplitType2["File"] = "file";
750
+ SplitType2["Page"] = "page";
751
+ SplitType2["Custom"] = "custom";
752
+ SplitType2["QrInvoice"] = "qr_invoice";
753
+ return SplitType2;
754
+ })(SplitType || {});
755
+ var SplitPosition = /* @__PURE__ */ ((SplitPosition2) => {
756
+ SplitPosition2["FirstPage"] = "first_page";
757
+ SplitPosition2["LastPage"] = "last_page";
758
+ return SplitPosition2;
759
+ })(SplitPosition || {});
760
+ function createBatchDeliveryProduct(country, deliveryProduct) {
761
+ return { country, delivery_product: deliveryProduct };
762
+ }
763
+
764
+ // src/resources/ebills/ebills.ts
765
+ var Ebills = class extends OrgResource {
766
+ getDetails(ebillId, params) {
767
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/ebills/${ebillId}`, params);
768
+ }
769
+ getCollection(params) {
770
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/ebills`, params);
771
+ }
772
+ uploadAndCreate(opts) {
773
+ return this.uploadAndCall(opts, (rest) => this.create(rest));
774
+ }
775
+ create(opts) {
776
+ const attributes = definedOnly({
777
+ file_original_name: opts.fileOriginalName,
778
+ file_url: opts.fileUrl,
779
+ file_url_signature: opts.fileSignature,
780
+ auto_send: opts.autoSend,
781
+ meta_data: opts.metaData
782
+ });
783
+ return this.requestor.post(
784
+ `/organisations/${this.orgId}/deliveries/ebills`,
785
+ buildJsonApi({ type: "ebills", attributes, relationships: opts.preset?.toValue() })
786
+ );
787
+ }
788
+ cancel(ebillId) {
789
+ return this.requestor.patch(`/organisations/${this.orgId}/deliveries/ebills/${ebillId}/cancel`);
790
+ }
791
+ delete(ebillId) {
792
+ return this.requestor.delete(`/organisations/${this.orgId}/deliveries/ebills/${ebillId}`);
793
+ }
794
+ getFile(ebillId) {
795
+ return this.requestor.stream(`/organisations/${this.orgId}/deliveries/ebills/${ebillId}/file`);
796
+ }
797
+ };
798
+
799
+ // src/resources/emails/emails.ts
800
+ var Emails = class extends OrgResource {
801
+ getDetails(emailId, params) {
802
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/emails/${emailId}`, params);
803
+ }
804
+ getCollection(params) {
805
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/emails`, params);
806
+ }
807
+ uploadAndCreate(opts) {
808
+ return this.uploadAndCall(opts, (rest) => this.create(rest));
809
+ }
810
+ create(opts) {
811
+ const attributes = definedOnly({
812
+ file_original_name: opts.fileOriginalName,
813
+ file_url: opts.fileUrl,
814
+ file_url_signature: opts.fileSignature,
815
+ auto_send: opts.autoSend,
816
+ meta_data: opts.metaData
817
+ });
818
+ return this.requestor.post(
819
+ `/organisations/${this.orgId}/deliveries/emails`,
820
+ buildJsonApi({ type: "emails", attributes, relationships: opts.preset?.toValue() })
821
+ );
822
+ }
823
+ cancel(emailId) {
824
+ return this.requestor.patch(`/organisations/${this.orgId}/deliveries/emails/${emailId}/cancel`);
825
+ }
826
+ delete(emailId) {
827
+ return this.requestor.delete(`/organisations/${this.orgId}/deliveries/emails/${emailId}`);
828
+ }
829
+ getFile(emailId) {
830
+ return this.requestor.stream(`/organisations/${this.orgId}/deliveries/emails/${emailId}/file`);
831
+ }
832
+ };
833
+
834
+ // src/resources/webhooks/webhooks.ts
835
+ var Webhooks = class extends OrgResource {
836
+ getDetails(webhookId, params) {
837
+ return this.requestor.get(`/organisations/${this.orgId}/webhooks/${webhookId}`, params);
838
+ }
839
+ getCollection(params) {
840
+ return this.requestor.get(`/organisations/${this.orgId}/webhooks`, params);
841
+ }
842
+ create(opts) {
843
+ return this.requestor.post(
844
+ `/organisations/${this.orgId}/webhooks`,
845
+ buildJsonApi({
846
+ type: "webhooks",
847
+ attributes: { event_category: opts.eventCategory, url: opts.url, signing_key: opts.signingKey }
848
+ })
849
+ );
850
+ }
851
+ delete(webhookId) {
852
+ return this.requestor.delete(`/organisations/${this.orgId}/webhooks/${webhookId}`);
853
+ }
854
+ };
855
+
856
+ // src/resources/webhooks/enums.ts
857
+ var WebhookEventCategory = /* @__PURE__ */ ((WebhookEventCategory2) => {
858
+ WebhookEventCategory2["Issues"] = "issues";
859
+ WebhookEventCategory2["Sent"] = "sent";
860
+ WebhookEventCategory2["Undeliverable"] = "undeliverable";
861
+ WebhookEventCategory2["Delivered"] = "delivered";
862
+ WebhookEventCategory2["ChannelSubscriptions"] = "channel_subscriptions";
863
+ return WebhookEventCategory2;
864
+ })(WebhookEventCategory || {});
865
+
866
+ // src/resources/events/letter-events.ts
867
+ var LetterEvents = class extends OrgResource {
868
+ getCollection(letterId, params) {
869
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/letters/${letterId}/events`, params);
870
+ }
871
+ getIssueCollection(params) {
872
+ return this.eventsFeed("issues", params);
873
+ }
874
+ getUndeliverableCollection(params) {
875
+ return this.eventsFeed("undeliverable", params);
876
+ }
877
+ getDeliveredCollection(params) {
878
+ return this.eventsFeed("delivered", params);
879
+ }
880
+ getSentCollection(params) {
881
+ return this.eventsFeed("sent", params);
882
+ }
883
+ eventsFeed(feed, params) {
884
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/letters/events/${feed}`, params);
885
+ }
886
+ };
887
+
888
+ // src/resources/events/batch-events.ts
889
+ var BatchEvents = class extends OrgResource {
890
+ getCollection(batchId, params) {
891
+ return this.requestor.get(`/organisations/${this.orgId}/batches/${batchId}/events`, params);
892
+ }
893
+ };
894
+
895
+ // src/resources/events/ebill-events.ts
896
+ var EbillEvents = class extends OrgResource {
897
+ getCollection(ebillId, params) {
898
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/ebills/${ebillId}/events`, params);
899
+ }
900
+ };
901
+
902
+ // src/resources/events/email-events.ts
903
+ var EmailEvents = class extends OrgResource {
904
+ getCollection(emailId, params) {
905
+ return this.requestor.get(`/organisations/${this.orgId}/deliveries/emails/${emailId}/events`, params);
906
+ }
907
+ };
908
+
909
+ // src/resources/organisations/organisations.ts
910
+ var Organisations = class extends BaseResource {
911
+ getDetails(orgId, params) {
912
+ return this.requestor.get(`/organisations/${orgId}`, params);
913
+ }
914
+ getCollection(params) {
915
+ return this.requestor.get("/organisations", params);
916
+ }
917
+ };
918
+
919
+ // src/resources/users/users.ts
920
+ var Users = class extends BaseResource {
921
+ getDetails(params) {
922
+ return this.requestor.get("/user", params);
923
+ }
924
+ };
925
+
926
+ // src/resources/users/user-associations.ts
927
+ var UserAssociations = class extends BaseResource {
928
+ getCollection(params) {
929
+ return this.requestor.get("/user/associations", params);
930
+ }
931
+ };
932
+
933
+ // src/client.ts
934
+ var PingenClient = class {
935
+ constructor(configOrClientId, clientSecret, useStaging) {
936
+ const config = typeof configOrClientId === "string" ? { clientId: configOrClientId, clientSecret, useStaging } : configOrClientId;
937
+ this.oauth = new OAuth({
938
+ clientId: config.clientId,
939
+ clientSecret: config.clientSecret,
940
+ useStaging: config.useStaging ?? false
941
+ });
942
+ this.requestor = new ApiRequestor(null, this.buildRequestorOptions(config));
943
+ }
944
+ async ensureToken() {
945
+ this.requestor.setAccessToken(await this.oauth.getAccessToken());
946
+ }
947
+ letters(orgId) {
948
+ return new Letters(orgId, this.requestor);
949
+ }
950
+ batches(orgId) {
951
+ return new Batches(orgId, this.requestor);
952
+ }
953
+ letterEvents(orgId) {
954
+ return new LetterEvents(orgId, this.requestor);
955
+ }
956
+ batchEvents(orgId) {
957
+ return new BatchEvents(orgId, this.requestor);
958
+ }
959
+ ebillEvents(orgId) {
960
+ return new EbillEvents(orgId, this.requestor);
961
+ }
962
+ emailEvents(orgId) {
963
+ return new EmailEvents(orgId, this.requestor);
964
+ }
965
+ organisations() {
966
+ return new Organisations(this.requestor);
967
+ }
968
+ users() {
969
+ return new Users(this.requestor);
970
+ }
971
+ userAssociations() {
972
+ return new UserAssociations(this.requestor);
973
+ }
974
+ webhooks(orgId) {
975
+ return new Webhooks(orgId, this.requestor);
976
+ }
977
+ ebills(orgId) {
978
+ return new Ebills(orgId, this.requestor);
979
+ }
980
+ emails(orgId) {
981
+ return new Emails(orgId, this.requestor);
982
+ }
983
+ buildRequestorOptions(config) {
984
+ return {
985
+ useStaging: config.useStaging,
986
+ maxAttempts: config.maxAttempts,
987
+ timeoutMs: config.timeoutMs,
988
+ uploadTimeoutMs: config.uploadTimeoutMs,
989
+ on401: async () => {
990
+ this.oauth.invalidate();
991
+ return this.oauth.getAccessToken();
992
+ }
993
+ };
994
+ }
995
+ };
996
+
997
+ // src/webhook.ts
998
+ import { createHmac, timingSafeEqual } from "crypto";
999
+ function verifyWebhookSignature(payload, signature, secret) {
1000
+ if (!signature) {
1001
+ throw new WebhookSignatureError("Signature missing.");
1002
+ }
1003
+ const expected = createHmac("sha256", secret).update(payload).digest("hex");
1004
+ if (expected.length !== signature.length || !/^[0-9a-f]+$/.test(signature)) {
1005
+ throw new WebhookSignatureError("Webhook signature matching failed.");
1006
+ }
1007
+ const expectedBytes = Buffer.from(expected, "utf8");
1008
+ const providedBytes = Buffer.from(signature, "utf8");
1009
+ if (!timingSafeEqual(expectedBytes, providedBytes)) {
1010
+ throw new WebhookSignatureError("Webhook signature matching failed.");
1011
+ }
1012
+ }
1013
+ function constructWebhookEvent(payload, signature, secret) {
1014
+ verifyWebhookSignature(payload, signature, secret);
1015
+ return { body: payload, data: JSON.parse(payload) };
1016
+ }
1017
+
1018
+ // src/common/enums/address-position.ts
1019
+ var AddressPosition = /* @__PURE__ */ ((AddressPosition2) => {
1020
+ AddressPosition2["Left"] = "left";
1021
+ AddressPosition2["Right"] = "right";
1022
+ return AddressPosition2;
1023
+ })(AddressPosition || {});
1024
+
1025
+ // src/common/enums/delivery-product.ts
1026
+ var DeliveryProduct = /* @__PURE__ */ ((DeliveryProduct2) => {
1027
+ DeliveryProduct2["Cheap"] = "cheap";
1028
+ DeliveryProduct2["Fast"] = "fast";
1029
+ DeliveryProduct2["Registered"] = "registered";
1030
+ DeliveryProduct2["Bulk"] = "bulk";
1031
+ DeliveryProduct2["Premium"] = "premium";
1032
+ return DeliveryProduct2;
1033
+ })(DeliveryProduct || {});
1034
+
1035
+ // src/common/enums/paper-type.ts
1036
+ var PaperType = /* @__PURE__ */ ((PaperType2) => {
1037
+ PaperType2["Normal"] = "normal";
1038
+ PaperType2["Qr"] = "qr";
1039
+ PaperType2["SepaAt"] = "sepa_at";
1040
+ PaperType2["SepaDe"] = "sepa_de";
1041
+ return PaperType2;
1042
+ })(PaperType || {});
1043
+
1044
+ // src/common/enums/print-mode.ts
1045
+ var PrintMode = /* @__PURE__ */ ((PrintMode2) => {
1046
+ PrintMode2["Simplex"] = "simplex";
1047
+ PrintMode2["Duplex"] = "duplex";
1048
+ return PrintMode2;
1049
+ })(PrintMode || {});
1050
+
1051
+ // src/common/enums/print-spectrum.ts
1052
+ var PrintSpectrum = /* @__PURE__ */ ((PrintSpectrum2) => {
1053
+ PrintSpectrum2["Color"] = "color";
1054
+ PrintSpectrum2["Grayscale"] = "grayscale";
1055
+ return PrintSpectrum2;
1056
+ })(PrintSpectrum || {});
1057
+
1058
+ // src/common/preset.ts
1059
+ var PresetRelationship = class {
1060
+ constructor(presetId) {
1061
+ this.presetId = presetId;
1062
+ }
1063
+ toValue() {
1064
+ return {
1065
+ preset: {
1066
+ data: {
1067
+ id: this.presetId,
1068
+ type: "presets"
1069
+ }
1070
+ }
1071
+ };
1072
+ }
1073
+ };
1074
+ export {
1075
+ AddressPosition,
1076
+ ApiRequestor,
1077
+ AuthenticationError,
1078
+ BaseResource,
1079
+ BatchEvents,
1080
+ BatchIcon,
1081
+ Batches,
1082
+ DeliveryProduct,
1083
+ EbillEvents,
1084
+ Ebills,
1085
+ EmailEvents,
1086
+ Emails,
1087
+ FileUpload,
1088
+ GroupingType,
1089
+ LetterEvents,
1090
+ Letters,
1091
+ OAuth,
1092
+ OrgResource,
1093
+ Organisations,
1094
+ PaperType,
1095
+ PingenBadRequestError,
1096
+ PingenClient,
1097
+ PingenConflictError,
1098
+ PingenDependencyError,
1099
+ PingenError,
1100
+ PingenForbiddenError,
1101
+ PingenGoneError,
1102
+ PingenMethodNotAllowedError,
1103
+ PingenNotAcceptableError,
1104
+ PingenNotFoundError,
1105
+ PingenRateLimitError,
1106
+ PingenResponse,
1107
+ PingenServerError,
1108
+ PingenServiceUnavailableError,
1109
+ PingenTimeoutError,
1110
+ PingenUnauthorizedError,
1111
+ PingenUnprocessableEntityError,
1112
+ PingenUnsupportedMediaError,
1113
+ PresetRelationship,
1114
+ PrintMode,
1115
+ PrintSpectrum,
1116
+ SplitPosition,
1117
+ SplitType,
1118
+ UserAssociations,
1119
+ Users,
1120
+ ValidationError,
1121
+ WebhookEventCategory,
1122
+ WebhookSignatureError,
1123
+ Webhooks,
1124
+ buildJsonApi,
1125
+ computeBackoffMs,
1126
+ constructWebhookEvent,
1127
+ createBatchDeliveryProduct,
1128
+ createPingenError,
1129
+ definedOnly,
1130
+ isRetryableStatus,
1131
+ newIdempotencyKey,
1132
+ serializeListParams,
1133
+ shouldAttachIdempotencyKey,
1134
+ sleep,
1135
+ verifyWebhookSignature
1136
+ };
1137
+ //# sourceMappingURL=index.mjs.map