@afromero/kin3o 0.1.0 → 0.2.1

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/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  **Text to Motion. From your terminal.**
6
6
 
7
- [![npm](https://img.shields.io/npm/v/kin3o)](https://www.npmjs.com/package/kin3o)
7
+ [![npm](https://img.shields.io/npm/v/@afromero/kin3o)](https://www.npmjs.com/package/@afromero/kin3o)
8
8
  [![CI](https://github.com/affromero/kin3o/actions/workflows/ci.yml/badge.svg)](https://github.com/affromero/kin3o/actions/workflows/ci.yml)
9
9
  [![TypeScript](https://img.shields.io/badge/TypeScript-strict-blue)](https://www.typescriptlang.org/)
10
10
  [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
@@ -12,36 +12,33 @@
12
12
 
13
13
  AI-powered Lottie animation generator. Turns natural language prompts into valid, playable Lottie JSON and interactive dotLottie state machines using your existing Claude or Codex subscription.
14
14
 
15
+ <img src="assets/stick-figure-demo.gif" alt="Interactive state machine demo — hover to walk, press to run" width="640" />
16
+
15
17
  </div>
16
18
 
17
19
  ## Why?
18
20
 
19
- Every motion design tool (Rive, LottieFiles, Hera) sandboxes its AI inside a walled-garden editor, charges per-generation credits, and requires designs we don't have. kin3o spawns `claude --print` or `codex exec` as subprocesses to use existing Max/Pro subscriptions at zero marginal cost, with full context control via system prompts.
21
+ Great tools like [LottieFiles](https://lottiefiles.com), [Lottielab](https://www.lottielab.com), and [Rive](https://rive.app) offer powerful visual editors, massive animation libraries, and team collaboration if you need a full design workflow, they're excellent choices.
22
+
23
+ kin3o takes a different approach: it's a CLI tool for developers who want to generate animations from their terminal using AI subscriptions they already pay for. Search and download from the [LottieFiles](https://lottiefiles.com) marketplace (122K+ community animations), refine with AI, and publish back — all without leaving the terminal.
20
24
 
21
- ## Competitors
25
+ ## Choosing the right tool
22
26
 
23
- | Feature | **kin3o** | [LottieFiles](https://lottiefiles.com) | [LottieGen](https://lottiegenai.webflow.io/) | [Recraft](https://www.recraft.ai) | [Lottielab](https://www.lottielab.com) |
24
- |---------|-----------|-----------------|---------------|-------------|---------------|
25
- | Text → Lottie JSON | **Yes** | Yes (Motion Copilot) | Yes | Yes (via export) | No |
26
- | Text → State machines | **Yes (dotLottie)** | No | No | No | No |
27
- | CLI | **Yes** | No | No | No | No |
28
- | Web editor | **CLI-first** | Yes | Yes | Yes | Yes |
29
- | Open source | **Yes** | No | No | No | No |
30
- | Uses your own AI sub | **Yes** | No | No | No | No |
31
- | Custom design tokens | **Yes** | No | No | No | No |
32
- | Animation library | **Compatible with [LottieFiles](https://lottiefiles.com)** | Yes (massive) | No | Yes | Yes |
33
- | State machines | **Yes (dotLottie)** | Yes | No | No | Yes |
34
- | Team collaboration | **Git-native** | Yes | No | Yes | Yes |
35
- | Programmatic access | **Yes (CLI + stdout)** | Yes (REST API) | No | Yes (REST API) | Yes (REST API) |
36
- | **Price** | **Free (OSS)** | Free / $19.99+/mo | Waitlist (TBD) | Free (50/day) / $10+/mo | Free / up to $99/mo |
27
+ There are great tools for different animation workflows. Here's an honest look at where each shines:
37
28
 
38
- > Prices as of March 2026.
29
+ | Tool | Best for | Strengths |
30
+ |------|----------|-----------|
31
+ | **kin3o** | Developers who want animations from their terminal | CLI-first, uses your existing AI subscription, open source, git-friendly JSON output, interactive state machines from text |
32
+ | [**Rive**](https://rive.app) | Complex interactive animations with a visual editor | Skeletal animation, mesh deformation, runtime inputs (cursor tracking, sliders), built-in state machines, beautiful visual editor |
33
+ | [**LottieFiles**](https://lottiefiles.com) | Finding and sharing animations | Massive community library, Motion Copilot AI, After Effects integration, team collaboration — kin3o integrates directly for search, download, and publish |
34
+ | [**Lottielab**](https://www.lottielab.com) | Designing Lottie animations visually | Polished editor with timeline and keyframes, team collaboration, export to Lottie JSON |
35
+ | [**Recraft**](https://www.recraft.ai) | AI-powered design with animation export | Visual AI design tool, vector and animation output, broad creative capabilities |
39
36
 
40
37
  ## Quick Start
41
38
 
42
39
  ```bash
43
40
  # Install globally
44
- npm install -g kin3o
41
+ npm install -g @afromero/kin3o
45
42
 
46
43
  # Generate a static animation
47
44
  kin3o generate "loading spinner with 3 dots"
@@ -53,7 +50,7 @@ kin3o generate "toggle switch with on/off states" --interactive
53
50
  Or use without installing:
54
51
 
55
52
  ```bash
56
- npx kin3o generate "pulsing circle"
53
+ npx @afromero/kin3o generate "pulsing circle"
57
54
  ```
58
55
 
59
56
  ## CLI Usage
@@ -69,6 +66,10 @@ kin3o generate "loading dots" --tokens sotto
69
66
  kin3o generate "toggle switch with on/off states" --interactive
70
67
  kin3o generate "like button with hover and click" --interactive
71
68
 
69
+ # Refine an existing animation
70
+ kin3o refine output/animation.json "make it faster and add easing"
71
+ kin3o refine output/animation.lottie "add a bounce on the pressed state"
72
+
72
73
  # Preview
73
74
  kin3o preview output/animation.json
74
75
  kin3o preview output/animation.lottie
@@ -79,6 +80,21 @@ kin3o validate output/animation.lottie
79
80
 
80
81
  # List available AI providers
81
82
  kin3o providers
83
+
84
+ # Marketplace (LottieFiles)
85
+ kin3o search "loading spinner" # Search marketplace
86
+ kin3o search --featured --limit 10 # Browse featured
87
+ kin3o search --popular # Browse popular
88
+ kin3o search "button" --no-browser # Terminal output only
89
+ kin3o download abc12345 # Download by UUID
90
+ kin3o download <url> --lottie # Download as .lottie
91
+ kin3o login # Authenticate for publishing
92
+ kin3o publish output/anim.json --name "My Anim" --tags "loading,ui"
93
+ kin3o logout # Clear auth token
94
+
95
+ # Live preview with hot reload
96
+ kin3o view output/animation.json # File watcher + auto-reload
97
+ kin3o view output/animation.lottie --port 3000 # Specific port
82
98
  ```
83
99
 
84
100
  ### Options
@@ -91,6 +107,13 @@ kin3o providers
91
107
  | `--no-preview` | Skip browser preview |
92
108
  | `-i, --interactive` | Generate interactive state machine (`.lottie` output) |
93
109
  | `-t, --tokens <path>` | Design tokens JSON or `sotto` preset |
110
+ | `--featured` | Browse featured marketplace animations |
111
+ | `--popular` | Browse popular marketplace animations |
112
+ | `--recent` | Browse recent marketplace animations |
113
+ | `--limit <n>` | Number of search results (default: 20) |
114
+ | `--no-browser` | Print search results in terminal |
115
+ | `--lottie` | Download `.lottie` format instead of `.json` |
116
+ | `--port <n>` | Port for view server (auto-selects if omitted) |
94
117
 
95
118
  ## Using Generated Animations
96
119
 
@@ -139,41 +162,29 @@ animationView.play()
139
162
  </script>
140
163
  ```
141
164
 
142
- ## Why Lottie over Rive?
143
-
144
- ### For AI generation
145
-
146
- | Criteria | Lottie | Rive |
147
- |----------|--------|------|
148
- | Format | JSON (text, diffable) | Binary (.riv) |
149
- | LLM can generate? | Yes (structured JSON) | No (binary, no public writer) |
150
- | Web runtime | lottie-web (165KB) | @rive-app/canvas (200KB+) |
151
- | React integration | lottie-react | @rive-app/react-canvas |
152
- | Ecosystem | Massive (LottieFiles, AE) | Growing (Rive editor) |
153
- | **Verdict for AI gen** | **Winner** | Binary format = blocker |
165
+ ## Why Lottie?
154
166
 
155
- ### Animation capabilities
167
+ kin3o generates [Lottie](https://airbnb.io/lottie/) because its JSON format is ideal for AI generation — structured, text-based, and diffable. [Rive](https://rive.app) is a fantastic tool with capabilities Lottie doesn't have (skeletal animation, mesh deformation, runtime inputs), but its binary `.riv` format can't be generated by LLMs today.
156
168
 
157
- | Capability | Lottie | Rive |
158
- |-----------|--------|------|
159
- | Shape animation (scale, rotate, position, opacity) | | |
160
- | Path morphing, trim paths | | |
161
- | Color transitions | | |
162
- | Multi-layer compositions | | |
163
- | Masking, mattes | | |
164
- | Easing curves | | |
165
- | State machines (hover, click, drag states) | (dotLottie) | ✓ |
166
- | Skeletal/bone animation | ✗ | ✓ |
167
- | Mesh deformation | ✗ | ✓ |
168
- | Runtime input (eyes follow cursor, sliders) | ✗ | ✓ |
169
+ | What you need | Best tool |
170
+ |--------------|-----------|
171
+ | AI-generated animations from text | **kin3o** (Lottie JSON) |
172
+ | Interactive state machines from text | **kin3o** (dotLottie) |
173
+ | Skeletal animation, mesh deformation | [Rive](https://rive.app) (visual editor) |
174
+ | Massive animation library + community | [LottieFiles](https://lottiefiles.com) |
175
+ | Polished visual animation editor | [Lottielab](https://www.lottielab.com) or [Rive](https://rive.app) |
176
+ | Runtime inputs (cursor tracking, sliders) | [Rive](https://rive.app) |
177
+ | Search, download, publish to marketplace | **kin3o** + [LottieFiles](https://lottiefiles.com) |
169
178
 
170
- Lottie covers ~90% of real-world animation needs. The 10% Rive wins on skeletal animation, mesh deformation requires an interactive editor to wire up, not something generatable from a text prompt. State machines are now covered by kin3o via dotLottie.
179
+ Lottie covers shapes, paths, easing, color transitions, masking, andvia dotLottie — interactive state machines (hover, click, tap). That handles the vast majority of UI animations, loading states, and micro-interactions.
171
180
 
172
181
  ## Architecture
173
182
 
174
183
  ```
175
184
  Static: prompt → generate() → extractJson() → validateLottie() → autoFix() → .json → preview
176
185
  Interactive: prompt → generate() → extractInteractiveJson() → validate animations + state machine → .lottie → preview
186
+ Marketplace: search → browse → download → validate → .json/.lottie → refine → publish
187
+ Live preview: view <file> → HTTP server + fs.watch → SSE → browser auto-reload
177
188
  ```
178
189
 
179
190
  ### Prompt System
package/dist/index.js CHANGED
@@ -1,15 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from 'node:fs';
3
- import { writeFileSync } from 'node:fs';
4
- import { join } from 'node:path';
2
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
5
4
  import { Command } from 'commander';
6
5
  import { PROVIDERS, detectAvailableProviders, getDefaultProvider } from './providers/registry.js';
7
- import { buildSystemPrompt, buildInteractiveSystemPrompt, loadDesignTokens } from './prompts/index.js';
6
+ import { buildSystemPrompt, buildInteractiveSystemPrompt, buildRefinementUserPrompt, buildInteractiveRefinementUserPrompt, loadDesignTokens } from './prompts/index.js';
8
7
  import { validateLottie, autoFix } from './validator.js';
9
8
  import { validateStateMachine } from './state-machine-validator.js';
10
9
  import { openPreview, openDotLottiePreview } from './preview.js';
11
10
  import { writeDotLottie, readDotLottie } from './packager.js';
12
- import { extractJson, extractInteractiveJson, slugify, ensureOutputDir } from './utils.js';
11
+ import { extractJson, extractInteractiveJson, slugify, ensureOutputDir, nextVersionedPath } from './utils.js';
12
+ import { searchAnimations, featuredAnimations, popularAnimations, recentAnimations, resolveTarget, createLoginToken, pollForAccessToken, createUploadRequest, uploadFile, publishAnimation } from './marketplace.js';
13
+ import { openSearchResults } from './marketplace-preview.js';
14
+ import { loadAuthToken, loadAuthExpiry, saveAuthToken, clearAuthToken } from './marketplace-auth.js';
15
+ import { startViewServer } from './view.js';
13
16
  const program = new Command();
14
17
  program
15
18
  .name('kin3o')
@@ -154,6 +157,92 @@ async function handleInteractiveOutput(content, prompt, options) {
154
157
  console.log(` ✓ Preview opened: ${previewPath}`);
155
158
  }
156
159
  }
160
+ program
161
+ .command('refine <file> <prompt>')
162
+ .description('Refine an existing Lottie animation with a follow-up instruction')
163
+ .option('-p, --provider <provider>', 'AI provider to use')
164
+ .option('-m, --model <model>', 'Model to use')
165
+ .option('-o, --output <path>', 'Output file path')
166
+ .option('--no-preview', 'Skip opening preview in browser')
167
+ .option('-t, --tokens <path>', 'Path to design tokens JSON (or "sotto" for built-in)')
168
+ .action(async (file, prompt, rawOptions) => {
169
+ const resolvedPath = resolve(file);
170
+ // 1. Validate input file
171
+ if (!existsSync(resolvedPath)) {
172
+ console.error(` ✗ File not found: ${resolvedPath}`);
173
+ process.exit(1);
174
+ }
175
+ const isInteractive = file.endsWith('.lottie');
176
+ const mode = isInteractive ? 'interactive' : 'static';
177
+ console.log(`\nkin3o — Refining ${mode} animation...`);
178
+ // 2. Read current animation
179
+ let currentJson;
180
+ try {
181
+ if (isInteractive) {
182
+ const { animations, stateMachine } = await readDotLottie(resolvedPath);
183
+ currentJson = JSON.stringify({ animations, stateMachine }, null, 2);
184
+ }
185
+ else {
186
+ currentJson = readFileSync(resolvedPath, 'utf-8');
187
+ JSON.parse(currentJson); // validate it's valid JSON
188
+ }
189
+ }
190
+ catch (err) {
191
+ console.error(` ✗ Failed to read input file: ${err instanceof Error ? err.message : String(err)}`);
192
+ process.exit(1);
193
+ }
194
+ // 3. Warn on large files
195
+ const sizeKb = Math.round(statSync(resolvedPath).size / 1024);
196
+ if (sizeKb > 500) {
197
+ console.log(` ⚠ Large animation (${sizeKb}KB) — may hit provider token limits`);
198
+ }
199
+ // 4. Detect provider
200
+ let providerKey = rawOptions.provider;
201
+ if (!providerKey) {
202
+ providerKey = await getDefaultProvider() ?? undefined;
203
+ if (!providerKey) {
204
+ console.error(' ✗ No AI providers available. Install Claude Code, Codex, or set ANTHROPIC_API_KEY.');
205
+ process.exit(1);
206
+ }
207
+ }
208
+ const provider = PROVIDERS[providerKey];
209
+ if (!provider) {
210
+ console.error(` ✗ Unknown provider "${providerKey}". Run "kin3o providers" to see available options.`);
211
+ process.exit(1);
212
+ }
213
+ const model = rawOptions.model ?? provider.defaultModel;
214
+ console.log(` Provider: ${provider.displayName} (${model})`);
215
+ console.log(` Refining: ${file}`);
216
+ console.log(` Instruction: "${prompt}"\n`);
217
+ // 5. Build prompts
218
+ const tokens = rawOptions.tokens ? loadDesignTokens(rawOptions.tokens) : undefined;
219
+ const systemPrompt = isInteractive
220
+ ? buildInteractiveSystemPrompt(tokens)
221
+ : buildSystemPrompt(tokens);
222
+ const userPrompt = isInteractive
223
+ ? buildInteractiveRefinementUserPrompt(currentJson, prompt)
224
+ : buildRefinementUserPrompt(currentJson, prompt);
225
+ // 6. Generate refined output
226
+ try {
227
+ const result = await provider.generate(model, systemPrompt, userPrompt);
228
+ console.log(` ✓ Refined in ${(result.durationMs / 1000).toFixed(1)}s`);
229
+ // 7. Compute output path
230
+ const outputDir = ensureOutputDir();
231
+ const outputFile = rawOptions.output ?? nextVersionedPath(resolvedPath, outputDir);
232
+ const options = { ...rawOptions, interactive: isInteractive, output: outputFile };
233
+ if (isInteractive) {
234
+ await handleInteractiveOutput(result.content, prompt, options);
235
+ }
236
+ else {
237
+ await handleStaticOutput(result.content, prompt, options);
238
+ }
239
+ console.log('');
240
+ }
241
+ catch (err) {
242
+ console.error(` ✗ Refinement failed: ${err instanceof Error ? err.message : String(err)}`);
243
+ process.exit(1);
244
+ }
245
+ });
157
246
  program
158
247
  .command('preview <file>')
159
248
  .description('Preview a Lottie JSON or .lottie file in the browser')
@@ -176,6 +265,33 @@ program
176
265
  process.exit(1);
177
266
  }
178
267
  });
268
+ program
269
+ .command('view <file>')
270
+ .description('Live preview with hot reload (file watcher + auto-reload)')
271
+ .option('--port <n>', 'Port number (auto-selects if omitted)')
272
+ .action(async (file, options) => {
273
+ const resolvedPath = resolve(file);
274
+ if (!existsSync(resolvedPath)) {
275
+ console.error(` ✗ File not found: ${resolvedPath}`);
276
+ process.exit(1);
277
+ }
278
+ const ext = resolvedPath.split('.').pop()?.toLowerCase();
279
+ if (ext !== 'json' && ext !== 'lottie') {
280
+ console.error(' ✗ Unsupported file type. Use .json or .lottie');
281
+ process.exit(1);
282
+ }
283
+ const port = options.port ? parseInt(options.port, 10) : undefined;
284
+ console.log('\nkin3o — Live preview');
285
+ const server = await startViewServer(resolvedPath, { port });
286
+ console.log(` ✓ Serving ${file}`);
287
+ console.log(` ✓ ${server.url}`);
288
+ console.log(' Watching for changes... (Ctrl+C to stop)\n');
289
+ process.on('SIGINT', () => {
290
+ server.close();
291
+ console.log('\n ✓ Server stopped');
292
+ process.exit(0);
293
+ });
294
+ });
179
295
  program
180
296
  .command('providers')
181
297
  .description('List available AI providers')
@@ -246,4 +362,238 @@ program
246
362
  process.exit(1);
247
363
  }
248
364
  });
365
+ program
366
+ .command('search [query]')
367
+ .description('Search LottieFiles marketplace for animations')
368
+ .option('--featured', 'Show featured animations', false)
369
+ .option('--popular', 'Show popular animations', false)
370
+ .option('--recent', 'Show recent animations', false)
371
+ .option('--limit <n>', 'Number of results', '20')
372
+ .option('--no-browser', 'Print results to terminal instead')
373
+ .action(async (query, options) => {
374
+ const limit = parseInt(options.limit, 10) || 20;
375
+ const isBrowse = options.featured || options.popular || options.recent;
376
+ if (!query && !isBrowse) {
377
+ console.error(' ✗ Provide a search query or use --featured, --popular, or --recent');
378
+ process.exit(1);
379
+ }
380
+ console.log('\nkin3o — Searching LottieFiles...');
381
+ try {
382
+ let result;
383
+ let mode;
384
+ if (options.featured) {
385
+ mode = 'featured';
386
+ result = await featuredAnimations(limit);
387
+ }
388
+ else if (options.popular) {
389
+ mode = 'popular';
390
+ result = await popularAnimations(limit);
391
+ }
392
+ else if (options.recent) {
393
+ mode = 'recent';
394
+ result = await recentAnimations(limit);
395
+ }
396
+ else {
397
+ mode = 'search';
398
+ result = await searchAnimations(query, { first: limit });
399
+ }
400
+ console.log(` ✓ Found ${result.totalCount} animations${query ? ` for "${query}"` : ''}`);
401
+ if (result.animations.length === 0) {
402
+ console.log(' No results found.\n');
403
+ return;
404
+ }
405
+ if (!options.browser) {
406
+ // Terminal table output
407
+ console.log('');
408
+ const header = ' Name Author UUID Likes Downloads';
409
+ console.log(header);
410
+ console.log(' ' + '─'.repeat(header.length - 2));
411
+ for (const anim of result.animations) {
412
+ const name = (anim.name || '').slice(0, 32).padEnd(34);
413
+ const author = (anim.createdBy?.username || 'Unknown').slice(0, 14).padEnd(16);
414
+ const uuid = anim.uuid.slice(0, 14).padEnd(17);
415
+ const likes = String(anim.likesCount).padStart(5);
416
+ const dl = String(anim.downloads ?? 0).padStart(10);
417
+ console.log(` ${name}${author}${uuid}${likes}${dl}`);
418
+ }
419
+ console.log('');
420
+ }
421
+ else {
422
+ const previewPath = await openSearchResults(result.animations, {
423
+ query: query || '',
424
+ totalCount: result.totalCount,
425
+ mode,
426
+ });
427
+ console.log(` ✓ Results opened in browser: ${previewPath}`);
428
+ }
429
+ console.log(' Tip: Run "kin3o download <uuid>" to save an animation to output/\n');
430
+ }
431
+ catch (err) {
432
+ console.error(` ✗ Search failed: ${err instanceof Error ? err.message : String(err)}`);
433
+ process.exit(1);
434
+ }
435
+ });
436
+ program
437
+ .command('download <target>')
438
+ .description('Download an animation from LottieFiles (UUID, URL, or CDN link)')
439
+ .option('-o, --output <path>', 'Output file path')
440
+ .option('--no-preview', 'Skip preview')
441
+ .option('--lottie', 'Download .lottie format instead of .json', false)
442
+ .action(async (target, options) => {
443
+ console.log('\nkin3o — Downloading from LottieFiles...');
444
+ try {
445
+ const resolved = await resolveTarget(target, options.lottie);
446
+ if (options.lottie && resolved.lottieBuffer) {
447
+ const outputDir = ensureOutputDir();
448
+ const slug = resolved.meta ? slugify(resolved.meta.name) : 'animation';
449
+ const timestamp = Math.floor(Date.now() / 1000);
450
+ const outputPath = options.output
451
+ ? join(outputDir, options.output)
452
+ : join(outputDir, `${slug}-${timestamp}.lottie`);
453
+ writeFileSync(outputPath, resolved.lottieBuffer);
454
+ if (resolved.meta) {
455
+ console.log(` ✓ Downloaded: ${resolved.meta.name} by ${resolved.meta.createdBy?.username ?? 'Unknown'}`);
456
+ }
457
+ console.log(` ✓ Written to ${outputPath}`);
458
+ if (options.preview) {
459
+ const previewPath = await openDotLottiePreview(resolved.lottieBuffer);
460
+ console.log(` ✓ Preview opened: ${previewPath}`);
461
+ }
462
+ console.log(` Tip: Run "kin3o refine ${outputPath} 'your instruction'" to modify\n`);
463
+ return;
464
+ }
465
+ // JSON download
466
+ const lottieJson = resolved.json;
467
+ const validation = validateLottie(lottieJson);
468
+ if (!validation.valid) {
469
+ console.error(' ⚠ Downloaded Lottie has validation errors:');
470
+ validation.errors.forEach(e => console.error(` - ${e}`));
471
+ }
472
+ let finalJson = lottieJson;
473
+ if (validation.warnings.length > 0) {
474
+ finalJson = autoFix(lottieJson);
475
+ const fixes = validation.warnings.length;
476
+ console.log(` ✓ Valid Lottie JSON (${fixes} auto-fix${fixes > 1 ? 'es' : ''}: ${validation.warnings.join(', ')})`);
477
+ }
478
+ else if (validation.valid) {
479
+ console.log(' ✓ Valid Lottie JSON');
480
+ }
481
+ const outputDir = ensureOutputDir();
482
+ const slug = resolved.meta ? slugify(resolved.meta.name) : 'animation';
483
+ const timestamp = Math.floor(Date.now() / 1000);
484
+ const outputPath = options.output
485
+ ? join(outputDir, options.output)
486
+ : join(outputDir, `${slug}-${timestamp}.json`);
487
+ writeFileSync(outputPath, JSON.stringify(finalJson, null, 2), 'utf-8');
488
+ if (resolved.meta) {
489
+ console.log(` ✓ Downloaded: ${resolved.meta.name} by ${resolved.meta.createdBy?.username ?? 'Unknown'}`);
490
+ }
491
+ console.log(` ✓ Written to ${outputPath}`);
492
+ if (options.preview) {
493
+ const previewPath = await openPreview(finalJson);
494
+ console.log(` ✓ Preview opened: ${previewPath}`);
495
+ }
496
+ console.log(` Tip: Run "kin3o refine ${outputPath} 'your instruction'" to modify\n`);
497
+ }
498
+ catch (err) {
499
+ console.error(` ✗ Download failed: ${err instanceof Error ? err.message : String(err)}`);
500
+ process.exit(1);
501
+ }
502
+ });
503
+ // --- Auth + Publish commands ---
504
+ program
505
+ .command('login')
506
+ .description('Log in to LottieFiles to enable publishing')
507
+ .action(async () => {
508
+ const existing = loadAuthToken();
509
+ if (existing) {
510
+ const expiry = loadAuthExpiry();
511
+ console.log(` ✓ Already logged in (expires ${expiry ?? 'unknown'})`);
512
+ return;
513
+ }
514
+ const appKey = process.env['LOTTIEFILES_APP_KEY'];
515
+ if (!appKey) {
516
+ console.error(' ✗ LOTTIEFILES_APP_KEY environment variable is required.');
517
+ console.error(' Set it to your LottieFiles app key to enable login.');
518
+ process.exit(1);
519
+ }
520
+ console.log('\nkin3o — Logging in to LottieFiles...');
521
+ try {
522
+ const { loginUrl, token } = await createLoginToken(appKey);
523
+ const open = (await import('open')).default;
524
+ await open(loginUrl);
525
+ console.log(' Waiting for authentication... (complete login in browser)');
526
+ const { accessToken, expiresAt } = await pollForAccessToken(token);
527
+ saveAuthToken(accessToken, expiresAt);
528
+ console.log(` ✓ Logged in! Token expires ${expiresAt}\n`);
529
+ }
530
+ catch (err) {
531
+ console.error(` ✗ Login failed: ${err instanceof Error ? err.message : String(err)}`);
532
+ process.exit(1);
533
+ }
534
+ });
535
+ program
536
+ .command('logout')
537
+ .description('Log out from LottieFiles')
538
+ .action(() => {
539
+ clearAuthToken();
540
+ console.log(' ✓ Logged out');
541
+ });
542
+ program
543
+ .command('publish <file>')
544
+ .description('Publish an animation to LottieFiles marketplace')
545
+ .requiredOption('--name <name>', 'Animation name')
546
+ .requiredOption('--tags <tags>', 'Comma-separated tags')
547
+ .option('--description <desc>', 'Optional description')
548
+ .action(async (file, options) => {
549
+ const token = loadAuthToken();
550
+ if (!token) {
551
+ console.error(' ✗ Not logged in. Run "kin3o login" first.');
552
+ process.exit(1);
553
+ }
554
+ const resolvedPath = resolve(file);
555
+ if (!existsSync(resolvedPath)) {
556
+ console.error(` ✗ File not found: ${resolvedPath}`);
557
+ process.exit(1);
558
+ }
559
+ console.log('\nkin3o — Publishing to LottieFiles...');
560
+ try {
561
+ // Validate the file
562
+ const isLottie = file.endsWith('.lottie');
563
+ if (!isLottie) {
564
+ const raw = readFileSync(resolvedPath, 'utf-8');
565
+ const json = JSON.parse(raw);
566
+ const validation = validateLottie(json);
567
+ if (!validation.valid) {
568
+ console.error(' ✗ Invalid Lottie JSON:');
569
+ validation.errors.forEach(e => console.error(` - ${e}`));
570
+ process.exit(1);
571
+ }
572
+ console.log(' ✓ Validation passed');
573
+ }
574
+ const fileBuffer = readFileSync(resolvedPath);
575
+ const type = isLottie ? 'DOT_LOTTIE' : 'LOTTIE';
576
+ const filename = resolvedPath.split('/').pop() ?? 'animation.json';
577
+ // Create upload request
578
+ const { requestId, presignedUrl } = await createUploadRequest(token, filename, type);
579
+ console.log(' ✓ Upload request created');
580
+ // Upload file
581
+ await uploadFile(presignedUrl, fileBuffer);
582
+ console.log(' ✓ File uploaded');
583
+ // Create animation entry
584
+ const tags = options.tags.split(',').map(t => t.trim()).filter(Boolean);
585
+ const result = await publishAnimation(token, {
586
+ name: options.name,
587
+ requestId,
588
+ tags,
589
+ description: options.description,
590
+ });
591
+ console.log(` ✓ Published: ${options.name}`);
592
+ console.log(` ✓ View at: ${result.url}\n`);
593
+ }
594
+ catch (err) {
595
+ console.error(` ✗ Publish failed: ${err instanceof Error ? err.message : String(err)}`);
596
+ process.exit(1);
597
+ }
598
+ });
249
599
  program.parse();
@@ -0,0 +1,4 @@
1
+ export declare function loadAuthToken(): string | null;
2
+ export declare function loadAuthExpiry(): string | null;
3
+ export declare function saveAuthToken(token: string, expiresAt: string): void;
4
+ export declare function clearAuthToken(): void;
@@ -0,0 +1,44 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ const AUTH_DIR = join(homedir(), '.kin3o');
5
+ const AUTH_FILE = join(AUTH_DIR, 'auth.json');
6
+ export function loadAuthToken() {
7
+ if (!existsSync(AUTH_FILE))
8
+ return null;
9
+ try {
10
+ const raw = readFileSync(AUTH_FILE, 'utf-8');
11
+ const data = JSON.parse(raw);
12
+ if (!data.accessToken || !data.expiresAt)
13
+ return null;
14
+ const expires = new Date(data.expiresAt);
15
+ if (expires.getTime() <= Date.now())
16
+ return null;
17
+ return data.accessToken;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ export function loadAuthExpiry() {
24
+ if (!existsSync(AUTH_FILE))
25
+ return null;
26
+ try {
27
+ const raw = readFileSync(AUTH_FILE, 'utf-8');
28
+ const data = JSON.parse(raw);
29
+ return data.expiresAt ?? null;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ export function saveAuthToken(token, expiresAt) {
36
+ mkdirSync(AUTH_DIR, { recursive: true });
37
+ const data = { accessToken: token, expiresAt };
38
+ writeFileSync(AUTH_FILE, JSON.stringify(data, null, 2), 'utf-8');
39
+ }
40
+ export function clearAuthToken() {
41
+ if (existsSync(AUTH_FILE)) {
42
+ unlinkSync(AUTH_FILE);
43
+ }
44
+ }
@@ -0,0 +1,7 @@
1
+ import type { LottieFilesAnimation } from './marketplace.js';
2
+ export interface SearchMeta {
3
+ query: string;
4
+ totalCount: number;
5
+ mode: 'search' | 'featured' | 'popular' | 'recent';
6
+ }
7
+ export declare function openSearchResults(animations: LottieFilesAnimation[], meta: SearchMeta): Promise<string>;
@@ -0,0 +1,18 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import open from 'open';
5
+ import { ensureOutputDir } from './utils.js';
6
+ const templateDir = join(fileURLToPath(new URL('.', import.meta.url)), '..', 'preview');
7
+ export async function openSearchResults(animations, meta) {
8
+ const template = readFileSync(join(templateDir, 'template-search.html'), 'utf-8');
9
+ const html = template
10
+ .replace('__SEARCH_RESULTS__', JSON.stringify(animations))
11
+ .replace('__SEARCH_META__', JSON.stringify(meta));
12
+ const outputDir = ensureOutputDir();
13
+ const filename = `search-${Date.now()}.html`;
14
+ const fullPath = join(outputDir, filename);
15
+ writeFileSync(fullPath, html, 'utf-8');
16
+ await open(fullPath);
17
+ return fullPath;
18
+ }