twitterviewer 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +259 -2
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +33 -0
- package/dist/cli/cli.d.ts +21 -0
- package/dist/cli/cli.js +242 -0
- package/dist/cli/credentials.d.ts +16 -0
- package/dist/cli/credentials.js +44 -0
- package/dist/cli/errors.d.ts +21 -0
- package/dist/cli/errors.js +38 -0
- package/dist/cli/login.d.ts +24 -0
- package/dist/cli/login.js +78 -0
- package/dist/client.d.ts +62 -0
- package/dist/client.js +109 -0
- package/dist/errors.d.ts +27 -0
- package/dist/errors.js +39 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +3 -0
- package/dist/transport.d.ts +26 -0
- package/dist/transport.js +122 -0
- package/dist/types.d.ts +211 -0
- package/dist/types.js +5 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/package.json +44 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TwitterViewer
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,260 @@
|
|
|
1
|
-
#
|
|
1
|
+
# twitterviewer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript SDK and command line client for the [TwitterViewer](https://twitterviewer.ai) API: read public X (Twitter) posts, threads, Articles, profiles and replies as JSON, Markdown, text or PDF. All access is read-only. Independent service, not the official X API and not affiliated with X.
|
|
4
|
+
|
|
5
|
+
**Just want to read X in a browser?** [twitterviewer.app](https://twitterviewer.app) is the TwitterViewer web app: paste a post link or @username to read public X posts, threads, replies and profiles, no X account needed. [twitterviewer.ai](https://twitterviewer.ai) is the developer API that this package calls.
|
|
6
|
+
|
|
7
|
+
One package, two uses: `import { TwitterViewer } from 'twitterviewer'` is the SDK, `npx twitterviewer` is the CLI. Requires Node.js 20 or newer. No runtime dependencies.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install twitterviewer
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
The API and the CLI need a [Plus](https://twitterviewer.ai/pricing) subscription. Create an API key at <https://twitterviewer.ai/account/api> and set `TWITTERVIEWER_API_KEY`.
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { TwitterViewer } from 'twitterviewer'
|
|
21
|
+
|
|
22
|
+
const client = new TwitterViewer()
|
|
23
|
+
const result = await client.convert({ url: 'https://x.com/jack/status/20' })
|
|
24
|
+
|
|
25
|
+
console.log(result.markdown)
|
|
26
|
+
console.log(result.postsReturned, result.credits.remaining)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Configuration
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
const client = new TwitterViewer({
|
|
33
|
+
apiKey: 'tv_live_...', // default: TWITTERVIEWER_API_KEY
|
|
34
|
+
baseUrl: 'https://twitterviewer.ai', // default: TWITTERVIEWER_BASE_URL, then this
|
|
35
|
+
timeout: 30_000, // milliseconds per attempt; default 90000
|
|
36
|
+
maxRetries: 2, // default 2; 0 turns retries off
|
|
37
|
+
})
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`headers` adds request headers and `fetch` replaces the global `fetch`. Every method takes a last argument `{ signal, timeout }` for that call only.
|
|
41
|
+
|
|
42
|
+
## Methods
|
|
43
|
+
|
|
44
|
+
| Method | Operation | Returns |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `convert(params)` | `POST /api/v1/convert` | `ConvertResult` |
|
|
47
|
+
| `convertByQuery(params)` | `GET /api/v1/convert` | `ConvertResult` |
|
|
48
|
+
| `convertText(params)` | `POST /api/v1/convert` | `TextDocument` |
|
|
49
|
+
| `convertPdf(params)` | `POST /api/v1/convert` | `PdfDocument` |
|
|
50
|
+
| `replies(params)` | `GET /api/v1/replies` | `RepliesResult` |
|
|
51
|
+
| `credits()` | `GET /api/v1/credits` | `CreditBalance` |
|
|
52
|
+
| `swapPost(handle, id, params?)` | `GET /api/v1/swap/{handle}/status/{id}` | `TextDocument`, or by `format` |
|
|
53
|
+
| `swapProfile(handle, params?)` | `GET /api/v1/swap/{handle}` | `TextDocument`, or by `format` |
|
|
54
|
+
|
|
55
|
+
### convert
|
|
56
|
+
|
|
57
|
+
Structured posts plus the rendered document. `url` is a post or profile link on x.com or twitter.com, or an @handle.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const thread = await client.convert({ url: 'https://x.com/jack/status/20' }) // scope: 'thread' (default)
|
|
61
|
+
const one = await client.convert({ url: 'https://x.com/jack/status/20', scope: 'post', stats: 'off' })
|
|
62
|
+
const talk = await client.convert({ url: 'https://x.com/jack/status/20', scope: 'conversation' })
|
|
63
|
+
console.log(talk.replies.length)
|
|
64
|
+
|
|
65
|
+
const profile = await client.convert({ url: '@NASA', max: 50, replies: false, reposts: false })
|
|
66
|
+
for (const post of profile.posts) console.log(post.createdAt, post.likeCount, post.text)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`format: 'obsidian'` renders the `markdown` field with YAML frontmatter.
|
|
70
|
+
|
|
71
|
+
### convertByQuery
|
|
72
|
+
|
|
73
|
+
The same conversion sent as a GET request.
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
const result = await client.convertByQuery({ url: '@NASA', max: 10 })
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### convertText
|
|
80
|
+
|
|
81
|
+
The document itself: `markdown` (default), `obsidian` or `text`.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
const doc = await client.convertText({ url: 'https://x.com/jack/status/20', format: 'obsidian' })
|
|
85
|
+
console.log(doc.content, doc.postsReturned, doc.creditsCharged, doc.creditsRemaining)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### convertPdf
|
|
89
|
+
|
|
90
|
+
A PDF rendered on the server.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { writeFile } from 'node:fs/promises'
|
|
94
|
+
|
|
95
|
+
const pdf = await client.convertPdf({ url: 'https://x.com/jack/status/20', paper: 'letter' })
|
|
96
|
+
await writeFile(pdf.filename ?? 'post.pdf', pdf.data)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### replies
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
const result = await client.replies({ url: 'https://x.com/jack/status/20', max: 50 })
|
|
103
|
+
for (const reply of result.replies) console.log(reply.author.handle, reply.text)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### credits
|
|
107
|
+
|
|
108
|
+
Costs no credits.
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const balance = await client.credits()
|
|
112
|
+
console.log(balance.total, balance.plan.remaining, balance.purchased.remaining, balance.unlimited)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### swapPost and swapProfile
|
|
116
|
+
|
|
117
|
+
The address-style endpoints: the same conversion as `convert`, addressed by handle and post id. Markdown by default; `format: 'json'` returns a `ConvertResult` and `format: 'pdf'` a `PdfDocument`.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const markdown = await client.swapPost('jack', '20', { scope: 'post' })
|
|
121
|
+
const json = await client.swapPost('jack', '20', { format: 'json' })
|
|
122
|
+
const recent = await client.swapProfile('NASA', { max: 10 })
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Errors
|
|
126
|
+
|
|
127
|
+
Every failure is a `TwitterViewerError`. Branch on `code` and `details.reason`, not on `message`. An aborted call rejects with the abort reason instead.
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
import { TwitterViewer, TwitterViewerError } from 'twitterviewer'
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
await new TwitterViewer().convert({ url: 'https://x.com/jack/status/20' })
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (!(error instanceof TwitterViewerError)) throw error
|
|
136
|
+
console.error(error.status, error.code, error.message, error.retryAfterSec, error.details)
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
| Status | `code` | Meaning |
|
|
141
|
+
| --- | --- | --- |
|
|
142
|
+
| 400 | `INVALID_INPUT` | A parameter is missing or invalid, or the link is not an X post or profile |
|
|
143
|
+
| 401 | `UNAUTHORIZED` | No API key, or the key is malformed, unknown or deleted |
|
|
144
|
+
| 402 | `LIMIT_REACHED` | `details.reason` is `PLUS_REQUIRED` (the account has no Plus plan) or `INSUFFICIENT_CREDITS` (with `details.required`, `details.balance`) |
|
|
145
|
+
| 403 | `PROTECTED` | The X account is protected |
|
|
146
|
+
| 404 | `NOT_FOUND` | The post, account or address does not exist |
|
|
147
|
+
| 410 | `SUSPENDED` | The X account is suspended |
|
|
148
|
+
| 429 | `RATE_LIMITED` | Wait `retryAfterSec` seconds |
|
|
149
|
+
| 500 | `INTERNAL` | Unexpected server error |
|
|
150
|
+
| 501 | `UNSUPPORTED` | No data source can serve this kind of request right now |
|
|
151
|
+
| 502 | `UPSTREAM` | The X data source or PDF rendering failed |
|
|
152
|
+
| 503 | `SERVICE_UNAVAILABLE` | A part of the service is unavailable |
|
|
153
|
+
|
|
154
|
+
Codes produced by the library: `NETWORK`, `TIMEOUT`, `HTTP_ERROR` (an error status without an API error body) and `INVALID_RESPONSE`. The full list of API codes is exported as `API_ERROR_CODES`.
|
|
155
|
+
|
|
156
|
+
## Retries
|
|
157
|
+
|
|
158
|
+
Up to `maxRetries` (default 2) extra attempts, with the same rules for every method:
|
|
159
|
+
|
|
160
|
+
- **Retried**: a failed connection, a timeout, a connection dropped after the request was sent, a gateway error page, 429 and 5xx (including 503 with `details.reason` = `IN_PROGRESS`, which means the same request is still running).
|
|
161
|
+
- **Wait**: `retryAfterSec` when present, otherwise exponential backoff with jitter (about 0.5 s, 1 s, 2 s, at most 8 s). A `retryAfterSec` above 120 is not slept through; the error is thrown.
|
|
162
|
+
- **Not retried**: 402, other 4xx and 501 (`UNSUPPORTED`).
|
|
163
|
+
|
|
164
|
+
Retrying is safe: within 10 minutes the server answers a repeated request with the first result and does not charge again. Every authenticated request counts towards the rate limit, including failed ones.
|
|
165
|
+
|
|
166
|
+
## Credits and rate limits
|
|
167
|
+
|
|
168
|
+
- 1 credit = 1 post returned. A quoted post counts as one more post. Author profile data is free.
|
|
169
|
+
- A repeated request by the same account within 10 minutes returns the first result and is not charged again. Same request means: a conversion (the swap methods included), the same link (case-insensitive) with the same `scope`, `max`, `replies` and `reposts`, where changing `format` or `stats` does not matter and PDF is tracked separately; `replies`, the same post and `max`.
|
|
170
|
+
- If that result was partial (limited by the balance, or a free website preview of a conversion) and the account now has credits, the request is treated as new and charged.
|
|
171
|
+
- An identical request sent while the first is still running waits for it and gets its result without a second charge. If it is still running after a minute, the answer is 503 with `retryAfterSec` and `details.reason` = `IN_PROGRESS`.
|
|
172
|
+
- Errors and empty results are free.
|
|
173
|
+
- With a zero balance, billable calls fail with 402 before anything is fetched (a repeat within the 10 minutes still returns the earlier result).
|
|
174
|
+
- `replies` returns only as many posts as the balance covers. A post or thread conversion that costs more than the balance fails with 402 and nothing is charged. A profile conversion requests at most as many posts as the balance, and still fails with 402 if quoted posts push the cost above it.
|
|
175
|
+
- Plus adds 3,000 credits a month.
|
|
176
|
+
- Rate limits are counted per account over all keys and MCP: 30 requests a minute.
|
|
177
|
+
|
|
178
|
+
## CLI
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
npx twitterviewer login
|
|
182
|
+
npx twitterviewer https://x.com/jack/status/20
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Install it globally with `npm install -g twitterviewer` to type `twitterviewer` directly.
|
|
186
|
+
|
|
187
|
+
### Sign in
|
|
188
|
+
|
|
189
|
+
Signing in needs a Plus account, in the browser as well as with an existing key.
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
twitterviewer login # opens your browser, confirm the code shown in the terminal
|
|
193
|
+
twitterviewer login --no-open # only print the link
|
|
194
|
+
twitterviewer login --key tv_live_... # save an existing API key
|
|
195
|
+
echo "$KEY" | twitterviewer login --key-stdin
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
The key is saved to `~/.config/twitterviewer/credentials.json` (mode 600). `XDG_CONFIG_HOME` and `TWITTERVIEWER_CONFIG_DIR` change the location. Set `TWITTERVIEWER_API_KEY` to use a key without saving it; it takes priority over the saved one. Create and delete keys at <https://twitterviewer.ai/account/api>.
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
twitterviewer credits # remaining credits
|
|
202
|
+
twitterviewer logout # remove the saved key
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
### Convert
|
|
206
|
+
|
|
207
|
+
```bash
|
|
208
|
+
twitterviewer https://x.com/jack/status/20 # thread (default), Markdown on stdout
|
|
209
|
+
twitterviewer https://x.com/jack/status/20 --scope post # only that post
|
|
210
|
+
twitterviewer https://x.com/jack/status/20 --scope conversation
|
|
211
|
+
twitterviewer https://x.com/user/status/123 -o post.md # an Article post, saved to a file
|
|
212
|
+
twitterviewer @jack --max 50 --replies --reposts # a profile's recent posts
|
|
213
|
+
twitterviewer profile jack --format obsidian -o jack.md
|
|
214
|
+
twitterviewer <link> --format pdf -o thread.pdf # server-side PDF
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Markdown goes to stdout and the status line goes to stderr, so pipes stay clean:
|
|
218
|
+
|
|
219
|
+
```
|
|
220
|
+
$ twitterviewer https://x.com/jack/status/20 > post.md
|
|
221
|
+
1 post · 1 credit · 49 left
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
| Option | Values | Default |
|
|
225
|
+
| --- | --- | --- |
|
|
226
|
+
| `--scope` | `thread`, `post`, `conversation` | `thread` |
|
|
227
|
+
| `--format` | `md`, `obsidian`, `json`, `text`, `pdf` | `md` |
|
|
228
|
+
| `--stats` | `all`, `root`, `off` | `all` |
|
|
229
|
+
| `-o`, `--output` | file path (required for `pdf`) | stdout |
|
|
230
|
+
| `--max` | 1 to 200, profiles only | 20 |
|
|
231
|
+
| `--replies`, `--reposts` | profiles only | off |
|
|
232
|
+
| `--paper` | `a4`, `letter` (PDF) | `a4` |
|
|
233
|
+
| `-q`, `--quiet` | no status line | |
|
|
234
|
+
| `--base-url` | API host, or `TWITTERVIEWER_BASE_URL` | `https://twitterviewer.ai` |
|
|
235
|
+
|
|
236
|
+
Requests are retried the same way as in the SDK (up to 2 extra attempts), so a rate limited command may wait before it finishes.
|
|
237
|
+
|
|
238
|
+
### Exit codes
|
|
239
|
+
|
|
240
|
+
| Code | Meaning |
|
|
241
|
+
| --- | --- |
|
|
242
|
+
| 0 | success |
|
|
243
|
+
| 1 | error (network, not found, rate limit, upstream) |
|
|
244
|
+
| 2 | bad arguments |
|
|
245
|
+
| 3 | not signed in, invalid key, no Plus plan, or not enough credits |
|
|
246
|
+
|
|
247
|
+
## Development
|
|
248
|
+
|
|
249
|
+
```bash
|
|
250
|
+
bun install
|
|
251
|
+
bun run typecheck
|
|
252
|
+
bun run test
|
|
253
|
+
bun run build
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
`openapi.json` is a copy of the API specification; the tests check the SDK against it. Integration tests are skipped unless both `TWITTERVIEWER_BASE_URL` and `TWITTERVIEWER_API_KEY` are set, and they spend credits.
|
|
257
|
+
|
|
258
|
+
## License
|
|
259
|
+
|
|
260
|
+
[MIT](LICENSE)
|
package/dist/cli/bin.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { hostname } from 'node:os';
|
|
4
|
+
import { VERSION } from '../version.js';
|
|
5
|
+
import { run } from './cli.js';
|
|
6
|
+
function openBrowser(url) {
|
|
7
|
+
const [cmd, args] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
|
|
8
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
9
|
+
child.on('error', () => { });
|
|
10
|
+
child.unref();
|
|
11
|
+
}
|
|
12
|
+
async function readStdin() {
|
|
13
|
+
const chunks = [];
|
|
14
|
+
for await (const chunk of process.stdin)
|
|
15
|
+
chunks.push(chunk);
|
|
16
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
17
|
+
}
|
|
18
|
+
// A pipe closed early (| head) is not an error
|
|
19
|
+
process.stdout.on('error', (err) => {
|
|
20
|
+
if (err.code !== 'EPIPE')
|
|
21
|
+
throw err;
|
|
22
|
+
});
|
|
23
|
+
process.exitCode = await run(process.argv.slice(2), {
|
|
24
|
+
env: process.env,
|
|
25
|
+
version: VERSION,
|
|
26
|
+
fetch,
|
|
27
|
+
stdout: process.stdout,
|
|
28
|
+
stderr: process.stderr,
|
|
29
|
+
readStdin,
|
|
30
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
31
|
+
openBrowser,
|
|
32
|
+
hostname,
|
|
33
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { TwitterViewer } from '../client.js';
|
|
2
|
+
import { type LoginDeps } from './login.js';
|
|
3
|
+
export declare const USAGE = "twitterviewer - turn X (Twitter) posts, threads and profiles into Markdown\n\nUsage:\n twitterviewer <link> Convert a post, thread or Article link\n twitterviewer @handle Export a profile's recent posts\n twitterviewer profile <handle> Same as @handle\n twitterviewer login Sign in (device code in your browser)\n twitterviewer logout Remove the saved API key\n twitterviewer credits Show your credit balance\n\nOptions:\n --scope <thread|post|conversation> What to export for a post link (default: thread)\n --format <md|obsidian|json|text|pdf> Output format (default: md; pdf needs -o)\n --stats <all|root|off> Engagement numbers (default: all)\n -o, --output <file> Write to a file instead of stdout\n --max <n> Posts to export for a profile (default 20, max 200)\n --replies Profile: include replies\n --reposts Profile: include reposts\n --paper <a4|letter> PDF paper size (default: a4)\n -q, --quiet No status line on stderr\n --base-url <url> API host (env TWITTERVIEWER_BASE_URL)\n -h, --help Show this help\n -v, --version Show the version\n\nLogin options:\n --no-open Print the link, do not open the browser\n --key <key> Save an existing API key instead of the device flow\n --key-stdin Read an existing API key from stdin\n\nEnvironment:\n TWITTERVIEWER_API_KEY API key (takes priority over the saved one)\n TWITTERVIEWER_BASE_URL API host (default https://twitterviewer.ai)\n\nExit codes: 0 ok, 1 error, 2 bad arguments, 3 sign-in, Plus or credits needed.\nThe CLI needs Plus: https://twitterviewer.ai/pricing Keys: https://twitterviewer.ai/account/api\n";
|
|
4
|
+
export interface Deps extends LoginDeps {
|
|
5
|
+
env: Record<string, string | undefined>;
|
|
6
|
+
version: string;
|
|
7
|
+
stdout: {
|
|
8
|
+
write(chunk: string | Uint8Array): unknown;
|
|
9
|
+
};
|
|
10
|
+
readStdin: () => Promise<string>;
|
|
11
|
+
}
|
|
12
|
+
/** Entry point; returns the exit code. Network, terminal and file locations come from deps so tests can replace them. */
|
|
13
|
+
export declare function run(argv: string[], deps: Deps): Promise<number>;
|
|
14
|
+
export interface Status {
|
|
15
|
+
posts?: number | null;
|
|
16
|
+
charged?: number | null;
|
|
17
|
+
remaining?: number | null;
|
|
18
|
+
}
|
|
19
|
+
/** Status line on stderr, such as "12 posts · 12 credits · 4,988 left", plus the path when writing a file. */
|
|
20
|
+
export declare function statusLine({ posts, charged, remaining }: Status, output?: string): string;
|
|
21
|
+
export declare function credits(api: TwitterViewer, baseUrl: string, deps: Pick<Deps, 'stdout' | 'stderr'>): Promise<void>;
|
package/dist/cli/cli.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { TwitterViewer } from '../client.js';
|
|
5
|
+
import { TwitterViewerError } from '../errors.js';
|
|
6
|
+
import { configDir, DEFAULT_BASE_URL, deleteCredentials, readCredentials } from './credentials.js';
|
|
7
|
+
import { CliError, EXIT, fromApiError, keysUrl, normalizeBaseUrl, pricingUrl } from './errors.js';
|
|
8
|
+
import { cliHeaders, login } from './login.js';
|
|
9
|
+
export const USAGE = `twitterviewer - turn X (Twitter) posts, threads and profiles into Markdown
|
|
10
|
+
|
|
11
|
+
Usage:
|
|
12
|
+
twitterviewer <link> Convert a post, thread or Article link
|
|
13
|
+
twitterviewer @handle Export a profile's recent posts
|
|
14
|
+
twitterviewer profile <handle> Same as @handle
|
|
15
|
+
twitterviewer login Sign in (device code in your browser)
|
|
16
|
+
twitterviewer logout Remove the saved API key
|
|
17
|
+
twitterviewer credits Show your credit balance
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
--scope <thread|post|conversation> What to export for a post link (default: thread)
|
|
21
|
+
--format <md|obsidian|json|text|pdf> Output format (default: md; pdf needs -o)
|
|
22
|
+
--stats <all|root|off> Engagement numbers (default: all)
|
|
23
|
+
-o, --output <file> Write to a file instead of stdout
|
|
24
|
+
--max <n> Posts to export for a profile (default 20, max 200)
|
|
25
|
+
--replies Profile: include replies
|
|
26
|
+
--reposts Profile: include reposts
|
|
27
|
+
--paper <a4|letter> PDF paper size (default: a4)
|
|
28
|
+
-q, --quiet No status line on stderr
|
|
29
|
+
--base-url <url> API host (env TWITTERVIEWER_BASE_URL)
|
|
30
|
+
-h, --help Show this help
|
|
31
|
+
-v, --version Show the version
|
|
32
|
+
|
|
33
|
+
Login options:
|
|
34
|
+
--no-open Print the link, do not open the browser
|
|
35
|
+
--key <key> Save an existing API key instead of the device flow
|
|
36
|
+
--key-stdin Read an existing API key from stdin
|
|
37
|
+
|
|
38
|
+
Environment:
|
|
39
|
+
TWITTERVIEWER_API_KEY API key (takes priority over the saved one)
|
|
40
|
+
TWITTERVIEWER_BASE_URL API host (default ${DEFAULT_BASE_URL})
|
|
41
|
+
|
|
42
|
+
Exit codes: 0 ok, 1 error, 2 bad arguments, 3 sign-in, Plus or credits needed.
|
|
43
|
+
The CLI needs Plus: ${DEFAULT_BASE_URL}/pricing Keys: ${DEFAULT_BASE_URL}/account/api
|
|
44
|
+
`;
|
|
45
|
+
const FORMATS = { md: 'markdown', markdown: 'markdown', obsidian: 'obsidian', json: 'json', text: 'text', pdf: 'pdf' };
|
|
46
|
+
const SCOPES = ['thread', 'post', 'conversation'];
|
|
47
|
+
const STATS = ['all', 'root', 'off'];
|
|
48
|
+
const PAPERS = ['a4', 'letter'];
|
|
49
|
+
const usageError = (message) => new CliError(message, EXIT.usage);
|
|
50
|
+
function choice(name, value, allowed) {
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
return undefined;
|
|
53
|
+
if (!allowed.includes(value))
|
|
54
|
+
throw usageError(`Invalid --${name} "${value}". Use one of: ${allowed.join(', ')}.`);
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
const num = (n) => n.toLocaleString('en-US');
|
|
58
|
+
/** Entry point; returns the exit code. Network, terminal and file locations come from deps so tests can replace them. */
|
|
59
|
+
export async function run(argv, deps) {
|
|
60
|
+
try {
|
|
61
|
+
await dispatch(argv, deps);
|
|
62
|
+
return EXIT.ok;
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
if (err instanceof CliError) {
|
|
66
|
+
deps.stderr.write(`error: ${err.message}\n`);
|
|
67
|
+
if (err.info.hint)
|
|
68
|
+
deps.stderr.write(`${err.info.hint}\n`);
|
|
69
|
+
if (err.exitCode === EXIT.usage)
|
|
70
|
+
deps.stderr.write('Run "twitterviewer --help" for usage.\n');
|
|
71
|
+
return err.exitCode;
|
|
72
|
+
}
|
|
73
|
+
deps.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
74
|
+
return EXIT.error;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async function dispatch(argv, deps) {
|
|
78
|
+
let parsed;
|
|
79
|
+
try {
|
|
80
|
+
parsed = parse(argv);
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
throw usageError(err instanceof Error ? err.message : String(err));
|
|
84
|
+
}
|
|
85
|
+
const { values: v, positionals } = parsed;
|
|
86
|
+
if (v.help)
|
|
87
|
+
return void deps.stdout.write(USAGE);
|
|
88
|
+
if (v.version)
|
|
89
|
+
return void deps.stdout.write(`${deps.version}\n`);
|
|
90
|
+
const [first, ...rest] = positionals;
|
|
91
|
+
if (!first) {
|
|
92
|
+
deps.stdout.write(USAGE);
|
|
93
|
+
throw usageError('Missing link. Example: twitterviewer https://x.com/jack/status/20');
|
|
94
|
+
}
|
|
95
|
+
const dir = configDir(deps.env);
|
|
96
|
+
const stored = readCredentials(dir);
|
|
97
|
+
const baseUrl = normalizeBaseUrl(v['base-url'] || deps.env.TWITTERVIEWER_BASE_URL || stored?.baseUrl || DEFAULT_BASE_URL);
|
|
98
|
+
const envKey = deps.env.TWITTERVIEWER_API_KEY?.trim();
|
|
99
|
+
const apiKey = envKey || stored?.apiKey;
|
|
100
|
+
const client = () => {
|
|
101
|
+
if (!apiKey)
|
|
102
|
+
throw new CliError('Not signed in.', EXIT.auth, { hint: `Run "twitterviewer login", or set TWITTERVIEWER_API_KEY. Keys: ${keysUrl(baseUrl)}` });
|
|
103
|
+
return new TwitterViewer({ apiKey, baseUrl, fetch: deps.fetch, headers: cliHeaders(deps.version) });
|
|
104
|
+
};
|
|
105
|
+
try {
|
|
106
|
+
await command(first, rest, v, { dir, baseUrl, envKey, client }, deps);
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
throw err instanceof TwitterViewerError ? fromApiError(err, baseUrl) : err;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
async function command(first, rest, v, { dir, baseUrl, envKey, client }, deps) {
|
|
113
|
+
switch (first) {
|
|
114
|
+
case 'login':
|
|
115
|
+
if (rest.length)
|
|
116
|
+
throw usageError(`Unexpected argument "${rest[0]}".`);
|
|
117
|
+
return login({ baseUrl, version: deps.version, noOpen: Boolean(v['no-open']), key: v.key, keyStdin: Boolean(v['key-stdin']), dir }, deps);
|
|
118
|
+
case 'logout': {
|
|
119
|
+
const removed = deleteCredentials(dir);
|
|
120
|
+
deps.stderr.write(removed ? 'Logged out. The saved API key was removed (the key itself still works until you delete it on the API page).\n' : 'No saved API key.\n');
|
|
121
|
+
if (envKey)
|
|
122
|
+
deps.stderr.write('TWITTERVIEWER_API_KEY is still set in your environment.\n');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
case 'credits':
|
|
126
|
+
return credits(client(), baseUrl, deps);
|
|
127
|
+
case 'profile': {
|
|
128
|
+
const handle = rest[0];
|
|
129
|
+
if (!handle || rest.length > 1)
|
|
130
|
+
throw usageError('Usage: twitterviewer profile <handle>');
|
|
131
|
+
return convert(profileUrl(handle), v, client, deps);
|
|
132
|
+
}
|
|
133
|
+
default:
|
|
134
|
+
if (rest.length)
|
|
135
|
+
throw usageError(`Unexpected argument "${rest[0]}".`);
|
|
136
|
+
return convert(first.startsWith('@') ? profileUrl(first) : first, v, client, deps);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function parse(argv) {
|
|
140
|
+
return parseArgs({
|
|
141
|
+
args: argv,
|
|
142
|
+
allowPositionals: true,
|
|
143
|
+
options: {
|
|
144
|
+
scope: { type: 'string' },
|
|
145
|
+
format: { type: 'string' },
|
|
146
|
+
stats: { type: 'string' },
|
|
147
|
+
output: { type: 'string', short: 'o' },
|
|
148
|
+
max: { type: 'string' },
|
|
149
|
+
replies: { type: 'boolean' },
|
|
150
|
+
reposts: { type: 'boolean' },
|
|
151
|
+
paper: { type: 'string' },
|
|
152
|
+
quiet: { type: 'boolean', short: 'q' },
|
|
153
|
+
'base-url': { type: 'string' },
|
|
154
|
+
'no-open': { type: 'boolean' },
|
|
155
|
+
key: { type: 'string' },
|
|
156
|
+
'key-stdin': { type: 'boolean' },
|
|
157
|
+
help: { type: 'boolean', short: 'h' },
|
|
158
|
+
version: { type: 'boolean', short: 'v' },
|
|
159
|
+
},
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
function profileUrl(raw) {
|
|
163
|
+
const handle = raw.replace(/^@/, '');
|
|
164
|
+
if (!/^[A-Za-z0-9_]{1,15}$/.test(handle))
|
|
165
|
+
throw usageError(`Invalid X handle "${raw}".`);
|
|
166
|
+
return `https://x.com/${handle}`;
|
|
167
|
+
}
|
|
168
|
+
async function convert(url, v, client, deps) {
|
|
169
|
+
const format = v.format === undefined ? 'markdown' : Object.hasOwn(FORMATS, v.format) ? FORMATS[v.format] : undefined;
|
|
170
|
+
if (!format)
|
|
171
|
+
throw usageError(`Invalid --format "${v.format}". Use one of: md, obsidian, json, text, pdf.`);
|
|
172
|
+
const params = { url };
|
|
173
|
+
const scope = choice('scope', v.scope, SCOPES);
|
|
174
|
+
const stats = choice('stats', v.stats, STATS);
|
|
175
|
+
const paper = choice('paper', v.paper, PAPERS);
|
|
176
|
+
if (scope)
|
|
177
|
+
params.scope = scope;
|
|
178
|
+
if (stats)
|
|
179
|
+
params.stats = stats;
|
|
180
|
+
if (paper)
|
|
181
|
+
params.paper = paper;
|
|
182
|
+
if (v.max !== undefined) {
|
|
183
|
+
const max = Number(v.max);
|
|
184
|
+
if (!Number.isInteger(max) || max < 1 || max > 200)
|
|
185
|
+
throw usageError('--max must be a whole number from 1 to 200.');
|
|
186
|
+
params.max = max;
|
|
187
|
+
}
|
|
188
|
+
if (v.replies)
|
|
189
|
+
params.replies = true;
|
|
190
|
+
if (v.reposts)
|
|
191
|
+
params.reposts = true;
|
|
192
|
+
if (format === 'pdf' && !v.output)
|
|
193
|
+
throw usageError('--format pdf needs -o <file>: a PDF cannot be printed to the terminal.');
|
|
194
|
+
const { payload, ...status } = await fetchDocument(client(), format, params);
|
|
195
|
+
if (v.output) {
|
|
196
|
+
mkdirSync(dirname(v.output), { recursive: true });
|
|
197
|
+
writeFileSync(v.output, payload);
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
deps.stdout.write(payload);
|
|
201
|
+
}
|
|
202
|
+
if (v.quiet)
|
|
203
|
+
return;
|
|
204
|
+
deps.stderr.write(`${statusLine(status, v.output)}\n`);
|
|
205
|
+
}
|
|
206
|
+
async function fetchDocument(api, format, params) {
|
|
207
|
+
if (format === 'json') {
|
|
208
|
+
const result = await api.convert({ ...params, format });
|
|
209
|
+
return { payload: JSON.stringify(result), posts: result.postsReturned, charged: result.credits?.charged, remaining: result.credits?.remaining };
|
|
210
|
+
}
|
|
211
|
+
const doc = format === 'pdf' ? await api.convertPdf(params) : await api.convertText({ ...params, format });
|
|
212
|
+
return {
|
|
213
|
+
payload: 'data' in doc ? doc.data : doc.content,
|
|
214
|
+
posts: 'data' in doc ? null : doc.postsReturned,
|
|
215
|
+
charged: doc.creditsCharged,
|
|
216
|
+
remaining: doc.creditsRemaining,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/** Status line on stderr, such as "12 posts · 12 credits · 4,988 left", plus the path when writing a file. */
|
|
220
|
+
export function statusLine({ posts, charged, remaining }, output) {
|
|
221
|
+
const parts = [];
|
|
222
|
+
if (posts != null)
|
|
223
|
+
parts.push(`${num(posts)} ${posts === 1 ? 'post' : 'posts'}`);
|
|
224
|
+
if (charged != null)
|
|
225
|
+
parts.push(charged === 0 ? 'free' : `${num(charged)} ${charged === 1 ? 'credit' : 'credits'}`);
|
|
226
|
+
if (remaining != null)
|
|
227
|
+
parts.push(`${num(remaining)} left`);
|
|
228
|
+
if (output)
|
|
229
|
+
parts.push(`saved to ${output}`);
|
|
230
|
+
return parts.join(' · ') || 'done';
|
|
231
|
+
}
|
|
232
|
+
export async function credits(api, baseUrl, deps) {
|
|
233
|
+
const data = await api.credits();
|
|
234
|
+
const lines = [`Credits: ${num(data.total)}`];
|
|
235
|
+
if (data.plan?.remaining !== undefined)
|
|
236
|
+
lines.push(` Plan: ${num(data.plan.remaining)}${data.plan.expiresAt ? ` (resets ${data.plan.expiresAt.slice(0, 10)})` : ''}`);
|
|
237
|
+
if (data.purchased?.remaining !== undefined)
|
|
238
|
+
lines.push(` Purchased: ${num(data.purchased.remaining)}`);
|
|
239
|
+
deps.stdout.write(`${lines.join('\n')}\n`);
|
|
240
|
+
if (data.total === 0)
|
|
241
|
+
deps.stderr.write(`Get more credits: ${pricingUrl(baseUrl)}\n`);
|
|
242
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DEFAULT_BASE_URL } from '../client.js';
|
|
2
|
+
export { DEFAULT_BASE_URL };
|
|
3
|
+
export declare const KEY_PATTERN: RegExp;
|
|
4
|
+
export interface StoredCredentials {
|
|
5
|
+
apiKey: string;
|
|
6
|
+
/** The site the key was saved for; used when no base URL is given */
|
|
7
|
+
baseUrl: string;
|
|
8
|
+
}
|
|
9
|
+
/** Credentials directory: TWITTERVIEWER_CONFIG_DIR > $XDG_CONFIG_HOME/twitterviewer > ~/.config/twitterviewer. */
|
|
10
|
+
export declare function configDir(env: Record<string, string | undefined>): string;
|
|
11
|
+
export declare const credentialsPath: (dir: string) => string;
|
|
12
|
+
export declare function readCredentials(dir: string): StoredCredentials | null;
|
|
13
|
+
/** Directory 700, file 600; written to a temporary file and renamed, so a failure leaves no partial file. */
|
|
14
|
+
export declare function writeCredentials(dir: string, creds: StoredCredentials): void;
|
|
15
|
+
/** Deletes the credentials; returns whether they existed. */
|
|
16
|
+
export declare function deleteCredentials(dir: string): boolean;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { DEFAULT_BASE_URL } from '../client.js';
|
|
5
|
+
export { DEFAULT_BASE_URL };
|
|
6
|
+
export const KEY_PATTERN = /^tv_live_[A-Za-z0-9]{32}$/;
|
|
7
|
+
/** Credentials directory: TWITTERVIEWER_CONFIG_DIR > $XDG_CONFIG_HOME/twitterviewer > ~/.config/twitterviewer. */
|
|
8
|
+
export function configDir(env) {
|
|
9
|
+
if (env.TWITTERVIEWER_CONFIG_DIR)
|
|
10
|
+
return env.TWITTERVIEWER_CONFIG_DIR;
|
|
11
|
+
return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'twitterviewer');
|
|
12
|
+
}
|
|
13
|
+
export const credentialsPath = (dir) => join(dir, 'credentials.json');
|
|
14
|
+
export function readCredentials(dir) {
|
|
15
|
+
const file = credentialsPath(dir);
|
|
16
|
+
if (!existsSync(file))
|
|
17
|
+
return null;
|
|
18
|
+
try {
|
|
19
|
+
const data = JSON.parse(readFileSync(file, 'utf8'));
|
|
20
|
+
if (typeof data.apiKey !== 'string' || !KEY_PATTERN.test(data.apiKey))
|
|
21
|
+
return null;
|
|
22
|
+
return { apiKey: data.apiKey, baseUrl: typeof data.baseUrl === 'string' ? data.baseUrl : DEFAULT_BASE_URL };
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** Directory 700, file 600; written to a temporary file and renamed, so a failure leaves no partial file. */
|
|
29
|
+
export function writeCredentials(dir, creds) {
|
|
30
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
31
|
+
const file = credentialsPath(dir);
|
|
32
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
33
|
+
writeFileSync(tmp, `${JSON.stringify(creds, null, 2)}\n`, { mode: 0o600 });
|
|
34
|
+
chmodSync(tmp, 0o600);
|
|
35
|
+
renameSync(tmp, file);
|
|
36
|
+
}
|
|
37
|
+
/** Deletes the credentials; returns whether they existed. */
|
|
38
|
+
export function deleteCredentials(dir) {
|
|
39
|
+
const file = credentialsPath(dir);
|
|
40
|
+
if (!existsSync(file))
|
|
41
|
+
return false;
|
|
42
|
+
rmSync(file, { force: true });
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { TwitterViewerError } from '../errors.js';
|
|
2
|
+
export declare const EXIT: {
|
|
3
|
+
readonly ok: 0;
|
|
4
|
+
readonly error: 1;
|
|
5
|
+
readonly usage: 2;
|
|
6
|
+
readonly auth: 3;
|
|
7
|
+
};
|
|
8
|
+
export declare class CliError extends Error {
|
|
9
|
+
readonly exitCode: number;
|
|
10
|
+
readonly info: {
|
|
11
|
+
hint?: string;
|
|
12
|
+
};
|
|
13
|
+
constructor(message: string, exitCode?: number, info?: {
|
|
14
|
+
hint?: string;
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export declare function normalizeBaseUrl(raw: string): string;
|
|
18
|
+
export declare const pricingUrl: (baseUrl: string) => string;
|
|
19
|
+
export declare const keysUrl: (baseUrl: string) => string;
|
|
20
|
+
/** SDK error to exit code and hint: 401 and 402 exit with 3 (sign-in, Plus or credits needed), everything else with 1. */
|
|
21
|
+
export declare function fromApiError(err: TwitterViewerError, baseUrl: string): CliError;
|