26 Commits
Author SHA1 Message Date
KydoimosandClaude Opus 5 51dfade4f9 Sign the automated version bump commit
CI / Typecheck, test, build (pull_request) Successful in 38s
Publish / Build and push (pull_request) Successful in 1m48s
Publish / Move the working version on (pull_request) Skipped
main requires signed commits, so the pull request the bump job opens after a
release cannot be merged while the commit in it is unsigned. The key the server
signs merge commits with is not reachable from a runner, so the job signs with a
dedicated release-bot SSH key that the instance trusts through
TRUSTED_SSH_KEYS — no bot account, because an account key is only consulted
after the web Verify flow and that flow has no API.

Inert until the key is trusted and RELEASE_BOT_SIGNING_KEY is set, and loudly so:
the step checks the secret and ssh-keygen before it starts, runs the key through
ssh-keygen -y so a truncated or re-wrapped one is caught as itself rather than as
"gpg failed to sign the data", and the commit is re-read for a gpgsig header
before it is pushed.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-05 20:30:09 -03:00
thatguygriff 6e687cdddc Merge pull request 'Set the working version to 1.2.5' (#15) from release/bump-1.2.5 into main
CI / Typecheck, test, build (push) Successful in 17s
Publish / Build and push (push) Successful in 35s
Publish / Move the working version on (push) Skipped
Reviewed-on: #15
2026-09-03 00:58:52 +00:00
Release bot 4e45456097 Set the working version to 1.2.5 2026-09-03 00:58:17 +00:00
thatguygriff 05455a86da Merge pull request 'Ask iOS for the playback audio session on a page with a video' (#14) from video-audio-session-on-ios into main
CI / Typecheck, test, build (push) Successful in 46s
Publish / Build and push (push) Successful in 28s
Publish / Move the working version on (push) Successful in 4s
Reviewed-on: #14
2026-09-03 00:56:04 +00:00
thatguygriffandClaude Opus 5 4c78ce8a27 Ask iOS for the playback audio session on a page with a video
CI / Typecheck, test, build (pull_request) Successful in 12s
A TikTok post played perfectly and said nothing on an iPhone. The file was
not the problem: every rendition TikTok offers for it carries a full AAC
track, and the page as served measures loud audio in WebKit and Chromium
alike, straight through the /m/ proxy.

iOS is the problem. A video playing inline gets the "ambient" audio session,
which the Ring/Silent switch mutes; only going fullscreen gets the sound
back. Claiming "playback" says what is true of this page -- the sound is the
point, not decoration -- and the switch stops applying.

Declared only where there is a video, so an ordinary text post never claims
it, and the session activates when something plays rather than on load, so
it interrupts nothing on a page nobody presses play on.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B3RUMiXa6eAW3okw9nB9NF
2026-09-02 21:06:12 -03:00
thatguygriff d9fa2f5768 Merge pull request 'Set the working version to 1.2.4' (#12) from release/bump-1.2.4 into main
CI / Typecheck, test, build (push) Successful in 17s
Publish / Build and push (push) Successful in 35s
Publish / Move the working version on (push) Skipped
Reviewed-on: #12
2026-08-31 02:44:07 +00:00
Release bot dfabfc18d6 Set the working version to 1.2.4 2026-08-31 02:42:23 +00:00
thatguygriff 3afdf6ffe2 Merge pull request 'Render giphy tokens, and give a video its shape before it plays' (#11) from giphy-tokens-and-video-posters into main
CI / Typecheck, test, build (push) Successful in 12s
Publish / Build and push (push) Successful in 1m51s
Publish / Move the working version on (push) Skipped
Reviewed-on: #11
2026-08-31 02:41:07 +00:00
thatguygriffandClaude Opus 5 5b4378a838 Give a video its shape before it has any data
CI / Typecheck, test, build (pull_request) Successful in 26s
A Reddit video sat in the wrong box until you pressed play, for two reasons
that looked like one.

The renderer put only `aspect-ratio` on the `<video>`. A video with no data
has a natural size of 300x150, and WebKit sizes a replaced element from that
rather than from the ratio, so a portrait video got a squat landscape box and
kept it until playback supplied real dimensions. Chromium stretch-fits
instead and gets it right, which is why this only showed on Safari. A
video's size before its data arrives is its poster's, so one with no poster
of its own now gets an empty SVG of the right shape as a stand-in: a data
URI, so it costs no request. Measured in both engines across portrait,
landscape, square and small.

And Reddit's videos with sound had no poster to be sized by, because
`fromRedditVideo` attached the still from `preview.images` to the MP4 branch
alone. The still belongs to the video, not to the format it is served in, so
every post with sound showed an empty box where a silent one showed a frame.
It now goes on both.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PLkmgp1fWbA4XbarxKdRKt
2026-08-30 23:37:59 -03:00
thatguygriffandClaude Opus 5 4669fe0b6a Resolve a giphy token with no metadata to look it up in
`![gif](giphy|zUW23b6FmzB5e)` is a token, not an address, and the only thing
that turned it into one was a lookup in the comment's own `media_metadata`.
Reddit ships plenty of comments carrying such a token and no `media_metadata`
at all, and with nothing to look it up in the token itself was what the
comment showed.

Giphy is the one of the three token kinds whose id means something off
Reddit, so that one can be resolved without the lookup. A variant name after
the id is dropped: Giphy does not serve every variant of every gif, but the
full one is always there.

The other two still resolve only through the metadata. An emote id and an
upload id name nothing outside Reddit, so with no entry for them there is
still nothing to point them at.

Closes #10

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PLkmgp1fWbA4XbarxKdRKt
2026-08-30 23:36:53 -03:00
thatguygriff ebfcc9ebf2 Merge pull request 'Set the working version to 1.2.3' (#9) from release/bump-1.2.3 into main
CI / Typecheck, test, build (push) Successful in 12s
Publish / Build and push (push) Successful in 1m50s
Publish / Move the working version on (push) Skipped
Reviewed-on: #9
2026-08-29 23:08:21 +00:00
Release bot 8fc7a83f8e Set the working version to 1.2.3 2026-08-29 22:56:36 +00:00
thatguygriff 91d4c2da50 Merge pull request 'Let the "Open on" button choose a browser' (#8) from choose-browser-for-open-on into main
CI / Typecheck, test, build (push) Successful in 18s
Publish / Build and push (push) Successful in 3m24s
Publish / Move the working version on (push) Successful in 23s
Reviewed-on: #8
2026-08-29 22:47:42 +00:00
thatguygriffandClaude Opus 5 899b6e38d8 No browser chosen, no "Open on" button
CI / Typecheck, test, build (pull_request) Successful in 26s
The plain address is the one thing that button must not offer -- followed
in the browser the rewrite rules are installed in, it comes straight back
here -- so there is nothing to show until there is a browser to hand it to.
The copy button and the selectable URL were always the part carrying the
weight; the open link now ships hidden and the script reveals it along with
the scheme.

That also settles what the button should say. It went back to "Open on
<platform>": the browser's name was there to explain a tap that went
nowhere, and a button that is not shown until it works needs no such
explanation.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KF5YF3iZVKbezwALap8LYd
2026-08-29 19:40:39 -03:00
thatguygriffandClaude Opus 5 abf8ec317c Let the "Open on" button choose a browser
CI / Typecheck, test, build (pull_request) Successful in 28s
The StopTheMadness rules are indiscriminate, which is the point, but they
catch the link on the way back out as well: in the browser they are
installed in, "Open on <platform>" redirects straight back here. The one
button meant to reach the app is the one that cannot.

Handing the address to a different browser is the way past it, and the only
way to do that from a page is that browser's own URL scheme. `/` gets a
picker for which one; the choice lives in that browser's localStorage,
because which browsers are installed is a fact about the device and the
phone's answer is not the Mac's.

The scheme table is its own module so a test can pin it -- every browser
spells it differently, and Edge differs between macOS and iOS. Firefox has
no scheme on macOS, so it is only offered on iOS, and an unknown or
schemeless choice keeps the plain link rather than producing a dead one.
The markup still carries the plain https address and the script swaps it
afterwards, so nothing changes without JavaScript. Once a browser is
chosen the button says which, since a scheme for a browser that is not
installed opens nothing and the tap would otherwise be silent.

Closes #7

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KF5YF3iZVKbezwALap8LYd
2026-08-29 19:36:00 -03:00
thatguygriff 3ff7375320 Merge pull request 'Open the version bump as a pull request' (#6) from bump-version-by-pull-request into main
Publish / Build and push (push) Successful in 6s
Publish / Move the working version on (push) Skipped
CI / Typecheck, test, build (push) Successful in 13s
Reviewed-on: #6
2026-08-27 23:57:23 +00:00
thatguygriffandClaude Opus 5 43dc10e1dc Set the working version to 1.2.2
CI / Typecheck, test, build (pull_request) Successful in 14s
Publish / Build and push (pull_request) Successful in 20s
Publish / Move the working version on (pull_request) Skipped
1.2.1 shipped, so the tree was left on a version that is published and
immutable, which is the thing the bump job exists to prevent. It failed before
it got that far. Done by hand here, once: the job only fires on a tag, so no
re-run of it will do this retroactively.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XBT25ZDzm453A8XViSRqRB
2026-08-27 20:35:36 -03:00
thatguygriffandClaude Opus 5 b94c43a10c Open the version bump as a pull request
The bump job has never once worked. Its first step died in two seconds on
`set: Illegal option -o pipefail` -- it is the only job here that runs in a
container, and a container job is handed `sh -e {0}` rather than the bash the
runner gives its own jobs. Dash has no `pipefail`, and no `10#` either, so the
arithmetic on the line after would have gone the same way. It now asks for
bash, which node:22 carries.

That would have got the job as far as its last step, which pushed straight to
main. Nothing had ever exercised that, and it needs the token to be allowed
past whatever protects the branch -- hence the second token, VERSION_BUMP_TOKEN,
standing by for where it is not. unsupervised-scheduler has been bumping its
version on every release for a while by pushing a branch and opening a pull
request with the ordinary task token, so that is what this does now. The second
token is no longer needed, and neither is `[skip ci]`: main is never pushed, so
there is no build of the just-published image to suppress. The pull request
puts the changed package.json through a build before it lands.

scheduler builds the request body with jq because its CI image carries jq. This
one is node:22, where node is the thing that certainly is there.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XBT25ZDzm453A8XViSRqRB
2026-08-27 20:35:33 -03:00
thatguygriff b9b56e2195 Merge pull request 'Show the pictures inside Reddit comments' (#5) from reddit-inline-images into main
CI / Typecheck, test, build (push) Successful in 17s
Publish / Build and push (push) Successful in 16s
Publish / Move the working version on (push) Failing after 2s
Reviewed-on: #5
2026-08-27 19:29:59 +00:00
thatguygriffandClaude Opus 5 031101c382 Show a picture whose address was typed without a scheme
CI / Typecheck, test, build (pull_request) Successful in 26s
`preview.redd.it/lz4drsqh0clh1.jpeg?width=1290&...` was rendering as plain
text -- not a picture, and not even a link. The bare-address rule has always
insisted on `https://`, so anything copied out of an address bar, where the
browser hides the scheme, fell through to nothing at all. That predates the
inline images from the last commit; it just did not matter until pictures
started being worth placing.

The rule is deliberately narrow: a host with a dot, a path, and an image
extension. Widening it to every schemeless address would be the obvious move
and is wrong, because a comment thread is full of dotted, slashed prose --
`src/render/post.ts` would become a link to a website in Tonga, and
`node_modules/foo/bar.js` a website in Jersey. Requiring the extension costs
nothing here, since the only thing worth guessing a scheme for is a picture.

https is assumed. Every host that serves these redirects to it anyway.

Checked both ways: the four address shapes that should become pictures do,
and nine pieces of ordinary prose that must not -- file paths, a Windows
drive letter, a relative path, an email address followed by a filename, a
version number -- still do not.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017nMQ2eDKnqALYhAibpTKTu
2026-08-27 16:19:25 -03:00
thatguygriffandClaude Opus 5 0db18547c8 Show the pictures inside Reddit comments
CI / Typecheck, test, build (pull_request) Successful in 11s
A comment that was a picture rendered as either a link or, for a Giphy, the
literal text `![gif](giphy|Ve7wX45gaOFmw8eeEM)`. On r/aww that is most of the
thread.

Reddit writes an inline image as a token rather than an address, in three
shapes: `![gif](giphy|ID)` for a Giphy, `![img](emote|t5_2th52|4358)` for a
subreddit emote, and `![img](jo8gf0ca92zd1)` for an image uploaded straight to
the comment. The useful part is that all three tokens are keys in that same
comment's own `media_metadata`, so this is one lookup and not three special
cases. Nothing in the adapter has to know what Giphy is.

The fourth shape is someone pasting the address of a picture, which on Reddit
is how most images in comments actually arrive -- 117 of them against 21
Giphys in the sample I scanned. Those are shown as pictures too, decided by
the file extension. A link that is not to an image stays a link.

Animated ones take `s.gif` over `s.mp4` even though the MP4 is several times
smaller: a GIF moves on its own in an `<img>`, and an MP4 would need a player
element with autoplay, loop and muted set, for something the size of a
postage stamp.

Everything goes through the `/m/` proxy, like all other media. Without that a
comment thread would have the reader's browser fetch dozens of files straight
from Reddit, which is the one thing this whole app exists to avoid.

Placing the image is the renderer's job, not the Markdown parser's, because
the proxy is a render-time concern and markdown.ts knows nothing about it --
so it takes an optional `ImageRenderer` and, without one, an image stays a
link exactly as before. The parser also learned `![...]` proper: the link rule
was matching from the `[` and stranding the `!` as text.

Verified on r/aww/comments/171dxph, which carries one Giphy and 77 pasted
images: 35 render on the first page, all 35 load, all 35 through the proxy,
no upstream address reaches the page, no token is left unresolved, and
nothing overflows the column or scrolls the page sideways.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017nMQ2eDKnqALYhAibpTKTu
2026-08-27 16:14:06 -03:00
thatguygriff 9abc0eaf62 Merge pull request 'Move the working version on after a release' (#4) from bump-version-after-release into main
CI / Typecheck, test, build (push) Waiting to run
Publish / Build and push (push) Waiting to run
Publish / Move the working version on (push) Blocked by required conditions
Reviewed-on: #4
2026-08-27 16:27:51 +00:00
thatguygriffandClaude Opus 5 24db9be5af Make the rewrite rules copyable from the file, not just the render
Publish / Build and push (pull_request) Successful in 26s
Publish / Move the working version on (pull_request) Skipped
CI / Typecheck, test, build (pull_request) Successful in 30s
The rules were a Markdown table, and a table cell cannot hold a bare `|`. It
has to be written `\|`, which renders as a pipe and copies as a backslash and
a pipe. Every one of these rules is an alternation full of pipes, so anyone
reading README.md rather than a rendered view -- which, for a self-hosted
thing, is most of the time -- got a regex whose alternation had quietly become
literal characters. It matches nothing, and nothing about it looks wrong.

That is not hypothetical: it is how this came up. The Reddit rule is the
longest row, and reading it out of the file gave something that plainly did
not work, so the backslashes came out. Which fixed the copy and broke the
table -- four pipes turned into column separators, the row became seven cells,
the separator row was widened to seven to match, and `(.*)` picked up an
escape on the way past.

Restoring the row would have left the trap exactly where it was, for the next
person or the same one. So the table is now a code block: each rule is a
comment naming the platform, then the find field, then the replace field, one
per line. Nothing is escaped, the file and the render agree, and each field is
a whole line to select.

Every rule is checked from both directions. Out of README.md byte for byte
with no unescaping step, which is the copy-from-the-file path; and out of the
rendered HTML with entities decoded, which is the copy-from-the-page path.
Both give all seven rules, both compile, and both rewrite all seventeen sample
URLs correctly -- mobile.x.com, threads.net, the TikTok vm. and vt. hosts,
five Reddit subdomains, a /s/ share link and a redd.it short code. The two
extractions are byte-identical to each other, which is the property that was
missing before.

Also reformats the rest of the file, and stops calling it a table on the way
past.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017nMQ2eDKnqALYhAibpTKTu
2026-08-27 13:27:13 -03:00
thatguygriffandClaude Opus 5 503d8a8dec Move the working version on after a release
package.json has sat at 0.1.0 since the first commit, through three releases,
because nothing read it. That is fine right up until something does — an image
label, a health endpoint, a bug report quoting a version — at which point the
tree claims to be a version that shipped long ago.

A new `bump` job takes the tag that was just published, works out the next
patch from it, and commits that to main. After 1.2.0 the tree says 1.2.1: not
a version that exists, which is the point. A build from main is then legible
as "after 1.2.0" rather than as 1.2.0 itself.

It sits in publish.yml rather than a workflow of its own so that it can say
`needs: build`. A version that failed to publish has not been released, and
moving past it would say that it had. Prereleases are skipped for the same
reason -- 1.2.3-rc1 is a candidate for a version that has not shipped, so
there is nothing yet to move past.

The bump goes through `npm version` rather than editing the file. The version
is in the lockfile too, in two places, and a tree where those disagree is worse
than one that is merely out of date.

Three smaller things. The patch arithmetic forces base ten, because a patch
number written 08 is otherwise read as octal and kills the job. The commit
carries `[skip ci]`, or pushing it starts another build of the image that was
just published. And the committer is a name that is not a person at a reserved
address that can never become one, so nothing here names the instance it runs
on.

Pushing to main needs a token that may write to the repository. The Actions
task token can where the instance allows it; where it does not, setting a
VERSION_BUMP_TOKEN secret overrides it. A push that is refused fails the job
with both of those as the suggestion rather than a bare 403.

package.json goes to 1.2.1 here, which is where the job would have left it had
it existed when 1.2.0 went out.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017nMQ2eDKnqALYhAibpTKTu
2026-08-27 13:19:05 -03:00
thatguygriff 2ccc7bd618 Merge pull request 'Add Reddit with its comment threads, and show quoted posts whole' (#3) from reddit-and-quoted-posts into main
CI / Typecheck, test, build (push) Successful in 33s
Publish / Build and push (push) Successful in 2m3s
Reviewed-on: #3
2026-08-27 16:10:58 +00:00
thatguygriffandClaude Opus 5 6325f0ff32 Add Reddit with its comment threads, and show quoted posts whole
CI / Typecheck, test, build (pull_request) Successful in 9s
Two changes. They share the `Segment` model, which is why they arrive
together.

## Reddit

A new adapter under /reddit, plus the thread beneath the post -- on Reddit the
conversation is usually the reason the link was shared, so a viewer that showed
only the post would be showing the wrong half.

The `.json` twin of a post URL is the post and the whole first page of comments
in one response, far better than anything the page gives up, so it is the only
layer that normally runs. Reddit refuses it to a browser it has never seen and
answers with a JavaScript challenge, which any ordinary navigation solves by
itself; the adapter navigates once and retries, and the cookie left behind
serves every later post. Below that, `shreddit-comment` elements are read from
the rendered page -- flat, each carrying its own `depth`, so `treeFromDepths`
rebuilds the nesting.

`Post.comments` is a tree rather than a flat list with depths, because folding
a comment has to take everything under it along and nesting is what makes that
free. Each comment renders as a `<details open>`, so collapsing works with the
stylesheet off and from the keyboard, and a collapsed one says how many replies
it is hiding. "Collapse all" is the only part that needs the script, so it
ships hidden and appears once the script has run. What sits behind a "load
more" is not fetched -- that is a second page and often a third -- but it is
counted and said out loud rather than quietly dropped.

Four things the payloads got wrong on the first try, each now with a fixture:
`fallback_url` is the video track alone whenever `has_audio` is true, so a post
with sound has to use `hls_url` and only a silent one gets the proxied MP4;
`scrubber_media_url` looks like a poster and is a second MP4 for the timeline
thumbnails, while the still is in `preview.images`; a gallery's pictures live
in `media_metadata` keyed and unordered, with their order only in
`gallery_data`; and `replies` is the string "" rather than an object when there
are none. Comment bodies are Markdown, rendered by a new render/markdown.ts
that escapes first and then puts back only the constructs we chose to support
-- never Reddit's own `body_html`, which would mean trusting markup a stranger
caused to be generated.

An app share link (/r/<sub>/s/<code>) is a plain 301, so one request told not
to follow it is enough. The permalink it resolves to is what the copy button
hands back, since an opaque share code is a tracking parameter by another name.

## Quoted posts

Both X and Bluesky lifted the quoted post's media out and showed it as the
quoter's own, dropping the quoted words and the quoted author entirely. A quote
of a photo post therefore rendered as somebody else's picture under the wrong
name with nothing to say so, and a quote that had a picture of its own dropped
the quoted one instead -- the two could never both appear. Half the quote posts
people share are someone answering a stranger and the other half are someone
continuing a thought from an earlier post; neither reads with only one side of
it on the page.

`Segment.quoted` now carries the whole thing -- author, words, pictures, time
and a link to it -- and renders as a post inside the post. Neither payload
carries a usable address for it: X has no permalink and it is rebuilt from the
handle and `id_str`, Bluesky has an `at://` URI nobody can open and it is
rebuilt from the handle and the record key. On Bluesky the record sits at
`embed.record` for a plain quote and at `embed.record.record` when the quoting
post has media of its own, and a quote can also point at a feed, a list or a
post since deleted, which arrive in the same slot under a different `$type` --
only `app.bsky.embed.record#viewRecord` is taken.

Two things about X's text, both visible on any post and not only a quote. It
arrives pre-escaped, so an ampersand someone typed was reaching the page as the
literal `&amp;`; it is decoded in the adapter, where the encoding comes from,
leaving the escape-on-the-way-out rule alone. And every link is a `t.co`, which
tells the reader nothing and routes them through X's click tracker to find out
-- `entities.urls` carries the real address alongside, so it is put back. The
shortlink X staples onto the end of a quote post is dropped rather than
expanded, since the post it points at is already on the page;
`display_text_range` is where that boundary is and it keeps a link the author
put there deliberately. Its indices are UTF-16 units into the escaped text, so
the slice happens before decoding and before expanding, and splitting to
codepoints first overshoots past an emoji -- checked against a post carrying
one.

A quote is context, and context that fills the screen has stopped being
context, so a segment carrying one gives up the window-filling cap on its own
media.

## Along the way

setupMedia only ever wired `document.querySelector('.media')`, the first rail
on the page. That was already wrong for a Bluesky or Threads chain with media
in more than one post, and a quoted carousel would have hit it too. It now runs
per rail.

## Verified

108 tests, typecheck and build clean. Resolved end to end against the live
platforms: Reddit self, gallery, video, link and share-link posts; X quotes
with no media, with media on the quoted side, and with media on both; Bluesky
quotes in both embed shapes, including a ten-post chain where every post quotes
a different account and all nine quotes come back under the right name.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017nMQ2eDKnqALYhAibpTKTu
2026-08-27 11:45:40 -03:00
36 changed files with 4619 additions and 91 deletions
+188
View File
@@ -13,6 +13,7 @@ name: Publish
# vars.IMAGE_NAME optional, defaults to this repository's owner/name
# vars.REGISTRY_USER optional, defaults to the actor running the workflow
# secrets.REGISTRY_TOKEN required to push
# secrets.RELEASE_BOT_SIGNING_KEY required to sign the version bump commit
#
# Point REGISTRY at a host the runner reaches directly, without an intermediate
# proxy that caps request bodies: a browser image has layers well over 100MB,
@@ -141,3 +142,190 @@ jobs:
- name: Log out
if: always() && github.event_name != 'pull_request'
run: docker logout "${{ vars.REGISTRY }}" || true
# Once a release is out, the version in package.json has already shipped.
# Moving it on to the next patch means the working tree is never sitting on
# a number that is published and immutable, and that a build from main is
# always identifiable as "after 1.2.0" rather than "1.2.0, but not really".
#
# `needs: build` is the point of putting this here rather than in a workflow
# of its own: a version that failed to publish has not been released, and
# bumping past it would say it had.
bump:
name: Move the working version on
needs: build
# Tags only, and only final ones. A prerelease has not shipped the version
# it is a candidate for, so there is nothing yet to move past.
if: github.ref_type == 'tag' && !contains(github.ref_name, '-')
runs-on: ubuntu-latest
# npm does the bump, so this one job wants node. A job in a container is
# given `sh -e {0}` as its shell rather than the bash the runner's own jobs
# get, and dash has neither `pipefail` nor the `10#` below — which failed
# the first line of the first step the one time this ran. node:22 is Debian
# and carries bash, so asking for it keeps these scripts the same as the
# ones in the job above.
container:
image: node:22
defaults:
run:
shell: bash
steps:
# The tag names a commit in main's history, but the bump belongs on the
# branch, so this checks out main rather than the tag. The full history
# because a shallow clone cannot reliably push a branch back.
- uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Work out the next patch version
id: next
run: |
set -euo pipefail
version="${{ github.ref_name }}"
version="${version#v}"
major="${version%%.*}"
rest="${version#*.}"
minor="${rest%%.*}"
patch="${rest##*.}"
# `10#` forces base ten: a patch number written 08 would otherwise be
# read as octal and fail to parse.
next="${major}.${minor}.$((10#${patch} + 1))"
echo "next=${next}" >> "$GITHUB_OUTPUT"
echo "Released ${version}; the working version becomes ${next}"
- name: Bump package.json
id: bump
env:
NEXT: ${{ steps.next.outputs.next }}
run: |
set -euo pipefail
current="$(node -p "require('./package.json').version")"
if [ "${current}" = "${NEXT}" ]; then
echo "package.json is already ${NEXT}; nothing to do."
echo "changed=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# npm rather than editing the file: the version is in the lockfile
# too, in more than one place, and they have to agree.
npm version "${NEXT}" --no-git-tag-version --allow-same-version >/dev/null
echo "changed=true" >> "$GITHUB_OUTPUT"
echo "package.json ${current} -> ${NEXT}"
# main requires signed commits, and a pull request carrying an unsigned
# one cannot be merged. The key the server signs merge commits with lives
# on the server and no runner can reach it, so the bump commit is signed
# here with a dedicated key the instance trusts through
# `[repository.signing] TRUSTED_SSH_KEYS`. Setting that up is in
# CLAUDE.md; nothing about it is committed here.
- name: Configure signing as the release bot
if: steps.bump.outputs.changed == 'true'
env:
SIGNING_KEY: ${{ secrets.RELEASE_BOT_SIGNING_KEY }}
run: |
set -euo pipefail
if [ -z "${SIGNING_KEY}" ]; then
echo "RELEASE_BOT_SIGNING_KEY is not set; the bump commit would be unsigned and unmergeable." >&2
exit 1
fi
if ! command -v ssh-keygen >/dev/null; then
echo "ssh-keygen is missing from this image; git cannot make SSH signatures without it." >&2
exit 1
fi
# The secret holds an OpenSSH private key. git signs by shelling out
# to ssh-keygen, which wants the key on disk beside the `.pub` it is
# pointed at, readable only by us, and rejects it unless the trailing
# newline survived the round trip through the secret store.
keydir="${RUNNER_TEMP:-${TMPDIR:-/tmp}}/release-bot-signing"
install -m 700 -d "${keydir}"
printf '%s\n' "${SIGNING_KEY}" | tr -d '\r' > "${keydir}/key"
chmod 600 "${keydir}/key"
# Doubles as a format check: a truncated, re-wrapped or
# passphrase-protected key fails here rather than as "gpg failed to
# sign the data" three steps later.
if ! ssh-keygen -y -f "${keydir}/key" </dev/null > "${keydir}/key.pub"; then
echo "RELEASE_BOT_SIGNING_KEY is not a usable OpenSSH private key (passphrase-protected, truncated, or re-wrapped on paste)." >&2
exit 1
fi
# A name that is not a person, and an address no account backs: the
# signature verifies against the trusted key rather than against a
# user, so this is a label on the commit and not an identity.
git config user.name 'Release Bot'
git config user.email '[email protected]'
# `gpg.format` is the historical name; `ssh` is what switches git to
# signing with the key above rather than with a GPG key.
git config gpg.format ssh
git config user.signingkey "${keydir}/key.pub"
git config commit.gpgsign true
# The bump arrives as a pull request rather than as a commit straight to
# main. Pushing a branch asks nothing of the task token beyond ordinary
# write access, so nothing here depends on being allowed past whatever
# protects main; and the pull request puts the changed package.json
# through the build before it lands. Since main is never pushed, the
# `[skip ci]` that would otherwise be needed to stop this rebuilding the
# image just published is not.
- name: Open a pull request for it
if: steps.bump.outputs.changed == 'true'
env:
NEXT: ${{ steps.next.outputs.next }}
RELEASED: ${{ github.ref_name }}
TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
branch="release/bump-${NEXT}"
git checkout -b "${branch}"
git add package.json package-lock.json
git commit -m "Set the working version to ${NEXT}"
# An unsigned commit would go unnoticed until someone tried to merge
# the pull request, so it fails here instead, where the cause is in
# front of you.
if ! grep -q "^gpgsig" <<<"$(git cat-file commit HEAD)"; then
echo "The bump commit came out unsigned; refusing to push it." >&2
exit 1
fi
git push origin "${branch}"
# node rather than jq to build the request body: jq is not in this
# image, and node is the one thing that certainly is.
payload="$(BRANCH="${branch}" node -e 'process.stdout.write(JSON.stringify({
head: process.env.BRANCH,
base: "main",
title: `Set the working version to ${process.env.NEXT}`,
body: `${process.env.RELEASED} has shipped, so the tree was left on a version that is published and immutable. This moves it on to ${process.env.NEXT}, which is deliberately not a version that exists.`,
}))')"
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
response="$(mktemp)"
code="$(curl -sS -o "${response}" -w '%{http_code}' \
-X POST "${api}/pulls" \
-H "Authorization: token ${TOKEN}" \
-H 'Content-Type: application/json' \
-d "${payload}")"
case "${code}" in
201) echo "Opened ${branch} against main." ;;
# A release re-run that got this far: the branch and its pull
# request are already there, which is the state we wanted anyway.
409) echo "A pull request for ${branch} is already open." ;;
*)
echo "Could not open the pull request (HTTP ${code}):" >&2
cat "${response}" >&2
exit 1
;;
esac
+127 -4
View File
@@ -1,9 +1,9 @@
# antisocial — working notes
A self-hosted page that shows a social post without the app. StopTheMadness rewrites
links to X, Threads, Instagram, TikTok and Bluesky into `/<prefix>/<original path>`;
this resolves the post by driving a real headless Chromium and renders the media, the
text, a platform badge and a copy-the-original button.
links to X, Threads, Instagram, TikTok, Bluesky and Reddit into
`/<prefix>/<original path>`; this resolves the post by driving a real headless Chromium
and renders the media, the text, a platform badge and a copy-the-original button.
Built for one person on a private network, with no authentication. `README.md` has the
rewrite rules and the user-facing description. This file is the working context.
@@ -35,6 +35,7 @@ different fixes:
| Right media, wrong count | The structured payload was missed and it fell through to the DOM, which only shows the first carousel item. |
| Poster image where a video belongs | Same fall-through, plus the `<video>` had not hydrated when the DOM was read. |
| Nothing at all | The platform refused this specific post logged out, or a key moved. |
| Reddit post fine, no comments | The `.json` was refused and it fell through to the page, where the comment tree loads late. |
**3. Look at what the page actually served.**
@@ -66,6 +67,17 @@ A `Post` is a list of `Segment`s, not a single body. Most platforms produce one
(`oneSegment` in `types.ts`); Bluesky and Threads produce the author's whole chain,
with `isAnchor` marking the post that was linked — which need not be the first.
`Segment.quoted` is a post inside a post — someone else's words and pictures, kept
under their own name. X and Bluesky fill it in. Both used to lift the quoted post's
media out and show it as the quoter's own, which is the bug to avoid reintroducing:
a quoted picture without the name attached to it is a false attribution.
`Post.comments` is a separate thing and a tree, not a chain. Only Reddit fills it in,
because only there is the conversation usually the point of the link. It is a tree
rather than a flat list with depths because folding a comment has to take everything
under it along, and nesting is what makes that free — the renderer emits a `<details>`
per comment and gets collapsing without a line of JavaScript.
Things worth knowing before editing:
- **One Chromium, one context, persistent.** Cookies and dismissed banners accumulate on
@@ -84,6 +96,15 @@ Things worth knowing before editing:
`src/media/registry.ts` and served from `/m/<id>` with the `Referer`/`Cookie` the CDN
demands. `Range` is forwarded — without it the native video scrubber cannot seek.
The exception is HLS (`direct: true`), because proxying would mean rewriting playlists.
- **A video is sized by its poster**, not by the ratio the renderer puts on it. A
`<video>` with no data has a natural size of 300x150, and WebKit sizes it from that —
so one with no poster of its own gets an empty SVG of the right shape as a stand-in,
without which a portrait video sits in a squat landscape box until you press play.
- **A page with a video claims the `playback` audio session** (`public/app.js`). iOS
hands inline video the ambient session, which the Ring/Silent switch mutes, so
without this the video plays and says nothing until it goes fullscreen — and the
report that arrives is "this one platform has no sound". The session only activates
once something plays, so declaring it costs nothing on a page nobody presses play on.
- **Never a bare error page.** A failed resolve renders a card carrying the platform, the
original URL and the copy button. A broken adapter must still leave the link one tap
away.
@@ -95,8 +116,24 @@ Things worth knowing before editing:
deliberately matches only V1. Threads are built by walking `parent` up and the
author's own `replies` down; `depth`/`parentHeight` are what make that possible, at
the cost of dragging the whole reply tree along (a few hundred KB on a busy post).
A quote fills in `Segment.quoted`. The record sits at `embed.record` for a plain quote
and at `embed.record.record` when the quoting post has media of its own
(`recordWithMedia`) — check both. A quote can also point at a feed, a list or a post
since deleted, which arrive in the same slot under a different `$type`, so only
`app.bsky.embed.record#viewRecord` is accepted. The quoted post's address has to be
rebuilt: `uri` is an `at://` nobody can open.
- **X** — the `platform.twitter.com` embed calls the syndication endpoint; we catch that
response. A quote post carries no media of its own, so the quoted post's media is used.
response. A quote post keeps the post it quotes whole, in `Segment.quoted` — author,
words and pictures — rather than lifting its media out; doing that put someone else's
picture under the quoter's name, and dropped the quoted words entirely. There is no
permalink in the payload, so the quoted post's URL is rebuilt from the handle and
`id_str`. Two things about the text: it arrives pre-escaped (`&amp;`) and has to be
decoded, since everything downstream escapes again on the way out; and X staples a
`t.co` to the quoted post onto the end, which `display_text_range` trims — its indices
are UTF-16 units into the *escaped* text, so slice before decoding and do not split to
codepoints first. Every remaining link is a `t.co`, expanded from `entities.urls`
matched on the shortlink text rather than by `indices`, which are offsets into a string
the expansion is changing the length of.
- **Instagram** — the least reliable. It ships the structured payload only some of the
time, and refuses some posts from the embed entirely ("the link may be broken"). The
DOM is the floor and only ever shows the first carousel item. Reels hydrate their
@@ -106,6 +143,35 @@ Things worth knowing before editing:
carries an `itemStruct`; do not hardcode the key, photo posts use a different one.
Its CDN needs `Referer` *and* cookies. Short `vm.`/`vt.` links arrive as a bare path
segment and are rebuilt in `buildOriginalUrl`.
- **Reddit** — the `.json` twin of any post URL is the whole post plus the first page of
comments in one response, which is far better than anything the page gives up, so that
is the only layer that normally runs. A cold profile gets a JavaScript challenge
instead of JSON; an ordinary navigation solves it by itself, so the adapter navigates
once and retries, and the cookie serves every later post. The floor is
`shreddit-comment` elements, which are flat with a `depth` attribute — `treeFromDepths`
rebuilds the nesting. `replies` is `""` and not an object when there are none.
Video: `fallback_url` is the *video track alone* whenever `has_audio` is true, so a
post with sound has to use `hls_url`, direct and unproxied; a silent one gets the
proxied MP4. `scrubber_media_url` is not a poster — it is a second MP4 for the
timeline thumbnails, and the still is in `preview.images` — which belongs to both
forms: the HLS one used to go without, and showed an empty box where a silent post
showed a frame. A gallery's pictures are in `media_metadata`, keyed and unordered;
their order is only in `gallery_data`. Comment
bodies are Markdown, rendered by `src/render/markdown.ts` — escape first, then put
back the constructs we chose to support, never `body_html`. An image in a comment is
written as a token rather than an address — `![gif](giphy|Ve7wX45)`,
`![img](emote|t5_2th52|4358)`, `![img](jo8gf0ca92zd1)` — and the token is usually a key
in that same comment's own `media_metadata`, so `resolveInlineImages` is one lookup
rather than three special cases. Usually: plenty of comments carry a Giphy token and
no `media_metadata` at all, and Giphy is the one of the three whose id means something
off Reddit, so that token alone falls back to `i.giphy.com/media/<id>/giphy.gif`. A
variant name after the id is dropped — Giphy does not serve every variant of every
gif. A bare `preview.redd.it` address pasted into a comment is in there too, keyed by
the id inside the URL. Prefer `s.gif` over `s.mp4` for an animated one: a GIF moves in
an `<img>` and an MP4 needs a player. An address
typed without a scheme counts as well, but only when it ends in an image extension —
the rule wants a host, a path *and* that extension, because comments are full of
dotted, slashed prose that must not turn into links.
- **Threads** — same media schema as Instagram (`src/platforms/meta-media.ts`). Its
payloads are full of empty stub nodes, so the finder only accepts a node with actual
candidates in it. The page ships the linked post, the author's follow-ups, other
@@ -132,6 +198,10 @@ Login walls are not passed through — those need an account and cannot be solve
- **No ESLint** — `typescript-eslint` does not support TS 7 yet. `npm run typecheck` is
the lint step.
- Tests are `node:test` against captured fixtures. No network in the test suite.
- `public/` is served as-is to the browser, so what is in there is plain JS, not TS.
`public/browsers.js` — the per-browser URL schemes behind the "open in" picker — is
a module rather than more of `app.js` so a test can import it; that is what `allowJs`
in `tsconfig.json` is for.
- Comments explain *why*, especially where the code looks odd because a platform is odd.
Match that; do not add narration of what the next line does.
- Post text comes from strangers: everything goes through the `html` tagged template or
@@ -159,6 +229,59 @@ The registry comes from the `REGISTRY` repository variable, the image name from
`IMAGE_NAME` or the repository name, and credentials from `REGISTRY_USER` and the
`REGISTRY_TOKEN` secret. Nothing about any particular deployment is committed here.
A release also moves `package.json` on to the next patch version, opened as a pull
request by the `bump` job — so the number in the tree is never one that has already
shipped and been made immutable. It lives in `publish.yml` rather than a workflow of its
own so it can say `needs: build`: a version that failed to publish has not been
released, and bumping past it would claim otherwise. Prereleases are skipped, being
candidates for a version that has not shipped. The bump goes through `npm version`
rather than an edit in place, because the version is in the lockfile too, in more than
one place, and the two have to agree.
It arrives as a pull request rather than as a commit straight to main: pushing a branch
asks nothing of the task token beyond ordinary write access, so it does not matter what
protects main, and the changed `package.json` goes through a build before it lands.
Nothing pushes to main, so no `[skip ci]` is needed to stop the bump rebuilding the
image just published. The job is the only one that runs in a container (`node:22`, for
npm), and a job in a container is handed `sh`, not bash — hence the explicit
`shell: bash`, without which `set -o pipefail` fails the first line of the first step.
### Signing the bump commit
main requires signed commits, and a pull request carrying an unsigned one cannot be
merged — so the bump job signs the commit it makes. Not with the key the server signs
merge commits with: that one lives on the server and no runner can reach it. It uses a
dedicated release-bot SSH key instead, which also means it can be rotated on its own if
the secret ever leaks.
There is deliberately no release-bot account. A key attached to an account is only
consulted for signature checking once it has been through the web *Verify* flow, and
that flow has no API, so a bot account would need an interactive login to be worth
anything. Listing the key under `[repository.signing] TRUSTED_SSH_KEYS` instead makes
the signature verify with no account lookup at all, which is all the protected branch
asks for. `[email protected]` is therefore a label and not an identity, and
the signature is attributed to the instance's `SIGNING_NAME`/`SIGNING_EMAIL` rather
than to it. The other side of trusting a key instance-wide: a commit signed with it
verifies in *every* repository on that instance, because the trust is in the key and not
in a user whose permissions you could scope.
Set up once per instance, and again only on rotation:
1. Generate a passphrase-less key — it has to be usable unattended:
`ssh-keygen -t ed25519 -C release-bot -f release-bot -N ''`.
2. Add the public half to `TRUSTED_SSH_KEYS` in the server config and restart.
3. Store the private half as the `RELEASE_BOT_SIGNING_KEY` Actions secret — the whole
file verbatim, `-----BEGIN OPENSSH PRIVATE KEY-----` and footer included, not the
`.pub` and not a GPG export. An organisation secret covers every repository at once.
Delete both local files afterwards.
Until both are in place the bump job fails, loudly and on purpose: it checks the secret
is set and that `ssh-keygen` exists before it starts, feeds the key through
`ssh-keygen -y` so a truncated or re-wrapped one is caught as itself rather than as
"gpg failed to sign the data", and re-reads the commit for a `gpgsig` header before
pushing. Nothing else in the pipeline signs anything — release tags are made by hand,
and the merge commit is signed by the server.
Two things any deployment has to get right, both learned the hard way:
- **Chromium needs more than the default 64Mi `/dev/shm`** or it crashes. Mount a
+125 -22
View File
@@ -2,9 +2,9 @@
Reads social posts back to you without the app.
Links to X, Threads, Instagram, TikTok and Bluesky get shared constantly, and opening
one means an app interstitial, a login wall, a feed you didn't ask for, and a pile of
tracking. antisocial is the other half of a StopTheMadness rewrite rule: the link gets
Links to X, Threads, Instagram, TikTok, Bluesky and Reddit get shared constantly, and
opening one means an app interstitial, a login wall, a feed you didn't ask for, and a
pile of tracking. antisocial is the other half of a StopTheMadness rewrite rule: the link gets
redirected here, and you get the post — the media and the words — plus a badge saying
where it came from and a button to copy the original URL if you do want to go there.
@@ -21,23 +21,86 @@ readable in your history.
Replace `antisocial.example.com` with wherever you are running it.
| Platform | Find | Replace |
| --------- | ------------------------------------------------------------- | ------------------------------------------- |
| X | `/^https:\/\/(?:www\.\|mobile\.)?(?:x\|twitter)\.com\/(.*)$/` | `https://antisocial.example.com/x/$1` |
| Threads | `/^https:\/\/(?:www\.)?threads\.(?:net\|com)\/(.*)$/` | `https://antisocial.example.com/threads/$1` |
| Instagram | `/^https:\/\/(?:www\.)?instagram\.com\/(.*)$/` | `https://antisocial.example.com/ig/$1` |
| TikTok | `/^https:\/\/(?:www\.\|vm\.\|vt\.)?tiktok\.com\/(.*)$/` | `https://antisocial.example.com/tiktok/$1` |
| Bluesky | `/^https:\/\/bsky\.app\/(.*)$/` | `https://antisocial.example.com/bsky/$1` |
Each rule is two fields. Both are on their own line below, and neither needs any
escaping — copy them straight out of this file.
```text
# X
/^https:\/\/(?:www\.|mobile\.)?(?:x|twitter)\.com\/(.*)$/
https://antisocial.example.com/x/$1
# Threads
/^https:\/\/(?:www\.)?threads\.(?:net|com)\/(.*)$/
https://antisocial.example.com/threads/$1
# Instagram
/^https:\/\/(?:www\.)?instagram\.com\/(.*)$/
https://antisocial.example.com/ig/$1
# TikTok
/^https:\/\/(?:www\.|vm\.|vt\.)?tiktok\.com\/(.*)$/
https://antisocial.example.com/tiktok/$1
# Bluesky
/^https:\/\/bsky\.app\/(.*)$/
https://antisocial.example.com/bsky/$1
# Reddit
/^https:\/\/(?:www\.|old\.|new\.|np\.|m\.)?reddit\.com\/(.*)$/
https://antisocial.example.com/reddit/$1
# Reddit short links
/^https:\/\/redd\.it\/(.*)$/
https://antisocial.example.com/reddit/$1
```
A code block rather than a table, because a table cell cannot hold a bare `|` — it has
to be written `\|`, which renders correctly and copies wrongly. The alternation in these
rules is full of them, and a regex whose pipes arrive as literal pipes matches nothing
and says nothing about why.
So `https://x.com/user/status/123` becomes
`https://antisocial.example.com/x/user/status/123`.
Tracking parameters (`igsh`, `utm_*`, `s`, `t`, and friends) are stripped on arrival, so
the URL the copy button gives back is the clean one. TikTok `vm.`/`vt.` share codes lose
their subdomain in the rewrite; a single opaque path segment is recognised as a share
code and rebuilt as `vm.tiktok.com/<code>/`.
Tracking parameters (`igsh`, `utm_*`, `share_id`, `s`, `t`, and friends) are stripped on
arrival, so the URL the copy button gives back is the clean one. TikTok `vm.`/`vt.`
share codes lose their subdomain in the rewrite; a single opaque path segment is
recognised as a share code and rebuilt as `vm.tiktok.com/<code>/`, or `redd.it/<code>`
where it came from Reddit. A Reddit `/r/<sub>/s/<code>` share link is followed to the
post it points at, and that permalink — not the opaque share code — is what the copy
button hands back.
`/` serves this table with the live hostnames, if you'd rather read it there.
`/` serves these rules with the live hostname already filled in, if you'd rather copy
them from there.
## Opening the original
The rules are indiscriminate, which is the point — but that catches the way back out
too. Tapping "Open on Instagram" in the browser the rules are installed in redirects
straight back here, so the one button meant to get you to the app is the one button that
cannot.
The way past it is to hand the address to a *different* browser, by its own URL scheme.
`/` has a picker for which one:
| Browser | macOS | iOS |
| --- | --- | --- |
| Chrome | `googlechromes://…` | `googlechromes://…` |
| Edge | `microsoft-edge:https://…` | `microsoft-edge-https://…` |
| Orion | `orion://open-url?url=…` | `orion://open-url?url=…` |
| Firefox | — | `firefox://open-url?url=…` |
Firefox on macOS registers no scheme, so it is not offered there; nor is Safari itself,
which is the browser being escaped. The choice is kept in that browser's own
`localStorage` — not a cookie and not synced, because "which browser is installed" is a
fact about the device, not about you, and the phone's answer is not the Mac's.
Until a browser is chosen there is no "Open on …" button at all — the plain address is
the one thing it must not offer, since following it only comes back here. The markup
carries that address anyway, hidden, and the script swaps in the scheme and reveals the
button once there is somewhere to send it. So with JavaScript off, or with the default
left alone, the copy button and the selectable URL are the whole of it, which is all
that was ever load-bearing.
## How it works
@@ -54,13 +117,14 @@ Each adapter layers its extraction, most structured first:
3. **The rendered DOM** — whatever is actually on screen is real.
4. **Open Graph tags** — the floor, and enough to show something.
| Platform | Loads | Reads |
| --------- | ---------------------------- | -------------------------------------------------------- |
| Bluesky | the public AT Protocol API | `getPostThread`; falls back to the post page |
| X | `platform.twitter.com` embed | the `cdn.syndication.twimg.com/tweet-result` response |
| Instagram | `/embed/captioned/` | `shortcode_media`, then the rendered `<video>`/`<img>` |
| TikTok | the post page | `__UNIVERSAL_DATA_FOR_REHYDRATION__` |
| Threads | the post page | the Relay payloads in `<script type="application/json">` |
| Platform | Loads | Reads |
| --------- | ---------------------------- | --------------------------------------------------------------- |
| Bluesky | the public AT Protocol API | `getPostThread`; falls back to the post page |
| X | `platform.twitter.com` embed | the `cdn.syndication.twimg.com/tweet-result` response |
| Instagram | `/embed/captioned/` | `shortcode_media`, then the rendered `<video>`/`<img>` |
| TikTok | the post page | `__UNIVERSAL_DATA_FOR_REHYDRATION__` |
| Threads | the post page | the Relay payloads in `<script type="application/json">` |
| Reddit | the post's own `.json` | the post and the first page of comments; falls back to the page |
On Bluesky and Threads people write in chains, so where the linked post is part
of one, the author's own follow-ups are shown with it, in the order they were
@@ -68,6 +132,36 @@ written, with the post you actually followed marked. Other people's replies are
left out — they are a conversation, not the thing that was shared, and on a busy
post there are hundreds of them.
A post that quotes another shows both, on X and on Bluesky. The quoted post gets its own
author, its own words and its own pictures, in a block inside the one quoting it —
because half the quote posts people share are someone answering a stranger and the other
half are someone continuing a thought from an earlier post, and neither reads with only
one side of it on the page. Showing the quoted picture on its own, which is what used to
happen, put it under the wrong person's name.
X links are un-shortened. Every link in a post is rewritten to a `t.co` before it is
stored, so left alone the page shows `t.co/QdJhOVu4En` and sends you through X's click
tracker to find out where it goes; the real address is in the payload alongside. The
shortlink X staples onto the end of a quote post is dropped rather than expanded, since
the post it points at is already on the page — a link the author put there on purpose
is kept.
On Reddit the thread under the post is usually the reason the link was shared, so
Reddit posts come with it: every comment the first page carried, nested the way it was
written. Each comment is a `<details>` element, so folding one takes its whole subtree
with it, works without JavaScript and works from the keyboard; a collapsed comment says
how many replies it is hiding. "Collapse all" is the one piece that needs the script,
which is why it only appears once the script has run. What was behind a _load more_ is
not fetched — that is a second page and often a third — but it is counted and said out
loud rather than quietly dropped.
Pictures inside comments are shown as pictures. Reddit writes them as a token rather
than an address — a Giphy id, a subreddit emote, or an image uploaded to the comment —
and all three are looked up in the comment's own metadata to find the real file. An
image address someone simply pasted is shown too, which on Reddit is how most of them
arrive. All of it goes through the same `/m/` proxy as everything else, so reading a
comment thread never has your browser talking to Reddit.
Media never gets linked straight at a CDN. Instagram and TikTok reject requests without
a matching `Referer` (and sometimes cookies), and proxying keeps your browser from
talking to the platform at all. Every asset is registered under an opaque `/m/<id>` and
@@ -77,6 +171,10 @@ The one exception is Bluesky video, which is an HLS playlist — proxying it wou
rewriting the manifest and every segment, so it is linked directly. Safari plays HLS
natively; other browsers show a note.
A page carrying a video asks iOS for the playback audio session. Without it a video
playing inline is treated as ambience and the Ring/Silent switch mutes it, so the post
plays perfectly and says nothing unless you go fullscreen.
Resolved posts are cached in memory for an hour, so a reload or a back button doesn't
drive the browser again.
@@ -110,6 +208,11 @@ Known rough edges:
carousel will come back as its first image only.
- **TikTok sometimes answers with a slider puzzle** instead of the post. You get handed
the puzzle rather than an error — see below.
- **Reddit refuses `.json` to a browser it has never seen.** The first request of a cold
profile gets a JavaScript challenge, which the page solves by itself on an ordinary
navigation; the adapter does that once and retries, and the cookie it leaves behind
serves every later post. If the JSON is still refused, the rendered page is read
instead — the same comments, without the scores Reddit is withholding.
## Verification puzzles
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "antisocial",
"version": "0.1.0",
"version": "1.2.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "antisocial",
"version": "0.1.0",
"version": "1.2.5",
"license": "UNLICENSED",
"dependencies": {
"@fastify/static": "10.1.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "antisocial",
"version": "0.1.0",
"version": "1.2.5",
"private": true,
"description": "Reads social posts back to you without the app.",
"license": "UNLICENSED",
+269
View File
@@ -242,6 +242,30 @@ main { max-width: 680px; margin: 0 auto; }
.index__table td { padding: 8px 8px 8px 0; border-top: 1px solid var(--line); vertical-align: middle; }
.index__table code { overflow-wrap: anywhere; }
.picker {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 10px;
margin-top: 18px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
/* The control ships hidden and is revealed by the script, and `display:
flex` above would otherwise beat the browser's own rule for [hidden]. */
.picker[hidden] { display: none; }
.picker__label { font-size: 13px; color: var(--ink-dim); }
.picker__select {
font: inherit;
font-size: 14px;
padding: 7px 10px;
border-radius: 999px;
border: 1px solid var(--line);
background: var(--card);
color: var(--ink);
}
.picker__note { flex-basis: 100%; margin: 0; font-size: 12px; color: var(--ink-dim); }
/* ---------- verification puzzle ---------- */
.challenge__lede { margin: 14px; font-size: 14px; color: var(--ink-dim); }
@@ -330,3 +354,248 @@ main { max-width: 680px; margin: 0 auto; }
min-height: 220px;
}
}
/* ---------- a post with a headline ---------- */
/* Reddit is the one platform where the post has a title and the body is
optional, so the headline has to carry on its own. */
.text__title {
margin: 0 0 8px;
font-size: 19px;
line-height: 1.3;
font-weight: 650;
}
.text__title:only-child { margin-bottom: 0; }
/* ---------- comments ---------- */
.thread {
margin-top: 12px;
background: var(--card);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.thread__head {
display: flex;
align-items: baseline;
gap: 10px;
padding: 12px 14px;
border-bottom: 1px solid var(--line);
}
.thread__title { margin: 0; font-size: 15px; font-weight: 650; }
.thread__count { font-size: 12px; color: var(--ink-dim); }
.thread__toggle {
appearance: none;
margin-left: auto;
border: 1px solid var(--line);
background: transparent;
color: var(--ink-dim);
font: inherit;
font-size: 12px;
padding: 4px 12px;
border-radius: 999px;
cursor: pointer;
}
.thread__list { padding: 6px 14px 14px; }
.c { margin-top: 10px; }
/* The whole byline is the hit target for folding, so it wants to look like
one thing rather than a row of separate labels. */
.c__head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 8px;
font-size: 12px;
color: var(--ink-dim);
cursor: pointer;
list-style: none;
padding: 2px 0;
user-select: none;
}
.c__head::-webkit-details-marker { display: none; }
.c__head::before {
content: "";
display: inline-grid;
place-items: center;
width: 15px;
height: 15px;
border: 1px solid var(--line);
border-radius: 4px;
font-size: 11px;
line-height: 1;
color: var(--ink-dim);
flex: none;
}
.c:not([open]) > .c__head::before { content: "+"; }
.c__author { font-weight: 600; color: var(--ink); }
.c__hidden { font-variant-numeric: tabular-nums; }
.c[open] > .c__head .c__hidden { display: none; }
.c__mark {
padding: 1px 5px;
border-radius: 4px;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
color: var(--accent-ink);
background: var(--ink-dim);
}
.c__mark--op { background: #ff4500; }
.c__mark--mod, .c__mark--admin { background: #1a7f4b; }
.c__body { font-size: 15px; overflow-wrap: anywhere; }
.c__body > :first-child { margin-top: 4px; }
.c__body > :last-child { margin-bottom: 0; }
.c__body p { margin: 0 0 8px; }
.c__body a { color: inherit; text-decoration-color: var(--ink-dim); text-underline-offset: 2px; }
.c__body ul, .c__body ol { margin: 0 0 8px; padding-left: 20px; }
.c__body blockquote {
margin: 0 0 8px;
padding-left: 10px;
border-left: 3px solid var(--line);
color: var(--ink-dim);
}
.c__body pre {
margin: 0 0 8px;
padding: 8px 10px;
border-radius: 8px;
background: color-mix(in srgb, var(--ink) 6%, transparent);
overflow-x: auto;
}
.c__body code { font-size: 13px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.c__body pre code { font-size: 12px; }
/* The rule down the left is what tells you where a subtree ends, which is
the thing a wall of replies otherwise makes you count indents for. */
.c__replies {
margin: 6px 0 0 7px;
padding-left: 11px;
border-left: 1px solid var(--line);
}
.c__more { margin: 8px 0 0; font-size: 12px; color: var(--ink-dim); }
.thread__more {
margin: 0;
padding: 12px 14px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--ink-dim);
}
@media (max-width: 520px) {
.c__replies { margin-left: 4px; padding-left: 7px; }
}
/* ---------- a quoted post ---------- */
/*
* A post inside a post. Bordered and inset rather than merely indented,
* because the whole job of this block is to be unmistakably someone else's
* — an indent alone reads as a continuation of the words above it.
*/
.quote {
margin: 0 14px 14px;
border: 1px solid var(--line);
border-radius: 10px;
overflow: hidden;
}
.text + .quote, .media + .quote { margin-top: 14px; }
.quote__who {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 2px 6px;
padding: 10px 12px 0;
font-size: 13px;
min-width: 0;
}
.quote__avatar {
width: 20px;
height: 20px;
border-radius: 50%;
flex: none;
align-self: center;
}
.quote__name { font-weight: 600; }
.quote__handle, .quote__who time { color: var(--ink-dim); font-size: 12px; }
.quote__text { padding: 6px 12px 10px; font-size: 15px; overflow-wrap: anywhere; }
.quote__text a { color: inherit; text-decoration-color: var(--ink-dim); text-underline-offset: 2px; }
/* Its own media sits flush in the block, the way the post's own does in the
card, so the two read as the same kind of thing at different sizes. */
.quote .media { border-bottom: 0; }
.quote__text + .media, .quote__who + .media { border-top: 1px solid var(--line); }
.quote__open {
display: block;
padding: 9px 12px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--ink-dim);
text-decoration: none;
}
/*
* Deliberately smaller than the post's own media, and after the window-fitting
* rule above so it wins on source order at equal specificity. A quote is
* context for the post, and context that fills the screen has stopped being
* context.
*/
.post .quote .item img,
.post .quote .item video {
max-height: 40vh;
max-height: 40dvh;
min-height: 0;
}
/*
* A post that quotes another has two things to show, so its own media gives
* up the window-filling cap above. Left at full height the quote starts below
* the fold, which is the same as not having it — the whole reason it is here
* is that neither half reads without the other.
*/
.segment[data-quoted] .item img,
.segment[data-quoted] .item video {
max-height: 45vh;
max-height: 45dvh;
min-height: 0;
}
/* A picture someone put in a comment. Capped hard: it is a remark inside a
conversation, not the thing the page is about. */
.c__img {
display: block;
max-width: min(100%, 420px);
max-height: 40vh;
max-height: 40dvh;
width: auto;
height: auto;
margin: 8px 0;
border: 1px solid var(--line);
border-radius: 8px;
background: color-mix(in srgb, var(--ink) 4%, transparent);
}
/* A lone image is the whole comment more often than not, so it should not
carry a paragraph's worth of space above it as well as its own. */
.c__body > p:first-child > .c__img:first-child { margin-top: 2px; }
+109 -4
View File
@@ -1,7 +1,10 @@
// Progressive enhancement only. Without this file the page still shows the
// media in a swipeable rail and the original URL as selectable text.
import { browsersFor, detectOs, openUrlFor } from './browsers.js';
const VIEW_KEY = 'antisocial:view';
const BROWSER_KEY = 'antisocial:browser';
function setupCopy() {
for (const button of document.querySelectorAll('.copy')) {
@@ -37,10 +40,65 @@ function setupCopy() {
}
}
function setupMedia() {
const media = document.querySelector('.media');
if (!media) return;
function storedBrowser() {
try {
return localStorage.getItem(BROWSER_KEY) ?? 'default';
} catch {
return 'default';
}
}
// The markup carries the plain address, which is the one thing the button
// must not offer: followed in the browser the rewrite rules are installed
// in, it redirects straight back to this page. So the link ships hidden and
// is only revealed once a browser has been picked to hand it to. With no
// choice made -- or none this system has a scheme for -- the copy button
// and the URL below it are the whole of it.
function applyBrowser(id) {
const os = detectOs();
for (const link of document.querySelectorAll('.original__open')) {
link.dataset.original ??= link.getAttribute('href');
const href = openUrlFor(link.dataset.original, id, os);
link.href = href;
link.hidden = href === link.dataset.original;
}
}
// Only on the index page, and only with this file running: the choice is
// useless without the rewriting above, so the control ships hidden.
function setupBrowserPicker() {
const select = document.querySelector('.picker__select');
if (!select) return;
for (const browser of browsersFor(detectOs())) {
const option = document.createElement('option');
option.value = browser.id;
option.textContent = browser.label;
select.append(option);
}
// A stored id with no scheme on this system would leave the control
// showing nothing at all, so fall back rather than render a blank.
const stored = storedBrowser();
select.value = [...select.options].some((option) => option.value === stored) ? stored : 'default';
select.addEventListener('change', () => {
try {
localStorage.setItem(BROWSER_KEY, select.value);
} catch {
// Private browsing. The choice just won't survive the page.
}
applyBrowser(select.value);
});
select.closest('.picker').hidden = false;
}
// One per rail: a post can carry several -- a thread of them, or a post and
// the post it quotes -- and wiring only the first leaves the rest inert.
function setupMedia(media) {
const rail = media.querySelector('.media__rail');
const items = [...media.querySelectorAll('.item')];
const at = media.querySelector('.media__at');
@@ -97,8 +155,55 @@ function setupMedia() {
}
}
// On iOS a video playing inline gets the "ambient" audio session, which the
// Ring/Silent switch mutes -- so the post plays perfectly and says nothing,
// and the only way to hear it is to go fullscreen. Claiming "playback" says
// what is true here: the sound is the point, not decoration. The session is
// not activated until something actually plays, so declaring it up front
// interrupts nothing; it is declared only on a page that has a video so an
// ordinary text post never claims it at all.
function setupAudioSession() {
if (!('audioSession' in navigator)) return;
if (!document.querySelector('video')) return;
navigator.audioSession.type = 'playback';
}
// Every comment is a <details open>, so folding one already works with this
// file missing. All this adds is doing the whole page at once, which is why
// the button ships hidden and is only revealed here.
function setupComments() {
const toggle = document.querySelector('.thread__toggle');
if (!toggle) return;
const all = [...document.querySelectorAll('details.c')];
if (all.length === 0) return;
toggle.hidden = false;
toggle.addEventListener('click', () => {
const collapsing = toggle.dataset.collapsed !== 'true';
for (const comment of all) comment.open = !collapsing;
toggle.dataset.collapsed = String(collapsing);
toggle.textContent = collapsing ? 'Expand all' : 'Collapse all';
});
// Reopening one by hand means the page is no longer collapsed, so the
// button should offer the other thing.
for (const comment of all) {
comment.addEventListener('toggle', () => {
if (comment.open && toggle.dataset.collapsed === 'true') {
toggle.dataset.collapsed = 'false';
toggle.textContent = 'Collapse all';
}
});
}
}
setupCopy();
setupMedia();
applyBrowser(storedBrowser());
setupBrowserPicker();
for (const media of document.querySelectorAll('.media')) setupMedia(media);
setupAudioSession();
setupComments();
// --- Verification puzzles -------------------------------------------------
//
+64
View File
@@ -0,0 +1,64 @@
// The rewrite rules that send a shared link here catch the original link on
// the way back out too, so in Safari "Open on <platform>" lands back on this
// page. Handing the address to a different browser is the way out, and the
// only way to do that from a web page is that browser's own URL scheme --
// which every one of them spells differently. Some swap the scheme, some
// prefix it, some take the whole address as a query parameter.
/** http -> googlechrome://, https -> googlechromes:// */
const chrome = (url) => url.replace(/^http(s?):/, 'googlechrome$1:');
// Edge keeps the original scheme either way, but on macOS it stays in the
// address and the scheme is prefixed, while on iOS it is folded into the
// scheme itself.
const edgeMacos = (url) => `microsoft-edge:${url}`;
const edgeIos = (url) => url.replace(/^http(s?):/, 'microsoft-edge-http$1:');
/** Firefox and Orion take the address as a parameter instead. */
const openUrl = (scheme) => (url) => `${scheme}://open-url?url=${encodeURIComponent(url)}`;
// `null` means the browser is there but ships no scheme to reach it on that
// system, so there is nothing to offer beyond the plain link.
export const BROWSERS = [
{ id: 'default', label: 'Default browser', macos: null, ios: null },
{ id: 'chrome', label: 'Chrome', macos: chrome, ios: chrome },
{ id: 'edge', label: 'Edge', macos: edgeMacos, ios: edgeIos },
{ id: 'firefox', label: 'Firefox', macos: null, ios: openUrl('firefox') },
{ id: 'orion', label: 'Orion', macos: openUrl('orion'), ios: openUrl('orion') },
];
/**
* iPadOS calls itself MacIntel, so the platform string alone cannot tell the
* two apart; the touch points can. Everything else gets the desktop table --
* the only desktop this is ever opened on is a Mac.
*
* @param {{ platform?: string, maxTouchPoints?: number }} [nav]
*/
export function detectOs(nav = globalThis.navigator) {
const platform = nav?.platform ?? '';
if (/^iP(hone|ad|od)/.test(platform)) return 'ios';
if (platform === 'MacIntel' && (nav?.maxTouchPoints ?? 0) > 1) return 'ios';
return 'macos';
}
/** The browsers worth offering here: the default, plus the ones this system
* actually has a scheme for. */
export function browsersFor(os) {
return BROWSERS.filter((browser) => browser.id === 'default' || browser[os]);
}
function browserById(id) {
return BROWSERS.find((browser) => browser.id === id);
}
/**
* The address to open. A browser with no scheme on this system, an unknown
* id, or anything that is not an ordinary web link is handed back untouched:
* a dead custom scheme opens nothing at all, which is worse than the plain
* link opening in the wrong browser.
*/
export function openUrlFor(url, browserId, os) {
const rewrite = browserById(browserId)?.[os];
if (!rewrite || !/^https?:\/\//i.test(url)) return url;
return rewrite(url);
}
+55 -8
View File
@@ -1,5 +1,5 @@
import { config } from '../config.ts';
import { ResolveError, type Media, type Post, type Segment } from '../types.ts';
import { ResolveError, type Media, type Post, type Quoted, type Segment } from '../types.ts';
import { captureJson } from '../browser/capture.ts';
import { hostMatcher } from './url.ts';
import type { PlatformSpec, ResolveContext } from './types.ts';
@@ -8,6 +8,18 @@ const API = 'https://public.api.bsky.app/xrpc';
type Aspect = { width: number; height: number };
type Actor = { handle?: string; displayName?: string; avatar?: string };
/** The quoted post as the API hands it over, when it is a post at all — a
* quote can also point at a feed, a list, or something deleted. */
type ViewRecord = {
$type?: string;
uri?: string;
author?: Actor;
value?: { text?: string; createdAt?: string };
embeds?: Embed[];
};
type Embed = {
$type?: string;
images?: Array<{ thumb?: string; fullsize?: string; alt?: string; aspectRatio?: Aspect }>;
@@ -15,12 +27,14 @@ type Embed = {
thumbnail?: string;
aspectRatio?: Aspect;
media?: Embed;
record?: { embeds?: Embed[] };
/** A plain quote puts the record here; a quote with media of its own puts
* it one level further in. */
record?: ViewRecord & { record?: ViewRecord };
};
type BskyPost = {
uri?: string;
author?: { handle?: string; displayName?: string; avatar?: string };
author?: Actor;
record?: { text?: string; createdAt?: string };
embed?: Embed;
indexedAt?: string;
@@ -73,19 +87,52 @@ export function mediaFromEmbed(embed: Embed | undefined): Media[] {
}];
}
// A quote post carries the quoted post's media one level in. That is
// usually the thing being pointed at, so it is what to show.
const quoted = embed.record?.embeds?.[0];
if (quoted) return mediaFromEmbed(quoted);
// Nothing of its own. A quoted post's pictures belong to the quoted post
// and are shown with it, under the name of whoever actually posted them.
return [];
}
/** `at://<did>/app.bsky.feed.post/<rkey>` is not a link anyone can open, so
* the web address is rebuilt from the handle and the record key. */
function webUrlFor(uri: string | undefined, handle: string | undefined): string | undefined {
const rkey = uri?.split('/').pop();
return rkey && handle ? `https://bsky.app/profile/${handle}/post/${rkey}` : undefined;
}
/**
* The post being quoted.
*
* A quote can also point at a feed, a list or a post that has since been
* deleted or blocked, and those arrive under different `$type`s in the same
* slot. Only a real post is taken; anything else is left out rather than
* rendered as a nameless empty box.
*/
export function quotedFrom(embed: Embed | undefined): Quoted | undefined {
// A quote carrying media of its own nests the record one level deeper.
const record = embed?.record?.record ?? embed?.record;
if (record?.$type !== 'app.bsky.embed.record#viewRecord' || !record.author) return undefined;
const url = webUrlFor(record.uri, record.author.handle);
return {
author: {
handle: `@${record.author.handle ?? 'unknown'}`,
...(record.author.displayName ? { displayName: record.author.displayName } : {}),
...(record.author.avatar ? { avatar: { url: record.author.avatar } } : {}),
},
...(record.value?.text ? { text: record.value.text } : {}),
media: mediaFromEmbed(record.embeds?.[0]),
...(record.value?.createdAt ? { postedAt: record.value.createdAt } : {}),
...(url ? { url } : {}),
};
}
function segmentOf(post: BskyPost, isAnchor: boolean): Segment {
const quoted = quotedFrom(post.embed);
return {
...(post.record?.text ? { text: post.record.text } : {}),
media: mediaFromEmbed(post.embed),
...(post.record?.createdAt ? { postedAt: post.record.createdAt } : {}),
...(quoted ? { quoted } : {}),
...(isAnchor ? { isAnchor: true } : {}),
};
}
+2 -1
View File
@@ -5,8 +5,9 @@ import { threads } from './threads.ts';
import { instagram } from './instagram.ts';
import { tiktok } from './tiktok.ts';
import { bluesky } from './bluesky.ts';
import { reddit } from './reddit.ts';
export const platforms: readonly PlatformSpec[] = [x, threads, instagram, tiktok, bluesky];
export const platforms: readonly PlatformSpec[] = [x, threads, instagram, tiktok, bluesky, reddit];
const byPrefix = new Map(platforms.map((p) => [p.prefix, p]));
+515
View File
@@ -0,0 +1,515 @@
import type { Page } from 'playwright';
import { ResolveError, oneSegment, type Comment, type Media, type Post } from '../types.ts';
import { readOpenGraph } from '../browser/capture.ts';
import { stripTracking } from './url.ts';
import type { PlatformSpec, ResolveContext } from './types.ts';
const HOST = 'https://www.reddit.com';
/** Path roots that are really Reddit paths, so anything else that arrives as
* a single opaque segment is a `redd.it` share code. */
const KNOWN_ROOTS = new Set(['r', 'u', 'user', 'comments', 'gallery', 'media', 'wiki']);
type Listing<T> = { kind?: string; data?: { children?: Array<Thing<T>> } };
type Thing<T> = { kind?: string; data?: T };
type RedditVideo = {
fallback_url?: string;
hls_url?: string;
has_audio?: boolean;
width?: number;
height?: number;
duration?: number;
};
type MediaMeta = {
status?: string;
e?: string;
m?: string;
s?: { u?: string; gif?: string; mp4?: string; x?: number; y?: number };
};
type Link = {
title?: string;
author?: string;
subreddit_name_prefixed?: string;
created_utc?: number;
selftext?: string;
permalink?: string;
url?: string;
url_overridden_by_dest?: string;
domain?: string;
post_hint?: string;
is_self?: boolean;
is_video?: boolean;
is_gallery?: boolean;
over_18?: boolean;
spoiler?: boolean;
link_flair_text?: string | null;
num_comments?: number;
score?: number;
gallery_data?: { items?: Array<{ media_id?: string }> };
media_metadata?: Record<string, MediaMeta>;
secure_media?: { reddit_video?: RedditVideo } | null;
media?: { reddit_video?: RedditVideo } | null;
preview?: {
images?: Array<{ source?: { url?: string; width?: number; height?: number } }>;
reddit_video_preview?: RedditVideo;
};
crosspost_parent_list?: Link[];
};
type CommentData = {
author?: string;
body?: string;
media_metadata?: Record<string, MediaMeta>;
created_utc?: number;
score?: number;
score_hidden?: boolean;
is_submitter?: boolean;
distinguished?: string | null;
replies?: Listing<CommentData> | '';
};
type MoreData = { count?: number };
/** `[deleted]` and `[removed]` are the platform's own words, kept as they are. */
function authorName(author: string | undefined): string {
if (!author || author.startsWith('[')) return author ?? '[unknown]';
return `u/${author}`;
}
function isoFrom(seconds: number | undefined): string | undefined {
return seconds ? new Date(seconds * 1000).toISOString() : undefined;
}
function sized(width: number | undefined, height: number | undefined) {
return {
...(width ? { width } : {}),
...(height ? { height } : {}),
};
}
/**
* Reddit's own video, which arrives in three forms at once.
*
* `fallback_url` is a plain MP4 and the nicer thing to serve it proxies,
* so the viewer never talks to Reddit, and the native scrubber can seek it.
* But when a post has sound that MP4 is the video track alone: the audio is
* a separate file the DASH manifest stitches back on. So a silent post gets
* the MP4 and one with audio gets the HLS playlist, linked directly because
* proxying it would mean rewriting the manifest and every segment.
*/
function fromRedditVideo(video: RedditVideo, poster: string | undefined): Media[] {
const common = {
...sized(video.width, video.height),
...(video.duration ? { durationSec: video.duration } : {}),
// The still belongs to the video and not to the format it is served in.
// The HLS branch used to drop it, which is why a post with sound showed
// an empty box where every silent one showed a frame.
...(poster ? { poster: { url: poster } } : {}),
};
if (video.has_audio !== false && video.hls_url) {
return [{ kind: 'video', url: video.hls_url, hls: true, direct: true, ...common }];
}
const url = video.fallback_url ?? video.hls_url;
if (!url) return [];
if (url === video.hls_url) {
return [{ kind: 'video', url, hls: true, direct: true, ...common }];
}
return [{ kind: 'video', url, ...common }];
}
/** One entry of a gallery post. Reddit keeps the pictures somewhere other
* than the order it wants them shown in, so the two have to be joined. */
function fromGalleryItem(meta: MediaMeta | undefined): Media[] {
if (!meta || meta.status !== 'valid') return [];
const size = sized(meta.s?.x, meta.s?.y);
// An animated entry ships as a video as well; that is smaller and seekable.
if (meta.s?.mp4) return [{ kind: 'video', url: meta.s.mp4, ...size }];
const url = meta.s?.gif ?? meta.s?.u;
return url ? [{ kind: 'image', url, ...size }] : [];
}
export function mediaFromLink(link: Link): Media[] {
// A crosspost is a wrapper with nothing of its own in it.
const crossposted = link.crosspost_parent_list?.[0];
if (crossposted && !link.is_self) {
const inner = mediaFromLink(crossposted);
if (inner.length) return inner;
}
// `scrubber_media_url` looks like a poster and is not one: it is a second,
// tiny MP4 for the timeline thumbnails. The still is in the preview.
const still = link.preview?.images?.[0]?.source?.url;
const video = link.secure_media?.reddit_video ?? link.media?.reddit_video;
if (video) return fromRedditVideo(video, still);
if (link.is_gallery) {
const items = link.gallery_data?.items ?? [];
const gallery = items.flatMap((item) =>
fromGalleryItem(item.media_id ? link.media_metadata?.[item.media_id] : undefined));
if (gallery.length) return gallery;
}
// A GIF link is served as a video by the preview, which is the version
// worth having: the original is often tens of megabytes.
const asVideo = link.preview?.reddit_video_preview;
if (asVideo) return fromRedditVideo(asVideo, still);
const direct = link.url_overridden_by_dest ?? link.url;
if (direct && /\.(jpe?g|png|webp|gif)(\?|$)/i.test(direct)) {
const source = link.preview?.images?.[0]?.source;
return [{ kind: 'image', url: direct, ...sized(source?.width, source?.height) }];
}
// A link to somewhere else: the preview is all Reddit has, and it is still
// worth showing above the link itself.
const preview = link.preview?.images?.[0]?.source;
if (preview?.url) {
return [{ kind: 'image', url: preview.url, ...sized(preview.width, preview.height) }];
}
return [];
}
/**
* The words of the post: the self text, or for a link post the
* destination, which is the whole content of the post and needs to be
* tappable.
*/
function bodyOf(link: Link): string | undefined {
if (link.selftext?.trim()) return link.selftext;
const dest = link.url_overridden_by_dest;
if (dest && !dest.includes('redd.it') && !dest.startsWith(`${HOST}/gallery/`)) return dest;
return undefined;
}
/** The whole of `![...](...)`, with the target captured. */
const INLINE_IMAGE = /!\[([^\]\n]*)\]\(([^)\s]+)\)/g;
/**
* A Giphy token, which unlike the others says what it points at.
*
* Reddit writes a variant name after the id on some of them
* (`giphy|abc123|downsized`); only the id is kept, because Giphy does not
* serve every variant for every gif but always serves the full one.
*/
const GIPHY_TOKEN = /^giphy\|([A-Za-z0-9]+)(?:\|[a-z_]+)?$/;
/**
* Point a comment's inline images at something fetchable.
*
* Reddit writes them as `![gif](giphy|Ve7wX45)`, `![img](emote|t5_2th52|4358)`
* or `![img](jo8gf0ca92zd1)` a token rather than an address. Usually the
* token is a key in that same comment's `media_metadata`, which is where the
* real URL is, so one lookup covers all three and none of them needs naming
* here.
*
* Usually, not always: Reddit ships plenty of comments carrying a Giphy token
* and no `media_metadata` at all, and with nothing to look the token up in
* those showed the token itself where the gif should have been. Giphy is the
* one kind that can be resolved without the lookup, the id in it being Giphy's
* own, so it falls back to Giphy's address for that id. The other two cannot:
* their ids mean nothing off Reddit.
*
* A target that is already an address is not a key, so it falls through
* untouched.
*/
export function resolveInlineImages(
body: string,
meta: Record<string, MediaMeta> | undefined,
): string {
return body.replace(INLINE_IMAGE, (whole, alt: string, token: string) => {
const entry = meta?.[token];
if (entry?.status === 'valid') {
// An animated one has both; the GIF plays in an `<img>` on its own,
// which an MP4 does not.
const url = entry.s?.gif ?? entry.s?.u;
if (url) return `![${alt}](${url})`;
}
const giphy = GIPHY_TOKEN.exec(token)?.[1];
return giphy ? `![${alt}](https://i.giphy.com/media/${giphy}/giphy.gif)` : whole;
});
}
export function commentsFrom(listing: Listing<CommentData> | undefined): {
comments: Comment[];
more: number;
} {
const comments: Comment[] = [];
let more = 0;
for (const child of listing?.data?.children ?? []) {
if (child.kind === 'more') {
more += (child.data as MoreData | undefined)?.count ?? 0;
continue;
}
const data = child.data;
if (!data || data.body === undefined) continue;
const replies = data.replies && typeof data.replies === 'object'
? commentsFrom(data.replies)
: { comments: [], more: 0 };
comments.push({
author: authorName(data.author),
...(data.body ? { text: resolveInlineImages(data.body, data.media_metadata) } : {}),
...(isoFrom(data.created_utc) ? { postedAt: isoFrom(data.created_utc) } : {}),
// Reddit hides the score on a new comment so an early downvote cannot
// steer the rest. Showing a placeholder 1 would be a lie.
...(data.score_hidden !== true && typeof data.score === 'number' ? { score: data.score } : {}),
...(data.is_submitter ? { isAuthor: true } : {}),
...(data.distinguished ? { distinguished: data.distinguished } : {}),
replies: replies.comments,
...(replies.more ? { moreReplies: replies.more } : {}),
});
}
return { comments, more };
}
export function toPost(body: [Listing<Link>, Listing<CommentData>], originalUrl: string): Post {
const link = body[0]?.data?.children?.[0]?.data;
if (!link) throw new ResolveError('Reddit returned no post', 'reddit', originalUrl);
const { comments, more } = commentsFrom(body[1]);
const flags = [
link.link_flair_text?.trim(),
link.over_18 ? 'NSFW' : undefined,
link.spoiler ? 'Spoiler' : undefined,
].filter(Boolean);
return {
platform: 'reddit',
platformLabel: 'Reddit',
originalUrl,
author: {
// The subreddit is the identity a Reddit link carries — the poster is
// a detail underneath it, so it goes in the display name.
handle: link.subreddit_name_prefixed ?? 'reddit',
displayName: [authorName(link.author), ...flags].join(' · '),
},
textPosition: 'above',
segments: oneSegment({
...(link.title ? { title: link.title } : {}),
...(bodyOf(link) ? { text: bodyOf(link) } : {}),
media: mediaFromLink(link),
...(isoFrom(link.created_utc) ? { postedAt: isoFrom(link.created_utc) } : {}),
}),
comments,
...(more ? { moreComments: more } : {}),
...(typeof link.num_comments === 'number' ? { commentCount: link.num_comments } : {}),
};
}
export type FlatComment = {
depth: number;
author: string;
score: number;
created: string;
text: string;
};
/**
* Rebuild the nesting from a flat list of comments that each know only their
* own depth, which is how the rendered page presents them.
*/
export function treeFromDepths(flat: FlatComment[]): Comment[] {
const roots: Comment[] = [];
// The comment last seen at each depth, so a reply can be attached to
// whatever it appeared underneath.
const openAt: Comment[] = [];
for (const row of flat) {
if (!row.text) continue;
const comment: Comment = {
author: authorName(row.author),
text: row.text,
...(row.created && !Number.isNaN(Date.parse(row.created))
? { postedAt: new Date(row.created).toISOString() }
: {}),
...(Number.isFinite(row.score) ? { score: row.score } : {}),
replies: [],
};
const parent = openAt[row.depth - 1];
if (row.depth > 0 && parent) parent.replies.push(comment);
else roots.push(comment);
// Anything deeper belonged to the comment this one just replaced.
openAt.length = row.depth + 1;
openAt[row.depth] = comment;
}
return roots;
}
/**
* Reads the comment tree back out of the rendered page.
*
* The floor, for when the JSON is refused. Reddit renders every comment as a
* `<shreddit-comment>` carrying its own depth, flat in document order.
*/
async function commentsFromDom(page: Page): Promise<Comment[]> {
const flat = await page
.evaluate(() =>
[...document.querySelectorAll('shreddit-comment')].map((el) => ({
depth: Number(el.getAttribute('depth') ?? 0),
author: el.getAttribute('author') ?? '',
score: Number(el.getAttribute('score') ?? Number.NaN),
created: el.getAttribute('created') ?? '',
text: el.querySelector('[slot="comment"]')?.textContent?.trim() ?? '',
})))
.catch((): FlatComment[] => []);
return treeFromDepths(flat);
}
/** Whatever the page will admit to, when the JSON will not come. */
async function fromPage(page: Page, originalUrl: string): Promise<Post> {
const attrs = await page
.evaluate(() => {
const post = document.querySelector('shreddit-post');
if (!post) return null;
const get = (name: string): string | undefined => post.getAttribute(name) ?? undefined;
return {
title: get('post-title'),
author: get('author'),
subreddit: get('subreddit-prefixed-name'),
created: get('created-timestamp'),
score: get('score'),
comments: get('comment-count'),
image: get('content-href'),
};
})
.catch(() => null);
const og = await readOpenGraph(page);
const title = attrs?.title ?? og['og:title'];
if (!title) throw new ResolveError('Reddit served neither the post nor its data', 'reddit', originalUrl);
const image = attrs?.image ?? og['og:image'];
const media: Media[] =
image && /\.(jpe?g|png|webp|gif)(\?|$)/i.test(image) ? [{ kind: 'image', url: image }] : [];
const count = Number(attrs?.comments);
return {
platform: 'reddit',
platformLabel: 'Reddit',
originalUrl,
author: {
handle: attrs?.subreddit ?? 'reddit',
displayName: authorName(attrs?.author),
},
textPosition: 'above',
segments: oneSegment({
title,
media,
...(attrs?.created && !Number.isNaN(Date.parse(attrs.created))
? { postedAt: new Date(attrs.created).toISOString() }
: {}),
}),
comments: await commentsFromDom(page),
...(Number.isFinite(count) ? { commentCount: count } : {}),
};
}
/** The `.json` twin of a post URL, asked for at the size of one page. */
function jsonUrlFor(postUrl: string): string {
const url = new URL(postUrl);
url.pathname = `${url.pathname.replace(/\/+$/, '')}/.json`;
url.search = '';
url.searchParams.set('raw_json', '1');
url.searchParams.set('limit', '100');
url.searchParams.set('sort', 'confidence');
return url.href;
}
function isShareLink(url: URL): boolean {
return url.hostname === 'redd.it' || /^\/r\/[^/]+\/s\/[^/]+/.test(url.pathname);
}
/**
* Share links from the app are opaque, and the post id is only on the other
* side of a redirect. One request that is told not to follow it is enough
* far cheaper than loading the page to find out where it went.
*/
async function followShareLink(page: Page, originalUrl: string): Promise<string> {
const response = await page.request
.get(originalUrl, { maxRedirects: 0 })
.catch(() => undefined);
const location = response?.headers()['location'];
if (!location) return originalUrl;
try {
return stripTracking(new URL(location, originalUrl)).href;
} catch {
return originalUrl;
}
}
async function fetchJson(page: Page, url: string): Promise<[Listing<Link>, Listing<CommentData>] | undefined> {
const response = await page.request
.get(url, { headers: { Accept: 'application/json' } })
.catch(() => undefined);
if (!response?.ok()) return undefined;
if (!response.headers()['content-type']?.includes('json')) return undefined;
const body = (await response.json().catch(() => undefined)) as unknown;
return Array.isArray(body) && body.length >= 2 ? (body as [Listing<Link>, Listing<CommentData>]) : undefined;
}
async function resolve({ page, originalUrl }: ResolveContext): Promise<Post> {
let postUrl = originalUrl;
try {
if (isShareLink(new URL(originalUrl))) postUrl = await followShareLink(page, originalUrl);
} catch {
// Not a URL we can take apart; the request below will say so.
}
// Reddit's JSON is the whole post and the whole first page of comments in
// one response, which no amount of reading the page can match.
let body = await fetchJson(page, jsonUrlFor(postUrl));
if (!body) {
// A cold context gets a JavaScript challenge instead, which the page
// solves by itself on any ordinary navigation. Doing that once leaves the
// cookie behind and the JSON answers from then on, including for every
// later post.
await page.goto(postUrl, { waitUntil: 'domcontentloaded' }).catch(() => undefined);
await page.waitForTimeout(1500);
body = await fetchJson(page, jsonUrlFor(page.url() || postUrl));
if (!body) {
// Still refused. The page in front of us is the post, so read that.
await page.waitForSelector('shreddit-comment', { timeout: 5_000 }).catch(() => undefined);
return fromPage(page, originalUrl);
}
}
// The resolved permalink, not the share code we came in with: an opaque
// `/s/` link says nothing about what it points at, and handing it back is
// the same as handing back a tracking parameter.
return toPost(body, postUrl);
}
export const reddit: PlatformSpec = {
id: 'reddit',
label: 'Reddit',
prefix: 'reddit',
canonicalHost: 'www.reddit.com',
textPosition: 'above',
matchesHost: (host) => host === 'reddit.com' || host.endsWith('.reddit.com') || host === 'redd.it',
/** A single opaque segment is a `redd.it` share code the rewrite rule
* drops the host, so `redd.it/abc123` arrives as just `abc123`. */
buildOriginalUrl: (pathRest, search) => {
const first = pathRest.split('/')[0] ?? '';
if (first && !pathRest.includes('/') && !KNOWN_ROOTS.has(first)) {
return `https://redd.it/${first}${search}`;
}
return `${HOST}/${pathRest}${search}`;
},
resolve,
};
+1
View File
@@ -9,6 +9,7 @@ const TRACKING_PARAMS = new Set([
's', 't', 'si', 'xmt', '_r', '_t', '_d',
'is_from_webapp', 'sender_device', 'sender_web_id', 'web_id',
'share_app_id', 'share_link_id', 'share_item_id', 'tt_from',
'share_id', 'rdt', 'correlation_id', 'post_fullname', 'ref_campaign',
]);
export function stripTracking(url: URL): URL {
+119 -17
View File
@@ -1,5 +1,5 @@
import { config } from '../config.ts';
import { ResolveError, oneSegment, type Media, type Post } from '../types.ts';
import { ResolveError, oneSegment, type Author, type Media, type Post, type Quoted } from '../types.ts';
import { captureJson } from '../browser/capture.ts';
import { hostMatcher } from './url.ts';
import type { PlatformSpec, ResolveContext } from './types.ts';
@@ -16,15 +16,89 @@ type MediaDetail = {
video_info?: { duration_millis?: number; variants?: VideoVariant[] };
};
type TweetUser = { screen_name?: string; name?: string; profile_image_url_https?: string };
type TweetResult = {
id_str?: string;
text?: string;
/** Which slice of `text` X itself shows. UTF-16 indices. */
display_text_range?: [number, number];
entities?: { urls?: Array<{ url?: string; expanded_url?: string }> };
created_at?: string;
user?: { screen_name?: string; name?: string; profile_image_url_https?: string };
user?: TweetUser;
mediaDetails?: MediaDetail[];
quoted_tweet?: TweetResult;
tombstone?: unknown;
};
/**
* X hands back post text with the markup-significant characters already
* escaped an ampersand someone typed arrives as `&amp;`. Everything
* downstream escapes on the way out, so leaving them would put the entity
* itself on screen.
*/
const ENTITIES: Record<string, string> = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
};
function decodeEntities(text: string): string {
// `&amp;` last would double-decode `&amp;lt;`; one pass over the lot cannot.
return text.replace(/&(?:amp|lt|gt|quot|#39);/g, (entity) => ENTITIES[entity] ?? entity);
}
const SHORTLINK = /https?:\/\/t\.co\/[A-Za-z0-9]+/g;
/**
* Put back the addresses `t.co` stands in for.
*
* Every link in a post is rewritten to a shortlink before it is stored, so
* left alone the page shows `t.co/QdJhOVu4En` which says nothing about
* where it goes, and routes the reader through X's click tracker to find
* out. The payload carries the real address alongside, so there is no reason
* to show the stand-in.
*
* Matched on the shortlink itself rather than by `indices`, which are offsets
* into a string this function is in the middle of changing the length of.
*/
function expandShortlinks(text: string, result: TweetResult): string {
const expansions = new Map<string, string>();
for (const entity of result.entities?.urls ?? []) {
if (!entity.url || !entity.expanded_url) continue;
if (!/^https?:\/\//.test(entity.expanded_url)) continue;
expansions.set(entity.url, entity.expanded_url);
}
if (expansions.size === 0) return text;
return text.replace(SHORTLINK, (link) => expansions.get(link) ?? link);
}
/**
* The words of the post, as X itself would show them.
*
* A quote post gets a `t.co` link to the post it quotes stapled to the end of
* its text, and X hides it the quoted post is on the page, so a shortlink
* to it is noise. `display_text_range` is where that boundary is, and it also
* keeps a link the author put there on purpose, which is why the range is
* used rather than stripping trailing URLs.
*
* Sliced before decoding: the indices are into the escaped text, where an
* ampersand is five characters. They are UTF-16 units, so a plain `slice` is
* right and splitting to codepoints first would overshoot past an emoji.
*/
function visibleText(result: TweetResult): string | undefined {
const raw = result.text;
if (!raw) return undefined;
const range = result.display_text_range;
const shown = Array.isArray(range) ? raw.slice(range[0], range[1]) : raw;
// Expanded after the slice for the same reason: the range is measured
// against the text as it arrived.
const text = expandShortlinks(decodeEntities(shown), result).trimEnd();
return text || undefined;
}
/** Every X post URL ends in `/status/<id>`, whatever precedes it. */
function tweetId(pathRest: string): string | undefined {
return /\/status(?:es)?\/(\d+)/.exec(`/${pathRest}`)?.[1];
@@ -75,29 +149,57 @@ export function mediaFromDetails(details: MediaDetail[] | undefined): Media[] {
});
}
function authorOf(user: TweetUser | undefined): Author {
const avatar = user?.profile_image_url_https;
return {
handle: `@${user?.screen_name ?? 'unknown'}`,
...(user?.name ? { displayName: user.name } : {}),
// `_normal` is a 48px thumbnail; `_x96` is the same file at 96.
...(avatar ? { avatar: { url: avatar.replace('_normal', '_x96') } } : {}),
};
}
/**
* The post a quote post is talking about.
*
* Shown in full whose it is, what it said and what it showed rather than
* having its picture lifted out and hung under the quoter's name. Half the
* quote posts people share are someone answering a stranger, and the other
* half are someone continuing their own thought from an earlier post; both
* are unreadable with only one side of them on the page.
*
* The syndication payload carries no permalink for the quoted post, so its
* URL is rebuilt from the handle and the id, the same shape every X post has.
*/
export function quotedFrom(quoted: TweetResult | undefined): Quoted | undefined {
if (!quoted?.user) return undefined;
const handle = quoted.user.screen_name;
return {
author: authorOf(quoted.user),
...(visibleText(quoted) ? { text: visibleText(quoted) } : {}),
media: mediaFromDetails(quoted.mediaDetails),
...(quoted.created_at ? { postedAt: quoted.created_at } : {}),
...(handle && quoted.id_str
? { url: `https://x.com/${handle}/status/${quoted.id_str}` }
: {}),
};
}
export function toPost(result: TweetResult, originalUrl: string): Post {
const handle = result.user?.screen_name ?? 'unknown';
const avatar = result.user?.profile_image_url_https;
const quoted = quotedFrom(result.quoted_tweet);
return {
platform: 'x',
platformLabel: 'X',
originalUrl,
author: {
handle: `@${handle}`,
...(result.user?.name ? { displayName: result.user.name } : {}),
// `_normal` is a 48px thumbnail; `_x96` is the same file at 96.
...(avatar ? { avatar: { url: avatar.replace('_normal', '_x96') } } : {}),
},
author: authorOf(result.user),
textPosition: 'above',
segments: oneSegment({
...(result.text ? { text: result.text } : {}),
// A quote post usually carries no media of its own — the picture being
// talked about belongs to the post it quotes, and that is the thing
// worth showing.
media: mediaFromDetails(
result.mediaDetails?.length ? result.mediaDetails : result.quoted_tweet?.mediaDetails,
),
...(visibleText(result) ? { text: visibleText(result) } : {}),
// Only its own. The quoted post's pictures are shown with the quoted
// post, where it is clear whose they are.
media: mediaFromDetails(result.mediaDetails),
...(result.created_at ? { postedAt: result.created_at } : {}),
...(quoted ? { quoted } : {}),
}),
};
}
+1 -1
View File
@@ -28,7 +28,7 @@ export function renderChallenge(challenge: Challenge, box: Box | undefined): str
<footer class="post__foot">
<div class="original">
<button type="button" class="copy" id="give-up">Give up and show me the link</button>
<a class="original__open" href="${challenge.originalUrl}" rel="noopener noreferrer nofollow" target="_blank">
<a class="original__open" href="${challenge.originalUrl}" rel="noopener noreferrer nofollow" target="_blank" hidden>
Open on ${challenge.platformLabel}
</a>
<p class="original__url"><code>${challenge.originalUrl}</code></p>
+8
View File
@@ -30,6 +30,14 @@ export function renderIndex(platforms: readonly PlatformSpec[]): string {
)}
</tbody>
</table>
<section class="picker" hidden>
<label class="picker__label" for="open-in">Open original links in</label>
<select class="picker__select" id="open-in"></select>
<p class="picker__note">
The rewrite rules catch the original link too, so in Safari Open on comes
straight back here. Another browser is a way out of that. Kept on this device.
</p>
</section>
</article>`;
return layout('antisocial', body);
+8 -2
View File
@@ -31,6 +31,7 @@ const ACCENT: Record<string, { color: string; monogram: string }> = {
instagram: { color: '#c13584', monogram: 'IG' },
tiktok: { color: '#fe2c55', monogram: '♪' },
bluesky: { color: '#0085ff', monogram: 'B' },
reddit: { color: '#ff4500', monogram: 'r' },
};
export function badge(platform: string, label: string): Raw {
@@ -42,14 +43,19 @@ export function badge(platform: string, label: string): Raw {
}
/** The copy control, plus the URL itself so it is always selectable even if
* the clipboard API is unavailable. */
* the clipboard API is unavailable.
*
* The open link ships hidden: followed in the browser the rewrite rules are
* installed in, it redirects straight back here, so it is only worth showing
* once a browser has been picked to hand it to. The script reveals it, and
* the href in the markup is the plain address it starts from. */
export function originalUrlBlock(originalUrl: string, platformLabel: string): Raw {
return html`<div class="original">
<button type="button" class="copy" data-url="${originalUrl}">
<span class="copy__idle">Copy original link</span>
<span class="copy__done" hidden>Copied</span>
</button>
<a class="original__open" href="${originalUrl}" rel="noopener noreferrer nofollow" target="_blank">Open on ${platformLabel}</a>
<a class="original__open" href="${originalUrl}" rel="noopener noreferrer nofollow" target="_blank" hidden>Open on ${platformLabel}</a>
<p class="original__url"><code>${originalUrl}</code></p>
</div>`;
}
+207
View File
@@ -0,0 +1,207 @@
import { escapeHtml, raw, type Raw } from './html.ts';
/**
* The small subset of Markdown people actually write in a Reddit comment.
*
* Not a Markdown implementation, and not trying to be one. Reddit hands us
* `body_html` too, but taking that would mean trusting markup a stranger
* caused to be generated; the rule here is the same as everywhere else in
* this project escape first, then put back only the constructs we chose to
* support. Anything unrecognised stays as the literal characters the
* commenter typed, which is the safe way to be wrong.
*/
const REDDIT = 'https://www.reddit.com';
/**
* How an image in a comment becomes markup.
*
* Supplied by the caller rather than decided here, because the address has to
* go through the media proxy and this file knows nothing about that. Without
* one an image degrades to a link, which is what it was before.
*/
export type ImageRenderer = (url: string, alt: string) => string;
/** Worth showing as a picture rather than as a link to one. */
function looksLikeImage(url: string): boolean {
return /\.(jpe?g|png|gif|webp|avif)(\?|$)/i.test(url);
}
/** Absolute http(s) only. `javascript:` and friends never become links. */
function safeHref(url: string): string | undefined {
try {
const parsed = new URL(url);
return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : undefined;
} catch {
return undefined;
}
}
function anchor(href: string, label: string): string {
return `<a href="${escapeHtml(href)}" rel="noopener noreferrer nofollow" target="_blank">${escapeHtml(label)}</a>`;
}
/**
* Trailing punctuation is far more often the end of the sentence than part
* of the address, and an unmatched closing bracket cannot belong to a URL
* that has no opening one.
*/
function trimUrlTail(url: string): string {
let out = url;
for (;;) {
const last = out.at(-1) ?? '';
if (',.;:!?'.includes(last)) out = out.slice(0, -1);
else if (last === ')' && (out.match(/\(/g)?.length ?? 0) < (out.match(/\)/g)?.length ?? 0)) {
out = out.slice(0, -1);
} else return out;
}
}
const INLINE = new RegExp(
[
'`([^`\\n]+)`', // 1 code
// Before the link rule, or the `[` of an image matches as a link and
// leaves its `!` behind as text.
'!\\[([^\\]\\n]*)\\]\\(([^)\\s]+)\\)', // 2 alt, 3 src
'\\[([^\\]\\n]+)\\]\\(([^)\\s]+)\\)', // 4 label, 5 href
'\\*\\*([^*\\n]+)\\*\\*', // 6 strong
'~~([^~\\n]+)~~', // 7 strike
'(?<![\\w*])\\*([^*\\n]+)\\*(?![\\w*])', // 8 em with asterisks
'(?<![\\w_])_([^_\\n]+)_(?![\\w_])', // 9 em with underscores
'(https?://[^\\s<>]+)', // 10 bare url
// 11 the same thing with the scheme left off, which is how people type
// them. Narrow on purpose: a host, a path, and an image extension. Prose
// is full of dotted words, and `src/render/post.ts` must not become a
// link to a website in Tonga.
'(?<![\\w@/.])((?:[a-z0-9-]+\\.)+[a-z]{2,}/[^\\s<>]*\\.(?:jpe?g|png|gif|webp|avif)(?:\\?[^\\s<>]*)?)',
'(?<![\\w/])(/?[ru]/[A-Za-z0-9_][A-Za-z0-9_-]{1,30})', // 12 r/sub and u/name
].join('|'),
'g',
);
/** One line of body text: escaped, with the inline constructs put back. */
function inline(text: string, image?: ImageRenderer): string {
let out = '';
let cursor = 0;
for (const match of text.matchAll(INLINE)) {
const [whole, code, alt, src, label, href, strong, strike, emStar, emScore, url, schemeless,
subOrUser] = match;
out += escapeHtml(text.slice(cursor, match.index));
cursor = match.index + whole.length;
if (code !== undefined) {
out += `<code>${escapeHtml(code)}</code>`;
} else if (src !== undefined) {
const safe = safeHref(src);
// Without a renderer to place it, an image is still a link to one.
out += safe ? (image ? image(safe, alt ?? '') : anchor(safe, alt || safe)) : escapeHtml(whole);
} else if (label !== undefined && href !== undefined) {
const safe = safeHref(href);
out += safe ? anchor(safe, label) : escapeHtml(whole);
} else if (strong !== undefined) {
out += `<strong>${inline(strong, image)}</strong>`;
} else if (strike !== undefined) {
out += `<del>${inline(strike, image)}</del>`;
} else if (emStar !== undefined || emScore !== undefined) {
out += `<em>${inline(emStar ?? emScore ?? '', image)}</em>`;
} else if (url !== undefined) {
const trimmed = trimUrlTail(url);
const safe = safeHref(trimmed);
const tail = escapeHtml(url.slice(trimmed.length));
if (!safe) {
out += escapeHtml(whole);
} else if (image && looksLikeImage(trimmed)) {
// People paste the address of a picture and mean the picture. On
// Reddit that is most of what an image in a comment even is.
out += image(safe, '') + tail;
} else {
out += anchor(safe, trimmed.replace(/^https?:\/\/(www\.)?/, '')) + tail;
}
} else if (schemeless !== undefined) {
// Assumed https: every host that serves these redirects to it anyway,
// and a picture is the one thing worth guessing a scheme for.
const safe = safeHref(`https://${schemeless}`);
out += safe ? (image ? image(safe, '') : anchor(safe, schemeless)) : escapeHtml(whole);
} else if (subOrUser !== undefined) {
const path = subOrUser.startsWith('/') ? subOrUser : `/${subOrUser}`;
out += anchor(`${REDDIT}${path}`, subOrUser);
}
}
return out + escapeHtml(text.slice(cursor));
}
const BULLET = /^\s{0,3}[-*+]\s+/;
const NUMBERED = /^\s{0,3}\d+[.)]\s+/;
/**
* Group lines into blocks and render each. Blocks are what separate a quote
* from the reply to it, and a comment that loses that separation reads as
* though the commenter said both halves.
*/
function blocks(lines: string[], image?: ImageRenderer): string {
let out = '';
let at = 0;
const takeWhile = (keep: (line: string) => boolean): string[] => {
const run: string[] = [];
while (at < lines.length && keep(lines[at] ?? '')) {
run.push(lines[at] ?? '');
at += 1;
}
return run;
};
while (at < lines.length) {
const line = lines[at] ?? '';
if (line.trim() === '') {
at += 1;
continue;
}
if (/^\s*```/.test(line)) {
at += 1;
const body = takeWhile((l) => !/^\s*```/.test(l));
if (at < lines.length) at += 1; // the closing fence
out += `<pre><code>${escapeHtml(body.join('\n'))}</code></pre>`;
continue;
}
if (/^ {4}\S/.test(line)) {
const body = takeWhile((l) => /^ {4}/.test(l) || l.trim() === '');
out += `<pre><code>${escapeHtml(body.map((l) => l.slice(4)).join('\n').trimEnd())}</code></pre>`;
continue;
}
if (/^\s*>/.test(line)) {
const body = takeWhile((l) => /^\s*>/.test(l));
// Nested, so a quote of a quote keeps its shape.
out += `<blockquote>${blocks(body.map((l) => l.replace(/^\s*>\s?/, '')), image)}</blockquote>`;
continue;
}
if (BULLET.test(line) || NUMBERED.test(line)) {
const ordered = !BULLET.test(line);
const pattern = ordered ? NUMBERED : BULLET;
const items = takeWhile((l) => pattern.test(l));
const tag = ordered ? 'ol' : 'ul';
out += `<${tag}>${items.map((l) => `<li>${inline(l.replace(pattern, ''), image)}</li>`).join('')}</${tag}>`;
continue;
}
const paragraph = takeWhile(
(l) => l.trim() !== '' && !/^\s*>/.test(l) && !BULLET.test(l) && !NUMBERED.test(l) && !/^\s*```/.test(l),
);
out += `<p>${paragraph.map((l) => inline(l, image)).join('<br>')}</p>`;
}
return out;
}
/** Comment text, as safe markup. `image` places the pictures; without it
* they stay links, which is what they were before. */
export function renderMarkdown(text: string, image?: ImageRenderer): Raw {
return raw(blocks(text.replace(/\r\n?/g, '\n').split('\n'), image));
}
+173 -6
View File
@@ -1,7 +1,8 @@
import { proxyUrlFor } from '../media/registry.ts';
import { anchorOf, type Media, type Post, type Segment } from '../types.ts';
import { anchorOf, type Comment, type Media, type Post, type Quoted, type Segment } from '../types.ts';
import { html, raw, type Raw } from './html.ts';
import { badge, layout, originalUrlBlock } from './layout.ts';
import { renderMarkdown } from './markdown.ts';
import { linkify } from './text.ts';
/**
@@ -13,11 +14,29 @@ function aspect(item: Media): string {
return item.width && item.height ? `aspect-ratio: ${item.width} / ${item.height};` : '';
}
/**
* A stand-in poster carrying nothing but the video's shape.
*
* The ratio above is not enough on its own before the video has any data: a
* `<video>` in that state has a natural size of 300x150, and WebKit sizes it
* from that rather than from the ratio, so a portrait video sat in a squat
* landscape box until you pressed play and it snapped to shape. A video's
* size before its data arrives is its poster's, which makes an empty SVG of
* the right shape enough to put the box right, and as a data URI it costs no
* request. Only for a video the platform gave no poster for, since a real one
* already says the same thing.
*/
function placeholderPoster(item: Media): string | undefined {
if (!item.width || !item.height) return undefined;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${item.width}" height="${item.height}"/>`;
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}
function renderItem(item: Media, index: number): Raw {
const src = proxyUrlFor(item);
if (item.kind === 'video') {
const poster = item.poster ? proxyUrlFor(item.poster) : undefined;
const poster = item.poster ? proxyUrlFor(item.poster) : placeholderPoster(item);
return html`<figure class="item item--video" data-index="${index}">
<video
controls
@@ -62,8 +81,11 @@ function renderMedia(media: Media[]): Raw {
}
function renderText(segment: Segment, post: Post): Raw {
if (!segment.text) return html``;
return html`<div class="text">${linkify(segment.text, post.platform)}</div>`;
if (!segment.text && !segment.title) return html``;
return html`<div class="text">
${segment.title ? html`<h1 class="text__title">${segment.title}</h1>` : ''}
${segment.text ? linkify(segment.text, post.platform) : ''}
</div>`;
}
function renderWhen(postedAt: string | undefined): Raw {
@@ -76,6 +98,36 @@ function renderWhen(postedAt: string | undefined): Raw {
})}</time>`;
}
/**
* The post being quoted, drawn as a post of its own inside the one quoting
* it: its author, its words, its pictures, and a way to open it.
*
* The author line is the point. Lifting only the media out which is what
* this used to do put someone else's picture under the quoter's name with
* nothing to say so.
*/
function renderQuoted(quoted: Quoted, post: Post): Raw {
const avatar = quoted.author.avatar ? proxyUrlFor(quoted.author.avatar) : undefined;
return html`<blockquote class="quote">
<header class="quote__who">
${avatar ? html`<img class="quote__avatar" src="${avatar}" alt="" loading="lazy">` : ''}
${quoted.author.displayName
? html`<span class="quote__name">${quoted.author.displayName}</span>`
: ''}
<span class="quote__handle">${quoted.author.handle}</span>
${renderWhen(quoted.postedAt)}
</header>
${quoted.text ? html`<div class="quote__text">${linkify(quoted.text, post.platform)}</div>` : ''}
${renderMedia(quoted.media)}
${quoted.url
? html`<a class="quote__open" href="${quoted.url}" rel="noopener noreferrer nofollow" target="_blank">
Open the quoted post on ${post.platformLabel}
</a>`
: ''}
</blockquote>`;
}
/**
* One post in the chain. When there is only one, the wrapper is invisible;
* when there are several, each is separated and the one that was actually
@@ -83,13 +135,127 @@ function renderWhen(postedAt: string | undefined): Raw {
*/
function renderSegment(segment: Segment, post: Post, threaded: boolean): Raw {
const above = post.textPosition === 'above';
return html`<section class="segment" ${threaded && segment.isAnchor ? raw('data-anchor="true"') : ''}>
return html`<section class="segment" ${threaded && segment.isAnchor ? raw('data-anchor="true"') : ''} ${
segment.quoted ? raw('data-quoted="true"') : ''
}>
${threaded && segment.isAnchor
? html`<p class="segment__mark">the post you followed</p>`
: ''}
${above ? renderText(segment, post) : ''}
${renderMedia(segment.media)}
${above ? '' : renderText(segment, post)}
${segment.quoted ? renderQuoted(segment.quoted, post) : ''}
</section>`;
}
/** Short enough to sit on a comment's byline without wrapping. Absolute
* rather than "3 hours ago", because the page is cached for an hour and a
* relative time would quietly become wrong while it sat there. */
function shortWhen(postedAt: string | undefined): Raw {
if (!postedAt) return html``;
const date = new Date(postedAt);
if (Number.isNaN(date.getTime())) return html``;
return html`<time datetime="${date.toISOString()}">${date.toLocaleString('en-CA', {
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
})}</time>`;
}
/**
* A picture inside a comment.
*
* Through the proxy like everything else a comment full of `preview.redd.it`
* addresses would otherwise have the viewer's browser fetch every one of them
* straight from Reddit, which is the thing this whole app exists to avoid.
*
* No dimensions to reserve space with: the size is in the payload but not in
* the Markdown, so these are capped by the stylesheet and load at whatever
* shape they are.
*/
function renderCommentImage(url: string, alt: string): string {
return html`<img class="c__img" src="${proxyUrlFor({ url })}" alt="${alt}" loading="lazy" decoding="async">`
.value;
}
/** Everything hanging off a comment, however deep. Shown only while it is
* collapsed, so what a fold is hiding is never a mystery. */
function descendantsOf(comment: Comment): number {
return comment.replies.reduce((total, reply) => total + 1 + descendantsOf(reply), 0);
}
/**
* One comment and everything under it.
*
* A `<details>` per comment, so collapsing works with the stylesheet turned
* off and the keyboard alone, and takes the whole subtree with it because
* the replies are nested inside rather than listed alongside.
*/
function renderComment(comment: Comment, depth: number): Raw {
const marks = [
comment.isAuthor ? 'OP' : undefined,
comment.distinguished === 'moderator' ? 'MOD' : undefined,
comment.distinguished === 'admin' ? 'ADMIN' : undefined,
].filter((mark) => mark !== undefined);
return html`<details class="c" open data-depth="${depth}">
<summary class="c__head">
<span class="c__author">${comment.author}</span>
${marks.map((mark) => html`<span class="c__mark c__mark--${mark.toLowerCase()}">${mark}</span>`)}
${typeof comment.score === 'number'
? html`<span class="c__score">${comment.score} ${Math.abs(comment.score) === 1 ? 'point' : 'points'}</span>`
: ''}
${shortWhen(comment.postedAt)}
${descendantsOf(comment) > 0
? html`<span class="c__hidden">+${descendantsOf(comment)} ${
descendantsOf(comment) === 1 ? 'reply' : 'replies'
}</span>`
: ''}
</summary>
${comment.text
? html`<div class="c__body">${renderMarkdown(comment.text, renderCommentImage)}</div>`
: ''}
${comment.replies.length || comment.moreReplies
? html`<div class="c__replies">
${comment.replies.map((reply) => renderComment(reply, depth + 1))}
${comment.moreReplies
? html`<p class="c__more">${comment.moreReplies} more ${
comment.moreReplies === 1 ? 'reply' : 'replies'
}, on Reddit</p>`
: ''}
</div>`
: ''}
</details>`;
}
/**
* The conversation under the post, where the platform has one.
*
* Everything the first page carried, in the order it was ranked. What is
* missing is what was behind a "load more" following those means going to
* the platform, so they are counted rather than pretended away.
*/
function renderComments(post: Post): Raw {
const comments = post.comments;
if (!comments?.length) return html``;
const threads = comments.length;
const shown = comments.reduce((total, comment) => total + 1 + descendantsOf(comment), 0);
const total = post.commentCount;
return html`<section class="thread" data-platform="${post.platform}">
<header class="thread__head">
<h2 class="thread__title">Comments</h2>
<span class="thread__count">${
total !== undefined && total > shown ? html`${shown} of ${total}` : html`${shown}`
}, in ${threads} ${threads === 1 ? 'thread' : 'threads'}</span>
<button type="button" class="thread__toggle" data-collapsed="false" hidden>Collapse all</button>
</header>
<div class="thread__list">${comments.map((comment) => renderComment(comment, 0))}</div>
${post.moreComments
? html`<p class="thread__more">${post.moreComments} more, behind “load more” on Reddit.</p>`
: ''}
</section>`;
}
@@ -118,7 +284,8 @@ export function renderPost(post: Post): string {
${renderWhen(anchor?.postedAt)}
${originalUrlBlock(post.originalUrl, post.platformLabel)}
</footer>
</article>`;
</article>
${renderComments(post)}`;
const who = post.author.displayName ?? post.author.handle;
return layout(`${who} on ${post.platformLabel}`, body);
+1
View File
@@ -8,6 +8,7 @@ const PROFILE_BASE: Record<PlatformId, string> = {
instagram: 'https://www.instagram.com/',
tiktok: 'https://www.tiktok.com/@',
bluesky: 'https://bsky.app/profile/',
reddit: 'https://www.reddit.com/user/',
};
const TAG_BASE: Partial<Record<PlatformId, string>> = {
+61 -2
View File
@@ -1,5 +1,5 @@
/** The five platforms v1 understands. */
export type PlatformId = 'x' | 'threads' | 'instagram' | 'tiktok' | 'bluesky';
/** The platforms antisocial understands. */
export type PlatformId = 'x' | 'threads' | 'instagram' | 'tiktok' | 'bluesky' | 'reddit';
/**
* Something fetchable that lives on someone else's CDN.
@@ -40,6 +40,24 @@ export type Author = {
avatar?: Asset;
};
/**
* A post that the post being shown is talking about.
*
* Held apart from the segment quoting it rather than folded into it. The
* words and the pictures belong to someone else, and showing them under the
* quoter's name which is what folding them in amounts to tells the
* reader something untrue about who said what.
*/
export type Quoted = {
author: Author;
text?: string;
media: Media[];
/** ISO 8601. */
postedAt?: string;
/** The quoted post's own URL, so it can be opened on its own. */
url?: string;
};
/**
* One post. Usually a whole `Post` is a single segment, but on the platforms
* where people write in chains Bluesky and Threads the author's own
@@ -47,15 +65,44 @@ export type Author = {
* do not.
*/
export type Segment = {
/** Only Reddit gives a post a headline of its own. Everywhere else the
* first words of the body do that job, so this is left unset. */
title?: string;
text?: string;
media: Media[];
/** ISO 8601. */
postedAt?: string;
/** The post this one quotes, where there is one. */
quoted?: Quoted;
/** The post the link actually pointed at. Only meaningful when a thread
* has more than one segment. */
isAnchor?: boolean;
};
/**
* One comment, with the replies that hang off it.
*
* A tree rather than a flat list with depths: collapsing a comment has to
* take everything under it along, and nesting is what makes that free.
*/
export type Comment = {
/** Already prefixed, e.g. `u/someone`. `[deleted]` is left as it came. */
author: string;
text?: string;
/** ISO 8601. */
postedAt?: string;
/** Absent when the platform is still hiding it on a new comment. */
score?: number;
/** The author of the post, replying under it. */
isAuthor?: boolean;
/** Marked by the platform as a moderator or admin comment. */
distinguished?: string;
replies: Comment[];
/** Replies that exist upstream but were not on the page we were given.
* Shown as a count, since following them means going to the platform. */
moreReplies?: number;
};
/**
* The single shape every adapter produces and the renderer consumes. Adding
* a platform means producing one of these; nothing downstream changes.
@@ -73,6 +120,18 @@ export type Post = {
textPosition: 'above' | 'below';
/** In the order they were written. Never empty. */
segments: Segment[];
/**
* The conversation under the post, where the platform has one worth
* showing. Only Reddit fills this in: elsewhere the replies are strangers
* arguing beneath something that was shared for its own sake, but on
* Reddit the thread is usually the point of the link.
*/
comments?: Comment[];
/** Top-level comments the first page did not carry. */
moreComments?: number;
/** What the platform says the total is, which is larger than what we
* show whenever `moreComments` is set. */
commentCount?: number;
};
/** Most platforms have no notion of a chain, so their adapters use this. */
+44 -9
View File
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mediaFromEmbed, selfThread, toPost } from '../src/platforms/bluesky.ts';
import { mediaFromEmbed, quotedFrom, selfThread, toPost } from '../src/platforms/bluesky.ts';
import { fixture } from './helpers.ts';
const URL_ = 'https://bsky.app/profile/example/post/abc';
@@ -45,14 +45,49 @@ test('a quote post with media reaches through the nested embed', () => {
assert.deepEqual(media, [{ kind: 'image', url: 'https://example/i.jpg' }]);
});
test('a quote post shows the media of the post it quotes', () => {
const media = mediaFromEmbed({
$type: 'app.bsky.embed.record#view',
record: {
embeds: [{ $type: 'app.bsky.embed.images#view', images: [{ fullsize: 'https://cdn/q.jpg' }] }],
},
});
assert.deepEqual(media, [{ kind: 'image', url: 'https://cdn/q.jpg' }]);
test('a quote post carries the post it quotes, whose it is included', () => {
const segment = toPost(fixture('bluesky/quote.json'), URL_).segments[0];
const quoted = segment?.quoted;
assert.ok(quoted, 'the quoted post must survive');
assert.equal(quoted?.author.handle, '@cpsc.gov');
assert.equal(quoted?.author.displayName, 'U.S. Consumer Product Safety Commission');
assert.match(quoted?.text ?? '', /Longer videos is great/);
assert.ok(quoted?.postedAt);
// `at://` is not an address anyone can open, so the web one is rebuilt.
assert.equal(quoted?.url, 'https://bsky.app/profile/cpsc.gov/post/3mtzkm3hmo222');
});
test('the quoted post keeps its own media instead of lending it to the quoter', () => {
const segment = toPost(fixture('bluesky/quote.json'), URL_).segments[0];
assert.deepEqual(segment?.media, [], 'the quoter attached nothing');
assert.equal(segment?.quoted?.media.length, 1);
assert.equal(segment?.quoted?.media[0]?.kind, 'video');
});
test('a quote with media of its own nests the quoted record one level deeper', () => {
// `recordWithMedia` puts it at `embed.record.record`; a plain quote puts it
// at `embed.record`. Reading only the first shape finds nothing here.
const quoted = toPost(fixture('bluesky/quote-with-media.json'), URL_).segments[0]?.quoted;
assert.equal(quoted?.author.handle, '@quillmatiq.com');
assert.match(quoted?.text ?? '', /huge value add/);
});
test('a quote pointing at something that is not a post is left out', () => {
// A quote can point at a feed, a list, or a post since deleted or blocked.
// They arrive in the same slot under a different type, carrying none of
// what a post has.
for (const $type of [
'app.bsky.embed.record#viewNotFound',
'app.bsky.embed.record#viewBlocked',
'app.bsky.embed.record#viewDetached',
'app.bsky.feed.defs#generatorView',
]) {
assert.equal(quotedFrom({ $type: 'app.bsky.embed.record#view', record: { $type } }), undefined);
}
assert.equal(quotedFrom(undefined), undefined);
assert.equal(quotedFrom({ $type: 'app.bsky.embed.images#view' }), undefined);
});
// The chain fixture is a real thread. Other people's replies were trimmed to
+47
View File
@@ -0,0 +1,47 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { browsersFor, detectOs, openUrlFor } from '../public/browsers.js';
const URL = 'https://www.instagram.com/p/ABC/?a=1&b=2';
test('each browser gets the scheme it actually answers to', () => {
assert.equal(openUrlFor(URL, 'chrome', 'macos'), 'googlechromes://www.instagram.com/p/ABC/?a=1&b=2');
assert.equal(openUrlFor(URL, 'chrome', 'ios'), 'googlechromes://www.instagram.com/p/ABC/?a=1&b=2');
assert.equal(openUrlFor('http://example.com/a', 'chrome', 'ios'), 'googlechrome://example.com/a');
// Edge folds the scheme into its own on iOS and prefixes it on macOS.
assert.equal(openUrlFor(URL, 'edge', 'macos'), `microsoft-edge:${URL}`);
assert.equal(openUrlFor(URL, 'edge', 'ios'), 'microsoft-edge-https://www.instagram.com/p/ABC/?a=1&b=2');
// The parameter form has to be encoded, or the original query string ends
// up read as the opener's own.
assert.equal(openUrlFor(URL, 'orion', 'macos'),
`orion://open-url?url=${encodeURIComponent(URL)}`);
assert.equal(openUrlFor(URL, 'firefox', 'ios'),
`firefox://open-url?url=${encodeURIComponent(URL)}`);
});
test('a browser with no scheme on this system keeps the plain link', () => {
// Firefox on macOS has none, and a dead scheme opens nothing at all --
// worse than opening in the wrong browser.
assert.equal(openUrlFor(URL, 'firefox', 'macos'), URL);
assert.equal(openUrlFor(URL, 'default', 'ios'), URL);
assert.equal(openUrlFor(URL, 'nonesuch', 'ios'), URL);
});
test('only ordinary web links are rewritten', () => {
assert.equal(openUrlFor('mailto:[email protected]', 'chrome', 'ios'), 'mailto:[email protected]');
assert.equal(openUrlFor('/reddit/r/a/comments/b', 'chrome', 'ios'), '/reddit/r/a/comments/b');
});
test('only the browsers reachable on that system are offered', () => {
assert.deepEqual(browsersFor('macos').map((b) => b.id), ['default', 'chrome', 'edge', 'orion']);
assert.deepEqual(browsersFor('ios').map((b) => b.id), ['default', 'chrome', 'edge', 'firefox', 'orion']);
});
test('an iPad is told from a Mac by its touch points, not its platform string', () => {
assert.equal(detectOs({ platform: 'iPhone', maxTouchPoints: 5 }), 'ios');
assert.equal(detectOs({ platform: 'MacIntel', maxTouchPoints: 5 }), 'ios');
assert.equal(detectOs({ platform: 'MacIntel', maxTouchPoints: 0 }), 'macos');
assert.equal(detectOs({}), 'macos');
});
+35
View File
@@ -0,0 +1,35 @@
{
"post": {
"uri": "at://did:plc:4hodhjl2kposuchzvpiviwps/app.bsky.feed.post/3mrvmbtqn2c24",
"author": {
"handle": "brittanyellich.com",
"displayName": "Brittany Ellich",
"avatar": "https://cdn.bsky.app/img/avatar/plain/did:plc:4hodhjl2kposuchzvpiviwps/bafkreidaibgqtw5rstbp6vmjvyv3zata5whjmhw2qerrbeqaq3gy7cfyzq"
},
"record": {
"text": "Thanks to this suggestion, you can now schedule updates to @attie.ai pages to build your own personal newsletter about whatever it is you care about ❤️\n\nattie.ai/@brittanyell...",
"createdAt": "2026-07-30T23:37:54.005Z"
},
"embed": {
"$type": "app.bsky.embed.recordWithMedia#view",
"media": {
"$type": "app.bsky.embed.external#view"
},
"record": {
"record": {
"$type": "app.bsky.embed.record#viewRecord",
"uri": "at://did:plc:xgvzy7ni6ig6ievcbls5jaxe/app.bsky.feed.post/3mrdeskslm222",
"author": {
"handle": "quillmatiq.com",
"displayName": "Anuj Ahooja",
"avatar": "https://cdn.bsky.app/img/avatar/plain/did:plc:xgvzy7ni6ig6ievcbls5jaxe/bafkreiaumjzoigdvnldguuxu3ytpzwglqgy3dckzg5cxwqcp5yjychrf4e"
},
"value": {
"text": "I think a huge value add here would be to have these pages periodically query for new info and create new versions of the pages, along with a notification (maybe on Bluesky or over email for visibility). A manual refresh button would be a good start!\n\ncc @jay.bsky.team @pfrazee.com",
"createdAt": "2026-07-23T17:36:09.832Z"
}
}
}
}
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"post": {
"uri": "at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.post/3mtzvbrnbds2q",
"author": {
"handle": "bsky.app",
"displayName": "Bluesky",
"avatar": "https://cdn.bsky.app/img/avatar/plain/did:plc:z72i7hdynmk6r22z27h6tvur/bafkreihwihm6kpd6zuwhhlro75p5qks5qtrcu55jp3gddbfjsieiv7wuka"
},
"record": {
"text": "NOW PLAYING: \"Beats To Relax / Be Safe To,\" by @cpsc.gov",
"createdAt": "2026-08-27T03:19:57.683Z"
},
"embed": {
"$type": "app.bsky.embed.record#view",
"record": {
"$type": "app.bsky.embed.record#viewRecord",
"uri": "at://did:plc:wbmw5r5a2j7txv72ggne2uoe/app.bsky.feed.post/3mtzkm3hmo222",
"author": {
"handle": "cpsc.gov",
"displayName": "U.S. Consumer Product Safety Commission",
"avatar": "https://cdn.bsky.app/img/avatar/plain/did:plc:wbmw5r5a2j7txv72ggne2uoe/bafkreic44z27sfbvclf2h2xjmsfbglhyqiobn2kigoayodampyvbiml3m4"
},
"value": {
"text": "Longer videos is great.",
"createdAt": "2026-08-27T00:08:52.368Z"
},
"embeds": [
{
"$type": "app.bsky.embed.video#view",
"playlist": "https://video.bsky.app/watch/did%3Aplc%3Awbmw5r5a2j7txv72ggne2uoe/bafkreia7e6rm7lq6k74ttdlbyx25g37eng3llqm7pex4fheah5voznais4/playlist.m3u8",
"thumbnail": "https://video.bsky.app/watch/did%3Aplc%3Awbmw5r5a2j7txv72ggne2uoe/bafkreia7e6rm7lq6k74ttdlbyx25g37eng3llqm7pex4fheah5voznais4/thumbnail.jpg",
"aspectRatio": {
"height": 1080,
"width": 1920
}
}
]
}
}
}
}
+541
View File
@@ -0,0 +1,541 @@
[
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t3",
"data": {
"title": "Spay day kinda nervy",
"author": "Background_Round_853",
"subreddit_name_prefixed": "r/aww",
"created_utc": 1786959785,
"selftext": "",
"permalink": "/r/aww/comments/1vqnp2e/spay_day_kinda_nervy/",
"url": "https://www.reddit.com/gallery/1vqnp2e",
"url_overridden_by_dest": "https://www.reddit.com/gallery/1vqnp2e",
"domain": "reddit.com",
"is_self": false,
"is_video": false,
"is_gallery": true,
"over_18": false,
"spoiler": false,
"num_comments": 443,
"score": 40774,
"gallery_data": {
"items": [
{
"is_deleted": false,
"media_id": "6xfm6s4wowjh1",
"id": 1020169008
},
{
"is_deleted": false,
"media_id": "x1o3cr4wowjh1",
"id": 1020169009
},
{
"is_deleted": false,
"media_id": "kury9t4wowjh1",
"id": 1020169010
},
{
"is_deleted": false,
"media_id": "v07ubs4wowjh1",
"id": 1020169011
}
]
},
"media_metadata": {
"v07ubs4wowjh1": {
"status": "valid",
"e": "Image",
"m": "image/jpg",
"p": [
{
"y": 155,
"x": 108,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=108&crop=smart&auto=webp&s=aa2a1ab3c453178f9ba6b8a06800c0fa923ad570"
},
{
"y": 311,
"x": 216,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=216&crop=smart&auto=webp&s=ec1e4d46b41511ffb3c27e2e331d23469c6be827"
},
{
"y": 461,
"x": 320,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=320&crop=smart&auto=webp&s=22812e3829549a461bdbcb81232a8edf752cac10"
},
{
"y": 922,
"x": 640,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=640&crop=smart&auto=webp&s=56315dc4cf19d12e6f19401792a059f70314ef04"
},
{
"y": 1383,
"x": 960,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=960&crop=smart&auto=webp&s=b706a7d2164462251f869651679c3635e15b6d25"
},
{
"y": 1555,
"x": 1080,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=1080&crop=smart&auto=webp&s=e5af0cc235a7b2583d8e8a87f7799607e41f1f23"
}
],
"s": {
"y": 1736,
"x": 1205,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=1205&format=pjpg&auto=webp&s=d5f2f69da610bf9a9b5b7cb99f94c21d21d4e75e"
},
"id": "v07ubs4wowjh1"
},
"6xfm6s4wowjh1": {
"status": "valid",
"e": "Image",
"m": "image/jpg",
"p": [
{
"y": 140,
"x": 108,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=108&crop=smart&auto=webp&s=231c0253d9ffcadcfa085c55264f968e1be7cd38"
},
{
"y": 281,
"x": 216,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=216&crop=smart&auto=webp&s=efb67b41fa2afbde45b4fbf3ff389cb7c98cbe62"
},
{
"y": 417,
"x": 320,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=320&crop=smart&auto=webp&s=4709db023af013805c8a0e4d64fdde867900df2c"
},
{
"y": 834,
"x": 640,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=640&crop=smart&auto=webp&s=2a43ebc507dc45cf578f7e74b62b6d37861d4f18"
},
{
"y": 1252,
"x": 960,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=960&crop=smart&auto=webp&s=f8f82d7392e30f1fb0d449489972ee2cd2e77d1f"
},
{
"y": 1408,
"x": 1080,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=1080&crop=smart&auto=webp&s=d438c9c25573da6b99ec89d26b373cf676d0a727"
}
],
"s": {
"y": 1572,
"x": 1205,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=1205&format=pjpg&auto=webp&s=ce8cff5c5c1d347a25c3c4431290fa76637f85b1"
},
"id": "6xfm6s4wowjh1"
},
"kury9t4wowjh1": {
"status": "valid",
"e": "Image",
"m": "image/jpg",
"p": [
{
"y": 141,
"x": 108,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=108&crop=smart&auto=webp&s=cca8d53fa39835bc14cfcb0b70f2409d2c0b41fd"
},
{
"y": 283,
"x": 216,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=216&crop=smart&auto=webp&s=5c196d8c1c5395b4388548729d779a74d011a6a7"
},
{
"y": 420,
"x": 320,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=320&crop=smart&auto=webp&s=6760b50b63edbf681e13739bbccc17551dbcacba"
},
{
"y": 840,
"x": 640,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=640&crop=smart&auto=webp&s=4cf3bb5bd6c53e6d9a8fff6560258da7fb9de4e1"
},
{
"y": 1261,
"x": 960,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=960&crop=smart&auto=webp&s=7c214c8d1a7a951b891b08d43cf445c28cb6ac20"
},
{
"y": 1418,
"x": 1080,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=1080&crop=smart&auto=webp&s=4eca14b69a68d05f78a5c6319867b4102fa3abfb"
}
],
"s": {
"y": 1583,
"x": 1205,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=1205&format=pjpg&auto=webp&s=24c97654ddd1d3bee61788a965223a9e40d92d6e"
},
"id": "kury9t4wowjh1"
},
"x1o3cr4wowjh1": {
"status": "valid",
"e": "Image",
"m": "image/jpg",
"p": [
{
"y": 80,
"x": 108,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=108&crop=smart&auto=webp&s=8a3211796cdf827ccdc39d76ff9aab299c4cbe2f"
},
{
"y": 160,
"x": 216,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=216&crop=smart&auto=webp&s=52c19a8c35965fccd08e4aaa7bb22f9aae22549e"
},
{
"y": 237,
"x": 320,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=320&crop=smart&auto=webp&s=c54e14e1989b0c1a67708fda3fe611da15f52414"
},
{
"y": 474,
"x": 640,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=640&crop=smart&auto=webp&s=4b7d4b60bb388c485024efe867466f6e5aba6fad"
},
{
"y": 711,
"x": 960,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=960&crop=smart&auto=webp&s=b0e46c04be74d31c5b00c0a704638888a4ca6781"
},
{
"y": 800,
"x": 1080,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=1080&crop=smart&auto=webp&s=c9bb5e091d769c8ec1360a83b6164117406641c8"
}
],
"s": {
"y": 893,
"x": 1205,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=1205&format=pjpg&auto=webp&s=20fbd865e429feb527bddb0b7f4bed3fc3281075"
},
"id": "x1o3cr4wowjh1"
}
}
}
}
]
}
},
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Background_Round_853",
"body": "https://preview.redd.it/d1m4kf45pwjh1.jpeg?width=1206&format=pjpg&auto=webp&s=6ccd095185d203c6569514e4b0bf93ed9de3ed2c\n\nDone ✅✅ she looks DEVASTATED",
"created_utc": 1786959888,
"score": 6583,
"score_hidden": false,
"is_submitter": true,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Fritzkreig",
"body": "Ah, may your lady and you share mutual joy for the years to come!",
"created_utc": 1786960145,
"score": 943,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "malk600",
"body": "She's coming off anaesthesia, idk what the SOC is in your country, but kitteh would typically get dexmedetomidine + opioid + something like ketamine. Vets will typically revert dexmedetomidine w/ atipamezol, which is about as mild and pleasant as being woken up by a swift kick in the nuts. The cat is just tired, confused, restless (it's possible she's going to be woozy and tired as hell but won't be able to sleep) and overall feels like a person would feel after doing a heavy night of things that are supposed to stay in Vegas.\n\nTake good care of her!",
"created_utc": 1786961915,
"score": 1298,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "teadazed",
"body": "Yes, I showed up to collect my two (brother and sister cats) and commented on their weirdass pupils. The nurse said fondly \"yeah... that's from all the drugs we've given them\".\nThey were both batting invisible butterflies the rest of the evening.",
"created_utc": 1786966670,
"score": 449,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "rocket_randall",
"body": "It's been a while since we had ours fixed, but we opted for a slow release pain killer that would keep them comfy for ~3 days after surgery while they healed. Of course our lunatics decided that once they were home and feeling no pain that it was time to lose their minds and nothing on earth could stop them running around and crashing into things. There was a bit of a scare after our little guy crashed into something and our daughter saw what looked like an eye injury, so off we went to the emergency vet just to be told that there was no injury, it was just the lubricant that was put on his eyes before surgery breaking up and he was fine. As a small consolation the vet said he was a huge endorphin hit for the staff at that time of night.",
"created_utc": 1786983276,
"score": 28,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "teadazed",
"body": "Oh of course they must have eye drops during surgery, their eyes stay open don't they? It's the right way round to take them in for something that turns out to be nothing.\n\nIt's funny, I also have a collie who unlike the cats did not enjoy the aftermath of her neutering drugs At All, she was a haunted-looking cuddlebug until she could move properly again.",
"created_utc": 1786984556,
"score": 18,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "more",
"data": {
"count": 1,
"id": "p4dtjha"
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Ashkir",
"body": "Some of the funniest things my dog has ever done was after they were waking up form anesthesia. She decided on a new place to potty that day too and to this day, years later, I cant train that spot out of her too 👀😭😂",
"created_utc": 1786975001,
"score": 112,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Winter_Fall_7066",
"body": "My dog was given a small sedative so the vet could witness a limp (he was excited and all over the place despite being in pain). Got home, ex asked “is the dog fucked up?” Dog immediately walks over to Christmas tree and pees on it. ",
"created_utc": 1786986392,
"score": 73,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Constant_Function238",
"body": "In his brain”thanks family for bringing my potty inside.”",
"created_utc": 1786990338,
"score": 28,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Pr0digy_",
"body": "My friend years ago dropped off his mastiff to get neutered and I was the one to pick him up because my friend was working late, he was dopey and groggy but really happy to see me. I took him home and watched him until my friend came home as soon as my friend entered the house the dog growled (nothing crazy) and went and hid behind me it was hilarious. Everything was forgiven with some treats and pets. ",
"created_utc": 1787001797,
"score": 19,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "werewooferer",
"body": "the dog knew who took him, and knew who saved him 🤣",
"created_utc": 1787167461,
"score": 3,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 1,
"id": "p4c9qw2"
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "chickens_for_laughs",
"body": "I remember that vet telling me to not let her jump onto furniture. Like I could get her to stop. She healed fine and lived to 20!",
"created_utc": 1786979935,
"score": 22,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "cAt_S0fa",
"body": "Lol yes the vet said the same thing to my mother when she got my childhood cat spayed. That night the cat was climbing the curtains...\n",
"created_utc": 1787000485,
"score": 3,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 21,
"id": "p49jamx"
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 24,
"id": "p4cqjj6"
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Shailo",
"body": "What a precious baby 🥺 those eyes omg. Wishing her a speedy recovery and lots of cuddles and treats in the meantime 💖",
"created_utc": 1786960262,
"score": 667,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "Trenzane",
"body": "I misread it as Spa day and was like ❤️ \n\nThen my brain worked and went ☹️",
"created_utc": 1786962348,
"score": 875,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "klgall1",
"body": "Glad I'm not the only one! I was reading the comments and saw the discussions about all the drugs and was very confused.\n\nI am not awake yet haha.",
"created_utc": 1786969784,
"score": 89,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "Cyber_Mermaid",
"body": "I still thought this said \"spa day\" until I read this comment lol",
"created_utc": 1786985184,
"score": 23,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "more",
"data": {
"count": 8,
"id": "p48kfhn"
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 195,
"id": "p4c6cph"
}
}
]
}
}
]
+102
View File
@@ -0,0 +1,102 @@
[
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t3",
"data": {
"title": "Ratko Mladic, Murderous Butcher of Bosnia, Dies at 83",
"author": "Knightro829",
"subreddit_name_prefixed": "r/news",
"created_utc": 1787836039,
"selftext": "",
"permalink": "/r/news/comments/1vzthbh/ratko_mladic_murderous_butcher_of_bosnia_dies_at/",
"url": "https://www.nytimes.com/2026/08/27/world/europe/ratko-mladic-dead.html?unlocked_article_code=1.8lA.Wgnd.qCJl7Bw9IdHl&smid=nytcore-ios-share",
"url_overridden_by_dest": "https://www.nytimes.com/2026/08/27/world/europe/ratko-mladic-dead.html?unlocked_article_code=1.8lA.Wgnd.qCJl7Bw9IdHl&smid=nytcore-ios-share",
"domain": "nytimes.com",
"is_self": false,
"is_video": false,
"over_18": false,
"spoiler": false,
"num_comments": 32,
"score": 187
}
}
]
}
},
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Knightro829",
"body": "Well, at least Death is getting closer to the mark after the past couple of days…. \n \nEdit: If you have several hours on your hands, go watch a.) The Death of Yugoslavia, a six-part documentary that aired on BBC in 1995-1996 (all episodes available on YouTube), and b.) PBS Frontlines “The Trial of Ratko Mladic”, also available on YouTube.",
"created_utc": 1787836109,
"score": 1,
"score_hidden": true,
"is_submitter": true,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "HungryCurrency8481",
"body": "Dolly Parton, Tim Curry, Ratko Mladic - what a trio ",
"created_utc": 1787836074,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "kataiga",
"body": "Unfortunately death also got Yayoi Kusama last night…",
"created_utc": 1787836540,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "RhoOfFeh",
"body": "He wasn't 80. I am holding out for completion of this deal.",
"created_utc": 1787836843,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "SheikhMahdeek",
"body": "See? Bad people live to ripe old age too",
"created_utc": 1787836434,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
]
+351
View File
@@ -0,0 +1,351 @@
[
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t3",
"data": {
"title": "What's a healthy food that pleases the taste buds too?",
"author": "Weary_Discipline_178",
"subreddit_name_prefixed": "r/AskReddit",
"created_utc": 1787833594,
"selftext": "",
"permalink": "/r/AskReddit/comments/1vzsjee/whats_a_healthy_food_that_pleases_the_taste_buds/",
"url": "https://www.reddit.com/r/AskReddit/comments/1vzsjee/whats_a_healthy_food_that_pleases_the_taste_buds/",
"domain": "self.AskReddit",
"is_self": true,
"is_video": false,
"over_18": false,
"spoiler": false,
"num_comments": 127,
"score": 94
}
}
]
}
},
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "manny221122",
"body": "greek yogurt with berries, honey and a little granola 😭 it tastes suspiciously close to dessert and somehow i get to pretend i have my life together while eating it",
"created_utc": 1787835955,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "more",
"data": {
"count": 1,
"id": "p67it4u"
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "CoconutxKitten",
"body": "The vast majority of fruit ",
"created_utc": 1787833703,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Technical_Buy_8198",
"body": "Currently cant get enough of a crunchy green grape. Almost ate an entire pack but had to stop myself. So good",
"created_utc": 1787833833,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "CoconutxKitten",
"body": "I love when theyre crunchy & slightly tart ",
"created_utc": 1787834158,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Ok_Reference_4860",
"body": "Yeppp and so delicious ",
"created_utc": 1787835229,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "deerhuntingdude",
"body": "Grapes are pretty low in fiber but high in sugar. They're good for you, but definitely only in moderation ",
"created_utc": 1787834561,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "random314",
"body": "Mangoes specifically.\n\nAlso watermelon.",
"created_utc": 1787834693,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "CoconutxKitten",
"body": "Watermelon is unhealthy specifically for me because Im allergic 😂",
"created_utc": 1787834743,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "more",
"data": {
"count": 2,
"id": "p67dyiw"
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "AngryBarista",
"body": "Chili",
"created_utc": 1787833749,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "VillagePlayful416",
"body": "good chili is basically a cheat code, you can dump a ton of veg in there and it still tastes like a proper meal\n\n \ni slow cook mine with black beans, capsicum, shredded carrot and sometimes a bit of sweet potato, the smoked paprika does all the heavy lifting\n\n \nmake a huge batch sunday and you're set for the week",
"created_utc": 1787833937,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "NOT_Frank_or_Joe",
"body": "A winter staple for me. I also add beets, cut them up small and cook fully on the side then in to simmer with the rest. \n\nEdit: forgot to add, replace the beef with ground turkey as well.",
"created_utc": 1787834097,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "AngryBarista",
"body": "Every time I make it, i look at my wife and say \"this has no business being as good as it is for how healthy it is. Just packed with protein and fiber and can have minimal fat if you use a lean protein",
"created_utc": 1787834149,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Klutzy-Client",
"body": "But triple the amount of beans in it and we are talking",
"created_utc": 1787836492,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "kitty_swankiss",
"body": "Everything Nuts in moderation 🥜🌰",
"created_utc": 1787833760,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "jefe_gonna_jefe",
"body": "Not me.",
"created_utc": 1787833889,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "BlueEyedMalachi",
"body": "Nice",
"created_utc": 1787833961,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "Lettuce_Milk",
"body": "Either you got all the nut or none at all 😎",
"created_utc": 1787836058,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "more",
"data": {
"count": 2,
"id": "p67a17t"
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Chicken-picante",
"body": "What about odyssey?\n\nOdyssey deez nutz",
"created_utc": 1787834927,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Perfectenschlag_",
"body": "Boooooo",
"created_utc": 1787836540,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 10,
"id": "p677sc7"
}
}
]
}
}
]
+451
View File
@@ -0,0 +1,451 @@
[
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t3",
"data": {
"title": "1957 Ford Fairlane",
"author": "icleanjaxfl",
"subreddit_name_prefixed": "r/oddlysatisfying",
"created_utc": 1787830536,
"selftext": "",
"permalink": "/r/oddlysatisfying/comments/1vzrfkw/1957_ford_fairlane/",
"url": "https://v.redd.it/74hudhx2mwlh1",
"url_overridden_by_dest": "https://v.redd.it/74hudhx2mwlh1",
"domain": "v.redd.it",
"post_hint": "hosted:video",
"is_self": false,
"is_video": true,
"over_18": false,
"spoiler": false,
"num_comments": 109,
"score": 3477,
"secure_media": {
"reddit_video": {
"bitrate_kbps": 2400,
"fallback_url": "https://v.redd.it/74hudhx2mwlh1/CMAF_720.mp4?source=fallback",
"has_audio": false,
"height": 1280,
"width": 720,
"scrubber_media_url": "https://v.redd.it/74hudhx2mwlh1/CMAF_96.mp4",
"dash_url": "https://v.redd.it/74hudhx2mwlh1/DASHPlaylist.mpd?a=1790429193%2CNjQwMTBmMDMxODhjMGViOGUyMjU2ZDE2NGFkNmI2MDU2ZDQ2NmVjNmEzNzg0MTQzNGVkMTU5OGI2ZTgyYTU3ZQ%3D%3D&v=1&f=sd",
"duration": 25,
"hls_url": "https://v.redd.it/74hudhx2mwlh1/HLSPlaylist.m3u8?a=1790429193%2CZjkwZmQwODJiYmRhNGY2NDkyYTMxMDZlYmVhMzQwYWVkYTg0MzMwOWEwYjAyMGZhMzY0MWJmYTIyMmE0OTQ3Zg%3D%3D&v=1&f=sd",
"is_gif": false,
"transcoding_status": "completed"
}
},
"media": {
"reddit_video": {
"bitrate_kbps": 2400,
"fallback_url": "https://v.redd.it/74hudhx2mwlh1/CMAF_720.mp4?source=fallback",
"has_audio": false,
"height": 1280,
"width": 720,
"scrubber_media_url": "https://v.redd.it/74hudhx2mwlh1/CMAF_96.mp4",
"dash_url": "https://v.redd.it/74hudhx2mwlh1/DASHPlaylist.mpd?a=1790429193%2CNjQwMTBmMDMxODhjMGViOGUyMjU2ZDE2NGFkNmI2MDU2ZDQ2NmVjNmEzNzg0MTQzNGVkMTU5OGI2ZTgyYTU3ZQ%3D%3D&v=1&f=sd",
"duration": 25,
"hls_url": "https://v.redd.it/74hudhx2mwlh1/HLSPlaylist.m3u8?a=1790429193%2CZjkwZmQwODJiYmRhNGY2NDkyYTMxMDZlYmVhMzQwYWVkYTg0MzMwOWEwYjAyMGZhMzY0MWJmYTIyMmE0OTQ3Zg%3D%3D&v=1&f=sd",
"is_gif": false,
"transcoding_status": "completed"
}
},
"preview": {
"images": [
{
"source": {
"url": "https://external-preview.redd.it/N245aGFidjJtd2xoMRGGAvg1khFB1AQL8vVunwC_Mb5qnXHCQGxm0j4C5bdR.png?format=pjpg&auto=webp&s=cd60e451633a907b172389c0cd1c09e174ac9f16",
"width": 405,
"height": 720
}
}
]
}
}
}
]
}
},
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Head-State-",
"body": "That retractable hardtop transformer mechanism is pure engineering wizardry.",
"created_utc": 1787830965,
"score": 328,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Pretend-Internet-625",
"body": "ya until you have to go and fix it and make it work properly. ",
"created_utc": 1787832356,
"score": 150,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "bigalindahouse",
"body": "Would much rather work on this than today's vehicles",
"created_utc": 1787833724,
"score": 63,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Pretend-Internet-625",
"body": "Well ya I get that but these were a real pain in the ",
"created_utc": 1787833961,
"score": 6,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Brasticus",
"body": "r/redditsniper claims another",
"created_utc": 1787834765,
"score": 21,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Andy_B_Goode",
"body": "Yeah, it's neat, but it also totally looks like one of those things that would break in the first two or three years and most people wouldn't bother fixing",
"created_utc": 1787835341,
"score": 6,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "utukore",
"body": "Same setup was used for the e93 roof. Other than the squeeks and rattles or the slow open/ close time they worked well.",
"created_utc": 1787836411,
"score": 3,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "kss1089",
"body": "Everything is a 4 bar mechanism. if it's super complicated, it's multiple 4 bar mechanisms. ",
"created_utc": 1787833936,
"score": 12,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Tony_Penny",
"body": "Ford Fairlane, rock and roll detective. ",
"created_utc": 1787831095,
"score": 29,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "perflubon",
"body": "One of the best \"worst\" movies ever.",
"created_utc": 1787832767,
"score": 7,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Tony_Penny",
"body": "I absolutely loved that movie as a kid. ",
"created_utc": 1787833553,
"score": 3,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "imamakebaddecisions",
"body": "Booty time, booty time, across the USA, booty time, booty time, hey hey hey!",
"created_utc": 1787833566,
"score": 5,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "[deleted]",
"body": "[removed]",
"created_utc": 1787833134,
"score": 145,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Bongressman",
"body": "And covering it for the winter... then uncovering it in the Spring. Getting that \"unwrapping a new gift\" endorphin rush all over again every year.",
"created_utc": 1787834518,
"score": 8,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "zytukin",
"body": "You'd leave it outside over winter???",
"created_utc": 1787834574,
"score": 4,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Bongressman",
"body": "I live in Seattle, so snow isnt a factor. Streets are dotted with covered cars in the winter. I guess it depends on location!",
"created_utc": 1787834801,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Flyingdutchman2305",
"body": "?? Isnt there lots of snow in seattle",
"created_utc": 1787835019,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Bongressman",
"body": "No. It doesn't snow in Seattle. We don't even have a snow removal budget in the city.\n\nWinter bottoms out at like 40-45 fahrenheit. It just mists, drizzles, gets overcast and grey for six months.",
"created_utc": 1787835128,
"score": 2,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Flyingdutchman2305",
"body": "Huh, my american Geography when it comes to latitude is apparently off\n\n![gif](giphy|QfzMP70zmNQiDf5sGP)",
"created_utc": 1787835286,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Bongressman",
"body": "It snows in Washington state, just not Seattle. We are surrounded by the Cascades and Olympic Mountains. Kind of boxed in and protected.\n\nOur weather closely mirrors London's, but with even less snowfall.",
"created_utc": 1787835622,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Flyingdutchman2305",
"body": "Never knew, always thought it was one of those typical snowy winter cities",
"created_utc": 1787835875,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "zytukin",
"body": "It's not due to latitude, Seattle is more north than Wyoming, Kansas, etc which get a lot of snow.\n\nI think it has to do with being near the west coast so it gets hit with warm air coming up from the tropics.",
"created_utc": 1787835832,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "its_Raze_7",
"body": "bot",
"created_utc": 1787836203,
"score": 2,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 1,
"id": "p676rzl"
}
}
]
}
}
]
+128
View File
@@ -0,0 +1,128 @@
{
"id_str": "2086902906171605466",
"text": "NEW: Joey McGuire tells @Brett_McMurphy Texas Tech can't find future games, with Texas A&amp;M, USC, NC State and Mississippi State saying no or canceling series❌\n\n\"Were talking to everybody and anybody. So far, everybodys told us no.\"\n\nhttps://t.co/rEGx9JN5pJ https://t.co/QdJhOVu4En",
"display_text_range": [
0,
262
],
"entities": {
"urls": [
{
"url": "https://t.co/rEGx9JN5pJ",
"expanded_url": "https://www.on3.com/news/joey-mcguire-on-texas-techs-villain-era-were-the-most-hated-team-in-college-football/"
}
]
},
"created_at": "2026-08-10T19:50:00.000Z",
"user": {
"screen_name": "On3",
"name": "On3",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1414989749203390470/D2B25n0r_normal.jpg"
},
"mediaDetails": [
{
"type": "photo",
"media_url_https": "https://pbs.twimg.com/media/HPYnDNPW0AAJd6h.jpg",
"original_info": {
"focus_rects": [
{
"h": 605,
"w": 1080,
"x": 0,
"y": 609
},
{
"h": 1080,
"w": 1080,
"x": 0,
"y": 270
},
{
"h": 1231,
"w": 1080,
"x": 0,
"y": 119
},
{
"h": 1350,
"w": 675,
"x": 169,
"y": 0
},
{
"h": 1350,
"w": 1080,
"x": 0,
"y": 0
}
],
"height": 1350,
"width": 1080
}
}
],
"quoted_tweet": {
"id_str": "2086832880676716740",
"text": "NEW: Texas Tech's Joey McGuire tells @Brett_McMurphy the Red Raiders are embracing the villain role🔥\n\n\"Were the most hated team in college football. And I absolutely love it,\" McGuire told his team in a meeting.\n\nStory: https://t.co/rEGx9JN5pJ https://t.co/q7m39MOMNo",
"display_text_range": [
0,
245
],
"entities": {
"urls": [
{
"url": "https://t.co/rEGx9JN5pJ",
"expanded_url": "https://www.on3.com/news/joey-mcguire-on-texas-techs-villain-era-were-the-most-hated-team-in-college-football/"
}
]
},
"created_at": "2026-08-10T15:11:44.000Z",
"user": {
"screen_name": "On3",
"name": "On3",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1414989749203390470/D2B25n0r_normal.jpg"
},
"mediaDetails": [
{
"type": "photo",
"media_url_https": "https://pbs.twimg.com/media/HPXqebKWkAA5gvA.jpg",
"original_info": {
"focus_rects": [
{
"h": 630,
"w": 1125,
"x": 0,
"y": 0
},
{
"h": 630,
"w": 630,
"x": 75,
"y": 0
},
{
"h": 630,
"w": 553,
"x": 114,
"y": 0
},
{
"h": 630,
"w": 315,
"x": 233,
"y": 0
},
{
"h": 630,
"w": 1200,
"x": 0,
"y": 0
}
],
"height": 630,
"width": 1200
}
}
]
}
}
+70
View File
@@ -0,0 +1,70 @@
{
"id_str": "2092384141488620017",
"text": "The SEC, as expected, adopts a ban on professional players returning to college, which also includes basketball.",
"display_text_range": [
0,
112
],
"created_at": "2026-08-25T22:50:28.000Z",
"user": {
"screen_name": "RossDellenger",
"name": "Ross Dellenger",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1174672001958649861/m2N_Dbim_normal.jpg"
},
"quoted_tweet": {
"id_str": "2092383884872765473",
"text": "Following meetings with the Presidents, Chancellors, and Athletics Directors of the Southeastern Conference, the SEC will enforce the following policy: https://t.co/LohWnb7G1J",
"display_text_range": [
0,
151
],
"created_at": "2026-08-25T22:49:27.000Z",
"user": {
"screen_name": "SEC",
"name": "Southeastern Conference",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1807664314687299584/qhj7cnXy_normal.jpg"
},
"mediaDetails": [
{
"type": "photo",
"media_url_https": "https://pbs.twimg.com/media/HQmj_lxW8AAlFmc.jpg",
"original_info": {
"focus_rects": [
{
"h": 605,
"w": 1080,
"x": 0,
"y": 742
},
{
"h": 1080,
"w": 1080,
"x": 0,
"y": 360
},
{
"h": 1231,
"w": 1080,
"x": 0,
"y": 209
},
{
"h": 1440,
"w": 720,
"x": 0,
"y": 0
},
{
"h": 1440,
"w": 1080,
"x": 0,
"y": 0
}
],
"height": 1440,
"width": 1080
}
}
]
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"id_str": "2092435281869738141",
"text": "Deacon Kevin Barron of the Catholic Community of Buffalo North led the prayer service on Tuesday for Mayich. In an interview with @azcentral, Barron said that Maywich suffered a “cardiac event” and is currently in a coma.",
"display_text_range": [
0,
221
],
"created_at": "2026-08-26T02:13:41.000Z",
"user": {
"screen_name": "MikeMcMahonCHN",
"name": "Mike McMahon",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2068376149747449856/oqDq3qs4_normal.jpg"
},
"quoted_tweet": {
"id_str": "2092384930034548928",
"text": "Matthew Mayich, a sophomore defenseman, is the player hospitalized. There was a virtual prayer service held today, shared on social media, in which Mayichs cousin spoke. I didnt want to share the players name before we were sure the players family was OK with it being shared.",
"display_text_range": [
0,
280
],
"created_at": "2026-08-25T22:53:36.000Z",
"user": {
"screen_name": "MikeMcMahonCHN",
"name": "Mike McMahon",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2068376149747449856/oqDq3qs4_normal.jpg"
}
}
}
+155
View File
@@ -0,0 +1,155 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { escapeHtml } from '../src/render/html.ts';
import { renderMarkdown } from '../src/render/markdown.ts';
const md = (text: string): string => String(renderMarkdown(text));
/** Stands in for the real one, which proxies. Escapes the way that one does:
* placing the image is the renderer's job, and so is making it safe. */
const img = (url: string, alt: string): string =>
`<img src="${escapeHtml(url)}" alt="${escapeHtml(alt)}">`;
const mdi = (text: string): string => String(renderMarkdown(text, img));
test('markup a commenter typed is text, not markup', () => {
const out = md('<script>alert(1)</script> & "quoted"');
assert.ok(!out.includes('<script>'));
assert.match(out, /&lt;script&gt;/);
assert.match(out, /&amp;/);
});
test('only http and https become links', () => {
assert.match(md('[go](https://example.com/a)'), /<a href="https:\/\/example\.com\/a"/);
// The label is still shown; it is only the link that is refused.
const dangerous = md('[go](javascript:alert(1))');
assert.ok(!dangerous.includes('<a '));
assert.match(dangerous, /\[go\]/);
});
test('a bare URL is linked without swallowing the sentence it ends', () => {
const out = md('see https://example.com/x.');
assert.match(out, /href="https:\/\/example\.com\/x"/);
assert.ok(out.endsWith('.</p>'), `trailing full stop should stay outside the link: ${out}`);
});
test('an ampersand in a link target survives as one', () => {
const out = md('[x](https://example.com/?a=1&b=2)');
assert.match(out, /href="https:\/\/example\.com\/\?a=1&amp;b=2"/);
});
test('a quote is a block of its own, so the reply is not read as part of it', () => {
const out = md('> they said this\n\nand I disagree');
assert.match(out, /<blockquote><p>they said this<\/p><\/blockquote><p>and I disagree<\/p>/);
});
test('quoting a quote keeps both levels', () => {
assert.match(md('> > deep\n> shallow'), /<blockquote><blockquote>/);
});
test('emphasis does not fire inside a word', () => {
// `snake_case_names` are ordinary in the subreddits this will be pointed at.
assert.equal(md('some_variable_name'), '<p>some_variable_name</p>');
assert.match(md('_yes_'), /<em>yes<\/em>/);
});
test('code is left exactly as typed', () => {
assert.match(md('`a < b && c`'), /<code>a &lt; b &amp;&amp; c<\/code>/);
assert.match(md('```\n<b>not bold</b>\n```'), /<pre><code>&lt;b&gt;not bold&lt;\/b&gt;<\/code><\/pre>/);
});
test('subreddit and user references link back to reddit', () => {
assert.match(md('over in r/aww'), /href="https:\/\/www\.reddit\.com\/r\/aww"/);
assert.match(md('ask u/someone'), /href="https:\/\/www\.reddit\.com\/u\/someone"/);
});
test('lists survive, both kinds', () => {
assert.match(md('- one\n- two'), /<ul><li>one<\/li><li>two<\/li><\/ul>/);
assert.match(md('1. one\n2. two'), /<ol><li>one<\/li><li>two<\/li><\/ol>/);
});
test('a single newline inside a paragraph is a line break, a blank line is a new one', () => {
assert.equal(md('one\ntwo'), '<p>one<br>two</p>');
assert.equal(md('one\n\ntwo'), '<p>one</p><p>two</p>');
});
test('an image is a picture when there is something to place it with', () => {
assert.equal(mdi('![a cat](https://i.redd.it/x.jpg)'),
'<p><img src="https://i.redd.it/x.jpg" alt="a cat"></p>');
});
test('an image degrades to a link when there is not', () => {
const out = md('![a cat](https://i.redd.it/x.jpg)');
assert.ok(out.includes('<a href="https://i.redd.it/x.jpg"'));
assert.ok(!out.includes('<img'));
});
test("an image's `!` is not left behind as text", () => {
// The link rule would otherwise match from the `[` and strand the bang.
assert.ok(!mdi('![](https://i.redd.it/x.png)').includes('!'));
});
test('a pasted image address becomes the picture, not a link to it', () => {
// Which is how most images in a Reddit comment arrive.
const out = mdi('look\n\nhttps://preview.redd.it/abc.jpeg?width=1274&s=deadbeef');
assert.ok(out.includes('<img src="https://preview.redd.it/abc.jpeg?width=1274&amp;s=deadbeef"'));
assert.ok(!out.includes('<a href'));
});
test('a link that is not an image is still a link', () => {
const out = mdi('see https://example.com/article');
assert.ok(out.includes('<a href="https://example.com/article"'));
assert.ok(!out.includes('<img'));
});
test('a sentence after a pasted image keeps its punctuation out of the address', () => {
const out = mdi('here https://i.redd.it/x.jpg.');
assert.ok(out.includes('src="https://i.redd.it/x.jpg"'), out);
assert.ok(out.endsWith('.</p>'), out);
});
test('only http and https become pictures', () => {
const out = mdi('![x](javascript:alert(1))');
assert.ok(!out.includes('<img'));
assert.ok(out.includes('![x]'));
});
test("an image's alt text is escaped like anything else a stranger wrote", () => {
const out = mdi('![" onerror=alert(1)](https://i.redd.it/x.jpg)');
assert.ok(!out.includes('onerror=alert(1)>'), out);
assert.ok(out.includes('&quot;'));
});
test('images inside a quote are still placed', () => {
assert.match(mdi('> ![](https://i.redd.it/x.gif)'), /<blockquote><p><img/);
});
test('an image address typed without a scheme is still the picture', () => {
// Which is how people type them: no https, straight from the address bar.
const out = mdi('preview.redd.it/lz4drsqh0clh1.jpeg?width=1290&s=b27e');
assert.ok(out.includes('<img src="https://preview.redd.it/lz4drsqh0clh1.jpeg?width=1290&amp;s=b27e"'), out);
});
test('a schemeless image address mid-sentence keeps the sentence', () => {
const out = mdi('look at i.redd.it/x.png nice one');
assert.ok(out.startsWith('<p>look at <img'), out);
assert.ok(out.endsWith(' nice one</p>'), out);
});
test('prose full of dots and slashes is not mistaken for an address', () => {
// The reason this rule insists on a host, a path and an image extension.
for (const text of [
'the file is at src/render/post.ts',
'see node_modules/foo/bar.js',
'a path like ./images/cat.jpg',
'C:/Users/x/cat.png',
'email [email protected]/nope.jpg',
'version 1.2.3/4.png',
]) {
assert.ok(!mdi(text).includes('<img'), `treated as an image: ${text}`);
}
});
test('a schemeless address that is not an image is left alone', () => {
// Guessing a scheme is worth it for a picture and not for prose.
assert.equal(mdi('example.com/article'), '<p>example.com/article</p>');
});
+303
View File
@@ -0,0 +1,303 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { commentsFrom, mediaFromLink, resolveInlineImages, toPost, treeFromDepths } from '../src/platforms/reddit.ts';
import { reddit } from '../src/platforms/reddit.ts';
import { originalUrlFor } from '../src/platforms/index.ts';
import { fixture } from './helpers.ts';
const URL_ = 'https://www.reddit.com/r/aww/comments/abc123/a_post/';
test('a text post is its title, and carries no media', () => {
const post = toPost(fixture('reddit/self.json'), URL_);
assert.equal(post.platform, 'reddit');
assert.equal(post.author.handle, 'r/AskReddit');
assert.match(post.author.displayName ?? '', /^u\//);
assert.equal(post.segments[0]?.title, "What's a healthy food that pleases the taste buds too?");
assert.deepEqual(post.segments[0]?.media, []);
assert.ok(post.segments[0]?.postedAt);
});
test('a gallery keeps every picture, in the order the post arranged them', () => {
const link = fixture<[{ data: { children: Array<{ data: Record<string, unknown> }> } }]>(
'reddit/gallery.json',
)[0].data.children[0]?.data as Parameters<typeof mediaFromLink>[0];
const media = mediaFromLink(link);
const ids = (link.gallery_data?.items ?? []).map((item) => item.media_id);
assert.equal(media.length, ids.length);
assert.ok(media.every((m) => m.kind === 'image'));
// The pictures live in `media_metadata`, keyed and unordered; the order is
// only in `gallery_data`, so joining the two is the whole job.
media.forEach((item, index) => assert.ok(item.url.includes(String(ids[index]))));
assert.ok(media.every((m) => m.width && m.height));
});
test('a silent video is served as the plain MP4, with a real image for a poster', () => {
const media = toPost(fixture('reddit/video.json'), URL_).segments[0]?.media ?? [];
assert.equal(media.length, 1);
const video = media[0];
assert.equal(video?.kind, 'video');
assert.match(video?.url ?? '', /\.mp4/);
assert.ok(video?.kind === 'video' && video.poster);
// Not the scrubber file, which is itself an MP4 and would render nothing.
assert.ok(video?.kind === 'video' && !video.poster?.url.endsWith('.mp4'));
assert.equal(video?.kind === 'video' ? video.hls : undefined, undefined);
});
test('a video with sound is the HLS playlist, because the MP4 has no audio track', () => {
const media = mediaFromLink({
secure_media: {
reddit_video: {
fallback_url: 'https://v.redd.it/abc/CMAF_720.mp4?source=fallback',
hls_url: 'https://v.redd.it/abc/HLSPlaylist.m3u8',
has_audio: true,
width: 1920,
height: 1080,
duration: 42,
},
},
preview: { images: [{ source: { url: 'https://external-preview.redd.it/still.png', width: 1920, height: 1080 } }] },
});
assert.deepEqual(media, [
{
kind: 'video',
url: 'https://v.redd.it/abc/HLSPlaylist.m3u8',
hls: true,
direct: true,
width: 1920,
height: 1080,
durationSec: 42,
// The still is the video's, not the MP4's. Dropping it here left every
// post with sound showing an empty box where a silent one showed a frame.
poster: { url: 'https://external-preview.redd.it/still.png' },
},
]);
});
test('a link post keeps the destination, since it is the whole content of the post', () => {
const post = toPost(fixture('reddit/link.json'), URL_);
assert.match(post.segments[0]?.text ?? '', /^https:\/\/www\.nytimes\.com\//);
});
test('a crosspost shows what it is crossposting', () => {
const media = mediaFromLink({
is_self: false,
crosspost_parent_list: [
{ url_overridden_by_dest: 'https://i.redd.it/inner.jpg', post_hint: 'image' },
],
});
assert.deepEqual(media, [{ kind: 'image', url: 'https://i.redd.it/inner.jpg' }]);
});
test('comments come back as a tree, with the counts of what is missing', () => {
const post = toPost(fixture('reddit/gallery.json'), URL_);
assert.equal(post.comments?.length, 3);
assert.ok((post.moreComments ?? 0) > 0, 'the "more comments" node should be counted, not dropped');
assert.equal(post.commentCount, 443);
const first = post.comments?.[0];
assert.equal(first?.author, 'u/Background_Round_853');
assert.equal(first?.isAuthor, true, 'the poster replying under their own post');
assert.equal(first?.score, 6583);
assert.ok((first?.replies.length ?? 0) > 0);
assert.ok(first?.replies.every((reply) => Array.isArray(reply.replies)));
});
test('a score the platform is still hiding is left off rather than guessed at', () => {
const { comments } = commentsFrom({
data: {
children: [
{ kind: 't1', data: { author: 'a', body: 'new', score: 1, score_hidden: true, replies: '' } },
{ kind: 't1', data: { author: 'b', body: 'older', score: 42, score_hidden: false, replies: '' } },
],
},
});
assert.equal(comments[0]?.score, undefined);
assert.equal(comments[1]?.score, 42);
});
test('a deleted commenter keeps the platform\'s own word for it', () => {
const { comments } = commentsFrom({
data: { children: [{ kind: 't1', data: { author: '[deleted]', body: '[removed]', replies: '' } }] },
});
assert.equal(comments[0]?.author, '[deleted]');
});
test('an empty reply listing is the string "", not an object', () => {
// Reddit says "no replies" with an empty string, which is the shape most
// likely to be read as a listing and crash the walk.
const { comments } = commentsFrom({
data: { children: [{ kind: 't1', data: { author: 'a', body: 'x', replies: '' } }] },
});
assert.deepEqual(comments[0]?.replies, []);
});
test('a redd.it share code is rebuilt, since the rewrite drops the host', () => {
assert.equal(originalUrlFor(reddit, 'abc123', ''), 'https://redd.it/abc123');
assert.equal(
originalUrlFor(reddit, 'r/aww/comments/abc123/a_post/', '?share_id=xyz&utm_source=share'),
'https://www.reddit.com/r/aww/comments/abc123/a_post/',
);
});
test('reddit links route to the adapter, and its media hosts do not', () => {
assert.ok(reddit.matchesHost('www.reddit.com'));
assert.ok(reddit.matchesHost('old.reddit.com'));
assert.ok(reddit.matchesHost('redd.it'));
assert.ok(!reddit.matchesHost('bsky.app'));
});
test('the page fallback rebuilds nesting from the depth on each comment', () => {
// Reddit renders the tree flat, so depth is the only thing saying what
// replies to what.
const tree = treeFromDepths([
{ depth: 0, author: 'a', score: 5, created: '', text: 'first' },
{ depth: 1, author: 'b', score: 4, created: '', text: 'under first' },
{ depth: 2, author: 'c', score: 3, created: '', text: 'under b' },
// Back up two levels: this belongs to `first`, not to `c`.
{ depth: 1, author: 'd', score: 2, created: '', text: 'also under first' },
{ depth: 0, author: 'e', score: 1, created: '', text: 'second' },
]);
assert.equal(tree.length, 2);
assert.equal(tree[0]?.replies.length, 2);
assert.equal(tree[0]?.replies[0]?.replies[0]?.text, 'under b');
assert.equal(tree[0]?.replies[1]?.text, 'also under first');
assert.deepEqual(tree[1]?.replies, []);
});
test('a comment the page gave no text for is dropped rather than shown empty', () => {
assert.deepEqual(treeFromDepths([{ depth: 0, author: 'a', score: 1, created: '', text: '' }]), []);
});
// Real shapes, captured from comments carrying each kind.
const GIPHY = {
'giphy|Ve7wX45gaOFmw8eeEM': {
status: 'valid',
e: 'AnimatedImage',
m: 'image/gif',
s: {
y: 200,
x: 304,
gif: 'https://external-preview.redd.it/CTp8.gif?width=304&height=200&s=b0e9',
mp4: 'https://external-preview.redd.it/CTp8.gif?width=304&height=200&format=mp4&s=a389',
},
},
};
const UPLOAD = {
jo8gf0ca92zd1: {
status: 'valid',
e: 'Image',
m: 'image/jpeg',
s: { y: 1270, x: 1274, u: 'https://preview.redd.it/jo8gf0ca92zd1.jpeg?width=1274&s=c226' },
},
};
test('a giphy comment points at the gif rather than at a token', () => {
// `![gif](giphy|ID)` is not an address, and renders as nothing at all until
// it is looked up in the comment's own media_metadata.
assert.equal(
resolveInlineImages('![gif](giphy|Ve7wX45gaOFmw8eeEM)', GIPHY),
'![gif](https://external-preview.redd.it/CTp8.gif?width=304&height=200&s=b0e9)',
);
});
test('the animated form takes the gif, which plays on its own', () => {
const out = resolveInlineImages('![gif](giphy|Ve7wX45gaOFmw8eeEM)', GIPHY);
assert.ok(out.includes('.gif?'), out);
assert.ok(!out.includes('format=mp4'), 'an mp4 would need a player to move');
});
test('an uploaded image resolves through the same lookup', () => {
// Giphy, emotes and uploads are all a token that is a key in the same map,
// so none of them needs naming.
assert.equal(
resolveInlineImages('![img](jo8gf0ca92zd1)', UPLOAD),
'![img](https://preview.redd.it/jo8gf0ca92zd1.jpeg?width=1274&s=c226)',
);
});
test('a target that is already an address is left alone', () => {
const already = '![a](https://i.redd.it/x.jpg)';
assert.equal(resolveInlineImages(already, UPLOAD), already);
assert.equal(resolveInlineImages(already, undefined), already);
});
test('a token with no entry, or a broken one, is not invented', () => {
// An upload id and an emote id mean nothing off Reddit, so with no entry to
// look them up in there is nothing to point them at.
assert.equal(resolveInlineImages('![img](missing)', GIPHY), '![img](missing)');
assert.equal(
resolveInlineImages('![img](gone)', { gone: { status: 'failed', e: 'Image' } }),
'![img](gone)',
);
});
test('a giphy token resolves even when the comment carried no metadata', () => {
// Reddit ships plenty of these with no `media_metadata` at all. The id in
// the token is Giphy's own, so it does not need Reddit to be readable.
assert.equal(
resolveInlineImages('![gif](giphy|zUW23b6FmzB5e)', undefined),
'![gif](https://i.giphy.com/media/zUW23b6FmzB5e/giphy.gif)',
);
assert.equal(
resolveInlineImages('![gif](giphy|missing)', GIPHY),
'![gif](https://i.giphy.com/media/missing/giphy.gif)',
);
});
test('the metadata still wins where there is any, being what Reddit will serve', () => {
assert.match(resolveInlineImages('![gif](giphy|Ve7wX45gaOFmw8eeEM)', GIPHY), /redd\.it/);
});
test('a variant name after the id is dropped, not all of them being served', () => {
assert.equal(
resolveInlineImages('![gif](giphy|zUW23b6FmzB5e|downsized)', undefined),
'![gif](https://i.giphy.com/media/zUW23b6FmzB5e/giphy.gif)',
);
});
test('only a giphy token is guessed at, and only a well-formed one', () => {
for (const token of ['emote|t5_2th52|4358', 'giphy|', 'giphy|../evil', 'giphy|a|b|c']) {
assert.equal(resolveInlineImages(`![x](${token})`, undefined), `![x](${token})`);
}
});
test('a real comment carrying a giphy token gets the gif', () => {
// Captured from the post itself: the comment has the token and no
// `media_metadata`, which is the shape that used to show the token instead.
const post = toPost(fixture('reddit/video.json'), URL_);
const all: string[] = [];
const walk = (list: typeof post.comments) => {
for (const comment of list ?? []) {
if (comment.text) all.push(comment.text);
walk(comment.replies);
}
};
walk(post.comments);
const gif = all.find((text) => text.includes('giphy'));
assert.ok(gif, 'the fixture should still carry a giphy comment');
assert.match(gif, /!\[gif\]\(https:\/\/i\.giphy\.com\/media\/QfzMP70zmNQiDf5sGP\/giphy\.gif\)/);
});
test('inline images survive the walk into the comment tree', () => {
const { comments } = commentsFrom({
data: {
children: [{
kind: 't1',
data: {
author: 'a',
body: 'ha ![gif](giphy|Ve7wX45gaOFmw8eeEM)',
media_metadata: GIPHY,
replies: '',
},
}],
},
});
assert.match(comments[0]?.text ?? '', /external-preview\.redd\.it/);
});
+173 -1
View File
@@ -90,6 +90,27 @@ test('a video gets native controls and a source, not an iframe', () => {
assert.ok(!page.includes('<iframe'));
});
test('a video with no poster still carries its shape, so the box is right before play', () => {
// WebKit sizes a video from its natural size, which without data or a
// poster is 300x150 — a portrait video sat in a landscape box until you
// pressed play. The poster is where the shape comes from until then.
const page = renderPost(withMedia([
{ kind: 'video', url: 'https://video.example/p.m3u8', hls: true, direct: true, width: 720, height: 1280 },
]));
assert.ok(page.includes('aspect-ratio: 720 / 1280;'));
assert.match(page, /poster="data:image\/svg\+xml,[^"]*width%3D%22720%22[^"]*height%3D%221280%22/);
});
test('a real poster is left in place, and an unmeasured video gets none', () => {
const withPoster = renderPost(withMedia([
{ kind: 'video', url: 'https://cdn/v.mp4', width: 720, height: 1280, poster: { url: 'https://cdn/p.jpg' } },
]));
assert.match(withPoster, /poster="\/m\//);
assert.ok(!withPoster.includes('data:image/svg'));
assert.ok(!renderPost(withMedia([{ kind: 'video', url: 'https://cdn/v.mp4' }])).includes('poster='));
});
test('the copy button carries the clean original URL, and so does the page text', () => {
const page = renderPost(post());
assert.ok(page.includes('data-url="https://www.instagram.com/p/ABC/"'));
@@ -105,6 +126,157 @@ test('a failure still hands the link back', () => {
detail: 'TikTok showed a verification puzzle instead of the post.',
});
assert.ok(page.includes('data-url="https://www.tiktok.com/@a/video/1"'));
assert.ok(page.includes('Open on TikTok'));
assert.ok(page.includes('<code>https://www.tiktok.com/@a/video/1</code>'));
assert.ok(page.includes('verification puzzle'));
// Following the original link in the browser the rewrite rules are
// installed in only comes back here, so it stays hidden until the script
// has a browser to hand it to.
assert.ok(/<a class="original__open"[^>]* hidden>Open on TikTok<\/a>/.test(page));
});
function redditPost(overrides: Partial<Post> = {}): Post {
return post({
platform: 'reddit',
platformLabel: 'Reddit',
originalUrl: 'https://www.reddit.com/r/aww/comments/abc/a/',
author: { handle: 'r/aww' },
textPosition: 'above',
segments: oneSegment({ title: 'A headline', media: [] }),
...overrides,
});
}
test('a post with no comments renders no comment section at all', () => {
assert.ok(!renderPost(redditPost()).includes('class="thread"'));
assert.ok(!renderPost(post()).includes('class="thread"'));
});
test('comments nest, so collapsing one takes its replies with it', () => {
const page = renderPost(redditPost({
comments: [
{
author: 'u/a',
text: 'top',
replies: [{ author: 'u/b', text: 'nested', replies: [] }],
},
],
}));
// The reply is inside the parent's <details>, not a sibling of it.
const parent = page.slice(page.indexOf('<details class="c"'));
const closing = parent.indexOf('</details>');
assert.ok(parent.slice(0, closing).includes('nested'), 'a reply must live inside its parent');
assert.ok(page.includes('<details class="c" open'), 'threads start expanded');
});
test('a comment says how much a fold would hide', () => {
const page = renderPost(redditPost({
comments: [
{
author: 'u/a',
text: 'top',
replies: [
{ author: 'u/b', text: 'one', replies: [{ author: 'u/c', text: 'two', replies: [] }] },
],
},
],
}));
assert.ok(page.includes('+2 replies'), 'the whole subtree is counted, not just direct replies');
});
test('comment text is escaped, and its markdown is rendered', () => {
const page = renderPost(redditPost({
comments: [{ author: 'u/a', text: '**bold** <img src=x onerror=alert(1)>', replies: [] }],
}));
assert.ok(!page.includes('<img src=x'), 'markup in a comment must not survive');
assert.ok(page.includes('<strong>bold</strong>'));
});
test('what the first page did not carry is counted rather than pretended away', () => {
const page = renderPost(redditPost({
comments: [{ author: 'u/a', text: 'x', replies: [], moreReplies: 3 }],
moreComments: 40,
commentCount: 443,
}));
assert.ok(page.includes('3 more replies, on Reddit'));
assert.ok(page.includes('40 more, behind'));
assert.ok(page.includes('1 of 443'));
});
function quoting(quoted: Post['segments'][number]['quoted']): Post {
return post({
platform: 'x',
platformLabel: 'X',
textPosition: 'above',
segments: oneSegment({ text: 'look at this', media: [], quoted }),
});
}
test('a quoted post is drawn with its own author, not folded under the quoter', () => {
const page = quoting({
author: { handle: '@other', displayName: 'Someone Else' },
text: 'the original words',
media: [],
url: 'https://x.com/other/status/9',
});
const html_ = renderPost(page);
assert.ok(html_.includes('class="quote"'));
assert.ok(html_.includes('@other'), 'the quoted handle must be on the page');
assert.ok(html_.includes('Someone Else'));
assert.ok(html_.includes('the original words'));
assert.ok(html_.includes('href="https://x.com/other/status/9"'));
});
test('a quoted post with no quote renders no block', () => {
assert.ok(!renderPost(quoting(undefined)).includes('class="quote"'));
});
test("the quoted post's media is proxied like any other", () => {
const html_ = renderPost(quoting({
author: { handle: '@other' },
media: [{ kind: 'image', url: 'https://pbs.twimg.com/q.jpg' }],
}));
assert.ok(!html_.includes('https://pbs.twimg.com/q.jpg'), 'upstream URLs must not reach the page');
assert.ok(html_.includes('src="/m/'));
});
test('a quoted post is separated from the words that quote it', () => {
const html_ = renderPost(quoting({
author: { handle: '@other' },
text: 'quoted words',
media: [],
}));
// The quoter's text closes before the block opens, so the two can never
// read as one paragraph by the same person.
assert.ok(html_.indexOf('look at this') < html_.indexOf('class="quote"'));
assert.ok(html_.indexOf('class="quote"') < html_.indexOf('quoted words'));
});
test('markup in a quoted post is escaped like any other stranger\'s text', () => {
const html_ = renderPost(quoting({
author: { handle: '<img src=x onerror=alert(1)>' },
text: '<script>alert(1)</script>',
media: [],
}));
assert.ok(!html_.includes('<script>alert(1)</script>'));
assert.ok(!html_.includes('<img src=x'));
});
test('a picture in a comment is proxied, and its alt text cannot break out', () => {
const page = renderPost(redditPost({
comments: [{
author: 'u/a',
text: '![" onerror=alert(1) x="](https://preview.redd.it/x.jpeg?s=abc)\n\nhttps://i.redd.it/y.png',
replies: [],
}],
}));
assert.ok(!page.includes('https://preview.redd.it/x.jpeg'), 'upstream URLs must not reach the page');
assert.ok(!page.includes('https://i.redd.it/y.png'), 'a pasted address is proxied too');
assert.equal((page.match(/<img class="c__img" src="\/m\//g) ?? []).length, 2);
// The payload survives as text inside the attribute, which is the point:
// its quotes are neutered, so it cannot close `alt="` and become markup.
assert.ok(page.includes('alt="&quot; onerror=alert(1) x=&quot;"'), 'alt text must be escaped');
assert.ok(!/alt="" onerror/.test(page), 'the attribute must not be closable');
});
+110 -11
View File
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mediaFromDetails, toPost } from '../src/platforms/x.ts';
import { mediaFromDetails, quotedFrom, toPost } from '../src/platforms/x.ts';
import { fixture } from './helpers.ts';
const URL_ = 'https://x.com/example/status/1';
@@ -50,20 +50,119 @@ test('a video picks the highest-bitrate mp4 and ignores the streaming variants',
]);
});
test('a quote post shows the media of the post it quotes', () => {
// The quote itself carries none; without this the page is text and nothing
// else, which is exactly the thing the reader wanted to see.
test('a quote post carries the post it quotes, whose it is included', () => {
// Someone continuing their own thought from an earlier post. Without the
// quoted half on the page the remaining half says nothing.
const post = toPost(fixture('x/quote-text.json'), URL_);
const quoted = post.segments[0]?.quoted;
assert.ok(quoted, 'the quoted post must survive');
assert.equal(quoted?.author.handle, '@MikeMcMahonCHN');
assert.ok(quoted?.author.displayName);
assert.match(quoted?.text ?? '', /Matthew Mayich/);
assert.ok(quoted?.postedAt);
// No permalink in the payload, so it is rebuilt from the handle and the id.
assert.equal(quoted?.url, 'https://x.com/MikeMcMahonCHN/status/2092384930034548928');
});
test('the quoted post keeps its own pictures instead of lending them to the quoter', () => {
const post = toPost(fixture('x/quote-photo.json'), URL_);
assert.deepEqual(post.segments[0]?.media, [], 'the quoter attached nothing');
assert.equal(post.segments[0]?.quoted?.media.length, 1);
assert.equal(post.segments[0]?.quoted?.media[0]?.kind, 'image');
});
test('media on both sides stays on the side it came from', () => {
// This is the case the old either-or could not represent at all: it showed
// the quoter's picture and silently dropped the one being talked about.
const segment = toPost(fixture('x/quote-both.json'), URL_).segments[0];
assert.equal(segment?.media.length, 1);
assert.equal(segment?.quoted?.media.length, 1);
assert.notEqual(segment?.media[0]?.url, segment?.quoted?.media[0]?.url);
});
test('a post quoting nothing has no quoted post', () => {
assert.equal(toPost(fixture('x/photo.json'), URL_).segments[0]?.quoted, undefined);
assert.equal(quotedFrom(undefined), undefined);
// A quoted post X will not describe is nothing to show.
assert.equal(quotedFrom({ text: 'orphaned' }), undefined);
});
test('the shortlink X staples to a quote post is not shown', () => {
// The quoted post is right there on the page; a t.co pointing at it is
// noise, which is why X hides it too. `display_text_range` says where it
// starts, and keeps a link the author put there deliberately.
const both = toPost(fixture('x/quote-both.json'), URL_).segments[0];
// Two links arrive: one the author wrote, one X appended pointing at the
// quoted post. Exactly the second goes.
assert.equal((both?.text?.match(/https?:\/\//g) ?? []).length, 1, "the author's own link stays");
assert.match(both?.text ?? '', /on3\.com/);
assert.ok(!both?.text?.includes('QdJhOVu4En'));
const photo = toPost(fixture('x/quote-photo.json'), URL_).segments[0];
assert.ok(!photo?.quoted?.text?.includes('t.co'), 'and the same on the quoted post');
});
test('a t.co stands aside for the address it stands in for', () => {
// Left alone the page says `t.co/rEGx9JN5pJ`, which tells the reader
// nothing and sends them through X's click tracker to find out.
const segment = toPost(fixture('x/quote-both.json'), URL_).segments[0];
assert.ok(!segment?.text?.includes('t.co/'), `still shortened: ${segment?.text}`);
assert.match(segment?.text ?? '', /on3\.com/);
assert.match(segment?.quoted?.text ?? '', /on3\.com/);
});
test('a shortlink the payload does not explain is left as it is', () => {
const post = toPost(
{
text: 'look at this',
text: 'see https://t.co/unknown1 and https://t.co/known123',
user: { screen_name: 'someone' },
mediaDetails: [],
quoted_tweet: {
mediaDetails: [{ type: 'photo', media_url_https: 'https://pbs.twimg.com/q.jpg' }],
},
entities: { urls: [{ url: 'https://t.co/known123', expanded_url: 'https://example.com/real' }] },
},
URL_,
);
assert.equal(post.segments[0]?.media.length, 1);
assert.equal(post.segments[0]?.media[0]?.url, 'https://pbs.twimg.com/q.jpg?name=orig');
assert.equal(post.segments[0]?.text, 'see https://t.co/unknown1 and https://example.com/real');
});
test('an expansion that is not an http address is refused', () => {
const post = toPost(
{
text: 'https://t.co/abc',
user: { screen_name: 'someone' },
entities: { urls: [{ url: 'https://t.co/abc', expanded_url: 'javascript:alert(1)' }] },
},
URL_,
);
assert.equal(post.segments[0]?.text, 'https://t.co/abc');
});
test('the visible range is applied before the entities are decoded', () => {
// The indices are into the escaped text, where `&amp;` is five characters.
// Decoding first shifts everything after it and truncates the tail.
const post = toPost(
{
text: 'Tom &amp; Jerry https://t.co/xxx',
display_text_range: [0, 15],
user: { screen_name: 'someone' },
},
URL_,
);
assert.equal(post.segments[0]?.text, 'Tom & Jerry');
});
test('escaped characters X hands back are decoded, not shown as entities', () => {
// The syndication payload arrives pre-escaped; everything downstream
// escapes again on the way out, so leaving these puts `&amp;` on screen.
const post = toPost(
{
text: 'Tom &amp; Jerry &lt;3 &quot;quoted&quot;',
user: { screen_name: 'someone' },
quoted_tweet: { text: 'me &amp; you', user: { screen_name: 'other' }, id_str: '9' },
},
URL_,
);
assert.equal(post.segments[0]?.text, 'Tom & Jerry <3 "quoted"');
assert.equal(post.segments[0]?.quoted?.text, 'me & you');
});
+4
View File
@@ -17,6 +17,10 @@
// Source imports carry the real `.ts` specifier so `node --experimental-
// strip-types` can run the tree directly for dev, tests and the resolve
// CLI. tsc rewrites them to `.js` on the way into dist.
// The client-side scheme table is plain JS, because the browser loads it
// as-is out of `public`. Its types are inferred so the test can check it.
"allowJs": true,
"allowImportingTsExtensions": true,
"rewriteRelativeImportExtensions": true,