-
Notifications
You must be signed in to change notification settings - Fork 418
/
index.ts
258 lines (215 loc) · 7.21 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import {
TriggerIntegration,
RunTaskOptions,
IO,
IOTask,
IntegrationTaskKey,
RunTaskErrorCallback,
Json,
retry,
ConnectionAuth,
} from "@trigger.dev/sdk";
import { OmitIndexSignature } from "@trigger.dev/integration-kit";
import {
ApiVersion,
HttpRetriableError,
HttpThrottlingError,
LATEST_API_VERSION,
LogSeverity,
Session,
shopifyApi,
ShopifyError,
} from "@shopify/shopify-api";
// this has to be updated manually with each LATEST_API_VERSION bump
import { restResources, type RestResources } from "@shopify/shopify-api/rest/admin/2023-10";
import { ApiScope } from "./schemas";
import { createWebhookEventCatalog, WebhookEventCatalog } from "./triggers";
import { Webhooks, createWebhookEventSource } from "./webhooks";
import { Rest, restProxy } from "./rest";
export type ShopifyRestResources = OmitIndexSignature<RestResources>;
export type ShopifyIntegrationOptions = {
id: string;
apiKey: string;
apiSecretKey: string;
apiVersion?: ApiVersion;
adminAccessToken: string;
hostName: string;
restResources?: RestResources;
scopes?: ApiScope[];
session?: Session;
};
export type ShopifyRunTask = InstanceType<typeof Shopify>["runTask"];
type EventNamesFromCatalog<TEventCatalog extends WebhookEventCatalog<any, any>> =
TEventCatalog extends WebhookEventCatalog<infer U, any> ? keyof U : never;
export class Shopify implements TriggerIntegration {
private _options: ShopifyIntegrationOptions;
private _client?: ReturnType<(typeof this)["createClient"]>;
private _io?: IO;
private _connectionKey?: string;
private _session?: Session;
private _shopDomain: string;
constructor(private options: ShopifyIntegrationOptions) {
if (Object.keys(options).includes("apiKey") && !options.apiKey) {
throw `Can't create Shopify integration (${options.id}) as apiKey was undefined`;
}
if (Object.keys(options).includes("apiSecretKey") && !options.apiSecretKey) {
throw `Can't create Shopify integration (${options.id}) as apiSecretKey was undefined`;
}
if (Object.keys(options).includes("adminAccessToken") && !options.adminAccessToken) {
throw `Can't create Shopify integration (${options.id}) as adminAccessToken was undefined`;
}
if (Object.keys(options).includes("hostName") && !options.hostName) {
throw `Can't create Shopify integration (${options.id}) as hostName was undefined`;
}
this._options = options;
// Extract the shop domain if user has entered the full URL
this._shopDomain = this._options.hostName
.replace(/^https?:\/\//, "") // Remove http:// or https://
.replace(/\/$/, ""); // Remove trailing slash if it exists (e.g. `example.myshopify.com/`)
// Regular expression to ensure the shopDomain is a valid `.myshopify.com` domain
const shopifyDomainPattern = /^[a-zA-Z0-9-]+\.myshopify\.com$/;
if (!shopifyDomainPattern.test(this._shopDomain)) {
throw `Can't create Shopify integration (${options.id}) because hostName should be a valid ".myshopify.com" domain, not a custom primary domain. For example: my-domain.myshopify.com`;
}
}
get authSource() {
return this._options.apiKey ? "LOCAL" : "HOSTED";
}
get id() {
return this.options.id;
}
get metadata() {
return { id: "shopify", name: "Shopify" };
}
get #source() {
return createWebhookEventSource(this);
}
get #eventCatalog() {
return createWebhookEventCatalog(this.#source);
}
cloneForRun(io: IO, connectionKey: string, auth?: ConnectionAuth) {
const shopify = new Shopify(this._options);
const client = this.createClient(auth);
const session = client.session.customAppSession(client.config.hostName);
session.accessToken = client.config.adminApiAccessToken;
shopify._io = io;
shopify._connectionKey = connectionKey;
shopify._client = client;
shopify._session = this._options.session ?? session;
return shopify;
}
createClient(auth?: ConnectionAuth) {
// oauth
// if (auth) {
// return shopifyApi({
// apiKey: this._options.apiKey,
// apiSecretKey: auth.accessToken,
// adminApiAccessToken: this._options.adminAccessToken,
// apiVersion: this._options.apiVersion ?? LATEST_API_VERSION,
// hostName: this._shopDomain,
// scopes: auth.scopes,
// restResources: this._options.restResources ?? restResources,
// isCustomStoreApp: false,
// isEmbeddedApp: true,
// logger: {
// level: LogSeverity.Warning,
// },
// });
// }
// apiKey auth
if (this._options.apiKey) {
return shopifyApi({
apiKey: this._options.apiKey,
apiSecretKey: this._options.apiSecretKey,
adminApiAccessToken: this._options.adminAccessToken,
apiVersion: this._options.apiVersion ?? LATEST_API_VERSION,
hostName: this._shopDomain,
scopes: this._options.scopes,
restResources: this._options.restResources ?? restResources,
isCustomStoreApp: true,
isEmbeddedApp: false,
logger: {
level: LogSeverity.Warning,
},
});
}
throw new Error("No auth");
}
runTask<T, TResult extends Json<T> | void>(
key: IntegrationTaskKey,
callback: (
client: ReturnType<Shopify["createClient"]>,
task: IOTask,
io: IO,
session: Session
) => Promise<TResult>,
options?: RunTaskOptions,
errorCallback?: RunTaskErrorCallback
): Promise<TResult> {
if (!this._io) throw new Error("No IO");
if (!this._connectionKey) throw new Error("No connection key");
return this._io.runTask<TResult>(
key,
(task, io) => {
if (!this._client) throw new Error("No client");
if (!this._session) throw new Error("No session");
return callback(this._client, task, io, this._session);
},
{
icon: "shopify",
retry: retry.standardBackoff,
...(options ?? {}),
connectionKey: this._connectionKey,
},
errorCallback ?? onError
);
}
/**
* Creates a webhook trigger.
*/
on<TName extends EventNamesFromCatalog<ReturnType<typeof createWebhookEventCatalog>>>(
name: TName
// additional params have been disabled, see WebhookSource schema
// params?: Omit<GetWebhookParams<ReturnType<typeof createWebhookEventSource>>, "topic">
) {
return this.#eventCatalog.on(name, { topic: name });
}
get #webhooks() {
return new Webhooks(this.runTask.bind(this));
}
get rest() {
if (!this._session) {
throw new Error("No session");
}
return restProxy(
new Rest(this.runTask.bind(this), this._session),
this._session,
this.runTask.bind(this)
);
}
}
export function onError(error: unknown): ReturnType<RunTaskErrorCallback> {
if (!(error instanceof ShopifyError)) {
return;
}
if (!(error instanceof HttpRetriableError)) {
return {
skipRetrying: true,
};
}
if (!(error instanceof HttpThrottlingError)) {
return;
}
const retryAfter = error.response.retryAfter;
if (retryAfter) {
const retryAfterMs = Number(retryAfter) * 1000;
if (Number.isNaN(retryAfterMs)) {
return;
}
const resetDate = new Date(Date.now() + retryAfterMs);
return {
retryAt: resetDate,
error,
};
}
}