-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
325 lines (269 loc) · 9.06 KB
/
index.js
File metadata and controls
325 lines (269 loc) · 9.06 KB
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
const core = require('@actions/core');
const fs = require('fs');
const path = require('path');
// Schema cache for the duration of the action run
const schemaCache = new Map();
/**
* Fetch API schema from APIVerve assets
*/
async function getSchema(api) {
if (schemaCache.has(api)) {
core.debug(`Schema cache hit: ${api}`);
return schemaCache.get(api);
}
const url = `https://assets.apiverve.com/schemas/${api}.json`;
core.debug(`Fetching schema: ${url}`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Unknown API: "${api}". Check available APIs at https://apiverve.com`);
}
const schema = await response.json();
schemaCache.set(api, schema);
return schema;
}
/**
* Validate parameters against schema
*/
function validateParams(params, endpoint) {
const missing = [];
const parameters = endpoint.parameters || {};
for (const [name, def] of Object.entries(parameters)) {
if (def.required && !(name in params)) {
missing.push(name);
}
}
return missing;
}
/**
* Find download URL(s) in an object
* Always prioritizes 'downloadURL' field
* Returns single URL or array of URLs for APIs with multiple downloads
*/
function findDownloadUrl(obj) {
if (!obj || typeof obj !== 'object') return null;
// Priority 1: Direct downloadURL field (most common)
if (obj.downloadURL && typeof obj.downloadURL === 'string') {
return obj.downloadURL;
}
// Priority 2: Array of items with downloadURL (e.g., crossword, multiple files)
const urls = [];
for (const key of Object.keys(obj)) {
const val = obj[key];
// Check arrays of objects with downloadURL
if (Array.isArray(val)) {
for (const item of val) {
if (item?.downloadURL) urls.push(item.downloadURL);
}
}
// Check nested object with downloadURL
else if (val && typeof val === 'object' && val.downloadURL) {
urls.push(val.downloadURL);
}
}
if (urls.length > 0) {
return urls.length === 1 ? urls[0] : urls;
}
// Priority 3: Fallback to other URL-like fields
const fallbackKeys = ['imageURL', 'pdfURL', 'fileURL', 'screenshotURL', 'url'];
for (const key of fallbackKeys) {
if (obj[key] && typeof obj[key] === 'string' && obj[key].startsWith('http')) {
return obj[key];
}
}
return null;
}
/**
* Download file from URL and save to disk
*/
async function downloadFile(url, outputPath) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to download file: ${response.status}`);
}
const buffer = await response.arrayBuffer();
const dir = path.dirname(outputPath);
if (dir && !fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(outputPath, Buffer.from(buffer));
return outputPath;
}
/**
* Main action entry point
*/
async function run() {
const api = core.getInput('api', { required: true });
const paramsInput = core.getInput('params') || '{}';
const outputFile = core.getInput('output_file');
const failOnError = core.getInput('fail_on_error') !== 'false';
const format = core.getInput('format') || 'json';
// Validate format
const formatMap = {
'json': 'application/json',
'yaml': 'application/yaml',
'xml': 'application/xml'
};
if (!formatMap[format]) {
core.setFailed(`Invalid format: ${format}. Must be json, yaml, or xml.`);
return;
}
// API key: check input first, then env var
let apiKey = core.getInput('api_key');
if (!apiKey) {
apiKey = process.env.APIVERVE_API_KEY || process.env.APIVERVE_KEY;
}
if (!apiKey) {
core.setFailed('API key is required. Set api_key input or APIVERVE_API_KEY environment variable.');
return;
}
// Mask API key in all logs
core.setSecret(apiKey);
let params;
try {
params = JSON.parse(paramsInput);
} catch (e) {
core.setFailed(`Invalid JSON in params: ${e.message}`);
return;
}
try {
// Fetch and validate schema
core.startGroup(`Preparing API call: ${api}`);
const schema = await getSchema(api);
const endpoint = schema.endpoints?.[0];
if (!endpoint) {
throw new Error(`No endpoint found for API: ${api}`);
}
const method = endpoint.method || 'GET';
core.info(`API: ${schema.title || api}`);
core.info(`Method: ${method}`);
core.info(`Parameters: ${JSON.stringify(params)}`);
// Validate required parameters
const missing = validateParams(params, endpoint);
if (missing.length > 0) {
const paramDocs = missing.map(name => {
const def = endpoint.parameters[name];
return ` - ${name}: ${def.description || 'No description'}${def.example ? ` (e.g., "${def.example}")` : ''}`;
}).join('\n');
core.error(`Missing required parameters:\n${paramDocs}`);
core.setFailed(`Missing required parameters: ${missing.join(', ')}`);
return;
}
core.endGroup();
// Make API call
core.startGroup('Calling APIVerve');
const startTime = Date.now();
const url = new URL(`https://api.apiverve.com/v1/${api}`);
const options = {
method,
headers: {
'x-api-key': apiKey,
'Accept': formatMap[format],
'User-Agent': 'APIVerve-GitHub-Action/0.1'
}
};
if (format !== 'json') {
core.info(`Response format: ${format}`);
}
if (method === 'GET') {
Object.entries(params).forEach(([key, value]) => {
url.searchParams.set(key, String(value));
});
} else {
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(params);
}
core.debug(`Request URL: ${url.toString()}`);
const response = await fetch(url, options);
const elapsed = Date.now() - startTime;
core.info(`Status: ${response.status}`);
core.info(`Time: ${elapsed}ms`);
core.endGroup();
// Parse response based on format
let data;
let rawResponse;
if (format === 'json') {
data = await response.json();
rawResponse = JSON.stringify(data);
core.debug(`Response: ${rawResponse}`);
} else {
// YAML or XML - store as raw text
rawResponse = await response.text();
core.debug(`Response (${format}): ${rawResponse.substring(0, 500)}...`);
// Try to detect errors from the raw response
data = { status: response.ok ? 'ok' : 'error' };
}
// Check for errors
const hasError = !response.ok || data.status === 'error';
if (hasError) {
const errorMsg = data.error || data.message || `API returned status ${response.status}`;
core.error(`API Error: ${errorMsg}`);
if (failOnError) {
core.setFailed(errorMsg);
return;
}
}
// Set outputs
core.setOutput('result', rawResponse);
core.setOutput('status', data.status || 'ok');
if (format === 'json' && data.data) {
core.setOutput('data', JSON.stringify(data.data));
}
// Handle file output (for QR codes, screenshots, PDFs, etc.)
// Only works with JSON format
if (outputFile && format === 'json' && data.data) {
const fileUrls = findDownloadUrl(data.data);
if (fileUrls) {
core.startGroup('Downloading file(s)');
// Handle single URL or array of URLs
const urls = Array.isArray(fileUrls) ? fileUrls : [fileUrls];
const downloadedFiles = [];
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
// For multiple files, append index to filename
let destPath = outputFile;
if (urls.length > 1) {
const ext = path.extname(outputFile);
const base = outputFile.slice(0, -ext.length || undefined);
destPath = `${base}_${i + 1}${ext || ''}`;
}
core.info(`Downloading: ${url}`);
core.info(` → ${destPath}`);
await downloadFile(url, destPath);
downloadedFiles.push(destPath);
}
core.setOutput('file', downloadedFiles.length === 1 ? downloadedFiles[0] : downloadedFiles.join(','));
core.info(`Downloaded ${downloadedFiles.length} file(s)`);
core.endGroup();
} else {
core.warning('output_file specified but no download URL found in response');
core.debug(`Response data keys: ${Object.keys(data.data).join(', ')}`);
}
} else if (outputFile && format !== 'json') {
core.warning('output_file requires format=json to download files');
}
// Write job summary
const { summary } = core;
await summary
.addHeading(`APIVerve: ${schema.title || api}`, 3)
.addTable([
[
{ data: 'Status', header: true },
{ data: 'Time', header: true },
{ data: 'API', header: true }
],
[
data.status === 'ok' ? '✅ Success' : '❌ Error',
`${elapsed}ms`,
`<a href="https://apiverve.com/api/${api}?utm_source=github&utm_medium=action&utm_campaign=summary">${api}</a>`
]
])
.write();
if (data.status === 'ok') {
core.notice(`✓ ${schema.title || api} completed in ${elapsed}ms`);
}
} catch (error) {
core.error(`Action failed: ${error.message}`);
core.setFailed(error.message);
}
}
run();