apibara 2.0.0-beta.40 → 2.0.0-beta.41

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.
@@ -0,0 +1,412 @@
1
+ import fs from "node:fs";
2
+ import path, { basename } from "node:path";
3
+ import prompts from "prompts";
4
+ import { blue, cyan, red, yellow } from "./colors";
5
+ import { dnaUrls, networks } from "./constants";
6
+ import type { Chain, Language, Network, PkgInfo } from "./types";
7
+
8
+ export function isEmpty(path: string) {
9
+ const files = fs.readdirSync(path);
10
+ return files.length === 0 || (files.length === 1 && files[0] === ".git");
11
+ }
12
+ export function emptyDir(dir: string) {
13
+ if (!fs.existsSync(dir)) {
14
+ return;
15
+ }
16
+ for (const file of fs.readdirSync(dir)) {
17
+ if (file === ".git") {
18
+ continue;
19
+ }
20
+ fs.rmSync(path.resolve(dir, file), { recursive: true, force: true });
21
+ }
22
+ }
23
+
24
+ export function validateLanguage(language?: string, throwError = false) {
25
+ if (!language) {
26
+ return false;
27
+ }
28
+
29
+ if (
30
+ language === "typescript" ||
31
+ language === "ts" ||
32
+ language === "javascript" ||
33
+ language === "js"
34
+ ) {
35
+ return true;
36
+ }
37
+
38
+ if (throwError) {
39
+ throw new Error(
40
+ `Invalid language ${cyan("(--language | -l)")}: ${red(language)}. Options: ${blue("typescript, ts")} or ${yellow("javascript, js")} | default: ${cyan("typescript")}`,
41
+ );
42
+ }
43
+
44
+ return false;
45
+ }
46
+
47
+ export function getLanguageFromAlias(alias: string): Language {
48
+ if (alias === "ts" || alias === "typescript") {
49
+ return "typescript";
50
+ }
51
+ if (alias === "js" || alias === "javascript") {
52
+ return "javascript";
53
+ }
54
+
55
+ throw new Error(
56
+ `Invalid language ${cyan("(--language | -l)")}: ${red(alias)}. Options: ${blue("typescript, ts")} or ${yellow("javascript, js")}`,
57
+ );
58
+ }
59
+
60
+ export function validateIndexerId(indexerId?: string, throwError = false) {
61
+ if (!indexerId) {
62
+ return false;
63
+ }
64
+ if (!/^[a-z0-9-]+$/.test(indexerId)) {
65
+ if (throwError) {
66
+ throw new Error(
67
+ `Invalid indexer ID ${cyan("(--indexer-id)")}: ${red(indexerId)}. Indexer ID must contain only lowercase letters, numbers, and hyphens.`,
68
+ );
69
+ }
70
+ return false;
71
+ }
72
+ return true;
73
+ }
74
+
75
+ export function validateChain(chain?: string, throwError = false) {
76
+ if (!chain) {
77
+ return false;
78
+ }
79
+ if (chain) {
80
+ if (chain === "starknet" || chain === "ethereum" || chain === "beaconchain")
81
+ return true;
82
+ if (throwError) {
83
+ throw new Error(
84
+ `Invalid chain ${cyan("(--chain)")}: ${red(chain)}. Chain must be one of ${blue("starknet, ethereum, beaconchain")}.`,
85
+ );
86
+ }
87
+ return false;
88
+ }
89
+ return true;
90
+ }
91
+
92
+ export function validateNetwork(
93
+ chain?: string,
94
+ network?: string,
95
+ throwError = false,
96
+ ) {
97
+ if (!network) {
98
+ return false;
99
+ }
100
+
101
+ if (network === "other") {
102
+ return true;
103
+ }
104
+
105
+ if (chain) {
106
+ if (chain === "starknet") {
107
+ if (network === "mainnet" || network === "sepolia") {
108
+ return true;
109
+ }
110
+ if (throwError) {
111
+ throw new Error(
112
+ `Invalid network ${cyan("(--network)")}: ${red(network)}. For chain ${blue("starknet")}, network must be one of ${blue("mainnet, sepolia, other")}.`,
113
+ );
114
+ }
115
+ return false;
116
+ }
117
+ if (chain === "ethereum") {
118
+ if (network === "mainnet" || network === "goerli") {
119
+ return true;
120
+ }
121
+ if (throwError) {
122
+ throw new Error(
123
+ `Invalid network ${cyan("(--network)")}: ${red(network)}. For chain ${blue("ethereum")}, network must be one of ${blue("mainnet, goerli, other")}.`,
124
+ );
125
+ }
126
+ return false;
127
+ }
128
+ if (chain === "beaconchain") {
129
+ if (network === "mainnet") {
130
+ return true;
131
+ }
132
+ if (throwError) {
133
+ throw new Error(
134
+ `Invalid network ${cyan("(--network)")}: ${red(network)}. For chain ${blue("beaconchain")}, network must be ${blue("mainnet, other")}.`,
135
+ );
136
+ }
137
+ return false;
138
+ }
139
+ }
140
+
141
+ if (networks.find((n) => n.name === network)) {
142
+ return true;
143
+ }
144
+
145
+ if (throwError) {
146
+ throw new Error(
147
+ `Invalid network ${cyan("(--network)")}: ${red(network)}. Network must be one of ${blue("mainnet, sepolia, goerli, other")}.`,
148
+ );
149
+ }
150
+ return false;
151
+ }
152
+
153
+ export function validateStorage(storage?: string, throwError = false) {
154
+ if (!storage) {
155
+ return false;
156
+ }
157
+ if (storage === "postgres" || storage === "none") {
158
+ return true;
159
+ }
160
+ if (throwError) {
161
+ throw new Error(
162
+ `Invalid storage ${cyan("(--storage)")}: ${red(storage)}. Storage must be one of ${blue("postgres, none")}.`,
163
+ );
164
+ }
165
+ return false;
166
+ }
167
+
168
+ export function validateDnaUrl(dnaUrl?: string, throwError = false) {
169
+ if (!dnaUrl) {
170
+ return false;
171
+ }
172
+ if (!dnaUrl.startsWith("https://") && !dnaUrl.startsWith("http://")) {
173
+ if (throwError) {
174
+ throw new Error(
175
+ `Invalid DNA URL ${cyan("(--dna-url)")}: ${red(dnaUrl)}. DNA URL must start with ${blue("https:// or http://")}.`,
176
+ );
177
+ }
178
+ return false;
179
+ }
180
+ return true;
181
+ }
182
+
183
+ export function hasApibaraConfig(cwd: string): boolean {
184
+ const configPathJS = path.join(cwd, "apibara.config.js");
185
+ const configPathTS = path.join(cwd, "apibara.config.ts");
186
+
187
+ return fs.existsSync(configPathJS) || fs.existsSync(configPathTS);
188
+ }
189
+
190
+ export function getApibaraConfigLanguage(cwd: string): Language {
191
+ const configPathJS = path.join(cwd, "apibara.config.js");
192
+ const configPathTS = path.join(cwd, "apibara.config.ts");
193
+
194
+ if (fs.existsSync(configPathJS)) {
195
+ return "javascript";
196
+ }
197
+ if (fs.existsSync(configPathTS)) {
198
+ return "typescript";
199
+ }
200
+
201
+ throw new Error(red("✖") + " No apibara.config found");
202
+ }
203
+
204
+ export function getDnaUrl(chain: Chain, network: Network) {
205
+ if (chain === "ethereum") {
206
+ if (network === "mainnet") {
207
+ return dnaUrls.ethereum;
208
+ }
209
+ if (network === "sepolia") {
210
+ return dnaUrls.ethereumSepolia;
211
+ }
212
+ }
213
+
214
+ if (chain === "beaconchain") {
215
+ if (network === "mainnet") {
216
+ return dnaUrls.beaconchain;
217
+ }
218
+ }
219
+
220
+ if (chain === "starknet") {
221
+ if (network === "mainnet") {
222
+ return dnaUrls.starknet;
223
+ }
224
+ if (network === "sepolia") {
225
+ return dnaUrls.starknetSepolia;
226
+ }
227
+ }
228
+
229
+ throw new Error(red("✖") + " Invalid chain or network");
230
+ }
231
+
232
+ /**
233
+ * Converts a kebab-case string to camelCase.
234
+ *
235
+ * Examples:
236
+ * - "hello-world" → "helloWorld"
237
+ * - "my-long-variable-name" → "myLongVariableName"
238
+ * - "MY-CAPS" → "myCaps"
239
+ * - "-leading-dash" → "leadingDash"
240
+ * - "trailing-dash-" → "trailingDash"
241
+ * - "double--dash" → "doubleDash"
242
+ * - "hello---world" → "helloWorld"
243
+ * - "mixed_dash-and_underscore" → "mixedDashAndUnderscore"
244
+ *
245
+ * @param str The kebab-case string to convert
246
+ * @returns The camelCase version of the string
247
+ */
248
+ export function convertKebabToCamelCase(_str: string): string {
249
+ let str = _str;
250
+
251
+ // Handle empty or invalid input
252
+ if (!str || typeof str !== "string") {
253
+ return "";
254
+ }
255
+
256
+ // Check if already camelCase
257
+ if (/^[a-z][a-zA-Z0-9]*$/.test(str)) {
258
+ return str;
259
+ }
260
+
261
+ // Trim leading/trailing dashes and spaces
262
+ str = str.trim().replace(/^-+|-+$/g, "");
263
+
264
+ // Handle empty string after trim
265
+ if (!str) {
266
+ return "";
267
+ }
268
+
269
+ return (
270
+ str
271
+ // Replace multiple consecutive dashes/underscores with a single dash
272
+ .replace(/[-_]+/g, "-")
273
+ // Split on dash
274
+ .split("-")
275
+ // Filter out empty strings (from consecutive dashes)
276
+ .filter(Boolean)
277
+ // Convert each word
278
+ .map((word, index) => {
279
+ // Convert word to lowercase
280
+ const _word = word.toLowerCase();
281
+
282
+ // Capitalize first letter if not the first word
283
+ if (index > 0) {
284
+ return _word.charAt(0).toUpperCase() + _word.slice(1);
285
+ }
286
+
287
+ return _word;
288
+ })
289
+ .join("")
290
+ );
291
+ }
292
+
293
+ export async function checkFileExists(
294
+ path: string,
295
+ options?: {
296
+ askPrompt?: boolean;
297
+ fileName?: string;
298
+ allowIgnore?: boolean;
299
+ },
300
+ ): Promise<{
301
+ exists: boolean;
302
+ overwrite: boolean;
303
+ }> {
304
+ const { askPrompt = false, fileName, allowIgnore = false } = options ?? {};
305
+
306
+ if (!fs.existsSync(path)) {
307
+ return {
308
+ exists: false,
309
+ overwrite: false,
310
+ };
311
+ }
312
+
313
+ if (askPrompt) {
314
+ const { overwrite } = await prompts({
315
+ type: "select",
316
+ name: "overwrite",
317
+ message: `${fileName ?? basename(path)} already exists. Please choose how to proceed:`,
318
+ initial: 0,
319
+ choices: [
320
+ ...(allowIgnore
321
+ ? [
322
+ {
323
+ title: "Keep original file",
324
+ value: "ignore",
325
+ },
326
+ ]
327
+ : []),
328
+ {
329
+ title: "Cancel operation",
330
+ value: "no",
331
+ },
332
+ {
333
+ title: "Overwrite file",
334
+ value: "yes",
335
+ },
336
+ ],
337
+ });
338
+
339
+ if (overwrite === "no") {
340
+ cancelOperation();
341
+ }
342
+
343
+ if (overwrite === "ignore") {
344
+ return {
345
+ exists: true,
346
+ overwrite: false,
347
+ };
348
+ }
349
+
350
+ return {
351
+ exists: true,
352
+ overwrite: true,
353
+ };
354
+ }
355
+
356
+ return {
357
+ exists: true,
358
+ overwrite: false,
359
+ };
360
+ }
361
+
362
+ export function cancelOperation(message?: string) {
363
+ throw new Error(red("✖") + (message ?? " Operation cancelled"));
364
+ }
365
+
366
+ export function getPackageManager(): PkgInfo {
367
+ const userAgent = process.env.npm_config_user_agent;
368
+ const pkgInfo = pkgFromUserAgent(userAgent);
369
+ if (pkgInfo) {
370
+ return pkgInfo;
371
+ }
372
+ return {
373
+ name: "npm",
374
+ };
375
+ }
376
+
377
+ /**
378
+
379
+ https://github.com/vitejs/vite/blob/07091a1e804e5934208ef0b6324a04317dd0d815/packages/create-vite/src/index.ts#L585
380
+
381
+ MIT License
382
+
383
+ Copyright (c) 2019-present, VoidZero Inc. and Vite contributors
384
+
385
+ Permission is hereby granted, free of charge, to any person obtaining a copy
386
+ of this software and associated documentation files (the "Software"), to deal
387
+ in the Software without restriction, including without limitation the rights
388
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
389
+ copies of the Software, and to permit persons to whom the Software is
390
+ furnished to do so, subject to the following conditions:
391
+
392
+ The above copyright notice and this permission notice shall be included in all
393
+ copies or substantial portions of the Software.
394
+
395
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
396
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
397
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
398
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
399
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
400
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
401
+ SOFTWARE.
402
+
403
+ */
404
+ function pkgFromUserAgent(userAgent: string | undefined): PkgInfo | undefined {
405
+ if (!userAgent) return undefined;
406
+ const pkgSpec = userAgent.split(" ")[0];
407
+ const pkgSpecArr = pkgSpec.split("/");
408
+ return {
409
+ name: pkgSpecArr[0],
410
+ version: pkgSpecArr[1],
411
+ };
412
+ }
@@ -1 +1,2 @@
1
1
  export * from "./config";
2
+ export type { Plugin } from "rollup";