dataandapis 0.0.0-stage → 0.1.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/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +467 -2
- package/dist/index.cjs +421 -0
- package/dist/index.d.cts +19538 -0
- package/dist/index.d.ts +19538 -0
- package/dist/index.js +411 -0
- package/package.json +70 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var __typeError = (msg) => {
|
|
4
|
+
throw TypeError(msg);
|
|
5
|
+
};
|
|
6
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
7
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), member.get(obj));
|
|
8
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
9
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
|
|
10
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
11
|
+
|
|
12
|
+
// src/errors.ts
|
|
13
|
+
var DataAndApisError = class extends Error {
|
|
14
|
+
constructor(message, options) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = new.target.name;
|
|
17
|
+
if (options && "cause" in options) this.cause = options.cause;
|
|
18
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var ApiError = class extends DataAndApisError {
|
|
22
|
+
constructor(message, details) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.status = details.status;
|
|
25
|
+
this.api = details.api;
|
|
26
|
+
this.method = details.method;
|
|
27
|
+
this.url = details.url;
|
|
28
|
+
this.body = details.body;
|
|
29
|
+
this.tokensRemaining = details.tokensRemaining;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
var AuthenticationError = class extends ApiError {
|
|
33
|
+
};
|
|
34
|
+
var PaymentRequiredError = class extends ApiError {
|
|
35
|
+
get paymentUrl() {
|
|
36
|
+
const url = this.body?.payment_url;
|
|
37
|
+
return typeof url === "string" ? url : void 0;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
var QuotaExceededError = class extends ApiError {
|
|
41
|
+
};
|
|
42
|
+
var ConnectionError = class extends DataAndApisError {
|
|
43
|
+
};
|
|
44
|
+
var TimeoutError = class extends DataAndApisError {
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// src/generated/endpoints.ts
|
|
48
|
+
var APIS = {
|
|
49
|
+
airQuality: ["air-quality", "https://api-air-quality.dataandapis.com", { dataSources: "GET /v1/sources", nearbyStations: "GET /v1/stations", nearestReadings: "GET /v1/air-quality", pollutantParameters: "GET /v1/parameters", stationDetail: "GET /v1/stations/{id}" }],
|
|
50
|
+
aircraft: ["aircraft", "https://api-aircraft.dataandapis.com", { aircraftManufacturers: "GET /v1/aircraft/manufacturers", engineTypes: "GET /v1/aircraft/engine-types", getAircraft: "GET /v1/aircraft/{idOrSlug}", listAircraft: "GET /v1/aircraft", lookupByDesignator: "GET /v1/aircraft/designator/{code}", randomAircraft: "GET /v1/aircraft/random" }],
|
|
51
|
+
aircraftRegistrations: ["aircraft-registrations", "https://api-aircraft-registrations.dataandapis.com", { dataSources: "GET /v1/sources", getAircraftByTailNumber: "GET /v1/aircraft/{n_number}", lookupByModeSHex: "GET /v1/aircraft/hex/{code}", randomAircraft: "GET /v1/aircraft/random", registrationStatistics: "GET /v1/stats", searchAircraft: "GET /v1/aircraft", searchAircraftModels: "GET /v1/models" }],
|
|
52
|
+
airlines: ["airlines", "https://api-airlines.dataandapis.com", { dataSources: "GET /v1/sources", getAirline: "GET /v1/airlines/{qid}", lookupByIataCode: "GET /v1/airlines/iata/{code}", lookupByIcaoCode: "GET /v1/airlines/icao/{code}", searchAirlines: "GET /v1/airlines" }],
|
|
53
|
+
airportStatus: ["airport-status", "https://api-airport-status.dataandapis.com", { affectedAirports: "GET /v1/airport-status/delays", airportStatus: "GET /v1/airport-status/{code}", dataSources: "GET /v1/sources", nationalStatus: "GET /v1/airport-status" }],
|
|
54
|
+
airports: ["airports", "https://api-airports.dataandapis.com", { getAirport: "GET /v1/airports/{code}", nearbyAirports: "GET /v1/airports/nearby", searchAirports: "GET /v1/airports/search" }],
|
|
55
|
+
animals: ["animals", "https://api-animals.dataandapis.com", { animalClasses: "GET /v1/animals/classes", conservationStatuses: "GET /v1/animals/statuses", getAnimal: "GET /v1/animals/{slug}", listAnimals: "GET /v1/animals", randomAnimals: "GET /v1/animals/random" }],
|
|
56
|
+
anime: ["anime", "https://anime.dataandapis.com", { anime: "GET /v1/anime", getAnimeById: "GET /v1/anime/{id}" }],
|
|
57
|
+
artworks: ["artworks", "https://api-artworks.dataandapis.com", { artists: "GET /v1/artworks/artists", artworkDetail: "GET /v1/artworks/{id}", dataSources: "GET /v1/sources", departments: "GET /v1/artworks/departments", randomArtwork: "GET /v1/artworks/random", searchArtworks: "GET /v1/artworks" }],
|
|
58
|
+
astronomy: ["astronomy", "https://api-astronomy.dataandapis.com", { moonPhaseTimes: "GET /v1/moon", multiDayAlmanac: "GET /v1/almanac", sunTimesPosition: "GET /v1/sun" }],
|
|
59
|
+
attractions: ["attractions", "https://api-attractions.dataandapis.com", { attractionsNearAPoint: "GET /v1/attractions/nearby", dataSources: "GET /v1/sources", getAttraction: "GET /v1/attractions/{qid}", randomAttraction: "GET /v1/attractions/random", searchAttractions: "GET /v1/attractions" }],
|
|
60
|
+
babyNames: ["baby-names", "https://api-baby-names.dataandapis.com", { getName: "GET /v1/names/{name}", nameTrend: "GET /v1/names/trend/{name}", randomName: "GET /v1/names/random", topNames: "GET /v1/names/top" }],
|
|
61
|
+
banks: ["banks", "https://api-banks.dataandapis.com", { bankBranches: "GET /v1/banks/{cert}/branches", bankFailures: "GET /v1/failures", dataSources: "GET /v1/sources", failureStatistics: "GET /v1/failures/stats", getBank: "GET /v1/banks/{cert}", largestBanks: "GET /v1/banks/largest", searchBanks: "GET /v1/banks", searchBranches: "GET /v1/branches" }],
|
|
62
|
+
barcodeGenerator: ["barcode-generator", "https://api-barcode.dataandapis.com", { generateBarcode: "GET /v1/barcode", listSymbologies: "GET /v1/symbologies" }],
|
|
63
|
+
barcodeLookup: ["barcode-lookup", "https://api-barcode-lookup.dataandapis.com", { catalogueStats: "GET /v1/products/stats", dataSources: "GET /v1/sources", lookupByBarcode: "GET /v1/products/{barcode}", randomProducts: "GET /v1/products/random", searchProducts: "GET /v1/products", topBrands: "GET /v1/brands" }],
|
|
64
|
+
bibleMultiTranslation: ["bible-multi-translation", "https://api-bible.dataandapis.com", { getSingleVerse: "GET /v1/versions/{versionCode}/books/{bookCode}/chapters/{chapter}/verses/{verse}", getTranslationDetails: "GET /v1/versions/{code}", listBibleBooks: "GET /v1/books", listBibleTranslations: "GET /v1/versions" }],
|
|
65
|
+
binCardValidator: ["bin-card-validator", "https://api-bin-lookup.dataandapis.com", { lookupBin: "GET /v1/bin/{bin}", validateCard: "GET /v1/validate" }],
|
|
66
|
+
books: ["books", "https://api-books.dataandapis.com", { bookDetail: "GET /v1/books/{id}", dataSources: "GET /v1/sources", randomBook: "GET /v1/books/random", searchBooks: "GET /v1/books" }],
|
|
67
|
+
buoys: ["buoys", "https://api-buoys.dataandapis.com", { buoyDetail: "GET /v1/buoys/{id}", dataSources: "GET /v1/sources", latestObservations: "GET /v1/buoys/observations", nearestBuoys: "GET /v1/buoys/nearest", searchStations: "GET /v1/buoys/stations" }],
|
|
68
|
+
businessPatterns: ["business-patterns", "https://api-business-patterns.dataandapis.com", { countyProfile: "GET /v1/counties/{fips}", dataSources: "GET /v1/sources", nationalStatistics: "GET /v1/national", searchCounties: "GET /v1/counties", searchIndustries: "GET /v1/industries", stateProfile: "GET /v1/states/{state}", stateRankings: "GET /v1/states", zipBusinessProfile: "GET /v1/zips/{zip}" }],
|
|
69
|
+
caloriesBurned: ["calories-burned", "https://api-calories.dataandapis.com", { activityDetail: "GET /v1/activities/{id}", caloriesBurned: "GET /v1/calories-burned", dataSources: "GET /v1/sources", listActivities: "GET /v1/activities", listCategories: "GET /v1/categories" }],
|
|
70
|
+
cars: ["cars", "https://api-cars.dataandapis.com", { getVehicle: "GET /v1/vehicles/{id}", listVehicles: "GET /v1/vehicles", randomVehicles: "GET /v1/vehicles/random", vehicleMakes: "GET /v1/vehicles/makes", vehicleModels: "GET /v1/vehicles/models" }],
|
|
71
|
+
cats: ["cats", "https://api-cats.dataandapis.com", { breedOrigins: "GET /v1/breeds/origins", getBreed: "GET /v1/breeds/{slug}", listBreeds: "GET /v1/breeds", randomBreeds: "GET /v1/breeds/random" }],
|
|
72
|
+
climateNormals: ["climate-normals", "https://api-climate-normals.dataandapis.com", { climateAtCoordinates: "GET /v1/climate", climateRankings: "GET /v1/rankings", dataSources: "GET /v1/sources", getStationNormals: "GET /v1/stations/{id}", searchStations: "GET /v1/stations" }],
|
|
73
|
+
cocktails: ["cocktails", "https://api-cocktails.dataandapis.com", { getCocktail: "GET /v1/cocktails/{slug}", listCocktails: "GET /v1/cocktails", listIngredients: "GET /v1/cocktails/ingredients", randomCocktail: "GET /v1/cocktails/random" }],
|
|
74
|
+
colors: ["colors", "https://api-colors.dataandapis.com", { convertColor: "GET /v1/colors/convert", dataSources: "GET /v1/sources", generatePalette: "GET /v1/colors/palette", nameAColor: "GET /v1/colors/name", randomColor: "GET /v1/colors/random", searchColors: "GET /v1/colors", wcagContrast: "GET /v1/colors/contrast" }],
|
|
75
|
+
companies: ["companies", "https://api-companies.dataandapis.com", { companyIndustries: "GET /v1/companies/industries", dataSources: "GET /v1/sources", enrichByDomain: "GET /v1/companies/domain/{domain}", getCompany: "GET /v1/companies/{id}", randomCompanies: "GET /v1/companies/random", searchCompanies: "GET /v1/companies" }],
|
|
76
|
+
companyFinancials: ["company-financials", "https://api-company-financials.dataandapis.com", { companyProfile: "GET /v1/company/{ticker}", companySearch: "GET /v1/search", dataSources: "GET /v1/sources", keyFinancials: "GET /v1/financials/{ticker}", rawConcept: "GET /v1/concept/{ticker}/{concept}", reportedConcepts: "GET /v1/concepts/{ticker}" }],
|
|
77
|
+
continentsCountriesAndCities: ["continents-countries-and-cities", "https://continents-countries-and-cities.dataandapis.com", { cities: "GET /v1/cities", continents: "GET /v1/continents", countries: "GET /v1/countries", dataSources: "GET /v1/sources", getCityById: "GET /v1/cities/{id}", getContinentById: "GET /v1/continents/{id}", getCountryById: "GET /v1/countries/{id}", nearbyCities: "GET /v1/cities/nearby" }],
|
|
78
|
+
countryFlags: ["country-flags", "https://api-country-flags.dataandapis.com", { getFlagByCode: "GET /v1/flags/{code}", listFlags: "GET /v1/flags" }],
|
|
79
|
+
countryIndicators: ["country-indicators", "https://api-country-indicators.dataandapis.com", { countryProfile: "GET /v1/country/{code}", countryRankings: "GET /v1/rankings", dataSources: "GET /v1/sources", indicatorCatalog: "GET /v1/indicators", indicatorSeries: "GET /v1/data", listCountries: "GET /v1/countries" }],
|
|
80
|
+
cryptoPrices: ["crypto-prices", "https://api-crypto.dataandapis.com", { batchPrices: "GET /v1/prices", convert: "GET /v1/convert", dataSources: "GET /v1/sources", listCurrencies: "GET /v1/currencies", pairSpotPrice: "GET /v1/price/{pair}", priceHistory: "GET /v1/history/{pair}", tradingPairs: "GET /v1/pairs" }],
|
|
81
|
+
currencyRates: ["currency-rates", "https://api-currency.dataandapis.com", { convert: "GET /v1/convert", dataSources: "GET /v1/sources", listCurrencies: "GET /v1/currencies", rateHistory: "GET /v1/history", rateTable: "GET /v1/rates" }],
|
|
82
|
+
dayInHistory: ["day-in-history", "https://api-day-in-history.dataandapis.com", { dataSources: "GET /v1/sources", onThisDay: "GET /v1/onthisday" }],
|
|
83
|
+
demographics: ["demographics", "https://api-demographics.dataandapis.com", { countyDemographics: "GET /v1/demographics/county/{fips}", dataSources: "GET /v1/sources", getByGeoId: "GET /v1/demographics/{geo_id}", nationalDemographics: "GET /v1/demographics/us", rankings: "GET /v1/rankings", searchGeographies: "GET /v1/search", stateDemographics: "GET /v1/demographics/state/{code}", zipDemographics: "GET /v1/demographics/zip/{zip}" }],
|
|
84
|
+
dictionary: ["dictionary", "https://api-dictionary.dataandapis.com", { defineWord: "GET /v1/define/{word}" }],
|
|
85
|
+
disposableEmailChecker: ["disposable-email-checker", "https://api-disposable-email.dataandapis.com", { checkDisposable: "GET /v1/check" }],
|
|
86
|
+
dnsWhoisLookup: ["dns-whois-lookup", "https://api-dns-whois.dataandapis.com", { dnsLookup: "GET /v1/dns", whoisLookup: "GET /v1/whois" }],
|
|
87
|
+
dogs: ["dogs", "https://api-dogs.dataandapis.com", { breedGroups: "GET /v1/breeds/groups", getBreed: "GET /v1/breeds/{slug}", listBreeds: "GET /v1/breeds", randomBreeds: "GET /v1/breeds/random" }],
|
|
88
|
+
drugs: ["drugs", "https://api-drugs.dataandapis.com", { dataSources: "GET /v1/sources", deaSchedules: "GET /v1/drugs/schedules", dosageForms: "GET /v1/drugs/forms", getDrugByNdc: "GET /v1/drugs/{ndc}", randomDrugs: "GET /v1/drugs/random", searchDrugs: "GET /v1/drugs", searchRecalls: "GET /v1/recalls" }],
|
|
89
|
+
earthquakes: ["earthquakes", "https://api-earthquakes.dataandapis.com", { dataSources: "GET /v1/sources", earthquakesNearAPoint: "GET /v1/earthquakes/nearby", getEarthquake: "GET /v1/earthquakes/{id}", largestEarthquakes: "GET /v1/earthquakes/largest", searchEarthquakes: "GET /v1/earthquakes" }],
|
|
90
|
+
elements: ["elements", "https://api-elements.dataandapis.com", { dataSources: "GET /v1/sources", elementLookup: "GET /v1/elements/{key}", listElements: "GET /v1/elements", randomElement: "GET /v1/elements/random" }],
|
|
91
|
+
emailValidation: ["email-validation", "https://api-email-validation.dataandapis.com", { validateEmail: "GET /v1/validate" }],
|
|
92
|
+
emissionFactors: ["emission-factors", "https://api-emission-factors.dataandapis.com", { calculateEmissions: "GET /v1/calculate", calculateEmissionsBatch: "POST /v1/calculate", factorCategories: "GET /v1/factors/categories", factorSets: "GET /v1/factors/sets", factorUnits: "GET /v1/factors/units", getFactor: "GET /v1/factors/{slug}", globalWarmingPotentials: "GET /v1/factors/gwp", listFactors: "GET /v1/factors", randomFactor: "GET /v1/factors/random", sourceFreshness: "GET /v1/factors/updates" }],
|
|
93
|
+
emoji: ["emoji", "https://api-emoji.dataandapis.com", { dataSources: "GET /v1/sources", emojiGroups: "GET /v1/emoji/groups", emojiLookup: "GET /v1/emoji/{key}", randomEmoji: "GET /v1/emoji/random", searchEmoji: "GET /v1/emoji" }],
|
|
94
|
+
evChargers: ["ev-chargers", "https://api-ev-chargers.dataandapis.com", { chargingNetworks: "GET /v1/stations/networks", getStation: "GET /v1/stations/{id}", listStations: "GET /v1/stations", nearbyStations: "GET /v1/stations/nearby", randomStations: "GET /v1/stations/random", stationsByState: "GET /v1/stations/states" }],
|
|
95
|
+
federalContracts: ["federal-contracts", "https://api-federal-contracts.dataandapis.com", { agencies: "GET /v1/opportunities/agencies", closingSoon: "GET /v1/opportunities/closing", dataSources: "GET /v1/sources", expiringAwards: "GET /v1/awards/expiring", getOpportunityByNoticeId: "GET /v1/opportunities/{notice_id}", searchAwards: "GET /v1/awards", searchOpportunities: "GET /v1/opportunities", topRecipients: "GET /v1/awards/recipients" }],
|
|
96
|
+
federalRegister: ["federal-register", "https://api-federal-register.dataandapis.com", { agencies: "GET /v1/federal-register/agencies", dataSources: "GET /v1/sources", documentDetail: "GET /v1/federal-register/documents/{number}", executiveOrders: "GET /v1/federal-register/executive-orders", searchDocuments: "GET /v1/federal-register/documents" }],
|
|
97
|
+
foodNutritionInformation: ["food-nutrition-information", "https://food-nutrition-information.dataandapis.com", { getFood: "GET /v1/food/{id}", searchFoods: "GET /v1/foods/search" }],
|
|
98
|
+
foodRecalls: ["food-recalls", "https://api-food-recalls.dataandapis.com", { dataSources: "GET /v1/sources", recallLookup: "GET /v1/food-recalls/{number}", recallStats: "GET /v1/food-recalls/stats", searchRecalls: "GET /v1/food-recalls" }],
|
|
99
|
+
fuelStations: ["fuel-stations", "https://api-fuel-stations.dataandapis.com", { dataSources: "GET /v1/sources", fuelsRollup: "GET /v1/stations/fuels", getStationById: "GET /v1/stations/{id}", nearbyStations: "GET /v1/stations/nearby", randomStations: "GET /v1/stations/random", searchStations: "GET /v1/stations", statesRollup: "GET /v1/stations/states" }],
|
|
100
|
+
geocoding: ["geocoding", "https://api-geocoding.dataandapis.com", { dataSources: "GET /v1/sources", forwardGeocode: "GET /v1/geocode", placeDetail: "GET /v1/place/{id}", reverseGeocode: "GET /v1/reverse" }],
|
|
101
|
+
grants: ["grants", "https://api-grants.dataandapis.com", { dataSources: "GET /v1/sources", grantAgencies: "GET /v1/grants/agencies", grantLookup: "GET /v1/grants/{id}", searchGrants: "GET /v1/grants" }],
|
|
102
|
+
healthcareProviders: ["healthcare-providers", "https://api-healthcare-providers.dataandapis.com", { dataSources: "GET /v1/sources", getProviderByNpi: "GET /v1/providers/{npi}", getTaxonomyCode: "GET /v1/taxonomies/{code}", randomProviders: "GET /v1/providers/random", searchProviders: "GET /v1/providers", searchTaxonomies: "GET /v1/taxonomies" }],
|
|
103
|
+
hearthstone: ["hearthstone", "https://hearthstone.dataandapis.com", { getCardById: "GET /v1/cards/{slug}", getCards: "GET /v1/cards" }],
|
|
104
|
+
horoscopeZodiac: ["horoscope-zodiac", "https://api-horoscope.dataandapis.com", { dailyHoroscope: "GET /v1/horoscope/{sign}", listSigns: "GET /v1/signs", signByDate: "GET /v1/sign" }],
|
|
105
|
+
hospitals: ["hospitals", "https://api-hospitals.dataandapis.com", { getHospital: "GET /v1/hospitals/{ccn}", hospitalsByState: "GET /v1/hospitals/states", hospitalTypes: "GET /v1/hospitals/types", listHospitals: "GET /v1/hospitals", nearbyHospitals: "GET /v1/hospitals/nearby", randomHospitals: "GET /v1/hospitals/random" }],
|
|
106
|
+
htmlRender: ["html-render", "https://html-render.dataandapis.com", { convertHtml: "POST /v1/convert" }],
|
|
107
|
+
hurricanes: ["hurricanes", "https://api-hurricanes.dataandapis.com", { dataSources: "GET /v1/sources", getStormTrack: "GET /v1/storms/{id}", searchStorms: "GET /v1/storms", seasonStatistics: "GET /v1/storms/stats", stormsNearAPoint: "GET /v1/storms/nearby" }],
|
|
108
|
+
ibanSwiftValidator: ["iban-swift-validator", "https://api-iban-swift.dataandapis.com", { validateIban: "GET /v1/iban", validateSwiftBic: "GET /v1/swift" }],
|
|
109
|
+
imageToText: ["image-to-text", "https://api-image-to-text.dataandapis.com", { describeImage: "GET /v1/describe", describeImagePost: "POST /v1/describe" }],
|
|
110
|
+
inflation: ["inflation", "https://api-inflation.dataandapis.com", { annualInflationHistory: "GET /v1/inflation/history", cpiSeriesCatalog: "GET /v1/cpi/series", cpiValues: "GET /v1/cpi", dataSources: "GET /v1/sources", inflationCalculator: "GET /v1/inflation/calculator", inflationRate: "GET /v1/inflation/rate" }],
|
|
111
|
+
ipIntelligence: ["ip-intelligence", "https://api-ip-intelligence.dataandapis.com", { dataSources: "GET /v1/sources", getAutonomousSystem: "GET /v1/asns/{asn}", hostingProviders: "GET /v1/providers", lookupCallerIp: "GET /v1/ip/me", lookupIp: "GET /v1/ip/{address}", lookupIpBatch: "POST /v1/ip", searchAutonomousSystems: "GET /v1/asns" }],
|
|
112
|
+
jokes: ["jokes", "https://api-jokes.dataandapis.com", { getJoke: "GET /v1/jokes/{id}", listCategories: "GET /v1/jokes/categories", listJokes: "GET /v1/jokes", randomJoke: "GET /v1/jokes/random" }],
|
|
113
|
+
languageDetection: ["language-detection", "https://api-language-detection.dataandapis.com", { detectLanguage: "GET /v1/detect", detectLanguagePost: "POST /v1/detect" }],
|
|
114
|
+
logos: ["logos", "https://api-logos.dataandapis.com", { getLogoImage: "GET /v1/logos/{domain}/image", getLogosByQuery: "GET /v1/logos", getLogosForDomain: "GET /v1/logos/{domain}" }],
|
|
115
|
+
loremIpsum: ["lorem-ipsum", "https://lorem-ipsum.dataandapis.com", { paragraph: "GET /v1/paragraph", sentence: "GET /v1/sentence", word: "GET /v1/word" }],
|
|
116
|
+
lottery: ["lottery", "https://api-lottery.dataandapis.com", { getDraw: "GET /v1/draws/{id}", getProvider: "GET /v1/providers/{slug}", latestDraws: "GET /v1/draws/latest", listDrawsByProvider: "GET /v1/providers/{slug}/draws", listProviders: "GET /v1/providers" }],
|
|
117
|
+
mangaManhuaManhwa: ["manga-manhua-manhwa", "https://manga-manhua-manhwa.dataandapis.com", { getMangaById: "GET /v1/manga/{id}", manga: "GET /v1/manga" }],
|
|
118
|
+
mobileDevices: ["mobile-devices", "https://cellphone-and-tablet.dataandapis.com", { getBrands: "GET /v1/brands", getDevices: "GET /v1/devices" }],
|
|
119
|
+
mortgageLoanCalculator: ["mortgage-loan-calculator", "https://api-mortgage-calculator.dataandapis.com", { mortgageCalculator: "GET /v1/mortgage" }],
|
|
120
|
+
motorcycles: ["motorcycles", "https://api-motorcycles.dataandapis.com", { getMotorcycle: "GET /v1/motorcycles/{idOrSlug}", listMotorcycles: "GET /v1/motorcycles", motorcycleBrands: "GET /v1/motorcycles/brands", motorcycleCategories: "GET /v1/motorcycles/categories", motorcycleImage: "GET /v1/motorcycles/{idOrSlug}/image", randomMotorcycles: "GET /v1/motorcycles/random" }],
|
|
121
|
+
movies: ["movies", "https://api-movies.dataandapis.com", { dataSources: "GET /v1/sources", getTitle: "GET /v1/titles/{qid}", lookupByImdbId: "GET /v1/titles/imdb/{id}", randomTitle: "GET /v1/titles/random", searchTitles: "GET /v1/titles" }],
|
|
122
|
+
nameIntelligence: ["name-intelligence", "https://api-name-intelligence.dataandapis.com", { batchInferGender: "POST /v1/gender", dataSources: "GET /v1/sources", getNameStatistics: "GET /v1/names/{name}", getSurname: "GET /v1/surnames/{name}", inferGender: "GET /v1/gender/{name}", searchFirstNames: "GET /v1/names", searchSurnames: "GET /v1/surnames" }],
|
|
123
|
+
nonprofits: ["nonprofits", "https://api-nonprofits.dataandapis.com", { dataSources: "GET /v1/sources", nonprofitCategories: "GET /v1/nonprofits/categories", nonprofitsByState: "GET /v1/nonprofits/states", randomNonprofits: "GET /v1/nonprofits/random", searchNonprofits: "GET /v1/nonprofits", verifyNonprofit: "GET /v1/nonprofits/{ein}" }],
|
|
124
|
+
notablePeople: ["notable-people", "https://api-notable-people.dataandapis.com", { bornOnDate: "GET /v1/people/born-on", dataSources: "GET /v1/sources", diedOnDate: "GET /v1/people/died-on", getPersonByQid: "GET /v1/people/{qid}", randomPeople: "GET /v1/people/random", searchPeople: "GET /v1/people" }],
|
|
125
|
+
novel: ["novel", "https://novel.dataandapis.com", { getNovelById: "GET /v1/novels/{id}", novel: "GET /v1/novels" }],
|
|
126
|
+
objectDetection: ["object-detection", "https://api-object-detection.dataandapis.com", { detectObjects: "GET /v1/detect", detectObjectsPost: "POST /v1/detect" }],
|
|
127
|
+
occupations: ["occupations", "https://api-occupations.dataandapis.com", { alternateTitles: "GET /v1/occupations/{code}/titles", dataSources: "GET /v1/sources", jobZones: "GET /v1/occupations/job-zones", occupationProfile: "GET /v1/occupations/{code}", searchOccupations: "GET /v1/occupations", technologyLookup: "GET /v1/occupations/technology" }],
|
|
128
|
+
passwordGenerator: ["password-generator", "https://password-generator.dataandapis.com", { generatePassword: "GET /v1/generate-password" }],
|
|
129
|
+
phoneValidation: ["phone-validation", "https://api-phone-validation.dataandapis.com", { validatePhone: "GET /v1/phone" }],
|
|
130
|
+
pokemonUnite: ["pokemon-unite", "https://pokemon-unite.dataandapis.com", { getPokemonDataByName: "GET /v1/pokemon/{name}", listAllPokemons: "GET /v1/pokemon" }],
|
|
131
|
+
population: ["population", "https://api-population.dataandapis.com", { dataSources: "GET /v1/sources", rankings: "GET /v1/population/rankings", searchLocations: "GET /v1/population/locations", timeSeries: "GET /v1/population", yearSnapshot: "GET /v1/population/{country}/{year}" }],
|
|
132
|
+
powerPlants: ["power-plants", "https://api-power-plants.dataandapis.com", { capacityStats: "GET /v1/power-plants/stats", dataSources: "GET /v1/sources", nearestPlants: "GET /v1/power-plants/nearest", plantDetail: "GET /v1/power-plants/{id}", searchPlants: "GET /v1/power-plants" }],
|
|
133
|
+
productRecalls: ["product-recalls", "https://api-product-recalls.dataandapis.com", { checkBarcode: "GET /v1/recalls/upc/{upc}", dataSources: "GET /v1/sources", getRecall: "GET /v1/recalls/{id}", latestRecalls: "GET /v1/recalls/latest", recallStatistics: "GET /v1/recalls/stats", searchRecalls: "GET /v1/recalls" }],
|
|
134
|
+
profanityFilter: ["profanity-filter", "https://api-profanity-filter.dataandapis.com", { checkText: "GET /v1/check", checkTextPost: "POST /v1/check" }],
|
|
135
|
+
publicHolidays: ["public-holidays", "https://public-holidays.dataandapis.com", { countryHolidaysByYear: "GET /v1/holidays/{country}/{year}", dataSources: "GET /v1/sources", isItAHoliday: "GET /v1/holidays/today", longWeekends: "GET /v1/holidays/long-weekends/{country}/{year}", nextHolidays: "GET /v1/holidays/next", supportedCountries: "GET /v1/countries" }],
|
|
136
|
+
qrCodeGenerator: ["qr-code-generator", "https://api-qrcode.dataandapis.com", { generateQrCode: "GET /v1/qrcode", generateQrCodeBase64: "GET /v1/qrcode/base64" }],
|
|
137
|
+
quotes: ["quotes", "https://quotes.dataandapis.com", { getQuoteById: "GET /v1/quotes/{id}", getRandomQuote: "GET /v1/random" }],
|
|
138
|
+
randomImage: ["random-image", "https://api-random-image.dataandapis.com", { placeholderImage: "GET /v1/image", randomImage: "GET /v1/image/random" }],
|
|
139
|
+
randomUser: ["random-user", "https://api-random-user.dataandapis.com", { generateRandomUsers: "GET /v1/user", listNationalities: "GET /v1/user/nationalities" }],
|
|
140
|
+
recipes: ["recipes", "https://api-recipes.dataandapis.com", { getRecipe: "GET /v1/recipes/{slug}", listCuisines: "GET /v1/recipes/cuisines", listRecipes: "GET /v1/recipes", randomRecipe: "GET /v1/recipes/random" }],
|
|
141
|
+
riddles: ["riddles", "https://api-riddles.dataandapis.com", { getRiddle: "GET /v1/riddles/{id}", listCategories: "GET /v1/riddles/categories", listRiddles: "GET /v1/riddles", randomRiddle: "GET /v1/riddles/random" }],
|
|
142
|
+
rivers: ["rivers", "https://api-rivers.dataandapis.com", { dataSources: "GET /v1/sources", gaugeDetail: "GET /v1/rivers/sites/{id}", liveConditions: "GET /v1/rivers/conditions", nearestGauges: "GET /v1/rivers/nearest", searchGauges: "GET /v1/rivers/sites" }],
|
|
143
|
+
salaryBenchmarks: ["salary-benchmarks", "https://api-salary-benchmarks.dataandapis.com", { dataSources: "GET /v1/sources", nationalBenchmark: "GET /v1/wages/national/{soc}", searchAreas: "GET /v1/areas", searchOccupations: "GET /v1/occupations", searchWages: "GET /v1/wages" }],
|
|
144
|
+
salesTaxVat: ["sales-tax-vat", "https://api-sales-tax.dataandapis.com", { calculateTax: "GET /v1/calculate", dataSources: "GET /v1/sources", listVatRates: "GET /v1/vat", usSalesTax: "GET /v1/sales-tax/us/{state}", usSalesTaxAllStates: "GET /v1/sales-tax/us", vatByCountry: "GET /v1/vat/{country}" }],
|
|
145
|
+
sanctions: ["sanctions", "https://api-sanctions.dataandapis.com", { browseEntities: "GET /v1/entities", entityPrograms: "GET /v1/entities/programs", getEntity: "GET /v1/entities/{id}", screenName: "GET /v1/screen", screenNamesBatch: "POST /v1/screen", sourceLists: "GET /v1/lists" }],
|
|
146
|
+
seaports: ["seaports", "https://api-seaports.dataandapis.com", { dataSources: "GET /v1/sources", nearestPorts: "GET /v1/seaports/nearest", portDetail: "GET /v1/seaports/{key}", portsByCountry: "GET /v1/seaports/stats", searchPorts: "GET /v1/seaports" }],
|
|
147
|
+
sentimentAnalysis: ["sentiment-analysis", "https://api-sentiment.dataandapis.com", { analyzeSentiment: "GET /v1/sentiment", analyzeSentimentPost: "POST /v1/sentiment" }],
|
|
148
|
+
spaceLaunches: ["space-launches", "https://api-space-launches.dataandapis.com", { dataSources: "GET /v1/sources", launchDetail: "GET /v1/launches/{tag}", launchStats: "GET /v1/launches/stats", nextLaunch: "GET /v1/launches/next", searchLaunches: "GET /v1/launches", upcomingLaunches: "GET /v1/launches/upcoming" }],
|
|
149
|
+
spellCheck: ["spell-check", "https://api-spell-check.dataandapis.com", { checkTextPost: "POST /v1/check", checkWord: "GET /v1/check" }],
|
|
150
|
+
sslChecker: ["ssl-checker-api", "https://ssl-checker-api.dataandapis.com", { checksSslCertificate: "GET /v1/check" }],
|
|
151
|
+
stockTickers: ["stock-tickers", "https://api-stock-tickers.dataandapis.com", { dataSources: "GET /v1/sources", getTicker: "GET /v1/tickers/{symbol}", listingStatistics: "GET /v1/tickers/stats", searchTickers: "GET /v1/tickers" }],
|
|
152
|
+
tariffCodes: ["tariff-codes", "https://api-tariff-codes.dataandapis.com", { dataSources: "GET /v1/sources", htsChapters: "GET /v1/tariffs/chapters", searchTariffs: "GET /v1/tariffs", tariffLookup: "GET /v1/tariffs/{code}" }],
|
|
153
|
+
techStack: ["tech-stack", "https://api-tech-stack.dataandapis.com", { detectStack: "GET /v1/stack/{target}", detectStackBatch: "POST /v1/stack", technologyCatalogue: "GET /v1/technologies" }],
|
|
154
|
+
textEmbeddings: ["text-embeddings", "https://api-embeddings.dataandapis.com", { embedText: "GET /v1/embeddings", embedTextPost: "POST /v1/embeddings" }],
|
|
155
|
+
thesaurus: ["thesaurus", "https://api-thesaurus.dataandapis.com", { fullThesaurus: "GET /v1/thesaurus/{word}", getAntonyms: "GET /v1/antonyms/{word}", getSynonyms: "GET /v1/synonyms/{word}" }],
|
|
156
|
+
tides: ["tides", "https://api-tides.dataandapis.com", { dataSources: "GET /v1/sources", nearestStations: "GET /v1/tides/nearest", searchStations: "GET /v1/tides/stations", stationDetail: "GET /v1/tides/stations/{id}", tidePredictions: "GET /v1/tides/predictions", waterTemperature: "GET /v1/tides/water" }],
|
|
157
|
+
timezoneWorldTime: ["timezone-world-time", "https://api-timezone.dataandapis.com", { getCurrentTime: "GET /v1/time", getTimeByTimezone: "GET /v1/time/{timezone}", listTimezones: "GET /v1/timezones" }],
|
|
158
|
+
tradingCalendar: ["trading-calendar", "https://api-trading-calendar.dataandapis.com", { marketHolidays: "GET /v1/holidays", marketStatus: "GET /v1/status", nextTradingDay: "GET /v1/next", tradingDaysInRange: "GET /v1/trading-days" }],
|
|
159
|
+
trafficFatalities: ["traffic-fatalities", "https://api-traffic-fatalities.dataandapis.com", { crashesNearAPoint: "GET /v1/crashes/nearby", crashStatistics: "GET /v1/crashes/stats", dataSources: "GET /v1/sources", getCrash: "GET /v1/crashes/{year}/{st_case}", searchCrashes: "GET /v1/crashes" }],
|
|
160
|
+
translation: ["translation", "https://api-translation.dataandapis.com", { translate: "GET /v1/translate", translatePost: "POST /v1/translate" }],
|
|
161
|
+
travelAdvisories: ["travel-advisories", "https://api-travel-advisories.dataandapis.com", { dataSources: "GET /v1/sources", getAdvisoryForDestination: "GET /v1/advisories/{country}", listAdvisories: "GET /v1/advisories" }],
|
|
162
|
+
trending: ["trending", "https://api-trending.dataandapis.com", { articleInterest: "GET /v1/trending/article", dataSources: "GET /v1/sources", trendingArticles: "GET /v1/trending" }],
|
|
163
|
+
trivia: ["trivia", "https://api-trivia.dataandapis.com", { getTriviaById: "GET /v1/trivia/{id}", listCategories: "GET /v1/trivia/categories", listTrivia: "GET /v1/trivia", randomTrivia: "GET /v1/trivia/random" }],
|
|
164
|
+
unitConverter: ["unit-converter", "https://unit-converter.dataandapis.com", { getUnitInfo: "GET /v1/info", transformUnits: "GET /v1/converter" }],
|
|
165
|
+
universities: ["universities", "https://api-universities.dataandapis.com", { dataSources: "GET /v1/sources", getInstitution: "GET /v1/universities/{unitid}", searchUsInstitutions: "GET /v1/universities", statesRollup: "GET /v1/universities/states", worldUniversities: "GET /v1/world" }],
|
|
166
|
+
urlMetadata: ["url-metadata", "https://api-url-metadata.dataandapis.com", { getMetadata: "GET /v1/metadata" }],
|
|
167
|
+
usLawyers: ["us-lawyers", "https://api-us-lawyers.dataandapis.com", { getState: "GET /v1/states/{code}", listStates: "GET /v1/states", searchAttorneys: "GET /v1/states/{code}/search" }],
|
|
168
|
+
userAgentParser: ["user-agent-parser", "https://api-user-agent.dataandapis.com", { parseUserAgent: "GET /v1/parse" }],
|
|
169
|
+
vat: ["vat", "https://api-vat.dataandapis.com", { checkFormat: "GET /v1/vat/format", dataSources: "GET /v1/sources", supportedCountries: "GET /v1/vat/countries", validateVatNumber: "GET /v1/vat/validate" }],
|
|
170
|
+
vehicleRecalls: ["vehicle-recalls", "https://api-vehicle-recalls.dataandapis.com", { dataSources: "GET /v1/sources", getComplaint: "GET /v1/complaints/{odino}", getRecallCampaign: "GET /v1/recalls/{nhtsa_id}", latestRecalls: "GET /v1/recalls/latest", recallComponents: "GET /v1/recalls/components", searchComplaints: "GET /v1/complaints", searchRecalls: "GET /v1/recalls", vehicleSafetyProfile: "GET /v1/complaints/stats" }],
|
|
171
|
+
videoGames: ["video-games", "https://api-video-games.dataandapis.com", { dataSources: "GET /v1/sources", getGame: "GET /v1/games/{qid}", lookupBySteamAppId: "GET /v1/games/steam/{appid}", randomGame: "GET /v1/games/random", searchGames: "GET /v1/games" }],
|
|
172
|
+
vinDecoder: ["vin-decoder", "https://vin-decoder.dataandapis.com", { decodeVin: "GET /v1/decode" }],
|
|
173
|
+
watches: ["watches", "https://api-watches.dataandapis.com", { dataSources: "GET /v1/sources", getBrand: "GET /v1/brands/{name}", getCaliberBySlug: "GET /v1/calibers/{slug}", movementTypes: "GET /v1/calibers/types", randomCalibers: "GET /v1/calibers/random", searchBrands: "GET /v1/brands", searchCalibers: "GET /v1/calibers" }],
|
|
174
|
+
weather: ["weather", "https://api-weather.dataandapis.com", { dataSources: "GET /v1/sources", getForecast: "GET /v1/weather" }],
|
|
175
|
+
wildfires: ["wildfires", "https://api-wildfires.dataandapis.com", { currentWildfires: "GET /v1/wildfires", dataSources: "GET /v1/sources", nationalStats: "GET /v1/wildfires/stats", wildfiresNearMe: "GET /v1/wildfires/nearest" }],
|
|
176
|
+
zipPostalCode: ["zip-postal-code", "https://api-postal-code.dataandapis.com", { postalCodeLookup: "GET /v1/postal-code", searchByPlace: "GET /v1/search" }]
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
// src/version.ts
|
|
180
|
+
var VERSION = "0.1.0";
|
|
181
|
+
|
|
182
|
+
// src/client.ts
|
|
183
|
+
var DEFAULT_TIMEOUT = 3e4;
|
|
184
|
+
var DEFAULT_MAX_RETRIES = 2;
|
|
185
|
+
var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 502, 503, 504]);
|
|
186
|
+
var MAX_RETRY_WAIT = 1e4;
|
|
187
|
+
var HOST = "dataandapis.com";
|
|
188
|
+
var BASE_URLS = {};
|
|
189
|
+
for (const name of Object.keys(APIS)) {
|
|
190
|
+
const [slug, baseUrl] = APIS[name];
|
|
191
|
+
BASE_URLS[slug] = baseUrl;
|
|
192
|
+
BASE_URLS[name] = baseUrl;
|
|
193
|
+
}
|
|
194
|
+
function envApiKey() {
|
|
195
|
+
try {
|
|
196
|
+
const env = globalThis.process?.env;
|
|
197
|
+
return env?.DATAANDAPIS_API_KEY || void 0;
|
|
198
|
+
} catch {
|
|
199
|
+
return void 0;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
203
|
+
function isAbort(err) {
|
|
204
|
+
return typeof err === "object" && err !== null && err.name === "AbortError";
|
|
205
|
+
}
|
|
206
|
+
async function parseBody(res) {
|
|
207
|
+
if (res.status === 204 || res.status === 205) return void 0;
|
|
208
|
+
const type = (res.headers.get("content-type") || "").toLowerCase();
|
|
209
|
+
if (type.includes("json")) {
|
|
210
|
+
const text = await res.text();
|
|
211
|
+
if (!text) return void 0;
|
|
212
|
+
try {
|
|
213
|
+
return JSON.parse(text);
|
|
214
|
+
} catch {
|
|
215
|
+
return text;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (type.startsWith("text/") || type.startsWith("application/xml")) return res.text();
|
|
219
|
+
return res.blob();
|
|
220
|
+
}
|
|
221
|
+
function errorMessage(status, body, fallback) {
|
|
222
|
+
if (body && typeof body === "object") {
|
|
223
|
+
const b = body;
|
|
224
|
+
if (typeof b.message === "string" && b.message) return b.message;
|
|
225
|
+
if (typeof b.error === "string" && b.error) return b.error;
|
|
226
|
+
}
|
|
227
|
+
if (typeof body === "string" && body && body.length < 300) return body;
|
|
228
|
+
return fallback || `Request failed with status ${status}`;
|
|
229
|
+
}
|
|
230
|
+
var _apiKey, _timeout, _maxRetries, _headers, _fetch, _onResponse, _DataAndApis_instances, buildApi_fn, send_fn;
|
|
231
|
+
var DataAndApis = class {
|
|
232
|
+
constructor(options = {}) {
|
|
233
|
+
__privateAdd(this, _DataAndApis_instances);
|
|
234
|
+
__privateAdd(this, _apiKey);
|
|
235
|
+
__privateAdd(this, _timeout);
|
|
236
|
+
__privateAdd(this, _maxRetries);
|
|
237
|
+
__privateAdd(this, _headers);
|
|
238
|
+
__privateAdd(this, _fetch);
|
|
239
|
+
__privateAdd(this, _onResponse);
|
|
240
|
+
const apiKey = options.apiKey ?? envApiKey();
|
|
241
|
+
if (!apiKey) {
|
|
242
|
+
throw new DataAndApisError(
|
|
243
|
+
"Missing API key. Pass { apiKey } or set the DATAANDAPIS_API_KEY environment variable. Create a free key at https://dataandapis.com/sign-up"
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
__privateSet(this, _apiKey, apiKey);
|
|
247
|
+
__privateSet(this, _timeout, options.timeout ?? DEFAULT_TIMEOUT);
|
|
248
|
+
__privateSet(this, _maxRetries, options.maxRetries ?? DEFAULT_MAX_RETRIES);
|
|
249
|
+
__privateSet(this, _headers, { ...options.headers });
|
|
250
|
+
__privateSet(this, _fetch, options.fetch);
|
|
251
|
+
__privateSet(this, _onResponse, options.onResponse);
|
|
252
|
+
for (const name of Object.keys(APIS)) {
|
|
253
|
+
let cached;
|
|
254
|
+
Object.defineProperty(this, name, {
|
|
255
|
+
enumerable: true,
|
|
256
|
+
get: () => cached ?? (cached = __privateMethod(this, _DataAndApis_instances, buildApi_fn).call(this, name))
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Call any endpoint by path. Use it for endpoints newer than this version of the SDK.
|
|
262
|
+
*
|
|
263
|
+
* ```ts
|
|
264
|
+
* const data = await client.request("vat", "/v1/vat/validate", { query: { vat: "IE6388047V" } });
|
|
265
|
+
* ```
|
|
266
|
+
*
|
|
267
|
+
* @param api The API's catalog slug (`"ip-intelligence"`), its name on the client (`"ipIntelligence"`) or its base URL.
|
|
268
|
+
* @param path Path on that API, starting with `/v1/`.
|
|
269
|
+
*/
|
|
270
|
+
request(api, path, options = {}) {
|
|
271
|
+
let base = BASE_URLS[api];
|
|
272
|
+
let slug = api;
|
|
273
|
+
if (!base) {
|
|
274
|
+
if (!/^https:\/\//i.test(api)) {
|
|
275
|
+
throw new DataAndApisError(`Unknown API "${api}". Use a slug from https://dataandapis.com/apis or the API's https:// base URL.`);
|
|
276
|
+
}
|
|
277
|
+
base = api.replace(/\/+$/, "");
|
|
278
|
+
slug = new URL(base).hostname.split(".")[0].replace(/^api-/, "");
|
|
279
|
+
} else if (APIS[api]) {
|
|
280
|
+
slug = APIS[api][0];
|
|
281
|
+
}
|
|
282
|
+
return __privateMethod(this, _DataAndApis_instances, send_fn).call(this, slug, (options.method || "GET").toUpperCase(), base + (path.startsWith("/") ? path : `/${path}`), options.query, options.body, options);
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
_apiKey = new WeakMap();
|
|
286
|
+
_timeout = new WeakMap();
|
|
287
|
+
_maxRetries = new WeakMap();
|
|
288
|
+
_headers = new WeakMap();
|
|
289
|
+
_fetch = new WeakMap();
|
|
290
|
+
_onResponse = new WeakMap();
|
|
291
|
+
_DataAndApis_instances = new WeakSet();
|
|
292
|
+
buildApi_fn = function(name) {
|
|
293
|
+
const [slug, baseUrl, operations] = APIS[name];
|
|
294
|
+
const api = {};
|
|
295
|
+
for (const op of Object.keys(operations)) {
|
|
296
|
+
const space = operations[op].indexOf(" ");
|
|
297
|
+
const method = operations[op].slice(0, space);
|
|
298
|
+
const template = operations[op].slice(space + 1);
|
|
299
|
+
api[op] = async (params, options) => {
|
|
300
|
+
const rest = { ...params };
|
|
301
|
+
const body = rest.body;
|
|
302
|
+
if (method !== "GET") delete rest.body;
|
|
303
|
+
const path = template.replace(/\{(\w+)\}/g, (_, key) => {
|
|
304
|
+
const value = rest[key];
|
|
305
|
+
if (value === void 0 || value === null || value === "") {
|
|
306
|
+
throw new DataAndApisError(`Missing "${key}" for ${name}.${op}(): it is part of the path ${template}`);
|
|
307
|
+
}
|
|
308
|
+
delete rest[key];
|
|
309
|
+
return encodeURIComponent(String(value)).replace(/%2F/gi, "/");
|
|
310
|
+
});
|
|
311
|
+
const query = { ...rest, ...options?.query };
|
|
312
|
+
return __privateMethod(this, _DataAndApis_instances, send_fn).call(this, slug, method, baseUrl + path, query, method === "GET" ? void 0 : body, options);
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
return api;
|
|
316
|
+
};
|
|
317
|
+
send_fn = async function(slug, method, target, query, body, options) {
|
|
318
|
+
const url = new URL(target);
|
|
319
|
+
if (url.protocol !== "https:" || url.hostname !== HOST && !url.hostname.endsWith(`.${HOST}`)) {
|
|
320
|
+
throw new DataAndApisError(`Refusing to send the API key to ${url.origin}: only https://*.${HOST} is allowed.`);
|
|
321
|
+
}
|
|
322
|
+
if (query) {
|
|
323
|
+
for (const key of Object.keys(query)) {
|
|
324
|
+
const value = query[key];
|
|
325
|
+
if (value !== void 0 && value !== null) url.searchParams.set(key, String(value));
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const doFetch = __privateGet(this, _fetch) ?? globalThis.fetch;
|
|
329
|
+
if (typeof doFetch !== "function") {
|
|
330
|
+
throw new DataAndApisError("No fetch available. Use Node.js 18 or later, or pass a fetch implementation as { fetch }.");
|
|
331
|
+
}
|
|
332
|
+
const headers = {
|
|
333
|
+
Accept: "application/json",
|
|
334
|
+
"User-Agent": `dataandapis-js/${VERSION}`,
|
|
335
|
+
...__privateGet(this, _headers),
|
|
336
|
+
...options?.headers,
|
|
337
|
+
"X-Api-Key": __privateGet(this, _apiKey)
|
|
338
|
+
};
|
|
339
|
+
let payload;
|
|
340
|
+
if (body !== void 0 && body !== null) {
|
|
341
|
+
payload = typeof body === "string" ? body : JSON.stringify(body);
|
|
342
|
+
if (!Object.keys(headers).some((h) => h.toLowerCase() === "content-type")) headers["Content-Type"] = "application/json";
|
|
343
|
+
}
|
|
344
|
+
const timeout = options?.timeout ?? __privateGet(this, _timeout);
|
|
345
|
+
const maxRetries = method === "GET" ? Math.max(0, options?.maxRetries ?? __privateGet(this, _maxRetries)) : 0;
|
|
346
|
+
const href = url.toString();
|
|
347
|
+
for (let attempt = 1; ; attempt++) {
|
|
348
|
+
const canRetry = attempt <= maxRetries;
|
|
349
|
+
const controller = new AbortController();
|
|
350
|
+
let timedOut = false;
|
|
351
|
+
const timer = timeout > 0 ? setTimeout(() => {
|
|
352
|
+
timedOut = true;
|
|
353
|
+
controller.abort();
|
|
354
|
+
}, timeout) : void 0;
|
|
355
|
+
const outer = options?.signal;
|
|
356
|
+
const onAbort = () => controller.abort(outer.reason);
|
|
357
|
+
if (outer) {
|
|
358
|
+
if (outer.aborted) onAbort();
|
|
359
|
+
else outer.addEventListener("abort", onAbort, { once: true });
|
|
360
|
+
}
|
|
361
|
+
const started = Date.now();
|
|
362
|
+
let res;
|
|
363
|
+
let data;
|
|
364
|
+
try {
|
|
365
|
+
res = await doFetch(href, { method, headers, body: payload, signal: controller.signal });
|
|
366
|
+
const remaining = res.headers.get("ratelimit-requests-remaining");
|
|
367
|
+
const tokensRemaining = remaining !== null && remaining !== "" && !Number.isNaN(Number(remaining)) ? Number(remaining) : void 0;
|
|
368
|
+
if (__privateGet(this, _onResponse)) {
|
|
369
|
+
try {
|
|
370
|
+
__privateGet(this, _onResponse).call(this, { api: slug, method, url: href, status: res.status, ok: res.ok, durationMs: Date.now() - started, tokensRemaining, attempt });
|
|
371
|
+
} catch {
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (!res.ok && canRetry && RETRY_STATUSES.has(res.status)) {
|
|
375
|
+
try {
|
|
376
|
+
await res.arrayBuffer();
|
|
377
|
+
} catch {
|
|
378
|
+
}
|
|
379
|
+
const retryAfter = Number(res.headers.get("retry-after"));
|
|
380
|
+
await sleep(retryAfter > 0 ? Math.min(retryAfter * 1e3, MAX_RETRY_WAIT) : backoff(attempt));
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
data = await parseBody(res);
|
|
384
|
+
if (!res.ok) {
|
|
385
|
+
const details = { status: res.status, api: slug, method, url: href, body: data, tokensRemaining };
|
|
386
|
+
const message = errorMessage(res.status, data, res.statusText);
|
|
387
|
+
if (res.status === 401) throw new AuthenticationError(message, details);
|
|
388
|
+
if (res.status === 402) throw new PaymentRequiredError(message, details);
|
|
389
|
+
if (res.status === 429) throw new QuotaExceededError(message, details);
|
|
390
|
+
throw new ApiError(message, details);
|
|
391
|
+
}
|
|
392
|
+
return data;
|
|
393
|
+
} catch (err) {
|
|
394
|
+
if (err instanceof DataAndApisError) throw err;
|
|
395
|
+
if (outer?.aborted && !timedOut) throw err;
|
|
396
|
+
if (canRetry) {
|
|
397
|
+
await sleep(backoff(attempt));
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
if (timedOut) throw new TimeoutError(`${method} ${href} timed out after ${timeout} ms`, { cause: err });
|
|
401
|
+
if (isAbort(err)) throw err;
|
|
402
|
+
throw new ConnectionError(`${method} ${href} failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
403
|
+
} finally {
|
|
404
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
405
|
+
if (outer) outer.removeEventListener("abort", onAbort);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
function backoff(attempt) {
|
|
410
|
+
return Math.min(500 * 2 ** (attempt - 1), MAX_RETRY_WAIT) * (0.75 + Math.random() * 0.5);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
exports.ApiError = ApiError;
|
|
414
|
+
exports.AuthenticationError = AuthenticationError;
|
|
415
|
+
exports.ConnectionError = ConnectionError;
|
|
416
|
+
exports.DataAndApis = DataAndApis;
|
|
417
|
+
exports.DataAndApisError = DataAndApisError;
|
|
418
|
+
exports.PaymentRequiredError = PaymentRequiredError;
|
|
419
|
+
exports.QuotaExceededError = QuotaExceededError;
|
|
420
|
+
exports.TimeoutError = TimeoutError;
|
|
421
|
+
exports.VERSION = VERSION;
|