@superdurable/connector-hubspot 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +27 -2
- package/dex-connector.json +426 -0
- package/dist/chunk-HHRHOJKC.js +340 -0
- package/dist/connection-pqfXajbM.d.ts +291 -0
- package/dist/index.d.ts +443 -0
- package/dist/index.js +1184 -0
- package/dist/mock.d.ts +118 -0
- package/dist/mock.js +284 -0
- package/package.json +63 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1184 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CRMObjectSchema,
|
|
3
|
+
ConfigSchema,
|
|
4
|
+
Connection,
|
|
5
|
+
ConnectorID,
|
|
6
|
+
GetObjectBranch,
|
|
7
|
+
GetObjectBranchDefect,
|
|
8
|
+
GetObjectBranchFound,
|
|
9
|
+
GetObjectBranchInvalidResponse,
|
|
10
|
+
GetObjectBranchNotFound,
|
|
11
|
+
GetObjectBranchProviderRejected,
|
|
12
|
+
GetObjectDefinition,
|
|
13
|
+
GetObjectInputSchema,
|
|
14
|
+
GetObjectMetadata,
|
|
15
|
+
ObjectPageSchema,
|
|
16
|
+
ProviderID,
|
|
17
|
+
SearchFilterGroupSchema,
|
|
18
|
+
SearchFilterSchema,
|
|
19
|
+
SearchObjectsBranch,
|
|
20
|
+
SearchObjectsBranchDefect,
|
|
21
|
+
SearchObjectsBranchInvalidResponse,
|
|
22
|
+
SearchObjectsBranchProviderRejected,
|
|
23
|
+
SearchObjectsBranchSearched,
|
|
24
|
+
SearchObjectsDefinition,
|
|
25
|
+
SearchObjectsInputSchema,
|
|
26
|
+
SearchObjectsMetadata,
|
|
27
|
+
SearchSortSchema,
|
|
28
|
+
UpdateObjectBranch,
|
|
29
|
+
UpdateObjectBranchConflict,
|
|
30
|
+
UpdateObjectBranchDefect,
|
|
31
|
+
UpdateObjectBranchInvalidResponse,
|
|
32
|
+
UpdateObjectBranchNotFound,
|
|
33
|
+
UpdateObjectBranchProviderRejected,
|
|
34
|
+
UpdateObjectBranchUpdated,
|
|
35
|
+
UpdateObjectDefinition,
|
|
36
|
+
UpdateObjectInputSchema,
|
|
37
|
+
UpdateObjectMetadata,
|
|
38
|
+
UpsertObjectBranch,
|
|
39
|
+
UpsertObjectBranchConflict,
|
|
40
|
+
UpsertObjectBranchDefect,
|
|
41
|
+
UpsertObjectBranchInvalidResponse,
|
|
42
|
+
UpsertObjectBranchProviderRejected,
|
|
43
|
+
UpsertObjectBranchUpserted,
|
|
44
|
+
UpsertObjectDefinition,
|
|
45
|
+
UpsertObjectInputSchema,
|
|
46
|
+
UpsertObjectMetadata,
|
|
47
|
+
UpsertedObjectSchema,
|
|
48
|
+
decodeCredentials,
|
|
49
|
+
decodeSharedCredentials,
|
|
50
|
+
newConnection,
|
|
51
|
+
newConnectionWithOperations,
|
|
52
|
+
newProjectConnection,
|
|
53
|
+
newProjectCredentialProvider
|
|
54
|
+
} from "./chunk-HHRHOJKC.js";
|
|
55
|
+
|
|
56
|
+
// src/generated/steps.ts
|
|
57
|
+
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
58
|
+
function newSearchObjectsStep(configuration) {
|
|
59
|
+
const { connection, connectionName, searched, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
60
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
61
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.searchObjects(), connection: connection.reference, branches: [
|
|
62
|
+
goToBranch("searched", searched),
|
|
63
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
64
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
65
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
66
|
+
] });
|
|
67
|
+
}
|
|
68
|
+
function newGetObjectStep(configuration) {
|
|
69
|
+
const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
70
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
71
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.getObject(), connection: connection.reference, branches: [
|
|
72
|
+
goToBranch("found", found),
|
|
73
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
74
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
75
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
76
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
77
|
+
] });
|
|
78
|
+
}
|
|
79
|
+
function newUpsertObjectStep(configuration) {
|
|
80
|
+
const { connection, connectionName, upserted, conflict, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
81
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
82
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.upsertObject(), connection: connection.reference, branches: [
|
|
83
|
+
goToBranch("upserted", upserted),
|
|
84
|
+
...conflict ? [goToBranch("conflict", conflict)] : [],
|
|
85
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
86
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
87
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
88
|
+
] });
|
|
89
|
+
}
|
|
90
|
+
function newUpdateObjectStep(configuration) {
|
|
91
|
+
const { connection, connectionName, updated, notFound, conflict, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
92
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
93
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateObject(), connection: connection.reference, branches: [
|
|
94
|
+
goToBranch("updated", updated),
|
|
95
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
96
|
+
...conflict ? [goToBranch("conflict", conflict)] : [],
|
|
97
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
98
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
99
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
100
|
+
] });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// src/client.ts
|
|
104
|
+
import { ReauthorizationRequiredError, RetryError, defaultTriggerLogger, resolveCredential, resolveCredentialAfterRejection, SecretString } from "@superdurable/connectors-sdk";
|
|
105
|
+
import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
|
|
106
|
+
import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
|
|
107
|
+
|
|
108
|
+
// src/generated/refresh.ts
|
|
109
|
+
var Authorization = {
|
|
110
|
+
"defaultMethod": "private-app-token",
|
|
111
|
+
"methods": [
|
|
112
|
+
{
|
|
113
|
+
"fields": [
|
|
114
|
+
{
|
|
115
|
+
"name": "access_token",
|
|
116
|
+
"required": true,
|
|
117
|
+
"type": "secretString"
|
|
118
|
+
}
|
|
119
|
+
],
|
|
120
|
+
"id": "private-app-token",
|
|
121
|
+
"type": "apiKey"
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
"fields": [
|
|
125
|
+
{
|
|
126
|
+
"name": "oauth_client_id",
|
|
127
|
+
"required": true,
|
|
128
|
+
"type": "string"
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
"name": "oauth_client_secret",
|
|
132
|
+
"required": true,
|
|
133
|
+
"type": "secretString"
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
"name": "access_token",
|
|
137
|
+
"required": true,
|
|
138
|
+
"type": "secretString"
|
|
139
|
+
},
|
|
140
|
+
{
|
|
141
|
+
"name": "refresh_token",
|
|
142
|
+
"required": true,
|
|
143
|
+
"type": "secretString"
|
|
144
|
+
}
|
|
145
|
+
],
|
|
146
|
+
"id": "hubspot-oauth",
|
|
147
|
+
"oauth2": {
|
|
148
|
+
"clientIDCredential": "oauth_client_id",
|
|
149
|
+
"clientSecretCredential": "oauth_client_secret",
|
|
150
|
+
"credentialMappings": [
|
|
151
|
+
{
|
|
152
|
+
"credential": "access_token",
|
|
153
|
+
"source": "access_token"
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
"credential": "refresh_token",
|
|
157
|
+
"source": "refresh_token"
|
|
158
|
+
}
|
|
159
|
+
],
|
|
160
|
+
"refresh": {
|
|
161
|
+
"missingExpiry": "reject",
|
|
162
|
+
"requiredScopes": [
|
|
163
|
+
"crm.objects.contacts.read",
|
|
164
|
+
"crm.objects.contacts.write",
|
|
165
|
+
"crm.objects.companies.read",
|
|
166
|
+
"crm.objects.companies.write",
|
|
167
|
+
"crm.objects.deals.read",
|
|
168
|
+
"crm.objects.deals.write",
|
|
169
|
+
"crm.objects.owners.read"
|
|
170
|
+
],
|
|
171
|
+
"responseScopeField": "scopesArray",
|
|
172
|
+
"storedMissingExpiry": "refresh",
|
|
173
|
+
"terminalErrorCodes": [
|
|
174
|
+
"invalid_grant",
|
|
175
|
+
"invalid_client",
|
|
176
|
+
"unauthorized_client"
|
|
177
|
+
],
|
|
178
|
+
"tokenExchangeTimeout": "25s"
|
|
179
|
+
},
|
|
180
|
+
"scopes": [
|
|
181
|
+
"oauth",
|
|
182
|
+
"crm.objects.contacts.read",
|
|
183
|
+
"crm.objects.contacts.write",
|
|
184
|
+
"crm.objects.companies.read",
|
|
185
|
+
"crm.objects.companies.write",
|
|
186
|
+
"crm.objects.deals.read",
|
|
187
|
+
"crm.objects.deals.write",
|
|
188
|
+
"crm.objects.owners.read"
|
|
189
|
+
],
|
|
190
|
+
"tokenEndpoint": "https://api.hubapi.com/oauth/2026-09/token"
|
|
191
|
+
},
|
|
192
|
+
"type": "oauth2"
|
|
193
|
+
}
|
|
194
|
+
],
|
|
195
|
+
"refreshable": true
|
|
196
|
+
};
|
|
197
|
+
var CredentialFields = {
|
|
198
|
+
"access_token": "accessToken",
|
|
199
|
+
"oauth_client_id": "oauthClientId",
|
|
200
|
+
"oauth_client_secret": "oauthClientSecret",
|
|
201
|
+
"refresh_token": "refreshToken"
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
// src/operations.ts
|
|
205
|
+
import { newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
|
|
206
|
+
var propertyName = /^[A-Za-z0-9][A-Za-z0-9_]{0,99}$/;
|
|
207
|
+
var associationName = /^associations\.[a-z][a-z0-9_]{0,63}$/;
|
|
208
|
+
var recordId = /^[0-9]{1,20}$/;
|
|
209
|
+
var cursor = /^[0-9]{1,5}$/;
|
|
210
|
+
var zeroObject = { objectType: "", id: "", archived: false };
|
|
211
|
+
var zeroPage = { objectType: "", total: 0, objects: [] };
|
|
212
|
+
var zeroUpsert = { object: zeroObject, created: false };
|
|
213
|
+
var SearchObjectsOperation = class {
|
|
214
|
+
/** Bind a client. */
|
|
215
|
+
constructor(client) {
|
|
216
|
+
this.client = client;
|
|
217
|
+
}
|
|
218
|
+
client;
|
|
219
|
+
/** Return the manifest definition. */
|
|
220
|
+
definition() {
|
|
221
|
+
return SearchObjectsDefinition;
|
|
222
|
+
}
|
|
223
|
+
/** Validate, send, and decode a search. */
|
|
224
|
+
async invoke(call, input) {
|
|
225
|
+
let body;
|
|
226
|
+
try {
|
|
227
|
+
body = searchBody(input);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
return queryFailure("searchObjects", "defect", "VALIDATION", zeroPage, {}, error);
|
|
230
|
+
}
|
|
231
|
+
const result = await this.client.exchange(call, "searchObjects", "", "POST", objectsPath(input.objectType, "search"), void 0, body);
|
|
232
|
+
if ("outcome" in result) return queryOutcome(result.outcome, zeroPage, "providerRejected");
|
|
233
|
+
const receipt = this.client.receipt(call, result.response);
|
|
234
|
+
try {
|
|
235
|
+
return newQueryBranch("searched", decodeObjectPage(input.objectType, result.response.body), receipt);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
return queryFailure("searchObjects", "invalidResponse", "PROTOCOL", zeroPage, receipt, error);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
var GetObjectOperation = class {
|
|
242
|
+
/** Bind a client. */
|
|
243
|
+
constructor(client) {
|
|
244
|
+
this.client = client;
|
|
245
|
+
}
|
|
246
|
+
client;
|
|
247
|
+
/** Return the manifest definition. */
|
|
248
|
+
definition() {
|
|
249
|
+
return GetObjectDefinition;
|
|
250
|
+
}
|
|
251
|
+
/** Validate, send, and decode one record. */
|
|
252
|
+
async invoke(call, input) {
|
|
253
|
+
let query;
|
|
254
|
+
try {
|
|
255
|
+
validateObjectType(input.objectType);
|
|
256
|
+
validateRecordId(input.objectId);
|
|
257
|
+
const properties = uniqueProperties(input.properties ?? []);
|
|
258
|
+
query = `archived=false${properties.length ? `&properties=${goQueryEscape(properties.join(","))}` : ""}`;
|
|
259
|
+
} catch (error) {
|
|
260
|
+
return queryFailure("getObject", "defect", "VALIDATION", zeroObject, {}, error);
|
|
261
|
+
}
|
|
262
|
+
const result = await this.client.exchange(call, "getObject", input.objectId, "GET", objectsPath(input.objectType, input.objectId), query);
|
|
263
|
+
if ("outcome" in result) return queryOutcome(result.outcome, zeroObject, "providerRejected", "notFound");
|
|
264
|
+
const receipt = this.client.receipt(call, result.response, input.objectId);
|
|
265
|
+
try {
|
|
266
|
+
const object = decodeCRMObject(input.objectType, jsonObject(result.response.body));
|
|
267
|
+
if (object.id !== input.objectId) throw new TypeError("HubSpot returned an invalid record");
|
|
268
|
+
return newQueryBranch("found", object, receipt);
|
|
269
|
+
} catch {
|
|
270
|
+
return queryFailure("getObject", "invalidResponse", "PROTOCOL", zeroObject, receipt, new Error("HubSpot returned an invalid record"));
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
var UpsertObjectOperation = class {
|
|
275
|
+
/** Bind a client. */
|
|
276
|
+
constructor(client) {
|
|
277
|
+
this.client = client;
|
|
278
|
+
}
|
|
279
|
+
client;
|
|
280
|
+
/** Return the manifest definition. */
|
|
281
|
+
definition() {
|
|
282
|
+
return UpsertObjectDefinition;
|
|
283
|
+
}
|
|
284
|
+
/** Reuse the stable Call ID for a repeat-safe upsert. */
|
|
285
|
+
idempotencyKey(callId) {
|
|
286
|
+
return callId;
|
|
287
|
+
}
|
|
288
|
+
/** Validate and dispatch, repeating one conflicting upsert. */
|
|
289
|
+
async invoke(call, input) {
|
|
290
|
+
let body;
|
|
291
|
+
try {
|
|
292
|
+
validateObjectType(input.objectType);
|
|
293
|
+
if (!propertyName.test(input.idProperty)) throw new Error("upsert ID property name is invalid");
|
|
294
|
+
if (!input.idValue.trim() || [...input.idValue].length > 65536) throw new Error("upsert ID value must be non-empty and within HubSpot's property value limit");
|
|
295
|
+
validateValues(input.properties ?? {}, false);
|
|
296
|
+
body = { inputs: [{ idProperty: input.idProperty, id: input.idValue, properties: input.properties ?? {} }] };
|
|
297
|
+
} catch (error) {
|
|
298
|
+
return mutationFailure("upsertObject", "defect", "VALIDATION", zeroUpsert, {}, error);
|
|
299
|
+
}
|
|
300
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
301
|
+
const result = await this.client.exchange(call, "upsertObject", "", "POST", objectsPath(input.objectType, "batch/upsert"), void 0, body);
|
|
302
|
+
if ("outcome" in result) {
|
|
303
|
+
if (result.outcome.disposition === "conflict" && attempt === 0) continue;
|
|
304
|
+
return mutationOutcome(result.outcome, zeroUpsert, "providerRejected", "providerRejected", "conflict");
|
|
305
|
+
}
|
|
306
|
+
const receipt = this.client.receipt(call, result.response);
|
|
307
|
+
try {
|
|
308
|
+
const decoded = jsonObject(result.response.body);
|
|
309
|
+
const results = arrayField(decoded, "results");
|
|
310
|
+
if (results.length === 0) {
|
|
311
|
+
const errors = arrayField(decoded, "errors");
|
|
312
|
+
if (errors.length) {
|
|
313
|
+
const first = requireObject(errors[0]);
|
|
314
|
+
const statusText = stringField(first, "status");
|
|
315
|
+
let status = /^[+-]?[0-9]+$/.test(statusText) && BigInt(statusText) <= 9223372036854775807n && BigInt(statusText) >= -9223372036854775808n ? Number(statusText) : 400;
|
|
316
|
+
if (!Number.isInteger(status) || status < 400) status = 400;
|
|
317
|
+
const category = stringField(first, "category");
|
|
318
|
+
const syntheticBody = Buffer.from(JSON.stringify({ category }));
|
|
319
|
+
const classified = this.client.classifyBatchError("upsertObject", { status, headers: result.response.headers, body: syntheticBody }, receipt);
|
|
320
|
+
if (classified.disposition === "conflict" && attempt === 0) continue;
|
|
321
|
+
return mutationOutcome(classified, zeroUpsert, "providerRejected", "providerRejected", "conflict");
|
|
322
|
+
}
|
|
323
|
+
throw new TypeError("HubSpot upsert response has no record");
|
|
324
|
+
}
|
|
325
|
+
if (results.length !== 1) throw new TypeError("HubSpot upsert response has more than one record");
|
|
326
|
+
const providerObject = requireObject(results[0]);
|
|
327
|
+
const object = decodeCRMObject(input.objectType, providerObject);
|
|
328
|
+
const created = booleanField(providerObject, "new");
|
|
329
|
+
return newMutationBranch("upserted", { object, created }, { ...receipt, providerObjectId: object.id });
|
|
330
|
+
} catch (error) {
|
|
331
|
+
return mutationFailure("upsertObject", "invalidResponse", "PROTOCOL", zeroUpsert, receipt, error);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
throw new TypeError("unreachable upsert attempt");
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
var UpdateObjectOperation = class {
|
|
338
|
+
/** Bind a client. */
|
|
339
|
+
constructor(client) {
|
|
340
|
+
this.client = client;
|
|
341
|
+
}
|
|
342
|
+
client;
|
|
343
|
+
/** Return the manifest definition. */
|
|
344
|
+
definition() {
|
|
345
|
+
return UpdateObjectDefinition;
|
|
346
|
+
}
|
|
347
|
+
/** Reuse the stable Call ID for an absolute update. */
|
|
348
|
+
idempotencyKey(callId) {
|
|
349
|
+
return callId;
|
|
350
|
+
}
|
|
351
|
+
/** Validate, send, and decode one update. */
|
|
352
|
+
async invoke(call, input) {
|
|
353
|
+
try {
|
|
354
|
+
validateObjectType(input.objectType);
|
|
355
|
+
validateRecordId(input.objectId);
|
|
356
|
+
validateValues(input.properties ?? void 0, true);
|
|
357
|
+
} catch (error) {
|
|
358
|
+
return mutationFailure("updateObject", "defect", "VALIDATION", zeroObject, {}, error);
|
|
359
|
+
}
|
|
360
|
+
const result = await this.client.exchange(call, "updateObject", input.objectId, "PATCH", objectsPath(input.objectType, input.objectId), void 0, { properties: input.properties });
|
|
361
|
+
if ("outcome" in result) return mutationOutcome(result.outcome, zeroObject, "providerRejected", "notFound", "conflict");
|
|
362
|
+
const receipt = this.client.receipt(call, result.response, input.objectId);
|
|
363
|
+
try {
|
|
364
|
+
const object = decodeCRMObject(input.objectType, jsonObject(result.response.body));
|
|
365
|
+
if (object.id !== input.objectId) throw new TypeError("HubSpot returned an invalid record");
|
|
366
|
+
return newMutationBranch("updated", object, receipt);
|
|
367
|
+
} catch {
|
|
368
|
+
return mutationFailure("updateObject", "invalidResponse", "PROTOCOL", zeroObject, receipt, new Error("HubSpot returned an invalid record"));
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
function queryOutcome(outcome, zero, rejected, notFound = rejected) {
|
|
373
|
+
if (outcome.disposition === "retry") return newQueryRetry(outcome.failure, outcome.retryAfterMs);
|
|
374
|
+
const branch = outcome.disposition === "notFound" ? notFound : outcome.disposition === "conflict" || outcome.disposition === "rejected" ? rejected : outcome.disposition;
|
|
375
|
+
return newQueryBranch(branch, zero, outcome.receipt, outcome.failure);
|
|
376
|
+
}
|
|
377
|
+
function mutationOutcome(outcome, zero, rejected, notFound = rejected, conflict = rejected) {
|
|
378
|
+
if (outcome.disposition === "retry") return newMutationRetry(outcome.failure, outcome.retryAfterMs);
|
|
379
|
+
const branch = outcome.disposition === "notFound" ? notFound : outcome.disposition === "conflict" ? conflict : outcome.disposition === "rejected" ? rejected : outcome.disposition;
|
|
380
|
+
return newMutationBranch(branch, zero, outcome.receipt, outcome.failure);
|
|
381
|
+
}
|
|
382
|
+
function queryFailure(operation, branch, kind, zero, receipt, error) {
|
|
383
|
+
return newQueryBranch(branch, zero, receipt, { kind, provider: "hubspot", operation, message: error instanceof Error ? error.message : "HubSpot returned a malformed response" });
|
|
384
|
+
}
|
|
385
|
+
function mutationFailure(operation, branch, kind, zero, receipt, error) {
|
|
386
|
+
return newMutationBranch(branch, zero, receipt, { kind, provider: "hubspot", operation, message: error instanceof Error ? error.message : "HubSpot returned a malformed response" });
|
|
387
|
+
}
|
|
388
|
+
function validateObjectType(value) {
|
|
389
|
+
if (!["contacts", "companies", "deals"].includes(value)) throw new Error("object type must be contacts, companies, or deals");
|
|
390
|
+
}
|
|
391
|
+
function validateRecordId(value) {
|
|
392
|
+
if (!recordId.test(value)) throw new Error("object ID must be a decimal HubSpot record ID");
|
|
393
|
+
}
|
|
394
|
+
function uniqueProperties(values) {
|
|
395
|
+
if (values.length > 100) throw new Error("at most 100 properties can be requested");
|
|
396
|
+
const unique = [...new Set(values)];
|
|
397
|
+
if (unique.some((value) => !propertyName.test(value))) throw new Error("requested property name is invalid");
|
|
398
|
+
return unique;
|
|
399
|
+
}
|
|
400
|
+
function validateValues(properties, required) {
|
|
401
|
+
if (required && !Object.keys(properties ?? {}).length) throw new Error("at least one property value is required");
|
|
402
|
+
if (Object.keys(properties ?? {}).length > 100) throw new Error("at most 100 property values can be written");
|
|
403
|
+
for (const [name, value] of Object.entries(properties ?? {})) {
|
|
404
|
+
if (!propertyName.test(name)) throw new Error("written property name is invalid");
|
|
405
|
+
if ([...value].length > 65536) throw new Error("property values cannot exceed 65536 characters");
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
function objectsPath(objectType, suffix) {
|
|
409
|
+
return `crm/objects/2026-09/${objectType}/${suffix}`;
|
|
410
|
+
}
|
|
411
|
+
function goQueryEscape(value) {
|
|
412
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
|
|
413
|
+
}
|
|
414
|
+
function searchBody(input) {
|
|
415
|
+
validateObjectType(input.objectType);
|
|
416
|
+
const groups = input.filterGroups ?? [];
|
|
417
|
+
if (groups.length > 5) throw new Error("search allows at most 5 filter groups");
|
|
418
|
+
let count = 0;
|
|
419
|
+
for (const group of groups) {
|
|
420
|
+
if (!group.filters || group.filters.length < 1 || group.filters.length > 6) throw new Error("each filter group needs 1 to 6 filters");
|
|
421
|
+
count += group.filters.length;
|
|
422
|
+
group.filters.forEach(validateFilter);
|
|
423
|
+
}
|
|
424
|
+
if (count > 18) throw new Error("search allows at most 18 filters in total");
|
|
425
|
+
const properties = uniqueProperties(input.properties ?? []);
|
|
426
|
+
const limit = input.limit || 10;
|
|
427
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new Error("search limit must be from 1 through 200");
|
|
428
|
+
if (input.after && !cursor.test(input.after)) throw new Error("search after cursor must be the decimal NextAfter value of a previous page");
|
|
429
|
+
if (Number(input.after || "0") + limit > 1e4) throw new Error("search paging cannot pass HubSpot's 10000-result limit");
|
|
430
|
+
const body = {
|
|
431
|
+
...groups.length ? { filterGroups: groups.map((group) => ({ filters: group.filters })) } : {},
|
|
432
|
+
...input.query ? { query: input.query } : {},
|
|
433
|
+
...input.sort ? { sorts: [input.sort] } : {},
|
|
434
|
+
...properties.length ? { properties } : {},
|
|
435
|
+
limit,
|
|
436
|
+
...input.after ? { after: input.after } : {}
|
|
437
|
+
};
|
|
438
|
+
if (input.sort && (!propertyName.test(input.sort.propertyName) || !["ASCENDING", "DESCENDING"].includes(input.sort.direction))) throw new Error("sort property or direction is invalid");
|
|
439
|
+
if (Buffer.byteLength(JSON.stringify(body).replace(/[<>&]/g, (character) => ({ "<": "\\u003c", ">": "\\u003e", "&": "\\u0026" })[character]).replace(/[\u2028\u2029]/g, (character) => character === "\u2028" ? "\\u2028" : "\\u2029")) > 3e3) throw new Error("search request exceeds HubSpot's 3000-character body limit");
|
|
440
|
+
return body;
|
|
441
|
+
}
|
|
442
|
+
function validateFilter(filter) {
|
|
443
|
+
if (!propertyName.test(filter.propertyName) && !associationName.test(filter.propertyName)) throw new Error("filter property name is invalid");
|
|
444
|
+
const hasValue = Boolean(filter.value), hasHigh = Boolean(filter.highValue), hasValues = Boolean(filter.values?.length);
|
|
445
|
+
const operator = filter.operator;
|
|
446
|
+
if (["EQ", "NEQ", "LT", "LTE", "GT", "GTE", "CONTAINS_TOKEN", "NOT_CONTAINS_TOKEN"].includes(operator)) {
|
|
447
|
+
if (!hasValue || hasHigh || hasValues) throw new Error(`filter operator ${operator} needs only a value`);
|
|
448
|
+
} else if (operator === "BETWEEN") {
|
|
449
|
+
if (!hasValue || !hasHigh || hasValues) throw new Error("filter operator BETWEEN needs a value and a highValue");
|
|
450
|
+
} else if (operator === "IN" || operator === "NOT_IN") {
|
|
451
|
+
if (hasValue || hasHigh || !hasValues || (filter.values?.length ?? 0) > 100 || filter.values?.some((value) => !value)) throw new Error(`filter operator ${operator} needs 1 to 100 values`);
|
|
452
|
+
} else if (operator === "HAS_PROPERTY" || operator === "NOT_HAS_PROPERTY") {
|
|
453
|
+
if (hasValue || hasHigh || hasValues) throw new Error(`filter operator ${operator} takes no value`);
|
|
454
|
+
} else throw new Error("filter operator is not supported");
|
|
455
|
+
}
|
|
456
|
+
function requireObject(value) {
|
|
457
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("HubSpot returned a malformed response");
|
|
458
|
+
return value;
|
|
459
|
+
}
|
|
460
|
+
function jsonObject(body) {
|
|
461
|
+
return requireObject(JSON.parse(Buffer.from(body).toString()));
|
|
462
|
+
}
|
|
463
|
+
function decodeObjectPage(objectType, body) {
|
|
464
|
+
const decoded = jsonObject(body);
|
|
465
|
+
const total = integerField(decoded, "total");
|
|
466
|
+
if (total < 0) throw new TypeError("HubSpot returned a malformed response");
|
|
467
|
+
const results = decoded.results;
|
|
468
|
+
if (results !== void 0 && results !== null && !Array.isArray(results)) throw new TypeError("HubSpot returned a malformed response");
|
|
469
|
+
const objects = (results ?? []).map((item) => decodeCRMObject(objectType, item));
|
|
470
|
+
const page = { objectType, total, objects };
|
|
471
|
+
if (decoded.paging !== void 0 && decoded.paging !== null) {
|
|
472
|
+
const paging = requireObject(decoded.paging);
|
|
473
|
+
if (paging.next !== void 0 && paging.next !== null) {
|
|
474
|
+
const after = stringField(requireObject(paging.next), "after");
|
|
475
|
+
if (after) {
|
|
476
|
+
if (!cursor.test(after)) throw new TypeError("HubSpot returned an invalid search cursor");
|
|
477
|
+
page.nextAfter = after;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return page;
|
|
482
|
+
}
|
|
483
|
+
function stringField(value, field) {
|
|
484
|
+
const candidate = value[field];
|
|
485
|
+
if (candidate === null || candidate === void 0) return "";
|
|
486
|
+
if (typeof candidate !== "string") throw new TypeError("HubSpot returned a malformed response");
|
|
487
|
+
return candidate;
|
|
488
|
+
}
|
|
489
|
+
function integerField(value, field) {
|
|
490
|
+
const candidate = value[field];
|
|
491
|
+
if (candidate === null || candidate === void 0) return 0;
|
|
492
|
+
if (!Number.isSafeInteger(candidate)) throw new TypeError("HubSpot returned a malformed response");
|
|
493
|
+
return candidate;
|
|
494
|
+
}
|
|
495
|
+
function booleanField(value, field) {
|
|
496
|
+
const candidate = value[field];
|
|
497
|
+
if (candidate === null || candidate === void 0) return false;
|
|
498
|
+
if (typeof candidate !== "boolean") throw new TypeError("HubSpot returned a malformed response");
|
|
499
|
+
return candidate;
|
|
500
|
+
}
|
|
501
|
+
function arrayField(value, field) {
|
|
502
|
+
const candidate = value[field];
|
|
503
|
+
if (candidate === null || candidate === void 0) return [];
|
|
504
|
+
if (!Array.isArray(candidate)) throw new TypeError("HubSpot returned a malformed response");
|
|
505
|
+
return candidate;
|
|
506
|
+
}
|
|
507
|
+
function decodeCRMObject(objectType, value) {
|
|
508
|
+
const provider = requireObject(value);
|
|
509
|
+
const id = stringField(provider, "id");
|
|
510
|
+
if (!recordId.test(id)) throw new TypeError("HubSpot returned a record without a valid ID");
|
|
511
|
+
const properties = provider.properties === null || provider.properties === void 0 ? void 0 : requireObject(provider.properties);
|
|
512
|
+
const cleaned = {};
|
|
513
|
+
for (const [name, property] of Object.entries(properties ?? {})) {
|
|
514
|
+
if (property === null) continue;
|
|
515
|
+
if (typeof property !== "string") throw new TypeError("HubSpot returned a malformed response");
|
|
516
|
+
cleaned[name] = property;
|
|
517
|
+
}
|
|
518
|
+
const createdAt = stringField(provider, "createdAt");
|
|
519
|
+
const updatedAt = stringField(provider, "updatedAt");
|
|
520
|
+
const result = {
|
|
521
|
+
objectType,
|
|
522
|
+
id,
|
|
523
|
+
...Object.keys(cleaned).length ? { properties: cleaned } : {},
|
|
524
|
+
...createdAt ? { createdAt } : {},
|
|
525
|
+
...updatedAt ? { updatedAt } : {},
|
|
526
|
+
archived: booleanField(provider, "archived")
|
|
527
|
+
};
|
|
528
|
+
const url = appURL(stringField(provider, "url"));
|
|
529
|
+
if (url) result.url = url;
|
|
530
|
+
const parsed = CRMObjectSchema.parse(result);
|
|
531
|
+
if (parsed.createdAt === "0001-01-01T00:00:00Z") delete parsed.createdAt;
|
|
532
|
+
if (parsed.updatedAt === "0001-01-01T00:00:00Z") delete parsed.updatedAt;
|
|
533
|
+
return parsed;
|
|
534
|
+
}
|
|
535
|
+
function appURL(value) {
|
|
536
|
+
try {
|
|
537
|
+
const parsed = new URL(value);
|
|
538
|
+
return parsed.protocol === "https:" && !parsed.username && !parsed.password && parsed.hostname.endsWith(".hubspot.com") ? value : "";
|
|
539
|
+
} catch {
|
|
540
|
+
return "";
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// src/client.ts
|
|
545
|
+
var defaultEndpoint = "https://api.hubapi.com";
|
|
546
|
+
var defaultPollIntervalMs = 3e4;
|
|
547
|
+
var minimumPollIntervalMs = 5e3;
|
|
548
|
+
var knownCategories = /* @__PURE__ */ new Set(["BAD_REQUEST", "CONFLICT", "EXPIRED_AUTHENTICATION", "INVALID_AUTHENTICATION", "MISSING_SCOPES", "OBJECT_ALREADY_EXISTS", "OBJECT_NOT_FOUND", "RATE_LIMITS", "VALIDATION_ERROR"]);
|
|
549
|
+
var HubSpotClient = class {
|
|
550
|
+
/**
|
|
551
|
+
* Validate settings and bind a credential source without contacting HubSpot. A blank endpoint uses
|
|
552
|
+
* https://api.hubapi.com, a zero maxResponseBytes uses one MiB, and a zero pollIntervalMs uses 30 seconds;
|
|
553
|
+
* pollIntervalMs must be at least 5 seconds.
|
|
554
|
+
*/
|
|
555
|
+
constructor(config, credentials, options = {}) {
|
|
556
|
+
this.credentials = credentials;
|
|
557
|
+
if (!credentials) throw new TypeError("HubSpot credential provider is required");
|
|
558
|
+
this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
|
|
559
|
+
this.maxResponseBytes = config.maxResponseBytes || 1048576;
|
|
560
|
+
if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("HubSpot maxResponseBytes must be positive");
|
|
561
|
+
this.pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
|
|
562
|
+
if (!Number.isFinite(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("HubSpot pollInterval must be at least 5s");
|
|
563
|
+
this.triggerLogger = options.logger ?? defaultTriggerLogger;
|
|
564
|
+
this.send = options.send ?? sendProviderRequest;
|
|
565
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
566
|
+
}
|
|
567
|
+
credentials;
|
|
568
|
+
endpoint;
|
|
569
|
+
maxResponseBytes;
|
|
570
|
+
send;
|
|
571
|
+
now;
|
|
572
|
+
/** Delay between crmObjectChanged polls in milliseconds. */
|
|
573
|
+
pollIntervalMs;
|
|
574
|
+
/** Trigger record destination. */
|
|
575
|
+
triggerLogger;
|
|
576
|
+
refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "HubSpot", auth: Authorization, credentialFields: CredentialFields });
|
|
577
|
+
/** Bind the search query. */
|
|
578
|
+
searchObjects() {
|
|
579
|
+
return new SearchObjectsOperation(this);
|
|
580
|
+
}
|
|
581
|
+
/** Bind the record query. */
|
|
582
|
+
getObject() {
|
|
583
|
+
return new GetObjectOperation(this);
|
|
584
|
+
}
|
|
585
|
+
/** Bind the unique-property upsert. */
|
|
586
|
+
upsertObject() {
|
|
587
|
+
return new UpsertObjectOperation(this);
|
|
588
|
+
}
|
|
589
|
+
/** Bind the absolute update. */
|
|
590
|
+
updateObject() {
|
|
591
|
+
return new UpdateObjectOperation(this);
|
|
592
|
+
}
|
|
593
|
+
/** Return a safe receipt for a completed provider attempt. */
|
|
594
|
+
receipt(call, response, objectId = "") {
|
|
595
|
+
const correlation = response ? header(response, "x-hubspot-correlation-id") : "";
|
|
596
|
+
return {
|
|
597
|
+
callId: call.id,
|
|
598
|
+
provider: "hubspot",
|
|
599
|
+
observedAt: this.now().toISOString(),
|
|
600
|
+
...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
|
|
601
|
+
...objectId ? { providerObjectId: objectId } : {},
|
|
602
|
+
.../^[A-Za-z0-9-]{1,64}$/.test(correlation) ? { providerRequestId: correlation } : {}
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
/** Resolve, send, refresh after one OAuth 401, then classify the response. */
|
|
606
|
+
async exchange(call, operation, objectId, method, path, query, body) {
|
|
607
|
+
let credentials;
|
|
608
|
+
try {
|
|
609
|
+
credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
|
|
610
|
+
this.validateCredentials(credentials);
|
|
611
|
+
} catch (error) {
|
|
612
|
+
if (error instanceof ReauthorizationRequiredError) return { outcome: this.failure("rejected", operation, "AUTHENTICATION", "HubSpot authorization must be renewed") };
|
|
613
|
+
if (error instanceof RetryError) return { outcome: this.failure("retry", operation, "AVAILABILITY", "HubSpot OAuth token refresh is temporarily unavailable") };
|
|
614
|
+
return { outcome: this.failure("defect", operation, "AUTHENTICATION", "HubSpot connection credentials are unavailable") };
|
|
615
|
+
}
|
|
616
|
+
let encoded;
|
|
617
|
+
try {
|
|
618
|
+
if (body !== void 0) encoded = Buffer.from(JSON.stringify(body));
|
|
619
|
+
} catch {
|
|
620
|
+
return { outcome: this.failure("defect", operation, "LOCAL_DEFECT", "HubSpot request could not be built") };
|
|
621
|
+
}
|
|
622
|
+
let response;
|
|
623
|
+
try {
|
|
624
|
+
response = await this.sendRequest(call, credentials, method, path, query, encoded);
|
|
625
|
+
if (response.status === 401 && credentials.authMethodId === "hubspot-oauth" && "resolveAfterRejection" in this.credentials) {
|
|
626
|
+
let replacement;
|
|
627
|
+
try {
|
|
628
|
+
const resolved = await resolveCredentialAfterRejection(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
|
|
629
|
+
this.validateCredentials(resolved);
|
|
630
|
+
replacement = resolved;
|
|
631
|
+
} catch {
|
|
632
|
+
}
|
|
633
|
+
if (replacement) response = await this.sendRequest(call, replacement, method, path, query, encoded);
|
|
634
|
+
}
|
|
635
|
+
} catch (error) {
|
|
636
|
+
const receipt = this.receipt(call, error instanceof BodyTooLargeError && error.headers ? { status: error.status ?? 0, headers: error.headers, body: new Uint8Array() } : void 0, objectId);
|
|
637
|
+
if (error instanceof BodyTooLargeError) return { outcome: this.failure("invalidResponse", operation, "RESPONSE_TOO_LARGE", "HubSpot response exceeds the configured size limit", receipt) };
|
|
638
|
+
return { outcome: this.failure("retry", operation, "TRANSPORT", "HubSpot did not return a complete response", receipt) };
|
|
639
|
+
}
|
|
640
|
+
if (response.status >= 200 && response.status < 300) return { response };
|
|
641
|
+
return { outcome: this.classify(operation, response, this.receipt(call, response, objectId)) };
|
|
642
|
+
}
|
|
643
|
+
validateCredentials(credentials) {
|
|
644
|
+
if (!(credentials.accessToken instanceof SecretString) || !isHeaderSafeCredential(credentials.accessToken.reveal())) throw new TypeError("HubSpot access token is missing or malformed");
|
|
645
|
+
}
|
|
646
|
+
sendRequest(call, credentials, method, path, query, body) {
|
|
647
|
+
return this.send({
|
|
648
|
+
url: `${this.endpoint}/${path}${query ? `?${query}` : ""}`,
|
|
649
|
+
method,
|
|
650
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${credentials.accessToken.reveal()}`, ...body ? { "Content-Type": "application/json" } : {} },
|
|
651
|
+
...body ? { body } : {},
|
|
652
|
+
maxResponseBytes: this.maxResponseBytes,
|
|
653
|
+
addressPolicy: this.endpoint.startsWith("http://") ? "privateNetworkHTTP" : "publicHTTPS",
|
|
654
|
+
timeoutMs: 25e3,
|
|
655
|
+
signal: call.context.cancellationSignal
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
/** Classify a batch upsert error using the same status rules as an HTTP error. */
|
|
659
|
+
classifyBatchError(operation, response, receipt) {
|
|
660
|
+
return this.classify(operation, response, receipt);
|
|
661
|
+
}
|
|
662
|
+
classify(operation, response, receipt) {
|
|
663
|
+
const status = response.status;
|
|
664
|
+
const errorBody = decodeErrorBody(response.body);
|
|
665
|
+
const retryAfter = parseRetryAfter(header(response, "retry-after"), this.now());
|
|
666
|
+
const detail = safeDetail(errorBody);
|
|
667
|
+
if (status === 429 && errorBody.policyName === "DAILY") return this.failure("rejected", operation, "QUOTA_EXHAUSTED", "HubSpot's daily API request limit is exhausted", receipt);
|
|
668
|
+
if (status === 429) return this.failure("retry", operation, "RATE_LIMIT", "HubSpot rate limited the request", receipt, Math.max(retryAfter, rateLimitDelay(header(response, "x-hubspot-ratelimit-interval-milliseconds"))));
|
|
669
|
+
if (status === 423) return this.failure("retry", operation, "RATE_LIMIT", "HubSpot locked the records for a high-volume sync", receipt, Math.max(retryAfter, 2e3));
|
|
670
|
+
if (status === 408 || status === 477 || status >= 500 && status !== 501) return this.failure("retry", operation, "AVAILABILITY", `HubSpot is temporarily unavailable (HTTP ${status})`, receipt, retryAfter);
|
|
671
|
+
if (status === 401) return this.failure("rejected", operation, "AUTHENTICATION", `HubSpot rejected the access token${detail}`, receipt);
|
|
672
|
+
if (status === 403 && errorBody.category === "MISSING_SCOPES") return this.failure("rejected", operation, "AUTHORIZATION", `HubSpot access token lacks a required scope${detail}`, receipt);
|
|
673
|
+
if (status === 403) return this.failure("rejected", operation, "AUTHORIZATION", `HubSpot denied access to the record${detail}`, receipt);
|
|
674
|
+
if (status === 404) return this.failure("notFound", operation, "NOT_FOUND", `HubSpot found no such record${detail}`, receipt);
|
|
675
|
+
if (status === 409) return this.failure("conflict", operation, "CONFLICT", `HubSpot reported a conflict with another record${detail}`, receipt);
|
|
676
|
+
if (status === 400 || status === 422 || errorBody.category === "VALIDATION_ERROR") return this.failure("rejected", operation, "VALIDATION", `HubSpot rejected the request as invalid${detail}`, receipt);
|
|
677
|
+
if (status >= 300 && status < 400) return this.failure("rejected", operation, "PROTOCOL", `HubSpot redirected the request (HTTP ${status})`, receipt);
|
|
678
|
+
return this.failure("rejected", operation, "PROVIDER_REJECTION", `HubSpot rejected the request (HTTP ${status})${detail}`, receipt);
|
|
679
|
+
}
|
|
680
|
+
failure(disposition, operation, kind, message, receipt = {}, retryAfterMs = 0) {
|
|
681
|
+
return { disposition, failure: { kind, provider: "hubspot", operation, message }, receipt, retryAfterMs };
|
|
682
|
+
}
|
|
683
|
+
};
|
|
684
|
+
function header(response, name) {
|
|
685
|
+
const value = response.headers[name];
|
|
686
|
+
return Array.isArray(value) ? value[0] ?? "" : value ?? "";
|
|
687
|
+
}
|
|
688
|
+
function rateLimitDelay(value) {
|
|
689
|
+
if (!/^[+-]?[0-9]+$/.test(value)) return 0;
|
|
690
|
+
const milliseconds = BigInt(value);
|
|
691
|
+
return milliseconds > 0n && milliseconds <= 9223372036854775807n ? Number(milliseconds > 10000n ? 10000n : milliseconds) : 0;
|
|
692
|
+
}
|
|
693
|
+
function decodeErrorBody(body) {
|
|
694
|
+
if (body.length > 65536) return {};
|
|
695
|
+
try {
|
|
696
|
+
const parsed = JSON.parse(Buffer.from(body).toString());
|
|
697
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
698
|
+
} catch {
|
|
699
|
+
return {};
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
function safeDetail(body) {
|
|
703
|
+
const tokens = [];
|
|
704
|
+
if (body.category && knownCategories.has(body.category)) tokens.push(body.category);
|
|
705
|
+
const code = body.errors?.[0]?.code;
|
|
706
|
+
if (typeof code === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(code) && code !== body.category) tokens.push(code);
|
|
707
|
+
return tokens.length ? ` (${tokens.join(", ")})` : "";
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// src/project.ts
|
|
711
|
+
function encodeCredentials(credentials) {
|
|
712
|
+
return {
|
|
713
|
+
auth_method: credentials.authMethodId ?? "",
|
|
714
|
+
access_token: credentials.accessToken.reveal(),
|
|
715
|
+
oauth_client_id: credentials.oauthClientId ?? "",
|
|
716
|
+
oauth_client_secret: credentials.oauthClientSecret?.reveal() ?? "",
|
|
717
|
+
refresh_token: credentials.refreshToken?.reveal() ?? ""
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
function newProjectConnection2(project, connectionName, options = {}) {
|
|
721
|
+
return newProjectConnection(project, connectionName, (loadedProject, name) => {
|
|
722
|
+
const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "hubspot" && entry.connectionName === name);
|
|
723
|
+
if (!selected) throw new TypeError("HubSpot project connection is not configured");
|
|
724
|
+
const { pollInterval, ...settings } = selected.configuration ?? {};
|
|
725
|
+
const config = ConfigSchema.parse({ ...settings, ...pollInterval === void 0 || pollInterval === null ? {} : { pollIntervalMs: pollIntervalMilliseconds(pollInterval) } });
|
|
726
|
+
return new HubSpotClient(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
function pollIntervalMilliseconds(value) {
|
|
730
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("HubSpot configuration pollInterval must be a whole number of nanoseconds");
|
|
731
|
+
return Math.floor(value / 1e6);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// src/crm_object_changed.ts
|
|
735
|
+
import { mustTriggerBindingDefinition } from "@superdurable/connectors-sdk";
|
|
736
|
+
import { z } from "zod";
|
|
737
|
+
|
|
738
|
+
// src/crm_object_change_search.ts
|
|
739
|
+
var MaximumSearchResults = 1e4;
|
|
740
|
+
var crmObjectChangePageSize = 100;
|
|
741
|
+
var rfc3339Pattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
|
|
742
|
+
function lastModifiedProperty(objectType) {
|
|
743
|
+
return objectType === "contacts" ? "lastmodifieddate" : "hs_lastmodifieddate";
|
|
744
|
+
}
|
|
745
|
+
function newCRMObjectChangeSearch(configuration, anchorMilliseconds, after) {
|
|
746
|
+
const modifiedProperty = lastModifiedProperty(configuration.objectType);
|
|
747
|
+
return {
|
|
748
|
+
objectType: configuration.objectType,
|
|
749
|
+
filterGroups: [{ filters: [{ propertyName: modifiedProperty, operator: "GTE", value: String(anchorMilliseconds) }] }],
|
|
750
|
+
sort: { propertyName: modifiedProperty, direction: "ASCENDING" },
|
|
751
|
+
properties: [...configuration.properties ?? [], "createdate", modifiedProperty],
|
|
752
|
+
limit: crmObjectChangePageSize,
|
|
753
|
+
...after ? { after } : {}
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
function parseRFC3339Milliseconds(text) {
|
|
757
|
+
const match = rfc3339Pattern.exec(text);
|
|
758
|
+
if (!match) return void 0;
|
|
759
|
+
const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
|
|
760
|
+
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month) || hour > 23 || minute > 59 || second > 59) return void 0;
|
|
761
|
+
let offsetMinutes = 0;
|
|
762
|
+
if (match[8] !== "Z") {
|
|
763
|
+
const offsetHours = Number(match[10]), offsetMinute = Number(match[11]);
|
|
764
|
+
if (offsetHours > 24 || offsetMinute > 60) return void 0;
|
|
765
|
+
offsetMinutes = (match[9] === "-" ? -1 : 1) * (offsetHours * 60 + offsetMinute);
|
|
766
|
+
}
|
|
767
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
768
|
+
date.setUTCFullYear(year, month - 1, day);
|
|
769
|
+
date.setUTCHours(hour, minute, second, 0);
|
|
770
|
+
const fractionMilliseconds = Math.floor(Number((match[7] ?? "").slice(0, 9).padEnd(9, "0") || "0") / 1e6);
|
|
771
|
+
return date.getTime() - offsetMinutes * 6e4 + fractionMilliseconds;
|
|
772
|
+
}
|
|
773
|
+
function formatGoTimeMilliseconds(milliseconds) {
|
|
774
|
+
return new Date(milliseconds).toISOString().replace(/\.(\d*?)0*Z$/, (_whole, digits) => digits ? `.${digits}Z` : "Z");
|
|
775
|
+
}
|
|
776
|
+
function recordModifiedMilliseconds(object) {
|
|
777
|
+
const value = object.properties?.[lastModifiedProperty(object.objectType)];
|
|
778
|
+
if (value !== void 0) {
|
|
779
|
+
const parsed = parseRFC3339Milliseconds(value);
|
|
780
|
+
if (parsed === void 0) throw new Error("HubSpot returned an invalid last-modified date");
|
|
781
|
+
return parsed;
|
|
782
|
+
}
|
|
783
|
+
const updated = object.updatedAt ? parseRFC3339Milliseconds(object.updatedAt) : void 0;
|
|
784
|
+
if (updated === void 0) throw new Error("HubSpot returned a record without a last-modified date");
|
|
785
|
+
return updated;
|
|
786
|
+
}
|
|
787
|
+
function recordCreatedMilliseconds(object) {
|
|
788
|
+
return (object.createdAt ? parseRFC3339Milliseconds(object.createdAt) : void 0) ?? Number.NEGATIVE_INFINITY;
|
|
789
|
+
}
|
|
790
|
+
function daysInMonth(year, month) {
|
|
791
|
+
if (month === 2) return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0 ? 29 : 28;
|
|
792
|
+
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// src/crm_object_changed.ts
|
|
796
|
+
var UIUnitObjectTypePicker = "objectTypePicker";
|
|
797
|
+
var UIObjectTypePickerPortObjectType = "objectType";
|
|
798
|
+
var maximumProperties = 100;
|
|
799
|
+
var MaximumTriggerProperties = maximumProperties - 2;
|
|
800
|
+
var CRMObjectChangeCreated = "created";
|
|
801
|
+
var CRMObjectChangeUpdated = "updated";
|
|
802
|
+
var CRMObjectChangedTriggerConfigurationSchema = z.strictObject({
|
|
803
|
+
objectType: z.string().nullable().optional().transform((value) => value ?? ""),
|
|
804
|
+
properties: z.array(z.string()).nullable().optional()
|
|
805
|
+
});
|
|
806
|
+
function validateCRMObjectChangedTriggerConfiguration(configuration) {
|
|
807
|
+
if (!configuration?.objectType) throw new Error("crmObjectChanged objectType is required");
|
|
808
|
+
if (!["contacts", "companies", "deals"].includes(configuration.objectType)) throw new Error("crmObjectChanged object type must be contacts, companies, or deals");
|
|
809
|
+
if ((configuration.properties ?? []).length > MaximumTriggerProperties) throw new Error(`crmObjectChanged allows at most ${MaximumTriggerProperties} properties`);
|
|
810
|
+
try {
|
|
811
|
+
searchBody(newCRMObjectChangeSearch(configuration, 0, String(MaximumSearchResults - crmObjectChangePageSize)));
|
|
812
|
+
} catch (error) {
|
|
813
|
+
throw new Error(`crmObjectChanged search: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
var CRMObjectChangedEventSchema = z.object({
|
|
817
|
+
objectType: z.enum(["contacts", "companies", "deals"]),
|
|
818
|
+
changeKind: z.enum([CRMObjectChangeCreated, CRMObjectChangeUpdated]),
|
|
819
|
+
modifiedAt: z.string().transform((value, context) => {
|
|
820
|
+
const milliseconds = parseRFC3339Milliseconds(value);
|
|
821
|
+
if (milliseconds === void 0) {
|
|
822
|
+
context.addIssue({ code: "custom", message: "modifiedAt must be an RFC 3339 time" });
|
|
823
|
+
return z.NEVER;
|
|
824
|
+
}
|
|
825
|
+
return formatGoTimeMilliseconds(milliseconds);
|
|
826
|
+
}),
|
|
827
|
+
object: CRMObjectSchema
|
|
828
|
+
});
|
|
829
|
+
var CRMObjectChangedTriggerDefinition = {
|
|
830
|
+
trigger: { connectorId: ConnectorID, triggerName: "crmObjectChanged" },
|
|
831
|
+
description: "Receive each HubSpot contact, company, or deal of one object type that is created or changed, read by polling CRM search on the last-modified date; the first run records a baseline and delivers no existing records."
|
|
832
|
+
};
|
|
833
|
+
function defineCRMObjectChangedTriggerBinding(config) {
|
|
834
|
+
return mustTriggerBindingDefinition({ definition: CRMObjectChangedTriggerDefinition, ...config });
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// src/crm_object_change_fetcher.ts
|
|
838
|
+
import { createHash } from "crypto";
|
|
839
|
+
import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
840
|
+
|
|
841
|
+
// src/crm_object_change_cursor.ts
|
|
842
|
+
var searchIndexLagWindowMs = 2 * 60 * 1e3;
|
|
843
|
+
var maximumSeenRecordVersions = 1500;
|
|
844
|
+
function lagWindowStart(position) {
|
|
845
|
+
return Math.max(position.floorMs + 1, position.highWaterMs - searchIndexLagWindowMs, position.droppedThroughMs + 1);
|
|
846
|
+
}
|
|
847
|
+
function pruneSeen(position) {
|
|
848
|
+
const windowStart = lagWindowStart(position);
|
|
849
|
+
const kept = [...position.seen].filter(([, modified]) => modified >= windowStart);
|
|
850
|
+
kept.sort(([leftID, left], [rightID, right]) => left !== right ? right - left : compareDecimalIDs(leftID, rightID));
|
|
851
|
+
if (kept.length > maximumSeenRecordVersions) {
|
|
852
|
+
position.droppedThroughMs = Math.max(position.droppedThroughMs, kept[maximumSeenRecordVersions][1]);
|
|
853
|
+
kept.length = maximumSeenRecordVersions;
|
|
854
|
+
}
|
|
855
|
+
position.seen = new Map(kept);
|
|
856
|
+
}
|
|
857
|
+
function compareDecimalIDs(left, right) {
|
|
858
|
+
if (left.length !== right.length) return left.length - right.length;
|
|
859
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
860
|
+
}
|
|
861
|
+
function encodeCRMObjectChangeCursor(position) {
|
|
862
|
+
let token = `{"objectType":${JSON.stringify(position.objectType)},"floorMs":${position.floorMs},"highWaterMs":${position.highWaterMs},"anchorMs":${position.anchorMs}`;
|
|
863
|
+
if (position.after) token += `,"after":${JSON.stringify(position.after)}`;
|
|
864
|
+
if (position.seen.size > 0) {
|
|
865
|
+
const keys = [...position.seen.keys()].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
|
|
866
|
+
token += `,"seen":{${keys.map((key) => `${JSON.stringify(key)}:${position.seen.get(key)}`).join(",")}}`;
|
|
867
|
+
}
|
|
868
|
+
if (position.droppedThroughMs !== 0) token += `,"droppedThroughMs":${position.droppedThroughMs}`;
|
|
869
|
+
return { token: `${token}}` };
|
|
870
|
+
}
|
|
871
|
+
var fieldNames = ["objectType", "floorMs", "highWaterMs", "anchorMs", "after", "seen", "droppedThroughMs"];
|
|
872
|
+
function decodeCRMObjectChangeCursor(token) {
|
|
873
|
+
const position = { objectType: "", floorMs: 0, highWaterMs: 0, anchorMs: 0, after: "", seen: /* @__PURE__ */ new Map(), droppedThroughMs: 0 };
|
|
874
|
+
try {
|
|
875
|
+
const decoded = JSON.parse(token, markNonIntegerLiterals);
|
|
876
|
+
if (decoded !== null) {
|
|
877
|
+
if (typeof decoded !== "object" || Array.isArray(decoded)) throw new TypeError("not an object");
|
|
878
|
+
for (const [key, value] of Object.entries(decoded)) {
|
|
879
|
+
const field = fieldNames.find((name) => name === key) ?? fieldNames.find((name) => name.toLowerCase() === key.toLowerCase());
|
|
880
|
+
if (!field || value === null) continue;
|
|
881
|
+
if (field === "objectType" || field === "after") position[field] = goString(value);
|
|
882
|
+
else if (field === "seen") position.seen = goSeen(value);
|
|
883
|
+
else position[field] = goInteger(value);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
} catch {
|
|
887
|
+
throw new Error("HubSpot change cursor is not decodable");
|
|
888
|
+
}
|
|
889
|
+
if (!["contacts", "companies", "deals"].includes(position.objectType)) throw new Error("HubSpot change cursor has no valid object type");
|
|
890
|
+
if (position.floorMs < 0 || position.highWaterMs < position.floorMs || position.anchorMs <= position.floorMs || position.droppedThroughMs < 0 || position.droppedThroughMs > position.highWaterMs) {
|
|
891
|
+
throw new Error("HubSpot change cursor times are inconsistent");
|
|
892
|
+
}
|
|
893
|
+
if (position.after && !cursor.test(position.after)) throw new Error("HubSpot change cursor has an invalid paging offset");
|
|
894
|
+
if (position.seen.size > maximumSeenRecordVersions) throw new Error("HubSpot change cursor holds too many record versions");
|
|
895
|
+
for (const objectID of position.seen.keys()) if (!recordId.test(objectID)) throw new Error("HubSpot change cursor has an invalid record ID");
|
|
896
|
+
return position;
|
|
897
|
+
}
|
|
898
|
+
var nonIntegerLiteral = /* @__PURE__ */ Symbol("nonIntegerLiteral");
|
|
899
|
+
var integerLiteral = /^-?(?:0|[1-9][0-9]*)$/;
|
|
900
|
+
function markNonIntegerLiterals(_key, value, context) {
|
|
901
|
+
if (typeof value === "number" && context?.source !== void 0 && !integerLiteral.test(context.source)) return nonIntegerLiteral;
|
|
902
|
+
return value;
|
|
903
|
+
}
|
|
904
|
+
function goString(value) {
|
|
905
|
+
if (typeof value !== "string") throw new TypeError("not a string");
|
|
906
|
+
return value;
|
|
907
|
+
}
|
|
908
|
+
function goInteger(value) {
|
|
909
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("not an integer");
|
|
910
|
+
return value;
|
|
911
|
+
}
|
|
912
|
+
function goSeen(value) {
|
|
913
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("not an object");
|
|
914
|
+
return new Map(Object.entries(value).map(([objectID, modified]) => [objectID, modified === null ? 0 : goInteger(modified)]));
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// src/crm_object_change_fetcher.ts
|
|
918
|
+
var crmObjectChangeOperation = "crmObjectChanged";
|
|
919
|
+
var CRMObjectChangeSearchError = class extends Error {
|
|
920
|
+
/** Wrap the classified failure of one search. */
|
|
921
|
+
constructor(failure) {
|
|
922
|
+
super(`HubSpot change search: ${failure.message}`);
|
|
923
|
+
this.failure = failure;
|
|
924
|
+
this.name = "CRMObjectChangeSearchError";
|
|
925
|
+
}
|
|
926
|
+
failure;
|
|
927
|
+
};
|
|
928
|
+
var CRMObjectChangeFetcher = class {
|
|
929
|
+
/** Bind the client, the connection whose credentials each poll resolves, and the validated configuration. */
|
|
930
|
+
constructor(client, connection, configuration) {
|
|
931
|
+
this.client = client;
|
|
932
|
+
this.connection = connection;
|
|
933
|
+
this.configuration = configuration;
|
|
934
|
+
}
|
|
935
|
+
client;
|
|
936
|
+
connection;
|
|
937
|
+
configuration;
|
|
938
|
+
/**
|
|
939
|
+
* Read the newest last-modified date, so every existing record becomes the baseline. An object type without
|
|
940
|
+
* records seeds at zero, so every later record is delivered.
|
|
941
|
+
*/
|
|
942
|
+
async seedCursor(context) {
|
|
943
|
+
const objectType = this.configuration.objectType;
|
|
944
|
+
const modifiedProperty = lastModifiedProperty(objectType);
|
|
945
|
+
const page = await this.search(context, { objectType, properties: [modifiedProperty], limit: 1, sort: { propertyName: modifiedProperty, direction: "DESCENDING" } });
|
|
946
|
+
const floor = page.objects?.[0] ? recordModifiedMilliseconds(page.objects[0]) : 0;
|
|
947
|
+
return encodeCRMObjectChangeCursor({ objectType, floorMs: floor, highWaterMs: floor, anchorMs: floor + 1, after: "", seen: /* @__PURE__ */ new Map(), droppedThroughMs: 0 });
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Read one search page after cursor. An undecodable cursor, a cursor for another object type, and a paging
|
|
951
|
+
* offset HubSpot rejects are marked invalid, so the kit records a new baseline.
|
|
952
|
+
*/
|
|
953
|
+
async fetchChanges(context, cursor2) {
|
|
954
|
+
let position;
|
|
955
|
+
try {
|
|
956
|
+
position = decodeCRMObjectChangeCursor(cursor2.token);
|
|
957
|
+
} catch (error) {
|
|
958
|
+
throw markCursorInvalid(error);
|
|
959
|
+
}
|
|
960
|
+
if (position.objectType !== this.configuration.objectType) throw markCursorInvalid(new Error("HubSpot change cursor belongs to another object type"));
|
|
961
|
+
let page;
|
|
962
|
+
try {
|
|
963
|
+
page = await this.search(context, newCRMObjectChangeSearch(this.configuration, position.anchorMs, position.after));
|
|
964
|
+
} catch (error) {
|
|
965
|
+
if (position.after && error instanceof CRMObjectChangeSearchError && error.failure.kind === "VALIDATION") {
|
|
966
|
+
throw markCursorInvalid(new Error(`HubSpot rejected the change search offset: ${error.message}`, { cause: error }));
|
|
967
|
+
}
|
|
968
|
+
throw error;
|
|
969
|
+
}
|
|
970
|
+
const next = { ...position, seen: new Map(position.seen) };
|
|
971
|
+
const changes = [];
|
|
972
|
+
let pageNewest = position.anchorMs;
|
|
973
|
+
for (const object of page.objects ?? []) {
|
|
974
|
+
const modified = recordModifiedMilliseconds(object);
|
|
975
|
+
pageNewest = Math.max(pageNewest, modified);
|
|
976
|
+
const delivered = next.seen.get(object.id);
|
|
977
|
+
if (delivered !== void 0 && delivered >= modified || modified <= position.floorMs) continue;
|
|
978
|
+
const kind = recordCreatedMilliseconds(object) > position.highWaterMs ? CRMObjectChangeCreated : CRMObjectChangeUpdated;
|
|
979
|
+
const modifiedAt = formatGoTimeMilliseconds(modified);
|
|
980
|
+
changes.push({
|
|
981
|
+
id: crmObjectChangeID(object.objectType, object.id, modified),
|
|
982
|
+
occurredAt: new Date(modified),
|
|
983
|
+
payload: { objectType: this.configuration.objectType, changeKind: kind, modifiedAt, object }
|
|
984
|
+
});
|
|
985
|
+
next.seen.set(object.id, modified);
|
|
986
|
+
next.highWaterMs = Math.max(next.highWaterMs, modified);
|
|
987
|
+
}
|
|
988
|
+
pruneSeen(next);
|
|
989
|
+
let hasMorePages = false;
|
|
990
|
+
if (page.nextAfter && pageNewest > position.anchorMs) {
|
|
991
|
+
next.anchorMs = pageNewest;
|
|
992
|
+
next.after = "";
|
|
993
|
+
hasMorePages = true;
|
|
994
|
+
} else if (page.nextAfter) {
|
|
995
|
+
if (Number(page.nextAfter) + crmObjectChangePageSize > MaximumSearchResults) {
|
|
996
|
+
throw markCursorInvalid(new Error(`more than ${MaximumSearchResults} HubSpot records share one last-modified time`));
|
|
997
|
+
}
|
|
998
|
+
next.after = page.nextAfter;
|
|
999
|
+
hasMorePages = true;
|
|
1000
|
+
} else {
|
|
1001
|
+
next.anchorMs = lagWindowStart(next);
|
|
1002
|
+
next.after = "";
|
|
1003
|
+
}
|
|
1004
|
+
return { changes, next: encodeCRMObjectChangeCursor(next), hasMorePages };
|
|
1005
|
+
}
|
|
1006
|
+
/** Send one CRM search; 429, 423, and the daily limit pause the whole connection. */
|
|
1007
|
+
async search(context, input) {
|
|
1008
|
+
let body;
|
|
1009
|
+
try {
|
|
1010
|
+
body = searchBody(input);
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
throw new Error(`hubspot crmObjectChanged configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1013
|
+
}
|
|
1014
|
+
await waitForPollRequest(context);
|
|
1015
|
+
const call = newTriggerCredentialCall(this.connection, CRMObjectChangedTriggerDefinition.trigger, context.signal);
|
|
1016
|
+
const result = await this.client.exchange(call, crmObjectChangeOperation, "", "POST", objectsPath(input.objectType, "search"), void 0, body);
|
|
1017
|
+
if ("outcome" in result) {
|
|
1018
|
+
const failure = new CRMObjectChangeSearchError(result.outcome.failure);
|
|
1019
|
+
if (result.outcome.failure.kind === "RATE_LIMIT") throw markRateLimited(failure, result.outcome.retryAfterMs);
|
|
1020
|
+
if (result.outcome.failure.kind === "QUOTA_EXHAUSTED") throw markRateLimited(failure, 0);
|
|
1021
|
+
throw failure;
|
|
1022
|
+
}
|
|
1023
|
+
let page;
|
|
1024
|
+
try {
|
|
1025
|
+
page = decodeObjectPage(input.objectType, result.response.body);
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
throw new Error(`HubSpot change search returned an invalid page: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1028
|
+
}
|
|
1029
|
+
const limit = input.limit ?? 0;
|
|
1030
|
+
if ((page.objects?.length ?? 0) > limit) throw new Error(`HubSpot change search returned ${page.objects?.length ?? 0} records, more than ${limit}`);
|
|
1031
|
+
return page;
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
function crmObjectChangeID(objectType, objectID, modifiedMilliseconds) {
|
|
1035
|
+
const digest = createHash("sha256").update([objectType, objectID, String(modifiedMilliseconds)].join("\0")).digest();
|
|
1036
|
+
return `hubspot-${digest.subarray(0, 16).toString("hex")}`;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// src/trigger.ts
|
|
1040
|
+
import { newTrigger } from "@superdurable/connectors-sdk";
|
|
1041
|
+
import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
1042
|
+
import { ObjectNotFoundError, decodeTriggerConfiguration, newDurableTriggerTarget, parseTriggerPayloadJSON } from "@superdurable/connectors-sdk/projectconfig";
|
|
1043
|
+
function newCRMObjectTriggerRunner(config) {
|
|
1044
|
+
const client = hubSpotClientOf(config.connection);
|
|
1045
|
+
if (!config.crmObjectChangedRoutes?.length) throw new TypeError("HubSpot crmObjectChanged routes are required");
|
|
1046
|
+
const pollers = config.crmObjectChangedRoutes.map((route) => newCRMObjectChangedPoller(client, config.connection.reference, route));
|
|
1047
|
+
return newRunner({ connection: config.connection.reference, schedule: { intervalMs: client.pollIntervalMs }, pollers, logger: client.triggerLogger });
|
|
1048
|
+
}
|
|
1049
|
+
function newProjectCRMObjectTriggerRunner(project, connectionName, config, options = {}) {
|
|
1050
|
+
const connection = newProjectConnection2(project, connectionName, options);
|
|
1051
|
+
const client = hubSpotClientOf(connection);
|
|
1052
|
+
const triggerName = CRMObjectChangedTriggerDefinition.trigger.triggerName;
|
|
1053
|
+
const routes = (config.crmObjectChangedRoutes ?? []).map((route) => {
|
|
1054
|
+
if (!route.target) throw new TypeError(`HubSpot crmObjectChanged binding "${route.bindingName}" target is required`);
|
|
1055
|
+
const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName, bindingName: route.bindingName };
|
|
1056
|
+
let configuration;
|
|
1057
|
+
try {
|
|
1058
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, CRMObjectChangedTriggerConfigurationSchema);
|
|
1059
|
+
} catch (error) {
|
|
1060
|
+
if (error instanceof ObjectNotFoundError) throw new Error(`hubspot crmObjectChanged binding "${route.bindingName}" has no saved object type; pick one in Dex Web`);
|
|
1061
|
+
throw new Error(`hubspot crmObjectChanged binding "${route.bindingName}" configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1062
|
+
}
|
|
1063
|
+
if (!configuration.properties?.length && route.properties) configuration = { ...configuration, properties: route.properties };
|
|
1064
|
+
const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, {
|
|
1065
|
+
logger: client.triggerLogger,
|
|
1066
|
+
decodePayload: (_payloadJSON, payloadBytes) => CRMObjectChangedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes))
|
|
1067
|
+
});
|
|
1068
|
+
return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
|
|
1069
|
+
});
|
|
1070
|
+
return newCRMObjectTriggerRunner({ connection, crmObjectChangedRoutes: routes });
|
|
1071
|
+
}
|
|
1072
|
+
function newCRMObjectChangedTrigger(config) {
|
|
1073
|
+
const client = hubSpotClientOf(config.connection);
|
|
1074
|
+
const reference = config.connection.reference;
|
|
1075
|
+
if (config.connectionName !== reference.name) throw new TypeError(`hubspot connector trigger connectionName "${config.connectionName}" must equal its connection's name "${reference.name}"`);
|
|
1076
|
+
validateConfiguration(config.configuration);
|
|
1077
|
+
const definition = CRMObjectChangedTriggerDefinition;
|
|
1078
|
+
const source = newBindingTriggerSource({
|
|
1079
|
+
definition,
|
|
1080
|
+
binding: { connection: reference, trigger: definition.trigger, name: definition.trigger.triggerName },
|
|
1081
|
+
cursor: newMemoryCursorStore(),
|
|
1082
|
+
fetcher: new CRMObjectChangeFetcher(client, reference, config.configuration)
|
|
1083
|
+
}, { intervalMs: client.pollIntervalMs }, client.triggerLogger);
|
|
1084
|
+
return newTrigger({ definition, binding: { connection: reference, trigger: definition.trigger, name: config.bindingName }, source, target: config.target, logger: client.triggerLogger });
|
|
1085
|
+
}
|
|
1086
|
+
function newCRMObjectChangedPoller(client, connection, route) {
|
|
1087
|
+
if (!route.bindingName?.trim() || !route.target) throw new TypeError("HubSpot crmObjectChanged binding name and target are required");
|
|
1088
|
+
validateConfiguration(route.configuration);
|
|
1089
|
+
const definition = CRMObjectChangedTriggerDefinition;
|
|
1090
|
+
return newBindingPoller({
|
|
1091
|
+
definition,
|
|
1092
|
+
binding: { connection, trigger: definition.trigger, name: route.bindingName },
|
|
1093
|
+
cursor: route.cursor ?? newMemoryCursorStore(),
|
|
1094
|
+
fetcher: new CRMObjectChangeFetcher(client, connection, route.configuration),
|
|
1095
|
+
target: route.target
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
function validateConfiguration(configuration) {
|
|
1099
|
+
try {
|
|
1100
|
+
validateCRMObjectChangedTriggerConfiguration(configuration);
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
throw new Error(`hubspot crmObjectChanged configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
function hubSpotClientOf(connection) {
|
|
1106
|
+
if (!(connection?.operations instanceof HubSpotClient)) throw new TypeError("HubSpot Triggers require a connection from newProjectConnection or newConnection with a HubSpotClient");
|
|
1107
|
+
return connection.operations;
|
|
1108
|
+
}
|
|
1109
|
+
export {
|
|
1110
|
+
CRMObjectChangeCreated,
|
|
1111
|
+
CRMObjectChangeSearchError,
|
|
1112
|
+
CRMObjectChangeUpdated,
|
|
1113
|
+
CRMObjectChangedEventSchema,
|
|
1114
|
+
CRMObjectChangedTriggerConfigurationSchema,
|
|
1115
|
+
CRMObjectChangedTriggerDefinition,
|
|
1116
|
+
CRMObjectSchema,
|
|
1117
|
+
ConfigSchema,
|
|
1118
|
+
Connection,
|
|
1119
|
+
ConnectorID,
|
|
1120
|
+
GetObjectBranch,
|
|
1121
|
+
GetObjectBranchDefect,
|
|
1122
|
+
GetObjectBranchFound,
|
|
1123
|
+
GetObjectBranchInvalidResponse,
|
|
1124
|
+
GetObjectBranchNotFound,
|
|
1125
|
+
GetObjectBranchProviderRejected,
|
|
1126
|
+
GetObjectDefinition,
|
|
1127
|
+
GetObjectInputSchema,
|
|
1128
|
+
GetObjectMetadata,
|
|
1129
|
+
GetObjectOperation,
|
|
1130
|
+
HubSpotClient,
|
|
1131
|
+
MaximumTriggerProperties,
|
|
1132
|
+
ObjectPageSchema,
|
|
1133
|
+
ProviderID,
|
|
1134
|
+
SearchFilterGroupSchema,
|
|
1135
|
+
SearchFilterSchema,
|
|
1136
|
+
SearchObjectsBranch,
|
|
1137
|
+
SearchObjectsBranchDefect,
|
|
1138
|
+
SearchObjectsBranchInvalidResponse,
|
|
1139
|
+
SearchObjectsBranchProviderRejected,
|
|
1140
|
+
SearchObjectsBranchSearched,
|
|
1141
|
+
SearchObjectsDefinition,
|
|
1142
|
+
SearchObjectsInputSchema,
|
|
1143
|
+
SearchObjectsMetadata,
|
|
1144
|
+
SearchObjectsOperation,
|
|
1145
|
+
SearchSortSchema,
|
|
1146
|
+
UIObjectTypePickerPortObjectType,
|
|
1147
|
+
UIUnitObjectTypePicker,
|
|
1148
|
+
UpdateObjectBranch,
|
|
1149
|
+
UpdateObjectBranchConflict,
|
|
1150
|
+
UpdateObjectBranchDefect,
|
|
1151
|
+
UpdateObjectBranchInvalidResponse,
|
|
1152
|
+
UpdateObjectBranchNotFound,
|
|
1153
|
+
UpdateObjectBranchProviderRejected,
|
|
1154
|
+
UpdateObjectBranchUpdated,
|
|
1155
|
+
UpdateObjectDefinition,
|
|
1156
|
+
UpdateObjectInputSchema,
|
|
1157
|
+
UpdateObjectMetadata,
|
|
1158
|
+
UpdateObjectOperation,
|
|
1159
|
+
UpsertObjectBranch,
|
|
1160
|
+
UpsertObjectBranchConflict,
|
|
1161
|
+
UpsertObjectBranchDefect,
|
|
1162
|
+
UpsertObjectBranchInvalidResponse,
|
|
1163
|
+
UpsertObjectBranchProviderRejected,
|
|
1164
|
+
UpsertObjectBranchUpserted,
|
|
1165
|
+
UpsertObjectDefinition,
|
|
1166
|
+
UpsertObjectInputSchema,
|
|
1167
|
+
UpsertObjectMetadata,
|
|
1168
|
+
UpsertObjectOperation,
|
|
1169
|
+
UpsertedObjectSchema,
|
|
1170
|
+
decodeCredentials,
|
|
1171
|
+
decodeSharedCredentials,
|
|
1172
|
+
defineCRMObjectChangedTriggerBinding,
|
|
1173
|
+
newCRMObjectChangedTrigger,
|
|
1174
|
+
newCRMObjectTriggerRunner,
|
|
1175
|
+
newConnection,
|
|
1176
|
+
newConnectionWithOperations,
|
|
1177
|
+
newGetObjectStep,
|
|
1178
|
+
newProjectCRMObjectTriggerRunner,
|
|
1179
|
+
newProjectConnection2 as newProjectConnection,
|
|
1180
|
+
newSearchObjectsStep,
|
|
1181
|
+
newUpdateObjectStep,
|
|
1182
|
+
newUpsertObjectStep,
|
|
1183
|
+
validateCRMObjectChangedTriggerConfiguration
|
|
1184
|
+
};
|