refineo-cli 0.0.3

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,498 @@
1
+ #!/usr/bin/env node
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
+ ));
25
+
26
+ // src/cli.ts
27
+ var import_fs2 = require("fs");
28
+
29
+ // src/config.ts
30
+ var import_os = require("os");
31
+ var import_path = require("path");
32
+ var import_fs = require("fs");
33
+ var CONFIG_DIR = (0, import_path.join)((0, import_os.homedir)(), ".refineo");
34
+ var CREDENTIALS_FILE = (0, import_path.join)(CONFIG_DIR, "credentials.json");
35
+ var API_BASE_URL = process.env.REFINEO_API_URL || "https://refineo.app";
36
+ function ensureConfigDir() {
37
+ if (!(0, import_fs.existsSync)(CONFIG_DIR)) {
38
+ (0, import_fs.mkdirSync)(CONFIG_DIR, { recursive: true, mode: 448 });
39
+ }
40
+ }
41
+ function loadCredentials() {
42
+ try {
43
+ if (!(0, import_fs.existsSync)(CREDENTIALS_FILE)) {
44
+ return null;
45
+ }
46
+ const data = (0, import_fs.readFileSync)(CREDENTIALS_FILE, "utf-8");
47
+ return JSON.parse(data);
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+ function saveCredentials(credentials) {
53
+ ensureConfigDir();
54
+ (0, import_fs.writeFileSync)(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2), {
55
+ mode: 384
56
+ // Read/write for owner only
57
+ });
58
+ }
59
+ function clearCredentials() {
60
+ try {
61
+ if ((0, import_fs.existsSync)(CREDENTIALS_FILE)) {
62
+ (0, import_fs.unlinkSync)(CREDENTIALS_FILE);
63
+ }
64
+ } catch {
65
+ }
66
+ }
67
+ function isTokenExpired(credentials) {
68
+ const now = Math.floor(Date.now() / 1e3);
69
+ return credentials.expiresAt <= now + 60;
70
+ }
71
+ function getPlatformInfo() {
72
+ const platform = process.platform;
73
+ const arch = process.arch;
74
+ const nodeVersion = process.version;
75
+ let os = "Unknown";
76
+ if (platform === "darwin") os = "macOS";
77
+ else if (platform === "win32") os = "Windows";
78
+ else if (platform === "linux") os = "Linux";
79
+ return `refineo-cli/0.1.0 (${os}; ${arch}) Node/${nodeVersion}`;
80
+ }
81
+
82
+ // src/api.ts
83
+ var USER_AGENT = getPlatformInfo();
84
+ async function apiRequest(path, options = {}) {
85
+ const credentials = loadCredentials();
86
+ if (!credentials) {
87
+ throw new Error("Not logged in. Run: refineo login");
88
+ }
89
+ let token = credentials.accessToken;
90
+ if (isTokenExpired(credentials)) {
91
+ const refreshed = await refreshToken(credentials.refreshToken);
92
+ if (refreshed) {
93
+ token = refreshed.accessToken;
94
+ } else {
95
+ throw new Error("Session expired. Run: refineo login");
96
+ }
97
+ }
98
+ const response = await fetch(`${API_BASE_URL}${path}`, {
99
+ ...options,
100
+ headers: {
101
+ "Content-Type": "application/json",
102
+ "Authorization": `Bearer ${token}`,
103
+ "User-Agent": USER_AGENT,
104
+ ...options.headers
105
+ }
106
+ });
107
+ if (!response.ok) {
108
+ const error = await response.json().catch(() => ({ error: "Unknown error" }));
109
+ throw new Error(error.message || error.error_description || error.error || `HTTP ${response.status}`);
110
+ }
111
+ return response.json();
112
+ }
113
+ async function refreshToken(refreshTokenValue) {
114
+ try {
115
+ const response = await fetch(`${API_BASE_URL}/api/auth/device/refresh`, {
116
+ method: "POST",
117
+ headers: {
118
+ "Content-Type": "application/json",
119
+ "User-Agent": USER_AGENT
120
+ },
121
+ body: JSON.stringify({
122
+ refresh_token: refreshTokenValue,
123
+ grant_type: "refresh_token"
124
+ })
125
+ });
126
+ if (!response.ok) {
127
+ return null;
128
+ }
129
+ const data = await response.json();
130
+ const oldCredentials = loadCredentials();
131
+ const credentials = {
132
+ accessToken: data.access_token,
133
+ refreshToken: data.refresh_token,
134
+ expiresAt: data.expires_at,
135
+ user: oldCredentials?.user || { email: "", tier: "" }
136
+ };
137
+ saveCredentials(credentials);
138
+ return credentials;
139
+ } catch {
140
+ return null;
141
+ }
142
+ }
143
+ async function startDeviceCodeFlow() {
144
+ const response = await fetch(`${API_BASE_URL}/api/auth/device/code`, {
145
+ method: "POST",
146
+ headers: {
147
+ "Content-Type": "application/json",
148
+ "User-Agent": USER_AGENT
149
+ }
150
+ });
151
+ if (!response.ok) {
152
+ throw new Error("Failed to start login flow");
153
+ }
154
+ return response.json();
155
+ }
156
+ async function pollForToken(deviceCode, interval, expiresIn, onPoll) {
157
+ const startTime = Date.now();
158
+ const timeout = expiresIn * 1e3;
159
+ while (Date.now() - startTime < timeout) {
160
+ onPoll?.();
161
+ const response = await fetch(`${API_BASE_URL}/api/auth/device/token`, {
162
+ method: "POST",
163
+ headers: {
164
+ "Content-Type": "application/json",
165
+ "User-Agent": USER_AGENT
166
+ },
167
+ body: JSON.stringify({
168
+ device_code: deviceCode,
169
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
170
+ })
171
+ });
172
+ const data = await response.json();
173
+ if (response.ok) {
174
+ const tokenData = data;
175
+ const credentials = {
176
+ accessToken: tokenData.access_token,
177
+ refreshToken: tokenData.refresh_token,
178
+ expiresAt: tokenData.expires_at,
179
+ user: tokenData.user || { email: "", tier: "" }
180
+ };
181
+ saveCredentials(credentials);
182
+ return credentials;
183
+ }
184
+ const error = data;
185
+ if (error.error === "authorization_pending") {
186
+ await new Promise((resolve) => setTimeout(resolve, interval * 1e3));
187
+ continue;
188
+ }
189
+ if (error.error === "slow_down") {
190
+ await new Promise((resolve) => setTimeout(resolve, (interval + 5) * 1e3));
191
+ continue;
192
+ }
193
+ if (error.error === "access_denied") {
194
+ throw new Error(
195
+ error.error_description || "Access denied. CLI requires Pro or Ultra subscription."
196
+ );
197
+ }
198
+ if (error.error === "expired_token") {
199
+ throw new Error("Login timed out. Please try again.");
200
+ }
201
+ throw new Error(error.error_description || error.error || "Login failed");
202
+ }
203
+ throw new Error("Login timed out. Please try again.");
204
+ }
205
+ async function humanize(text, model = "enhanced") {
206
+ const result = await apiRequest("/api/humanize", {
207
+ method: "POST",
208
+ body: JSON.stringify({
209
+ text,
210
+ model: model === "standard" ? "BALANCE" : "ENHANCED"
211
+ })
212
+ });
213
+ return {
214
+ humanizedText: result.data.humanizedText,
215
+ wordCount: result.data.wordCount,
216
+ model: result.data.model
217
+ };
218
+ }
219
+ async function getUsage() {
220
+ const result = await apiRequest("/api/usage");
221
+ return {
222
+ tier: result.tier,
223
+ used: result.used,
224
+ limit: result.limit,
225
+ remaining: result.remaining,
226
+ resetDate: result.resetDate,
227
+ wordLimit: result.wordLimit,
228
+ rateLimit: result.rateLimit
229
+ };
230
+ }
231
+
232
+ // src/cli.ts
233
+ var VERSION = "0.1.0";
234
+ var colors = {
235
+ reset: "\x1B[0m",
236
+ bold: "\x1B[1m",
237
+ dim: "\x1B[2m",
238
+ green: "\x1B[32m",
239
+ yellow: "\x1B[33m",
240
+ blue: "\x1B[34m",
241
+ cyan: "\x1B[36m",
242
+ red: "\x1B[31m"
243
+ };
244
+ function print(message) {
245
+ console.log(message);
246
+ }
247
+ function printError(message) {
248
+ console.error(`${colors.red}Error:${colors.reset} ${message}`);
249
+ }
250
+ function printSuccess(message) {
251
+ print(`${colors.green}\u2713${colors.reset} ${message}`);
252
+ }
253
+ async function openBrowser(url) {
254
+ const { exec } = await import("child_process");
255
+ const { promisify } = await import("util");
256
+ const execAsync = promisify(exec);
257
+ const platform = process.platform;
258
+ let command;
259
+ if (platform === "darwin") {
260
+ command = `open "${url}"`;
261
+ } else if (platform === "win32") {
262
+ command = `start "" "${url}"`;
263
+ } else {
264
+ command = `xdg-open "${url}"`;
265
+ }
266
+ try {
267
+ await execAsync(command);
268
+ } catch {
269
+ print(`Please open this URL in your browser: ${url}`);
270
+ }
271
+ }
272
+ async function loginCommand() {
273
+ const existing = loadCredentials();
274
+ if (existing) {
275
+ print(`Already logged in as ${colors.cyan}${existing.user.email}${colors.reset}`);
276
+ print(`Tier: ${colors.bold}${existing.user.tier}${colors.reset}`);
277
+ print(`
278
+ Run ${colors.dim}refineo logout${colors.reset} to switch accounts.`);
279
+ return;
280
+ }
281
+ print(`${colors.bold}Refineo CLI Login${colors.reset}
282
+ `);
283
+ try {
284
+ const deviceCode = await startDeviceCodeFlow();
285
+ print(`Your code: ${colors.bold}${colors.cyan}${deviceCode.user_code}${colors.reset}
286
+ `);
287
+ print(`Opening browser to authorize...`);
288
+ print(`${colors.dim}${deviceCode.verification_uri_complete}${colors.reset}
289
+ `);
290
+ await openBrowser(deviceCode.verification_uri_complete);
291
+ print(`Waiting for authorization...`);
292
+ let dots = 0;
293
+ const credentials = await pollForToken(
294
+ deviceCode.device_code,
295
+ deviceCode.interval,
296
+ deviceCode.expires_in,
297
+ () => {
298
+ process.stdout.write(`\rWaiting for authorization${".".repeat(dots++ % 3 + 1)} `);
299
+ }
300
+ );
301
+ process.stdout.write("\r \r");
302
+ printSuccess(`Logged in as ${colors.cyan}${credentials.user.email}${colors.reset}`);
303
+ print(`Tier: ${colors.bold}${credentials.user.tier}${colors.reset}`);
304
+ } catch (error) {
305
+ printError(error instanceof Error ? error.message : "Login failed");
306
+ process.exit(1);
307
+ }
308
+ }
309
+ function logoutCommand() {
310
+ const credentials = loadCredentials();
311
+ if (!credentials) {
312
+ print("Not logged in.");
313
+ return;
314
+ }
315
+ clearCredentials();
316
+ printSuccess(`Logged out from ${credentials.user.email}`);
317
+ }
318
+ async function statsCommand() {
319
+ const credentials = loadCredentials();
320
+ if (!credentials) {
321
+ printError("Not logged in. Run: refineo login");
322
+ process.exit(1);
323
+ }
324
+ try {
325
+ const usage = await getUsage();
326
+ print(`${colors.bold}Refineo Usage${colors.reset}
327
+ `);
328
+ print(`Account: ${colors.cyan}${credentials.user.email}${colors.reset}`);
329
+ print(`Plan: ${colors.bold}${usage.tier}${colors.reset}`);
330
+ print("");
331
+ if (usage.limit === -1) {
332
+ print(`Requests: ${colors.green}Unlimited${colors.reset}`);
333
+ if (usage.rateLimit) {
334
+ print(`Rate limit: ${usage.rateLimit} requests/hour`);
335
+ }
336
+ } else {
337
+ const percentage = Math.round(usage.used / usage.limit * 100);
338
+ const color = percentage >= 90 ? colors.red : percentage >= 70 ? colors.yellow : colors.green;
339
+ print(`Requests: ${color}${usage.used}${colors.reset} / ${usage.limit} (${percentage}%)`);
340
+ print(`Remaining: ${usage.remaining}`);
341
+ }
342
+ print(`Word limit: ${usage.wordLimit} words/request`);
343
+ if (usage.resetDate) {
344
+ print(`Resets: ${usage.resetDate}`);
345
+ }
346
+ } catch (error) {
347
+ printError(error instanceof Error ? error.message : "Failed to get usage");
348
+ process.exit(1);
349
+ }
350
+ }
351
+ async function humanizeCommand(args) {
352
+ const credentials = loadCredentials();
353
+ if (!credentials) {
354
+ printError("Not logged in. Run: refineo login");
355
+ process.exit(1);
356
+ }
357
+ let text = "";
358
+ let model = "enhanced";
359
+ let inputFile = "";
360
+ let outputFile = "";
361
+ for (let i = 0; i < args.length; i++) {
362
+ const arg = args[i];
363
+ if (arg === "--model" || arg === "-m") {
364
+ const value = args[++i];
365
+ if (value === "standard" || value === "enhanced") {
366
+ model = value;
367
+ } else {
368
+ printError('Model must be "standard" or "enhanced"');
369
+ process.exit(1);
370
+ }
371
+ } else if (arg === "--file" || arg === "-f") {
372
+ inputFile = args[++i];
373
+ } else if (arg === "--output" || arg === "-o") {
374
+ outputFile = args[++i];
375
+ } else if (!arg.startsWith("-")) {
376
+ text = arg;
377
+ }
378
+ }
379
+ if (inputFile) {
380
+ if (!(0, import_fs2.existsSync)(inputFile)) {
381
+ printError(`File not found: ${inputFile}`);
382
+ process.exit(1);
383
+ }
384
+ text = (0, import_fs2.readFileSync)(inputFile, "utf-8");
385
+ }
386
+ if (!text) {
387
+ if (process.stdin.isTTY) {
388
+ printError('No text provided. Usage: refineo humanize "your text" or echo "text" | refineo humanize');
389
+ process.exit(1);
390
+ }
391
+ const chunks = [];
392
+ for await (const chunk of process.stdin) {
393
+ chunks.push(chunk);
394
+ }
395
+ text = Buffer.concat(chunks).toString("utf-8").trim();
396
+ }
397
+ if (!text) {
398
+ printError("No text provided");
399
+ process.exit(1);
400
+ }
401
+ try {
402
+ const result = await humanize(text, model);
403
+ if (outputFile) {
404
+ const { writeFileSync: writeFileSync2 } = await import("fs");
405
+ writeFileSync2(outputFile, result.humanizedText);
406
+ printSuccess(`Output written to ${outputFile}`);
407
+ } else {
408
+ print(result.humanizedText);
409
+ }
410
+ } catch (error) {
411
+ printError(error instanceof Error ? error.message : "Humanization failed");
412
+ process.exit(1);
413
+ }
414
+ }
415
+ function helpCommand() {
416
+ print(`
417
+ ${colors.bold}Refineo CLI${colors.reset} - AI Text Humanizer
418
+ Version ${VERSION}
419
+
420
+ ${colors.bold}Usage:${colors.reset}
421
+ refineo <command> [options]
422
+
423
+ ${colors.bold}Commands:${colors.reset}
424
+ login Authenticate with your Refineo account
425
+ logout Clear stored credentials
426
+ stats Show usage statistics
427
+ humanize <text> Humanize AI-generated text
428
+
429
+ ${colors.bold}Humanize Options:${colors.reset}
430
+ -m, --model <model> Model: "standard" or "enhanced" (default: enhanced)
431
+ -f, --file <path> Read input from file
432
+ -o, --output <path> Write output to file
433
+
434
+ ${colors.bold}Examples:${colors.reset}
435
+ ${colors.dim}# Login to your account${colors.reset}
436
+ refineo login
437
+
438
+ ${colors.dim}# Humanize text directly${colors.reset}
439
+ refineo humanize "The results indicate a significant correlation."
440
+
441
+ ${colors.dim}# Use standard model${colors.reset}
442
+ refineo humanize "Text here" --model standard
443
+
444
+ ${colors.dim}# Read from file${colors.reset}
445
+ refineo humanize --file input.txt --output output.txt
446
+
447
+ ${colors.dim}# Pipe from stdin${colors.reset}
448
+ echo "AI-generated text" | refineo humanize
449
+
450
+ ${colors.dim}# Check usage${colors.reset}
451
+ refineo stats
452
+
453
+ ${colors.bold}More Info:${colors.reset}
454
+ https://refineo.app/docs/cli
455
+ `);
456
+ }
457
+ function versionCommand() {
458
+ print(`refineo ${VERSION}`);
459
+ }
460
+ async function main() {
461
+ const args = process.argv.slice(2);
462
+ const command = args[0];
463
+ switch (command) {
464
+ case "login":
465
+ await loginCommand();
466
+ break;
467
+ case "logout":
468
+ logoutCommand();
469
+ break;
470
+ case "stats":
471
+ await statsCommand();
472
+ break;
473
+ case "humanize":
474
+ await humanizeCommand(args.slice(1));
475
+ break;
476
+ case "help":
477
+ case "--help":
478
+ case "-h":
479
+ helpCommand();
480
+ break;
481
+ case "version":
482
+ case "--version":
483
+ case "-v":
484
+ versionCommand();
485
+ break;
486
+ case void 0:
487
+ helpCommand();
488
+ break;
489
+ default:
490
+ printError(`Unknown command: ${command}`);
491
+ print(`Run ${colors.dim}refineo help${colors.reset} for usage.`);
492
+ process.exit(1);
493
+ }
494
+ }
495
+ main().catch((error) => {
496
+ printError(error instanceof Error ? error.message : "Unknown error");
497
+ process.exit(1);
498
+ });
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/config.ts
21
+ var config_exports = {};
22
+ __export(config_exports, {
23
+ API_BASE_URL: () => API_BASE_URL,
24
+ clearCredentials: () => clearCredentials,
25
+ getPlatformInfo: () => getPlatformInfo,
26
+ isTokenExpired: () => isTokenExpired,
27
+ loadCredentials: () => loadCredentials,
28
+ saveCredentials: () => saveCredentials
29
+ });
30
+ module.exports = __toCommonJS(config_exports);
31
+ var import_os = require("os");
32
+ var import_path = require("path");
33
+ var import_fs = require("fs");
34
+ var CONFIG_DIR = (0, import_path.join)((0, import_os.homedir)(), ".refineo");
35
+ var CREDENTIALS_FILE = (0, import_path.join)(CONFIG_DIR, "credentials.json");
36
+ var API_BASE_URL = process.env.REFINEO_API_URL || "https://refineo.app";
37
+ function ensureConfigDir() {
38
+ if (!(0, import_fs.existsSync)(CONFIG_DIR)) {
39
+ (0, import_fs.mkdirSync)(CONFIG_DIR, { recursive: true, mode: 448 });
40
+ }
41
+ }
42
+ function loadCredentials() {
43
+ try {
44
+ if (!(0, import_fs.existsSync)(CREDENTIALS_FILE)) {
45
+ return null;
46
+ }
47
+ const data = (0, import_fs.readFileSync)(CREDENTIALS_FILE, "utf-8");
48
+ return JSON.parse(data);
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ function saveCredentials(credentials) {
54
+ ensureConfigDir();
55
+ (0, import_fs.writeFileSync)(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2), {
56
+ mode: 384
57
+ // Read/write for owner only
58
+ });
59
+ }
60
+ function clearCredentials() {
61
+ try {
62
+ if ((0, import_fs.existsSync)(CREDENTIALS_FILE)) {
63
+ (0, import_fs.unlinkSync)(CREDENTIALS_FILE);
64
+ }
65
+ } catch {
66
+ }
67
+ }
68
+ function isTokenExpired(credentials) {
69
+ const now = Math.floor(Date.now() / 1e3);
70
+ return credentials.expiresAt <= now + 60;
71
+ }
72
+ function getPlatformInfo() {
73
+ const platform = process.platform;
74
+ const arch = process.arch;
75
+ const nodeVersion = process.version;
76
+ let os = "Unknown";
77
+ if (platform === "darwin") os = "macOS";
78
+ else if (platform === "win32") os = "Windows";
79
+ else if (platform === "linux") os = "Linux";
80
+ return `refineo-cli/0.1.0 (${os}; ${arch}) Node/${nodeVersion}`;
81
+ }
82
+ // Annotate the CommonJS export names for ESM import in node:
83
+ 0 && (module.exports = {
84
+ API_BASE_URL,
85
+ clearCredentials,
86
+ getPlatformInfo,
87
+ isTokenExpired,
88
+ loadCredentials,
89
+ saveCredentials
90
+ });