@ohmagif/js 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +674 -0
- package/README.md +348 -2
- package/dist/fetch.d.ts +89 -0
- package/dist/fetch.js +239 -0
- package/dist/gif.d.ts +96 -0
- package/dist/gif.js +138 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/react/Card.d.ts +30 -0
- package/dist/react/Card.js +116 -0
- package/dist/react/Gif.d.ts +28 -0
- package/dist/react/Gif.js +12 -0
- package/dist/react/Grid.d.ts +55 -0
- package/dist/react/Grid.js +178 -0
- package/dist/react/Picture.d.ts +19 -0
- package/dist/react/Picture.js +22 -0
- package/dist/react/index.d.ts +3 -0
- package/dist/react/index.js +3 -0
- package/dist/react/layout.d.ts +34 -0
- package/dist/react/layout.js +43 -0
- package/package.json +69 -4
package/README.md
CHANGED
|
@@ -1,3 +1,349 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ohmagif-js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A client for the [ohmagif](https://ohmagif.com) API and a React GIF grid, for
|
|
4
|
+
chats, editors and anything else that lets people pick a GIF. It replaces
|
|
5
|
+
`@giphy/js-fetch-api` and `@giphy/react-components` with the same shape of
|
|
6
|
+
API. [Try it in an example chat](https://ohmagif.github.io/ohmagif-js/).
|
|
7
|
+
|
|
8
|
+
- No dependencies. React 18 or 19 is a peer, and only `@ohmagif/js/react` needs it.
|
|
9
|
+
- 5.6 kB gzipped, client and components together. The Giphy packages are
|
|
10
|
+
about 40 kB gzipped in the same app.
|
|
11
|
+
- No API key needed: the public API answers pages on any site.
|
|
12
|
+
- Requests carry no cookies and no referrer, and nothing reports what a person
|
|
13
|
+
looked at or picked.
|
|
14
|
+
- Every API answer is checked before it reaches the page: GIF ids are checked
|
|
15
|
+
before they go into a request, links and file addresses must be http or
|
|
16
|
+
https, and a GIF that does not check out is dropped.
|
|
17
|
+
- No injected CSS, so a strict `Content-Security-Policy` needs no
|
|
18
|
+
`'unsafe-inline'`.
|
|
19
|
+
- Each GIF is shown in the card ohmagif's embed draws: the frame, cut from
|
|
20
|
+
the credit strip burned into the file, and a line under it, "GIF by
|
|
21
|
+
@handle on ohmagif.com", that links to the GIF's page. A file that is
|
|
22
|
+
saved or shared keeps its strip.
|
|
23
|
+
- Every GIF's size is known before a byte of it arrives (`gifSize`), so a
|
|
24
|
+
chat can keep its room and nothing moves when it loads.
|
|
25
|
+
- Files are animated AVIF, with a JPEG first frame for browsers that cannot
|
|
26
|
+
show AVIF.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npm install @ohmagif/js
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Client
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { OhmagifFetch } from "@ohmagif/js";
|
|
38
|
+
|
|
39
|
+
const gf = new OhmagifFetch();
|
|
40
|
+
|
|
41
|
+
const { data, pagination } = await gf.search("side eye", { limit: 12, rating: "pg" });
|
|
42
|
+
const trending = await gf.trending({ offset: 12, limit: 12 });
|
|
43
|
+
const tagged = await gf.tag("oops");
|
|
44
|
+
const { data: gif } = await gf.gif("eTxuLnWv7C");
|
|
45
|
+
const { data: reactions } = await gf.reactions();
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
| Method | Answers |
|
|
49
|
+
|---|---|
|
|
50
|
+
| `search(term, options?)` | GIFs matching the words, best match first |
|
|
51
|
+
| `trending(options?)` | The GIFs shared most over the last days |
|
|
52
|
+
| `tag(slug, options?)` | GIFs with a tag or reaction |
|
|
53
|
+
| `gif(id, { signal }?)` | One GIF |
|
|
54
|
+
| `reactions({ signal }?)` | The curated reactions, each with its top GIF |
|
|
55
|
+
|
|
56
|
+
List options: `offset` (0 to 1000), `limit` (1 to 50, default 25), `rating`
|
|
57
|
+
(`g`, `pg` or `pg13`, the highest to include) and `signal`. Lists answer
|
|
58
|
+
`{ data, pagination: { total_count, count, offset, next } }`; `next` is the
|
|
59
|
+
offset of the next page, `null` after the last.
|
|
60
|
+
|
|
61
|
+
Constructor options, all optional:
|
|
62
|
+
|
|
63
|
+
| Option | |
|
|
64
|
+
|---|---|
|
|
65
|
+
| `apiKey` | Raises the limit from 60 requests a minute per address to 600 for the key. Anyone using a page can read a key sent from it, and keyed answers are never cached, so a browser app is better off without one. A string alone is taken as the key. |
|
|
66
|
+
| `baseURL` | `https://ohmagif.com` by default |
|
|
67
|
+
| `timeout` | Milliseconds, 10000 by default; 0 waits forever |
|
|
68
|
+
| `fetch` | A `fetch` to use instead of the global one |
|
|
69
|
+
|
|
70
|
+
Failures reject with an `OhmagifError` carrying `status`, `code` and
|
|
71
|
+
`retryAfter` (seconds, after a 429). `code` is the API's own (`not_found`,
|
|
72
|
+
`removed`, `search_unavailable`, ...) or one of `invalid_id` (no request was
|
|
73
|
+
sent), `network`, `timeout` and `invalid_response`. A request aborted through
|
|
74
|
+
its `signal` rejects with the signal's reason. Arguments out of range reject
|
|
75
|
+
with a `RangeError` before anything is sent.
|
|
76
|
+
|
|
77
|
+
`gf.uploadURL` is the site's upload page.
|
|
78
|
+
|
|
79
|
+
Ask for a GIF again rather than keeping it for long: when a GIF is rendered
|
|
80
|
+
again its files get new addresses and the old ones go an hour later. Store the
|
|
81
|
+
id, not the file address, and `frameSize(gif)` to hold the GIF's room before
|
|
82
|
+
it loads.
|
|
83
|
+
|
|
84
|
+
Every file has a 24 px credit strip under its frame (`CREDIT_STRIP_HEIGHT`).
|
|
85
|
+
`width` and `height` include it; `frameSize(gif)` is the frame alone, in
|
|
86
|
+
whole pixels, as the components show it.
|
|
87
|
+
|
|
88
|
+
## React
|
|
89
|
+
|
|
90
|
+
```tsx
|
|
91
|
+
import { useCallback } from "react";
|
|
92
|
+
import { OhmagifFetch, type Gif as GifData } from "@ohmagif/js";
|
|
93
|
+
import { Gif, Grid } from "@ohmagif/js/react";
|
|
94
|
+
|
|
95
|
+
const gf = new OhmagifFetch();
|
|
96
|
+
|
|
97
|
+
function Picker({ term, onPick }: { term: string; onPick: (gif: GifData) => void }) {
|
|
98
|
+
const fetchGifs = useCallback(
|
|
99
|
+
(offset: number, signal: AbortSignal) => {
|
|
100
|
+
const options = { offset, limit: 12, rating: "pg" as const, signal };
|
|
101
|
+
return term ? gf.search(term, options) : gf.trending(options);
|
|
102
|
+
},
|
|
103
|
+
[term],
|
|
104
|
+
);
|
|
105
|
+
return (
|
|
106
|
+
<Grid
|
|
107
|
+
key={term}
|
|
108
|
+
fetchGifs={fetchGifs}
|
|
109
|
+
width={336}
|
|
110
|
+
columns={2}
|
|
111
|
+
noLink
|
|
112
|
+
onGifClick={(gif) => onPick(gif)}
|
|
113
|
+
uploadURL={gf.uploadURL}
|
|
114
|
+
/>
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function Message({ gif }: { gif: GifData }) {
|
|
119
|
+
return <Gif gif={gif} width={322} />;
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### `Grid`
|
|
124
|
+
|
|
125
|
+
GIFs in columns, each in its card, loading the next page as the end comes
|
|
126
|
+
near. It watches from the element it scrolls in, so it works inside a
|
|
127
|
+
popover. Only tiles within a screen of the visible area hold a picture, so a
|
|
128
|
+
long scroll costs no more to show than the first page. When nothing matched,
|
|
129
|
+
and after the last page, it offers "Upload to ohmagif". A new `key` starts it
|
|
130
|
+
again from the first page.
|
|
131
|
+
|
|
132
|
+
| Prop | |
|
|
133
|
+
|---|---|
|
|
134
|
+
| `fetchGifs(offset, signal)` | Required. Answers a page; the grid aborts `signal` when it unmounts |
|
|
135
|
+
| `width`, `columns` | Required. Width in CSS pixels |
|
|
136
|
+
| `gutter` | Space between GIFs, 6 by default |
|
|
137
|
+
| `noLink` | The frame is a button (to pick the GIF) rather than a link to the GIF's page; the credit line still links there |
|
|
138
|
+
| `hideAttribution` | The frame alone, without the card and its credit line |
|
|
139
|
+
| `onGifClick(gif, event)` | |
|
|
140
|
+
| `onGifsFetched(gifs)` | Every GIF the grid holds, after each page |
|
|
141
|
+
| `onGifsFetchError(error)` | |
|
|
142
|
+
| `noResultsMessage` | Shown when the first page is empty, "No GIFs found" by default |
|
|
143
|
+
| `uploadURL` | Where "Upload to ohmagif" leads, `https://ohmagif.com/upload` by default (`gf.uploadURL`); `null` offers nothing |
|
|
144
|
+
| `errorMessage` | Shown with a Retry button when a page did not load |
|
|
145
|
+
| `loader` | A component shown while a page loads |
|
|
146
|
+
| `className` | |
|
|
147
|
+
|
|
148
|
+
### `Gif`
|
|
149
|
+
|
|
150
|
+
One GIF in its card at a given width, never wider than its container. The
|
|
151
|
+
whole card links to the GIF's page. The browser picks `tiny.avif` or
|
|
152
|
+
`full.avif` by the screen's density.
|
|
153
|
+
|
|
154
|
+
| Prop | |
|
|
155
|
+
|---|---|
|
|
156
|
+
| `gif`, `width` | Required. Width of the card in CSS pixels |
|
|
157
|
+
| `noLink` | The frame does not link (a button when `onGifClick` is set); the credit line still does |
|
|
158
|
+
| `onGifClick(gif, event)` | |
|
|
159
|
+
| `hideAttribution` | The frame alone, without the card and its credit line |
|
|
160
|
+
| `lazyLoad` | Load the file only near the screen, on by default |
|
|
161
|
+
| `onLoad`, `onError` | `onError` usually means the address is out of date: ask for the GIF again |
|
|
162
|
+
| `className` | |
|
|
163
|
+
|
|
164
|
+
### Sizes
|
|
165
|
+
|
|
166
|
+
`gifSize(frame, width)` is the room a GIF takes at a width: the frame inside
|
|
167
|
+
the card's 1 px border, and the 28 px credit line. With the frame size kept in
|
|
168
|
+
a message, a chat reserves exactly that while it asks for the GIF:
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
const box = gifSize({ width: 346, height: 205 }, 348); // { width: 348, height: 235 }
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Every `<img>` carries `width` and `height` attributes for the size it is shown
|
|
175
|
+
at, and every tile and card has its size before its file loads.
|
|
176
|
+
|
|
177
|
+
### Styling
|
|
178
|
+
|
|
179
|
+
Class names: `ohmagif-grid`, `ohmagif-tile`, `ohmagif-gif`, `ohmagif-card`,
|
|
180
|
+
`ohmagif-frame`, `ohmagif-credit`, `ohmagif-end`, `ohmagif-upload`,
|
|
181
|
+
`ohmagif-loading` and `ohmagif-error`.
|
|
182
|
+
|
|
183
|
+
Custom properties: `--ohmagif-card`, `--ohmagif-border`, `--ohmagif-muted`
|
|
184
|
+
(the credit line), `--ohmagif-link` (the handle and the buttons),
|
|
185
|
+
`--ohmagif-placeholder` (a GIF that has not loaded yet) and `--ohmagif-radius`.
|
|
186
|
+
By default the colours are the embed's, light or dark as the page's
|
|
187
|
+
`color-scheme` says. A page that switches to dark with a class says so:
|
|
188
|
+
|
|
189
|
+
```css
|
|
190
|
+
html.dark { color-scheme: dark; }
|
|
191
|
+
.ohmagif-frame:focus-visible, .ohmagif-credit:focus-visible { outline: 2px solid var(--accent); }
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Images, not iframes
|
|
195
|
+
|
|
196
|
+
Both components show the file itself in an `<img>`, so a GIF in a chat costs
|
|
197
|
+
one image request and nothing else runs in the page. An iframe embed is there
|
|
198
|
+
for pages that want one: `gif.embed_url` at `gif.embed_width` x
|
|
199
|
+
`gif.embed_height`, with `frame-src https://ohmagif.com` in the policy.
|
|
200
|
+
|
|
201
|
+
### Content-Security-Policy
|
|
202
|
+
|
|
203
|
+
```
|
|
204
|
+
img-src https://i.ohmagif.com;
|
|
205
|
+
connect-src https://ohmagif.com;
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## Moving from Giphy
|
|
209
|
+
|
|
210
|
+
| Giphy | ohmagif |
|
|
211
|
+
|---|---|
|
|
212
|
+
| `import { GiphyFetch } from "@giphy/js-fetch-api"` | `import { OhmagifFetch } from "@ohmagif/js"` |
|
|
213
|
+
| `import { Grid, Gif } from "@giphy/react-components"` | `import { Grid, Gif } from "@ohmagif/js/react"` |
|
|
214
|
+
| `IGif` | `Gif` from `@ohmagif/js` |
|
|
215
|
+
| `new GiphyFetch(key)` | `new OhmagifFetch()` |
|
|
216
|
+
| `gif.images.original.width`, `.height` | `frameSize(gif).width`, `.height` |
|
|
217
|
+
| `gif.images.original_mp4.mp4` | `gif.files.full.url` (AVIF, shown by an `<img>`) |
|
|
218
|
+
| `rating: "pg-13"` | `rating: "pg13"` |
|
|
219
|
+
| `hideAttribution` | The frame alone, without the card and its credit line |
|
|
220
|
+
| "Powered by GIPHY" | Not needed: every GIF has its credit line, linked to its page |
|
|
221
|
+
| `fetchGifs(offset)` | `fetchGifs(offset, signal)`; pass `signal` on to cancel |
|
|
222
|
+
|
|
223
|
+
A grid in a picker, before and after:
|
|
224
|
+
|
|
225
|
+
```diff
|
|
226
|
+
-import { GiphyFetch } from "@giphy/js-fetch-api";
|
|
227
|
+
-import { Grid } from "@giphy/react-components";
|
|
228
|
+
-import type IGif from "@giphy/js-types/dist/gif";
|
|
229
|
+
+import { frameSize, OhmagifFetch, type Gif } from "@ohmagif/js";
|
|
230
|
+
+import { Grid } from "@ohmagif/js/react";
|
|
231
|
+
|
|
232
|
+
-const gf = new GiphyFetch(apiKey);
|
|
233
|
+
+const gf = new OhmagifFetch();
|
|
234
|
+
|
|
235
|
+
const fetchGifs = useCallback(
|
|
236
|
+
- (offset: number) => {
|
|
237
|
+
- const options = { offset, limit: 12, rating: "pg" as const };
|
|
238
|
+
+ (offset: number, signal: AbortSignal) => {
|
|
239
|
+
+ const options = { offset, limit: 12, rating: "pg" as const, signal };
|
|
240
|
+
return query ? gf.search(query, options) : gf.trending(options);
|
|
241
|
+
},
|
|
242
|
+
[query],
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
-const onGifClick = (gif: IGif, e: React.SyntheticEvent) => {
|
|
246
|
+
- e.preventDefault();
|
|
247
|
+
- const { width, height } = gif.images.original;
|
|
248
|
+
- onPick({ id: String(gif.id), title: gif.title, width, height });
|
|
249
|
+
-};
|
|
250
|
+
+const onGifClick = (gif: Gif) => {
|
|
251
|
+
+ onPick({ id: gif.id, title: gif.title, ...frameSize(gif) });
|
|
252
|
+
+};
|
|
253
|
+
|
|
254
|
+
-<Grid key={query} width={width} columns={2} gutter={6} fetchGifs={fetchGifs} onGifClick={onGifClick} noLink hideAttribution />
|
|
255
|
+
+<Grid key={query} width={width} columns={2} gutter={6} fetchGifs={fetchGifs} onGifClick={onGifClick} noLink uploadURL={gf.uploadURL} />
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Keeping `hideAttribution` works too: the tiles then show the frame alone.
|
|
259
|
+
|
|
260
|
+
A GIF in a message, from its stored id:
|
|
261
|
+
|
|
262
|
+
```tsx
|
|
263
|
+
import { useEffect, useState } from "react";
|
|
264
|
+
import { OhmagifFetch, type Gif as GifData } from "@ohmagif/js";
|
|
265
|
+
import { Gif, gifSize } from "@ohmagif/js/react";
|
|
266
|
+
|
|
267
|
+
const gf = new OhmagifFetch();
|
|
268
|
+
|
|
269
|
+
/** `frame` is the frameSize(gif) kept with the message when it was picked. */
|
|
270
|
+
function GifMessage({ id, frame, width }: { id: string; frame: { width: number; height: number }; width: number }) {
|
|
271
|
+
const [gif, setGif] = useState<GifData | null>(null);
|
|
272
|
+
const [gone, setGone] = useState(false);
|
|
273
|
+
useEffect(() => {
|
|
274
|
+
const ctrl = new AbortController();
|
|
275
|
+
gf.gif(id, { signal: ctrl.signal }).then(
|
|
276
|
+
({ data }) => setGif(data),
|
|
277
|
+
() => !ctrl.signal.aborted && setGone(true),
|
|
278
|
+
);
|
|
279
|
+
return () => ctrl.abort();
|
|
280
|
+
}, [id]);
|
|
281
|
+
// The same room before and after the GIF arrives.
|
|
282
|
+
const box = gifSize(frame, width);
|
|
283
|
+
if (gone) return <span style={box}>GIF unavailable</span>;
|
|
284
|
+
return gif ? <Gif gif={gif} width={width} /> : <span style={{ display: "block", ...box }} />;
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Also:
|
|
289
|
+
|
|
290
|
+
- Messages that hold a Giphy id cannot be shown from ohmagif. Store picks
|
|
291
|
+
under a scheme of their own (`ohmagif:<id>`), and show the old ones as
|
|
292
|
+
unavailable. `isGifId()` tells an ohmagif id apart.
|
|
293
|
+
- A key in workspace settings is no longer needed to turn GIFs on.
|
|
294
|
+
- Keep a fetched GIF for less than an hour, or ask again when its `<Gif>`
|
|
295
|
+
reports `onError`.
|
|
296
|
+
- Keep `frameSize(gif)` with the message, not `gif.width` and `gif.height`,
|
|
297
|
+
and size its placeholder with `gifSize()`.
|
|
298
|
+
- Drop `media.giphy.com`, `api.giphy.com` and their friends from the
|
|
299
|
+
Content-Security-Policy and add the two lines above.
|
|
300
|
+
|
|
301
|
+
## Development
|
|
302
|
+
|
|
303
|
+
```sh
|
|
304
|
+
make install
|
|
305
|
+
make test
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
| Target | |
|
|
309
|
+
|---|---|
|
|
310
|
+
| `make install` | Install the dependencies |
|
|
311
|
+
| `make lint` | tsc |
|
|
312
|
+
| `make test` | vitest, gated at 100% coverage: every statement, branch, function and line |
|
|
313
|
+
| `make test-integration` | The client against the live API; `OHMAGIF_BASE_URL=http://localhost:8080` for a local ohmagif |
|
|
314
|
+
| `make build` | Build `dist/` |
|
|
315
|
+
| `make example` | A chat with a GIF picker against ohmagif.com on http://localhost:8082/; `?base=http://localhost:8080` for a local ohmagif |
|
|
316
|
+
| `make example-build` | Build the example into `examples/dist/` |
|
|
317
|
+
| `make e2e` | Playwright against the running example (`make example` first); `OHMAGIF_JS_E2E_URL` for another copy, a preview included |
|
|
318
|
+
| `make e2e-ci` | Build the example, serve it on :8083 and run Playwright against it |
|
|
319
|
+
| `make clean` | Remove build and test output |
|
|
320
|
+
|
|
321
|
+
`npx playwright install chromium` once before the first `make e2e`.
|
|
322
|
+
|
|
323
|
+
The pipeline runs every suite on each push and pull request, and weekly
|
|
324
|
+
against the live API. Each pull request from this repository gets its
|
|
325
|
+
example at `https://ohmagif.github.io/ohmagif-js/pr-preview/pr-<n>/`, linked
|
|
326
|
+
in a comment; main's is at https://ohmagif.github.io/ohmagif-js/. Pages
|
|
327
|
+
serves the `gh-pages` branch: Settings, Pages, Deploy from a branch,
|
|
328
|
+
`gh-pages`, `/ (root)`.
|
|
329
|
+
|
|
330
|
+
## Releasing
|
|
331
|
+
|
|
332
|
+
Set the version in `package.json`, merge, and tag the merge commit:
|
|
333
|
+
|
|
334
|
+
```sh
|
|
335
|
+
git tag v0.2.0
|
|
336
|
+
git push origin v0.2.0
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
The pipeline runs every check, then publishes to npm with provenance. A
|
|
340
|
+
version with a hyphen (`0.2.0-rc.1`) goes out under the dist-tag `next`. A
|
|
341
|
+
tag that does not match `package.json` stops the release.
|
|
342
|
+
|
|
343
|
+
npm takes the package from this repository's `ci.yml` through trusted
|
|
344
|
+
publishing, without a token. `npm trust list @ohmagif/js` shows the
|
|
345
|
+
configuration.
|
|
346
|
+
|
|
347
|
+
## Licence
|
|
348
|
+
|
|
349
|
+
GPL-3.0. See [LICENSE](LICENSE).
|
package/dist/fetch.d.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { type Gif, type Rating } from "./gif.js";
|
|
2
|
+
export interface OhmagifFetchOptions {
|
|
3
|
+
/**
|
|
4
|
+
* An integrator key (omg_...). Optional: without one the API allows 60
|
|
5
|
+
* requests a minute per address, with one 600 a minute for the key. A key
|
|
6
|
+
* sent from a browser can be read by anyone using the page, and its
|
|
7
|
+
* answers are never cached.
|
|
8
|
+
*/
|
|
9
|
+
apiKey?: string;
|
|
10
|
+
/** The site, https://ohmagif.com by default. */
|
|
11
|
+
baseURL?: string;
|
|
12
|
+
/** Milliseconds to wait for an answer, 10000 by default; 0 waits forever. */
|
|
13
|
+
timeout?: number;
|
|
14
|
+
/** A fetch to use instead of the global one. */
|
|
15
|
+
fetch?: typeof globalThis.fetch;
|
|
16
|
+
}
|
|
17
|
+
export interface RequestOptions {
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
export interface PageOptions extends RequestOptions {
|
|
21
|
+
/** 0 to 1000, 0 by default. */
|
|
22
|
+
offset?: number;
|
|
23
|
+
/** 1 to 50, 25 by default. */
|
|
24
|
+
limit?: number;
|
|
25
|
+
/** The highest rating to include. */
|
|
26
|
+
rating?: Rating;
|
|
27
|
+
}
|
|
28
|
+
export interface Pagination {
|
|
29
|
+
/** Every match, including those past the last reachable offset. */
|
|
30
|
+
total_count: number;
|
|
31
|
+
/** GIFs in this page. */
|
|
32
|
+
count: number;
|
|
33
|
+
/** The offset this page was asked for. */
|
|
34
|
+
offset: number;
|
|
35
|
+
/** The offset of the next page, null after the last one. */
|
|
36
|
+
next: number | null;
|
|
37
|
+
}
|
|
38
|
+
export interface GifsResult {
|
|
39
|
+
data: Gif[];
|
|
40
|
+
pagination: Pagination;
|
|
41
|
+
}
|
|
42
|
+
export interface GifResult {
|
|
43
|
+
data: Gif;
|
|
44
|
+
}
|
|
45
|
+
export interface Reaction {
|
|
46
|
+
slug: string;
|
|
47
|
+
name: string;
|
|
48
|
+
/** Live GIFs filed under the reaction. */
|
|
49
|
+
gifs: number;
|
|
50
|
+
/** Its top GIF, null while it has none. */
|
|
51
|
+
top: Gif | null;
|
|
52
|
+
}
|
|
53
|
+
export interface ReactionsResult {
|
|
54
|
+
data: Reaction[];
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* A request the API refused or did not answer. `code` is the API's own
|
|
58
|
+
* (not_found, removed, search_unavailable, ...) or one of: invalid_id (no
|
|
59
|
+
* request was sent), network, timeout, invalid_response.
|
|
60
|
+
*/
|
|
61
|
+
export declare class OhmagifError extends Error {
|
|
62
|
+
readonly status: number;
|
|
63
|
+
readonly code: string;
|
|
64
|
+
/** Seconds to wait before asking again, when the API said. */
|
|
65
|
+
readonly retryAfter: number | null;
|
|
66
|
+
constructor(status: number, code: string, message: string, retryAfter?: number | null);
|
|
67
|
+
}
|
|
68
|
+
export declare class OhmagifFetch {
|
|
69
|
+
#private;
|
|
70
|
+
/** Takes the options, or an API key alone. */
|
|
71
|
+
constructor(options?: OhmagifFetchOptions | string);
|
|
72
|
+
/** The page where people upload GIFs, for a link out of a picker. */
|
|
73
|
+
get uploadURL(): string;
|
|
74
|
+
/** GIFs matching the words, best match first. */
|
|
75
|
+
search(term: string, options?: PageOptions): Promise<GifsResult>;
|
|
76
|
+
/** The GIFs shared most over the last days. */
|
|
77
|
+
trending(options?: PageOptions): Promise<GifsResult>;
|
|
78
|
+
/** GIFs with a tag or reaction, by its slug (see reactions()). */
|
|
79
|
+
tag(slug: string, options?: PageOptions): Promise<GifsResult>;
|
|
80
|
+
/**
|
|
81
|
+
* One GIF by its id. A GIF that is gone rejects with code not_found or
|
|
82
|
+
* removed; an id that is not one rejects with invalid_id, without a
|
|
83
|
+
* request. Ask again rather than keep the answer for long: file addresses
|
|
84
|
+
* change when a GIF is rendered again, and the old files go an hour later.
|
|
85
|
+
*/
|
|
86
|
+
gif(id: string, options?: RequestOptions): Promise<GifResult>;
|
|
87
|
+
/** The curated reactions, each with its top GIF. */
|
|
88
|
+
reactions(options?: RequestOptions): Promise<ReactionsResult>;
|
|
89
|
+
}
|
package/dist/fetch.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// A client for the public read endpoints of the ohmagif API (/api/v1). They
|
|
2
|
+
// need no key and answer pages on any site.
|
|
3
|
+
import { asObject, DEFAULT_BASE_URL, isGifId, parseGif, RATINGS } from "./gif.js";
|
|
4
|
+
/**
|
|
5
|
+
* A request the API refused or did not answer. `code` is the API's own
|
|
6
|
+
* (not_found, removed, search_unavailable, ...) or one of: invalid_id (no
|
|
7
|
+
* request was sent), network, timeout, invalid_response.
|
|
8
|
+
*/
|
|
9
|
+
export class OhmagifError extends Error {
|
|
10
|
+
status;
|
|
11
|
+
code;
|
|
12
|
+
/** Seconds to wait before asking again, when the API said. */
|
|
13
|
+
retryAfter;
|
|
14
|
+
constructor(status, code, message, retryAfter = null) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "OhmagifError";
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.retryAfter = retryAfter;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const MAX_LIMIT = 50;
|
|
23
|
+
const MAX_OFFSET = 1000;
|
|
24
|
+
const TAG_SLUG = /^[a-z0-9-]{1,80}$/;
|
|
25
|
+
function baseURL(raw) {
|
|
26
|
+
let url;
|
|
27
|
+
try {
|
|
28
|
+
url = new URL(raw);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new TypeError(`baseURL is not an address: ${raw}`);
|
|
32
|
+
}
|
|
33
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
34
|
+
throw new TypeError(`baseURL must be http or https: ${raw}`);
|
|
35
|
+
}
|
|
36
|
+
if (url.search || url.hash || url.username || url.password) {
|
|
37
|
+
throw new TypeError(`baseURL takes no query, fragment or credentials: ${raw}`);
|
|
38
|
+
}
|
|
39
|
+
return url.href.replace(/\/+$/, "");
|
|
40
|
+
}
|
|
41
|
+
function pageParams(options) {
|
|
42
|
+
const { offset = 0, limit = 25, rating } = options;
|
|
43
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
44
|
+
throw new RangeError(`limit must be 1 to ${MAX_LIMIT}`);
|
|
45
|
+
}
|
|
46
|
+
if (!Number.isInteger(offset) || offset < 0 || offset > MAX_OFFSET) {
|
|
47
|
+
throw new RangeError(`offset must be 0 to ${MAX_OFFSET}`);
|
|
48
|
+
}
|
|
49
|
+
const params = { limit: String(limit), offset: String(offset) };
|
|
50
|
+
if (rating !== undefined) {
|
|
51
|
+
if (!RATINGS.includes(rating))
|
|
52
|
+
throw new RangeError("rating must be g, pg or pg13");
|
|
53
|
+
params.rating = rating;
|
|
54
|
+
}
|
|
55
|
+
return params;
|
|
56
|
+
}
|
|
57
|
+
function retryAfter(res) {
|
|
58
|
+
const v = res.headers.get("Retry-After");
|
|
59
|
+
if (!v)
|
|
60
|
+
return null;
|
|
61
|
+
const n = Number(v);
|
|
62
|
+
if (Number.isFinite(n) && n >= 0)
|
|
63
|
+
return n;
|
|
64
|
+
const at = Date.parse(v);
|
|
65
|
+
return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000));
|
|
66
|
+
}
|
|
67
|
+
function invalid(status) {
|
|
68
|
+
return new OhmagifError(status, "invalid_response", "Unreadable answer from ohmagif");
|
|
69
|
+
}
|
|
70
|
+
/** A count from the API: a non-negative integer, or null. */
|
|
71
|
+
function count(value) {
|
|
72
|
+
return Number.isInteger(value) && value >= 0 ? value : null;
|
|
73
|
+
}
|
|
74
|
+
/** Joins the caller's signal and the timeout into one. */
|
|
75
|
+
function deadline(signal, ms) {
|
|
76
|
+
if (!ms)
|
|
77
|
+
return { signal, timedOut: () => false, done: () => { } };
|
|
78
|
+
const ctrl = new AbortController();
|
|
79
|
+
let expired = false;
|
|
80
|
+
const timer = setTimeout(() => {
|
|
81
|
+
expired = true;
|
|
82
|
+
ctrl.abort(new DOMException("Timed out", "TimeoutError"));
|
|
83
|
+
}, ms);
|
|
84
|
+
const forward = () => ctrl.abort(signal?.reason);
|
|
85
|
+
if (signal?.aborted)
|
|
86
|
+
forward();
|
|
87
|
+
else
|
|
88
|
+
signal?.addEventListener("abort", forward, { once: true });
|
|
89
|
+
return {
|
|
90
|
+
signal: ctrl.signal,
|
|
91
|
+
timedOut: () => expired,
|
|
92
|
+
done: () => {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
signal?.removeEventListener("abort", forward);
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
export class OhmagifFetch {
|
|
99
|
+
#base;
|
|
100
|
+
#key;
|
|
101
|
+
#timeout;
|
|
102
|
+
#fetch;
|
|
103
|
+
/** Takes the options, or an API key alone. */
|
|
104
|
+
constructor(options = {}) {
|
|
105
|
+
const o = typeof options === "string" ? { apiKey: options } : options;
|
|
106
|
+
this.#base = baseURL(o.baseURL ?? DEFAULT_BASE_URL);
|
|
107
|
+
this.#key = (o.apiKey ?? "").trim();
|
|
108
|
+
this.#timeout = o.timeout ?? 10_000;
|
|
109
|
+
if (!Number.isFinite(this.#timeout) || this.#timeout < 0)
|
|
110
|
+
throw new RangeError("timeout must be 0 or more");
|
|
111
|
+
// Called unbound: a fetch kept as a method throws "Illegal invocation"
|
|
112
|
+
// in browsers.
|
|
113
|
+
const f = o.fetch ?? globalThis.fetch;
|
|
114
|
+
this.#fetch = (input, init) => f(input, init);
|
|
115
|
+
}
|
|
116
|
+
/** The page where people upload GIFs, for a link out of a picker. */
|
|
117
|
+
get uploadURL() {
|
|
118
|
+
return `${this.#base}/upload`;
|
|
119
|
+
}
|
|
120
|
+
/** GIFs matching the words, best match first. */
|
|
121
|
+
async search(term, options = {}) {
|
|
122
|
+
const q = term.trim();
|
|
123
|
+
if (!q)
|
|
124
|
+
throw new RangeError("term is empty");
|
|
125
|
+
return this.#list("/search", { q, ...pageParams(options) }, options);
|
|
126
|
+
}
|
|
127
|
+
/** The GIFs shared most over the last days. */
|
|
128
|
+
async trending(options = {}) {
|
|
129
|
+
return this.#list("/trending", pageParams(options), options);
|
|
130
|
+
}
|
|
131
|
+
/** GIFs with a tag or reaction, by its slug (see reactions()). */
|
|
132
|
+
async tag(slug, options = {}) {
|
|
133
|
+
const s = slug.trim().toLowerCase();
|
|
134
|
+
if (!TAG_SLUG.test(s))
|
|
135
|
+
throw new RangeError(`not a tag slug: ${slug}`);
|
|
136
|
+
return this.#list(`/tags/${s}`, pageParams(options), options);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* One GIF by its id. A GIF that is gone rejects with code not_found or
|
|
140
|
+
* removed; an id that is not one rejects with invalid_id, without a
|
|
141
|
+
* request. Ask again rather than keep the answer for long: file addresses
|
|
142
|
+
* change when a GIF is rendered again, and the old files go an hour later.
|
|
143
|
+
*/
|
|
144
|
+
async gif(id, options = {}) {
|
|
145
|
+
if (!isGifId(id))
|
|
146
|
+
throw new OhmagifError(0, "invalid_id", "Not a GIF id");
|
|
147
|
+
const { body, status } = await this.#get(`/gifs/${id}`, {}, options.signal);
|
|
148
|
+
const gif = parseGif(body);
|
|
149
|
+
if (!gif)
|
|
150
|
+
throw invalid(status);
|
|
151
|
+
return { data: gif };
|
|
152
|
+
}
|
|
153
|
+
/** The curated reactions, each with its top GIF. */
|
|
154
|
+
async reactions(options = {}) {
|
|
155
|
+
const { body, status } = await this.#get("/reactions", {}, options.signal);
|
|
156
|
+
const results = asObject(body)?.results;
|
|
157
|
+
if (!Array.isArray(results))
|
|
158
|
+
throw invalid(status);
|
|
159
|
+
const data = [];
|
|
160
|
+
for (const raw of results) {
|
|
161
|
+
const r = asObject(raw);
|
|
162
|
+
if (!r || typeof r.slug !== "string" || !TAG_SLUG.test(r.slug) || typeof r.name !== "string")
|
|
163
|
+
continue;
|
|
164
|
+
data.push({ slug: r.slug, name: r.name, gifs: count(r.gifs) ?? 0, top: parseGif(r.top) });
|
|
165
|
+
}
|
|
166
|
+
return { data };
|
|
167
|
+
}
|
|
168
|
+
async #list(path, params, options) {
|
|
169
|
+
const { body, status } = await this.#get(path, params, options.signal);
|
|
170
|
+
const o = asObject(body);
|
|
171
|
+
if (!o || !Array.isArray(o.results))
|
|
172
|
+
throw invalid(status);
|
|
173
|
+
const data = o.results.map(parseGif).filter((g) => g !== null);
|
|
174
|
+
const offset = Number(params.offset);
|
|
175
|
+
const next = count(o.next);
|
|
176
|
+
return {
|
|
177
|
+
data,
|
|
178
|
+
pagination: {
|
|
179
|
+
total_count: count(o.total) ?? offset + data.length,
|
|
180
|
+
count: data.length,
|
|
181
|
+
offset,
|
|
182
|
+
// A next page must move forward, or a paging loop never ends.
|
|
183
|
+
next: next !== null && next > offset ? next : null,
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
async #get(path, params, signal) {
|
|
188
|
+
const url = new URL(`${this.#base}/api/v1${path}`);
|
|
189
|
+
for (const [k, v] of Object.entries(params))
|
|
190
|
+
url.searchParams.set(k, v);
|
|
191
|
+
const headers = { Accept: "application/json" };
|
|
192
|
+
if (this.#key)
|
|
193
|
+
headers.Authorization = `Bearer ${this.#key}`;
|
|
194
|
+
const d = deadline(signal, this.#timeout);
|
|
195
|
+
let res;
|
|
196
|
+
let body;
|
|
197
|
+
try {
|
|
198
|
+
res = await this.#fetch(url.href, {
|
|
199
|
+
method: "GET",
|
|
200
|
+
headers,
|
|
201
|
+
// Nothing of the page travels with the request: no cookies, and not
|
|
202
|
+
// the address of the page (a chat room, a draft) it was made from.
|
|
203
|
+
credentials: "omit",
|
|
204
|
+
referrerPolicy: "no-referrer",
|
|
205
|
+
mode: "cors",
|
|
206
|
+
signal: d.signal ?? null,
|
|
207
|
+
});
|
|
208
|
+
try {
|
|
209
|
+
body = await res.json();
|
|
210
|
+
}
|
|
211
|
+
catch (err) {
|
|
212
|
+
// A body that is not JSON (a proxy's error page) is checked below;
|
|
213
|
+
// an abort while reading is not.
|
|
214
|
+
if (d.signal?.aborted)
|
|
215
|
+
throw err;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
catch (err) {
|
|
219
|
+
if (signal?.aborted)
|
|
220
|
+
throw signal.reason ?? err;
|
|
221
|
+
if (d.timedOut()) {
|
|
222
|
+
throw new OhmagifError(0, "timeout", `No answer from ohmagif within ${this.#timeout / 1000} s`);
|
|
223
|
+
}
|
|
224
|
+
throw new OhmagifError(0, "network", "No answer from ohmagif");
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
d.done();
|
|
228
|
+
}
|
|
229
|
+
if (!res.ok) {
|
|
230
|
+
const o = asObject(body);
|
|
231
|
+
const code = typeof o?.code === "string" ? o.code : `http_${res.status}`;
|
|
232
|
+
const message = typeof o?.error === "string" ? o.error : `ohmagif answered ${res.status}`;
|
|
233
|
+
throw new OhmagifError(res.status, code, message, retryAfter(res));
|
|
234
|
+
}
|
|
235
|
+
if (body === undefined)
|
|
236
|
+
throw invalid(res.status);
|
|
237
|
+
return { body, status: res.status };
|
|
238
|
+
}
|
|
239
|
+
}
|