algolia-codegen 0.1.0 → 0.1.2

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/dist/cli.cjs CHANGED
@@ -1,16 +1,617 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
3
25
 
4
26
  // src/cli.ts
27
+ var import_dotenv = require("dotenv");
28
+ var import_fs4 = require("fs");
29
+ var import_path3 = require("path");
5
30
  var import_commander = require("commander");
6
31
 
32
+ // src/utils/load-config.ts
33
+ var import_fs2 = require("fs");
34
+ var import_path = require("path");
35
+ var import_url = require("url");
36
+
37
+ // src/utils/load-typescript-config.ts
38
+ var import_fs = require("fs");
39
+ async function loadTypeScriptConfig(resolvedPath) {
40
+ const esbuild = await import("esbuild");
41
+ const source = (0, import_fs.readFileSync)(resolvedPath, "utf-8");
42
+ const result = esbuild.transformSync(source, {
43
+ loader: "ts",
44
+ format: "esm",
45
+ target: "node18",
46
+ sourcefile: resolvedPath
47
+ });
48
+ if (!result.code) {
49
+ throw new Error("Failed to transform TypeScript config file");
50
+ }
51
+ const dataUrl = `data:text/javascript;charset=utf-8,${encodeURIComponent(result.code)}`;
52
+ const module2 = await import(dataUrl);
53
+ return module2;
54
+ }
55
+
56
+ // src/utils/validations/generator-config.ts
57
+ function validateGeneratorConfig(config, path) {
58
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
59
+ throw new Error(
60
+ `Invalid generator config: must be an object
61
+ Path: ${path}`
62
+ );
63
+ }
64
+ const cfg = config;
65
+ const requiredFields = [
66
+ "appId",
67
+ "searchKey",
68
+ "indexName"
69
+ ];
70
+ for (const field of requiredFields) {
71
+ if (!(field in cfg)) {
72
+ throw new Error(
73
+ `Invalid generator config: missing required property '${field}'
74
+ Path: ${path}`
75
+ );
76
+ }
77
+ if (typeof cfg[field] !== "string") {
78
+ throw new Error(
79
+ `Invalid generator config: '${field}' must be a string
80
+ Path: ${path}
81
+ Received: ${typeof cfg[field]}`
82
+ );
83
+ }
84
+ }
85
+ if ("prefix" in cfg && cfg.prefix !== void 0 && typeof cfg.prefix !== "string") {
86
+ throw new Error(
87
+ `Invalid generator config: 'prefix' must be a string or undefined
88
+ Path: ${path}
89
+ Received: ${typeof cfg.prefix}`
90
+ );
91
+ }
92
+ if ("postfix" in cfg && cfg.postfix !== void 0 && typeof cfg.postfix !== "string") {
93
+ throw new Error(
94
+ `Invalid generator config: 'postfix' must be a string or undefined
95
+ Path: ${path}
96
+ Received: ${typeof cfg.postfix}`
97
+ );
98
+ }
99
+ }
100
+
101
+ // src/utils/validations/url-schema.ts
102
+ function validateUrlSchema(urlSchema, path) {
103
+ if (typeof urlSchema !== "object" || urlSchema === null || Array.isArray(urlSchema)) {
104
+ throw new Error(
105
+ `Invalid generates entry: must be an object
106
+ Path: ${path}`
107
+ );
108
+ }
109
+ const schema = urlSchema;
110
+ for (const [filePath, generatorConfig] of Object.entries(schema)) {
111
+ if (typeof filePath !== "string") {
112
+ throw new Error(
113
+ `Invalid generates entry: file path must be a string
114
+ Path: ${path}[${filePath}]`
115
+ );
116
+ }
117
+ validateGeneratorConfig(generatorConfig, `${path}["${filePath}"]`);
118
+ }
119
+ }
120
+
121
+ // src/utils/validations/config.ts
122
+ function validateConfig(config, configPath) {
123
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
124
+ throw new Error(
125
+ `Invalid config: must be an object
126
+ Config file: ${configPath}`
127
+ );
128
+ }
129
+ const cfg = config;
130
+ if (!("overwrite" in cfg)) {
131
+ throw new Error(
132
+ `Invalid config: missing required property 'overwrite'
133
+ Config file: ${configPath}`
134
+ );
135
+ }
136
+ if (typeof cfg.overwrite !== "boolean") {
137
+ throw new Error(
138
+ `Invalid config: 'overwrite' must be a boolean
139
+ Config file: ${configPath}
140
+ Received: ${typeof cfg.overwrite}`
141
+ );
142
+ }
143
+ if (!("generates" in cfg)) {
144
+ throw new Error(
145
+ `Invalid config: missing required property 'generates'
146
+ Config file: ${configPath}`
147
+ );
148
+ }
149
+ const generates = cfg.generates;
150
+ if (Array.isArray(generates)) {
151
+ generates.forEach((item, index) => {
152
+ validateUrlSchema(item, `${configPath}[generates][${index}]`);
153
+ });
154
+ } else if (typeof generates === "object" && generates !== null) {
155
+ validateUrlSchema(generates, `${configPath}[generates]`);
156
+ } else {
157
+ throw new Error(
158
+ `Invalid config: 'generates' must be an object or an array of objects
159
+ Config file: ${configPath}
160
+ Received: ${typeof generates}`
161
+ );
162
+ }
163
+ }
164
+
165
+ // src/utils/load-config.ts
166
+ async function loadConfig(configPath) {
167
+ const defaultConfigPath = "algolia-codegen.ts";
168
+ const finalConfigPath = configPath || defaultConfigPath;
169
+ const resolvedPath = (0, import_path.resolve)(process.cwd(), finalConfigPath);
170
+ if (!(0, import_fs2.existsSync)(resolvedPath)) {
171
+ throw new Error(
172
+ `Config file not found: ${resolvedPath}
173
+ Please create a config file or specify a different path using --config option.`
174
+ );
175
+ }
176
+ const configUrl = (0, import_url.pathToFileURL)(resolvedPath).href;
177
+ let configModule;
178
+ if (resolvedPath.endsWith(".ts")) {
179
+ try {
180
+ configModule = await loadTypeScriptConfig(resolvedPath);
181
+ } catch (tsError) {
182
+ const jsPath = resolvedPath.replace(/\.ts$/, ".js");
183
+ if ((0, import_fs2.existsSync)(jsPath)) {
184
+ const jsUrl = (0, import_url.pathToFileURL)(jsPath).href;
185
+ try {
186
+ configModule = await import(jsUrl);
187
+ } catch (jsImportError) {
188
+ throw new Error(
189
+ `Failed to import config file: ${resolvedPath}
190
+ Tried both .ts (via esbuild) and .js extensions.
191
+ TypeScript error: ${tsError instanceof Error ? tsError.message : String(tsError)}
192
+ JavaScript error: ${jsImportError instanceof Error ? jsImportError.message : String(jsImportError)}`
193
+ );
194
+ }
195
+ } else {
196
+ throw new Error(
197
+ `Failed to load TypeScript config file: ${resolvedPath}
198
+ Error: ${tsError instanceof Error ? tsError.message : String(tsError)}
199
+ Make sure esbuild is installed as a dependency.`
200
+ );
201
+ }
202
+ }
203
+ } else {
204
+ try {
205
+ configModule = await import(configUrl);
206
+ } catch (importError) {
207
+ const errorMessage = importError instanceof Error ? importError.message : String(importError);
208
+ throw new Error(
209
+ `Failed to import config file: ${resolvedPath}
210
+ Error: ${errorMessage}`
211
+ );
212
+ }
213
+ }
214
+ if (!configModule.default) {
215
+ throw new Error(
216
+ `Config file does not export a default object: ${resolvedPath}
217
+ Please ensure your config file exports a default object: export default { ... }`
218
+ );
219
+ }
220
+ const config = configModule.default;
221
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
222
+ throw new Error(
223
+ `Config file default export must be an object: ${resolvedPath}
224
+ Received: ${typeof config}`
225
+ );
226
+ }
227
+ validateConfig(config, resolvedPath);
228
+ return config;
229
+ }
230
+
231
+ // src/utils/fetch-algolia-data.ts
232
+ var import_algoliasearch = require("algoliasearch");
233
+ var import_fs3 = require("fs");
234
+ var import_path2 = require("path");
235
+
236
+ // src/utils/generate-typescript-types.ts
237
+ var TypeGenerator = class {
238
+ typeMap = /* @__PURE__ */ new Map();
239
+ generatedTypes = /* @__PURE__ */ new Set();
240
+ idValueTypes = /* @__PURE__ */ new Set();
241
+ prefix;
242
+ postfix;
243
+ indexName;
244
+ constructor(config) {
245
+ this.prefix = config.prefix || "";
246
+ this.postfix = config.postfix || "";
247
+ this.indexName = config.indexName;
248
+ }
249
+ /**
250
+ * Convert a value to its TypeScript type representation
251
+ */
252
+ inferType(value, path = []) {
253
+ if (value === null || value === void 0) {
254
+ return { type: "unknown", isOptional: true, isArray: false, nestedTypes: /* @__PURE__ */ new Map() };
255
+ }
256
+ if (Array.isArray(value)) {
257
+ if (value.length === 0) {
258
+ return { type: "unknown[]", isOptional: false, isArray: true, nestedTypes: /* @__PURE__ */ new Map() };
259
+ }
260
+ const itemTypes = value.map((item, idx) => this.inferType(item, [...path, `[${idx}]`]));
261
+ if (this.isIdValuePattern(value)) {
262
+ const firstItem = value[0];
263
+ const valueType = this.inferType(firstItem.value, [...path, "[0].value"]);
264
+ const idValueTypeName = `${this.prefix}IdValue`;
265
+ this.idValueTypes.add(idValueTypeName);
266
+ const typeString = valueType.type !== "string" ? `${idValueTypeName}<${valueType.type}>` : idValueTypeName;
267
+ return {
268
+ type: `${typeString}[]`,
269
+ isOptional: false,
270
+ isArray: true,
271
+ nestedTypes: /* @__PURE__ */ new Map()
272
+ };
273
+ }
274
+ const firstType = itemTypes[0];
275
+ const allSameType = itemTypes.every(
276
+ (t) => t.type === firstType.type && !t.isArray && t.nestedTypes.size === firstType.nestedTypes.size
277
+ );
278
+ if (allSameType && !firstType.isArray) {
279
+ return {
280
+ type: `${firstType.type}[]`,
281
+ isOptional: false,
282
+ isArray: true,
283
+ nestedTypes: firstType.nestedTypes
284
+ };
285
+ }
286
+ const uniqueTypes = Array.from(new Set(itemTypes.map((t) => t.type)));
287
+ const unionType = uniqueTypes.length === 1 ? uniqueTypes[0] : uniqueTypes.join(" | ");
288
+ return {
289
+ type: `${unionType}[]`,
290
+ isOptional: false,
291
+ isArray: true,
292
+ nestedTypes: /* @__PURE__ */ new Map()
293
+ };
294
+ }
295
+ if (typeof value === "object") {
296
+ const obj = value;
297
+ const typeName = this.generateTypeName(path);
298
+ const nestedTypes = /* @__PURE__ */ new Map();
299
+ for (const [key, val] of Object.entries(obj)) {
300
+ nestedTypes.set(key, this.inferType(val, [...path, key]));
301
+ }
302
+ if (!this.generatedTypes.has(typeName)) {
303
+ this.generatedTypes.add(typeName);
304
+ this.typeMap.set(typeName, this.generateInterface(typeName, nestedTypes, obj));
305
+ }
306
+ return {
307
+ type: typeName,
308
+ isOptional: false,
309
+ isArray: false,
310
+ nestedTypes
311
+ };
312
+ }
313
+ const jsType = typeof value;
314
+ let tsType;
315
+ if (jsType === "number") {
316
+ tsType = "number";
317
+ } else if (jsType === "boolean") {
318
+ tsType = "boolean";
319
+ } else {
320
+ tsType = "string";
321
+ }
322
+ return { type: tsType, isOptional: false, isArray: false, nestedTypes: /* @__PURE__ */ new Map() };
323
+ }
324
+ /**
325
+ * Check if an array follows the AlgoliaIdValue pattern
326
+ */
327
+ isIdValuePattern(arr) {
328
+ return arr.length > 0 && arr.every(
329
+ (item) => typeof item === "object" && item !== null && "id" in item && "value" in item && typeof item.id === "string"
330
+ );
331
+ }
332
+ /**
333
+ * Generate a TypeScript type name from a path
334
+ */
335
+ generateTypeName(path) {
336
+ if (path.length === 0) {
337
+ return `${this.prefix}Hit${this.postfix}`;
338
+ }
339
+ const lastPart = path[path.length - 1];
340
+ const parts = lastPart.replace(/[\[\]]/g, "").split(/[-_\s]+/).filter(Boolean);
341
+ const pascalCase = parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
342
+ if (path.length > 1) {
343
+ const parent = path[path.length - 2];
344
+ if (parent.includes("Info")) {
345
+ return `${this.prefix}${pascalCase}Info${this.postfix}`;
346
+ }
347
+ }
348
+ return `${this.prefix}${pascalCase}${this.postfix}`;
349
+ }
350
+ /**
351
+ * Generate TypeScript interface code
352
+ */
353
+ generateInterface(typeName, nestedTypes, sampleObj) {
354
+ const lines = [];
355
+ const description = this.getTypeDescription(typeName);
356
+ lines.push("/**");
357
+ lines.push(` * ${description}`);
358
+ lines.push(" */");
359
+ lines.push(`export interface ${typeName} {`);
360
+ const sortedKeys = Array.from(nestedTypes.keys()).sort();
361
+ for (const key of sortedKeys) {
362
+ const typeInfo = nestedTypes.get(key);
363
+ const value = sampleObj[key];
364
+ const isOptional = typeInfo.isOptional || value === null || value === void 0;
365
+ const optionalMarker = isOptional ? "?" : "";
366
+ let typeString = typeInfo.type;
367
+ if (typeInfo.isArray && !typeString.endsWith("[]")) {
368
+ typeString = `${typeString}[]`;
369
+ }
370
+ if (value === null && typeString !== "null") {
371
+ typeString = `${typeString} | null`;
372
+ }
373
+ lines.push(` ${key}${optionalMarker}: ${typeString};`);
374
+ }
375
+ lines.push("}");
376
+ lines.push("");
377
+ return lines.join("\n");
378
+ }
379
+ /**
380
+ * Get a description for a type based on its name
381
+ */
382
+ getTypeDescription(typeName) {
383
+ const withoutPrefix = typeName.replace(new RegExp(`^${this.prefix}`), "");
384
+ const withoutPostfix = withoutPrefix.replace(new RegExp(`${this.postfix}$`), "");
385
+ const readable = withoutPostfix.replace(/([A-Z])/g, " $1").trim().toLowerCase();
386
+ return readable.charAt(0).toUpperCase() + readable.slice(1) + " structure in Algolia";
387
+ }
388
+ /**
389
+ * Collect all types that need to be generated
390
+ */
391
+ collectTypes(typeInfo, typesToGenerate) {
392
+ if (typeInfo.nestedTypes.size > 0 && !typeInfo.isArray) {
393
+ typesToGenerate.add(typeInfo.type);
394
+ for (const nestedTypeInfo of typeInfo.nestedTypes.values()) {
395
+ this.collectTypes(nestedTypeInfo, typesToGenerate);
396
+ }
397
+ }
398
+ }
399
+ /**
400
+ * Get dependencies for a type (types that it references)
401
+ */
402
+ getTypeDependencies(typeName) {
403
+ const typeCode = this.typeMap.get(typeName);
404
+ if (!typeCode) return [];
405
+ const dependencies = [];
406
+ const importRegex = new RegExp(`(${this.prefix}\\w+)`, "g");
407
+ const matches = typeCode.matchAll(importRegex);
408
+ for (const match of matches) {
409
+ const depTypeName = match[1];
410
+ if (depTypeName !== typeName && this.generatedTypes.has(depTypeName)) {
411
+ dependencies.push(depTypeName);
412
+ }
413
+ }
414
+ return Array.from(new Set(dependencies));
415
+ }
416
+ /**
417
+ * Sort types by dependencies (topological sort)
418
+ */
419
+ sortTypesByDependencies(typeNames) {
420
+ const sorted = [];
421
+ const visited = /* @__PURE__ */ new Set();
422
+ const visiting = /* @__PURE__ */ new Set();
423
+ const visit = (typeName) => {
424
+ if (visiting.has(typeName)) {
425
+ return;
426
+ }
427
+ if (visited.has(typeName)) {
428
+ return;
429
+ }
430
+ visiting.add(typeName);
431
+ const dependencies = this.getTypeDependencies(typeName);
432
+ for (const dep of dependencies) {
433
+ visit(dep);
434
+ }
435
+ visiting.delete(typeName);
436
+ visited.add(typeName);
437
+ sorted.push(typeName);
438
+ };
439
+ for (const typeName of typeNames) {
440
+ visit(typeName);
441
+ }
442
+ return sorted;
443
+ }
444
+ /**
445
+ * Generate IdValue type definition (generic type)
446
+ */
447
+ generateIdValueType(typeName) {
448
+ return `export type ${typeName}<T = string> = {
449
+ id: string;
450
+ value: T;
451
+ };
452
+
453
+ `;
454
+ }
455
+ /**
456
+ * Generate all types as a single file content
457
+ */
458
+ generateAllTypes(sampleHit) {
459
+ const rootType = this.inferType(sampleHit, []);
460
+ const typesToGenerate = /* @__PURE__ */ new Set();
461
+ this.collectTypes(rootType, typesToGenerate);
462
+ const rootTypeName = rootType.type;
463
+ if (rootType.nestedTypes.size > 0 && !rootType.isArray) {
464
+ typesToGenerate.add(rootTypeName);
465
+ }
466
+ const sortedTypes = this.sortTypesByDependencies(Array.from(typesToGenerate));
467
+ const lines = [];
468
+ lines.push("/**");
469
+ lines.push(` * Generated TypeScript types for Algolia index: ${this.indexName}`);
470
+ lines.push(" * This file is auto-generated. Do not edit manually.");
471
+ lines.push(" */");
472
+ lines.push("");
473
+ if (this.idValueTypes.size > 0) {
474
+ const idValueTypeName = Array.from(this.idValueTypes)[0];
475
+ lines.push(this.generateIdValueType(idValueTypeName));
476
+ }
477
+ for (const typeName of sortedTypes) {
478
+ const typeCode = this.typeMap.get(typeName);
479
+ if (typeCode) {
480
+ lines.push(typeCode);
481
+ }
482
+ }
483
+ return lines.join("\n");
484
+ }
485
+ };
486
+ function generateTypeScriptTypes(sampleHit, config) {
487
+ const generator = new TypeGenerator(config);
488
+ return generator.generateAllTypes(sampleHit);
489
+ }
490
+
491
+ // src/utils/fetch-algolia-data.ts
492
+ async function fetchAlgoliaData(filePath, generatorConfig, overwrite) {
493
+ console.log(`
494
+ Processing file: ${filePath}`);
495
+ const resolvedPath = (0, import_path2.resolve)(process.cwd(), filePath);
496
+ if ((0, import_fs3.existsSync)(resolvedPath) && !overwrite) {
497
+ throw new Error(
498
+ `File already exists: ${resolvedPath}
499
+ Set overwrite: true in config to allow overwriting existing files.`
500
+ );
501
+ }
502
+ console.log(`Connecting to Algolia...`);
503
+ console.log(`App ID: ${generatorConfig.appId}`);
504
+ let client;
505
+ try {
506
+ client = (0, import_algoliasearch.algoliasearch)(
507
+ generatorConfig.appId,
508
+ generatorConfig.searchKey
509
+ );
510
+ } catch (error) {
511
+ throw new Error(
512
+ `Failed to initialize Algolia client: ${error instanceof Error ? error.message : String(error)}`
513
+ );
514
+ }
515
+ console.log(`Fetching sample record from index: ${generatorConfig.indexName}`);
516
+ let results;
517
+ try {
518
+ results = await client.search([
519
+ {
520
+ indexName: generatorConfig.indexName,
521
+ params: {
522
+ query: "",
523
+ hitsPerPage: 1
524
+ }
525
+ }
526
+ ]);
527
+ } catch (error) {
528
+ let errorMessage;
529
+ if (error instanceof Error) {
530
+ errorMessage = error.message;
531
+ } else if (error && typeof error === "object") {
532
+ const errorObj = error;
533
+ if (errorObj.message) {
534
+ errorMessage = String(errorObj.message);
535
+ } else if (errorObj.status) {
536
+ errorMessage = `HTTP ${errorObj.status}: ${errorObj.statusText || "Unknown error"}`;
537
+ } else {
538
+ try {
539
+ errorMessage = JSON.stringify(error, null, 2);
540
+ } catch {
541
+ errorMessage = String(error);
542
+ }
543
+ }
544
+ } else {
545
+ errorMessage = String(error);
546
+ }
547
+ throw new Error(
548
+ `Failed to fetch data from Algolia index "${generatorConfig.indexName}" (App ID: ${generatorConfig.appId}): ${errorMessage}`
549
+ );
550
+ }
551
+ if (!results.results || results.results.length === 0) {
552
+ throw new Error(`No results found in Algolia index: ${generatorConfig.indexName}`);
553
+ }
554
+ const result = results.results[0];
555
+ if (!("hits" in result) || !result.hits || result.hits.length === 0) {
556
+ throw new Error(`No hits found in Algolia index: ${generatorConfig.indexName}`);
557
+ }
558
+ const sampleHit = result.hits[0];
559
+ console.log("Sample record fetched successfully");
560
+ console.log(`ObjectID: ${sampleHit.objectID || "N/A"}`);
561
+ const fileContent = generateTypeScriptTypes(sampleHit, generatorConfig);
562
+ const dir = (0, import_path2.dirname)(resolvedPath);
563
+ if (!(0, import_fs3.existsSync)(dir)) {
564
+ (0, import_fs3.mkdirSync)(dir, { recursive: true });
565
+ }
566
+ (0, import_fs3.writeFileSync)(resolvedPath, fileContent, "utf-8");
567
+ console.log(`Generated file: ${filePath}`);
568
+ }
569
+
7
570
  // src/index.ts
8
- var main = () => {
9
- console.log("Main!");
571
+ var main = async (configPath) => {
572
+ try {
573
+ const config = await loadConfig(configPath);
574
+ console.log("Config loaded successfully");
575
+ const generatesArray = Array.isArray(config.generates) ? config.generates : [config.generates];
576
+ for (const urlSchema of generatesArray) {
577
+ for (const [filePath, generatorConfig] of Object.entries(urlSchema)) {
578
+ try {
579
+ await fetchAlgoliaData(filePath, generatorConfig, config.overwrite);
580
+ } catch (error) {
581
+ console.error(`
582
+ Error processing file: ${filePath}`);
583
+ if (error instanceof Error) {
584
+ console.error(error.message);
585
+ if (error.stack) {
586
+ console.error(error.stack);
587
+ }
588
+ } else {
589
+ try {
590
+ console.error(JSON.stringify(error, null, 2));
591
+ } catch {
592
+ console.error(String(error));
593
+ }
594
+ }
595
+ }
596
+ }
597
+ }
598
+ } catch (error) {
599
+ console.error("Error loading config:");
600
+ if (error instanceof Error) {
601
+ console.error(error.message);
602
+ } else {
603
+ console.error(String(error));
604
+ }
605
+ process.exit(1);
606
+ }
10
607
  };
11
608
 
12
609
  // src/cli.ts
610
+ var envPath = (0, import_path3.resolve)(process.cwd(), ".env");
611
+ if ((0, import_fs4.existsSync)(envPath)) {
612
+ (0, import_dotenv.config)({ path: envPath });
613
+ }
13
614
  var program = new import_commander.Command();
14
- program.name("algolia-codegen").description("Generate TypeScript types from Algolia index").option("-c, --config <path>", "Config file path").action(() => {
15
- main();
615
+ program.name("algolia-codegen").description("Generate TypeScript types from Algolia index").option("-c, --config <path>", "Config file path").action(async (options) => {
616
+ await main(options.config);
16
617
  }).parse();
package/dist/cli.js CHANGED
@@ -1,11 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  main
4
- } from "./chunk-U33HDFDI.js";
4
+ } from "./chunk-R66ECGLW.js";
5
5
 
6
6
  // src/cli.ts
7
+ import { config as loadDotenv } from "dotenv";
8
+ import { existsSync } from "fs";
9
+ import { resolve } from "path";
7
10
  import { Command } from "commander";
11
+ var envPath = resolve(process.cwd(), ".env");
12
+ if (existsSync(envPath)) {
13
+ loadDotenv({ path: envPath });
14
+ }
8
15
  var program = new Command();
9
- program.name("algolia-codegen").description("Generate TypeScript types from Algolia index").option("-c, --config <path>", "Config file path").action(() => {
10
- main();
16
+ program.name("algolia-codegen").description("Generate TypeScript types from Algolia index").option("-c, --config <path>", "Config file path").action(async (options) => {
17
+ await main(options.config);
11
18
  }).parse();