├── .editorconfig ├── types ├── jquery-onmutate.d.ts ├── jquery-highlighter.d.ts ├── gm-compat.d.ts └── imdb-tomatoes.user.d.ts ├── src ├── lib │ ├── util.ts │ └── observer.ts ├── twitter-direct │ ├── twitter-direct-cli.ts │ ├── util.ts │ └── replacer.ts ├── twitter-zoom-cursor.css ├── pagerize_ebay.user.js ├── highlight_lobsters.user.js ├── highlight_echo_js.user.js ├── highlight-hacker-news.user.js ├── hacker_news_date_tooltips.user.js ├── more-tomatoes.user.ts ├── highlight_reddit.user.js ├── pagerize_metafilter.user.js ├── pagerize_amazon.user.js ├── highlight_digg.user.js ├── pagerize_ars_technica.user.js ├── imdb-full-summary.user.ts ├── iso_8601_dates.user.js ├── github-my-issues.user.ts ├── reddit_toggle_custom_css.user.js ├── google-dwimages.user.ts ├── github-first-commit.user.ts ├── last_picture_show.user.js ├── twitter-direct.user.ts ├── amazon-international-links.user.js └── twitter-linkify-trends.user.ts ├── Makefile ├── dist ├── more-tomatoes.user.js ├── imdb-full-summary.user.js ├── github-my-issues.user.js ├── github-first-commit.user.js ├── google-dwimages.user.js ├── twitter-linkify-trends.user.js └── twitter-direct.user.js ├── package.json ├── tsconfig.json ├── README.md └── LICENSE.md /.editorconfig: -------------------------------------------------------------------------------- 1 | # https://EditorConfig.org 2 | 3 | # is this the topmost EditorConfig file? 4 | root = true 5 | 6 | [*] 7 | charset = utf-8 8 | end_of_line = lf 9 | indent_style = space 10 | insert_final_newline = true 11 | trim_trailing_whitespaces = true 12 | 13 | [*.{js,ts}] 14 | indent_size = 4 15 | max_line_length = 80 16 | quote_type = single 17 | 18 | [*.{yml,yaml}] 19 | indent_size = 2 20 | max_line_length = 80 21 | -------------------------------------------------------------------------------- /types/jquery-onmutate.d.ts: -------------------------------------------------------------------------------- 1 | import JQuery = require('jquery') 2 | 3 | declare global { 4 | interface JQueryStatic { 5 | onCreate (selector: JQuery.Selector, callback: ($results: JQuery) => void, multi?: boolean): void; 6 | } 7 | 8 | interface JQuery { 9 | onCreate (selector: JQuery.Selector, callback: ($results: JQuery) => void, multi?: boolean): void; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/lib/util.ts: -------------------------------------------------------------------------------- 1 | export type Json = 2 | | null 3 | | boolean 4 | | number 5 | | string 6 | | Json[] 7 | | { [key: string]: Json }; 8 | 9 | export type Maybe = T | null | undefined; 10 | 11 | export const constant = (value: T) => (..._args: unknown[]) => value 12 | export const pipe = (value: T, fn: (value: T) => U) => fn(value) 13 | export const tap = (value: T, fn: (value: T) => void) => (fn(value), value) 14 | -------------------------------------------------------------------------------- /src/twitter-direct/twitter-direct-cli.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bun 2 | 3 | /// 4 | 5 | // run the URL replacer on a local JSON file 6 | // 7 | // usage: 8 | // 9 | // twitter-direct-cli.ts /path/to/response.json 10 | 11 | import Replacer from './replacer' 12 | 13 | const path = process.argv[2] 14 | const file = Bun.file(path) 15 | const data = await file.json() 16 | const count = Replacer.transform(data, path) 17 | const urls = count === 1 ? 'url' : 'urls' 18 | 19 | console.log(`replaced ${count} ${urls} in ${path}`) 20 | -------------------------------------------------------------------------------- /src/twitter-zoom-cursor.css: -------------------------------------------------------------------------------- 1 | /* ==UserStyle== 2 | @name Twitter Zoom Cursor 3 | @description Distinguish between images and links on Twitter 4 | @author chocolateboy 5 | @copyright chocolateboy 6 | @version 0.1.0 7 | @namespace https://github.com/chocolateboy/userscripts 8 | @license GPL 9 | ==/UserStyle== */ 10 | 11 | @-moz-document url-prefix("https://twitter.com/"), url-prefix("https://mobile.twitter.com/"), url-prefix("https://x.com/"), url-prefix("https://mobile.x.com/") { 12 | a[role="link"][href^="/"][href$="/photo/1"], 13 | a[role="link"][href^="/"][href$="/photo/2"], 14 | a[role="link"][href^="/"][href$="/photo/3"], 15 | a[role="link"][href^="/"][href$="/photo/4"] { 16 | cursor: zoom-in !important; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/pagerize_ebay.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Pagerize eBay 3 | // @description Mark up eBay search results with pager metadata 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 0.2.2 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include http://*.ebay.tld/* 10 | // @include https://*.ebay.tld/* 11 | // @require https://code.jquery.com/jquery-3.5.1.slim.min.js 12 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-pagerizer@v1.0.0/dist/pagerizer.min.js 13 | // @grant GM_log 14 | // ==/UserScript== 15 | 16 | // XXX note: the unused grant is a workaround for a Greasemonkey bug: 17 | // https://github.com/greasemonkey/greasemonkey/issues/1614 18 | 19 | $('a.gspr.prev').addRel('prev'); 20 | $('a.gspr.next').addRel('next'); 21 | -------------------------------------------------------------------------------- /types/jquery-highlighter.d.ts: -------------------------------------------------------------------------------- 1 | import JQuery = require('jquery') 2 | 3 | type JQueryHighlighterOptions = { 4 | cache?: boolean; 5 | color?: string; 6 | debug?: boolean; 7 | dedup?: boolean; 8 | id?: string | ((this: T, target: JQuery) => string); 9 | item: string | (() => Iterable); 10 | onHighlight?: ((this: T, target: JQuery, options: { id: string, color: string }) => void); 11 | target?: string | ((this: T, item: U) => JQuery); 12 | ttl?: Record; 13 | } 14 | 15 | declare global { 16 | interface JQueryStatic { 17 | highlight: { 18 | (options: JQueryHighlighterOptions): Promise; 19 | className: string; 20 | selector: string; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/highlight_lobsters.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Lobsters Highlighter 3 | // @description Highlight new stories on Lobsters 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.0.1 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include https://lobste.rs/ 10 | // @include /^https://lobste\.rs/(newest|page|recent|t)\b/ 11 | // @require https://code.jquery.com/jquery-3.5.1.slim.min.js 12 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-highlighter@63adeb7dea43c47e210fd17b0589e648239e97f0/dist/highlighter.min.js 13 | // @grant GM_deleteValue 14 | // @grant GM_getValue 15 | // @grant GM_listValues 16 | // @grant GM_registerMenuCommand 17 | // @grant GM_setValue 18 | // ==/UserScript== 19 | 20 | $.highlight({ item: 'li.story', target: '.link a' }) 21 | -------------------------------------------------------------------------------- /src/highlight_echo_js.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Echo JS Highlighter 3 | // @description Highlight new stories on Echo JS 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.0.1 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include https://echojs.com/ 10 | // @include http://www.echojs.com/ 11 | // @include https://www.echojs.com/ 12 | // @require https://code.jquery.com/jquery-3.5.1.slim.min.js 13 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-highlighter@63adeb7dea43c47e210fd17b0589e648239e97f0/dist/highlighter.min.js 14 | // @grant GM_deleteValue 15 | // @grant GM_getValue 16 | // @grant GM_listValues 17 | // @grant GM_registerMenuCommand 18 | // @grant GM_setValue 19 | // ==/UserScript== 20 | 21 | $.highlight({ 22 | item: 'article[data-news-id]', 23 | target: 'h2 a', 24 | id: 'data-news-id', 25 | color: '#FFFFAB', 26 | ttl: { days: 28 } 27 | }); 28 | -------------------------------------------------------------------------------- /src/highlight-hacker-news.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Hacker News Highlighter 3 | // @description Highlight new stories on Hacker News 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.3.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://news.ycombinator.com/ 10 | // @include https://news.ycombinator.com/?p=* 11 | // @include /^https://news\.ycombinator\.com/(active|ask|best|front|newest|news|noobstories|show|shownew)\b/ 12 | // @require https://code.jquery.com/jquery-3.7.1.slim.min.js 13 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-highlighter@63adeb7dea43c47e210fd17b0589e648239e97f0/dist/highlighter.min.js 14 | // @grant GM_deleteValue 15 | // @grant GM_getValue 16 | // @grant GM_listValues 17 | // @grant GM_registerMenuCommand 18 | // @grant GM_setValue 19 | // ==/UserScript== 20 | 21 | $.highlight({ 22 | item: 'tr.athing[id]:has(> td.votelinks)', 23 | target: 'td.title .titleline > a[href]', 24 | }) 25 | -------------------------------------------------------------------------------- /src/hacker_news_date_tooltips.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Hacker News Date Tooltips 3 | // @description Deobfuscate the "n days ago" dates on Hacker News with YYYY-MM-DD tooltips 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.1.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include https://news.ycombinator.com/* 10 | // @require https://cdn.jsdelivr.net/npm/cash-dom@8.1.0/dist/cash.min.js 11 | // @require https://unpkg.com/dayjs@1.10.4/dayjs.min.js 12 | // @grant GM_log 13 | // ==/UserScript== 14 | 15 | const DATES = 'span.age a' 16 | const DELTA = 1, UNIT = 2 17 | 18 | function isoDate (ago) { 19 | const match = ago.match(/^(\d+)\s+(\w+)\s+ago$/) 20 | 21 | return match 22 | ? dayjs().subtract(match[DELTA], match[UNIT]).format('YYYY-MM-DD') 23 | : null 24 | } 25 | 26 | $(DATES).each(function () { 27 | const $this = $(this) 28 | const ago = $this.text().trim() 29 | const date = isoDate(ago) 30 | 31 | if (date) { 32 | $this.attr('title', date) 33 | } 34 | }) 35 | -------------------------------------------------------------------------------- /src/more-tomatoes.user.ts: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name More Tomatoes 3 | // @description Automatically show the full "Movie Info" plot synopsis on Rotten Tomatoes 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 2.0.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include http://rottentomatoes.com/m/* 10 | // @include http://*.rottentomatoes.com/m/* 11 | // @include https://rottentomatoes.com/m/* 12 | // @include https://*.rottentomatoes.com/m/* 13 | // @run-at document-start 14 | // @grant none 15 | // ==/UserScript== 16 | 17 | const run = () => { 18 | const synopsis = document.querySelector('[data-qa="section:media-scorecard"]') 19 | 20 | if (!synopsis) { 21 | return 22 | } 23 | 24 | const readLess = synopsis.querySelector('[slot="ctaClose"]') 25 | 26 | if (readLess) { 27 | readLess.style.display = 'none' 28 | } 29 | 30 | const readMore = synopsis.querySelector('[slot="ctaOpen"]') 31 | 32 | if (readMore) { 33 | readMore.click() 34 | } 35 | } 36 | 37 | window.addEventListener('load', run) 38 | -------------------------------------------------------------------------------- /src/highlight_reddit.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Reddit Highlighter 3 | // @description Highlight new stories on Reddit 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.2.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include https://*.reddit.com/ 10 | // @include https://*.reddit.com/?count=* 11 | // @include https://*.reddit.com/user/*/m/* 12 | // @include /^https://[^.]+\.reddit\.com/(r/[^/]+/)?($|(best|controversial|hot|new|rising|top)/)/ 13 | // @require https://code.jquery.com/jquery-3.5.1.slim.min.js 14 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-highlighter@63adeb7dea43c47e210fd17b0589e648239e97f0/dist/highlighter.min.js 15 | // @grant GM_deleteValue 16 | // @grant GM_getValue 17 | // @grant GM_listValues 18 | // @grant GM_registerMenuCommand 19 | // @grant GM_setValue 20 | // ==/UserScript== 21 | 22 | $.highlight({ 23 | item: 'div#siteTable div.thing[data-fullname]', 24 | target: 'a.title', 25 | id: 'data-fullname', 26 | ttl: { days: 30 }, 27 | }) 28 | -------------------------------------------------------------------------------- /types/gm-compat.d.ts: -------------------------------------------------------------------------------- 1 | // XXX temporary until the next gm-compat release 2 | 3 | export type CloneIntoOptions = { 4 | cloneFunctions?: boolean; 5 | target?: object; 6 | wrapReflectors?: boolean; 7 | }; 8 | 9 | export type ExportOptions = { 10 | target?: object; 11 | }; 12 | 13 | export type ExportFunctionOptions = { 14 | allowCrossOriginArguments?: boolean; 15 | defineAs?: string; 16 | target?: object; 17 | }; 18 | 19 | export interface GMCompatApply { 20 | ($this: T, fn: ((this: T, ...args: any[]) => R), args: A): R; 21 | ($this: T, fn: ((this: T, ...args: A) => R), args: A): R; 22 | } 23 | 24 | interface GMCompatAPI { 25 | readonly apply: GMCompatApply; 26 | readonly call: ($this: T, fn: ((this: T, ...args: A) => R), ...args: A) => R; 27 | readonly cloneInto: (object: T, options?: CloneIntoOptions) => T; 28 | readonly export: (value: T, options?: ExportOptions) => T; 29 | readonly exportFunction: (fn: T, options?: ExportFunctionOptions) => T; 30 | readonly unsafeWindow: typeof window; 31 | readonly unwrap: (object: T) => T; 32 | } 33 | 34 | declare global { 35 | const GMCompat: GMCompatAPI; 36 | } 37 | -------------------------------------------------------------------------------- /src/pagerize_metafilter.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Pagerize MetaFilter 3 | // @description Mark up MetaFilter with pager metadata 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 0.6.2 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include http://*.metafilter.com/* 10 | // @include http://metafilter.com/* 11 | // @include https://*.metafilter.com/* 12 | // @include https://metafilter.com/* 13 | // @require https://code.jquery.com/jquery-3.5.1.slim.min.js 14 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-pagerizer@v1.0.0/dist/pagerizer.min.js 15 | // @grant GM_log 16 | // ==/UserScript== 17 | 18 | // XXX note: the unused grant is a workaround for a Greasemonkey bug: 19 | // https://github.com/greasemonkey/greasemonkey/issues/1614 20 | 21 | /* 22 |

23 | « 24 | Older posts 25 | | 26 | Newer posts 27 | » 28 |

29 | */ 30 | 31 | var $links = $('p.copy').not('.whitesmallcopy').find('a[href]') 32 | 33 | $links.eq(0).addRel('prev') 34 | $links.eq(1).addRel('next') 35 | -------------------------------------------------------------------------------- /src/pagerize_amazon.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Pagerize Amazon 3 | // @description Mark up Amazon search results with pager metadata 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 0.1.2 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include http://*.amazon.tld/* 10 | // @include https://*.amazon.tld/* 11 | // @require https://code.jquery.com/jquery-3.5.1.slim.min.js 12 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-pagerizer@v1.0.0/dist/pagerizer.min.js 13 | // @require https://cdn.jsdelivr.net/gh/eclecto/jQuery-onMutate@79bbb2b8caccabfc9b9ade046fe63f15f593fef6/src/jquery.onmutate.min.js 14 | // @grant GM_log 15 | // ==/UserScript== 16 | 17 | // XXX note: the unused grant is a workaround for a Greasemonkey bug: 18 | // https://github.com/greasemonkey/greasemonkey/issues/1614 19 | 20 | // union the selectors to work around a jQuery-onMutate bug: 21 | // https://github.com/eclecto/jQuery-onMutate/issues/18 22 | 23 | function onLinks ($links) { 24 | $links.filter('a#pagnPrevLink').addRel('prev'); 25 | $links.filter('a#pagnNextLink').addRel('next'); 26 | } 27 | 28 | $.onCreate('a#pagnPrevLink, a#pagnNextLink', onLinks, true /* multi */); 29 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ##################################################### 2 | # strict mode: https://tech.davis-hansson.com/p/make/ 3 | 4 | SHELL := bash 5 | MAKEFLAGS += --warn-undefined-variables 6 | MAKEFLAGS += --no-builtin-rules 7 | 8 | .DELETE_ON_ERROR: 9 | .ONESHELL: 10 | .SHELLFLAGS := -eu -o pipefail -c 11 | 12 | ##################################################### 13 | 14 | BIN := ./node_modules/.bin 15 | BUILD := ./build 16 | BANNER := $(BUILD)/mk-banner.bash 17 | 18 | ESBUILD := esbuild --bundle --charset=utf8 --format=iife --legal-comments=inline --log-level=warning --outdir=./dist 19 | SOURCES := $(wildcard src/*.user.ts) 20 | TARGETS := $(patsubst src/%.ts,dist/%.js,$(SOURCES)) 21 | 22 | .PHONY: build 23 | build: $(TARGETS) 24 | 25 | .PHONY: build-doc 26 | build-doc: README.md 27 | $(BIN)/toc-md README.md 28 | 29 | dist/%.js: src/%.ts $(BANNER) 30 | @banner=$$($(BANNER) $<)$$'\n' 31 | command="$(ESBUILD) --banner:js=\"\$$banner\" $<" 32 | echo $$command 33 | eval $$command 34 | 35 | .PHONY: clean 36 | clean: 37 | rm -rf ./dist 38 | 39 | .PHONY: rebuild 40 | rebuild: clean build 41 | 42 | .PHONY: typecheck 43 | typecheck: 44 | $(BIN)/tsc-files --noEmit --noImplicitAny --noUnusedLocals --noUnusedParameters --strict src/**/*.ts 45 | 46 | # http://blog.melski.net/2010/11/30/makefile-hacks-print-the-value-of-any-variable/ 47 | print-%: 48 | @echo '$*=$($*)' 49 | -------------------------------------------------------------------------------- /dist/more-tomatoes.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name More Tomatoes 3 | // @description Automatically show the full "Movie Info" plot synopsis on Rotten Tomatoes 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 2.0.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include http://rottentomatoes.com/m/* 10 | // @include http://*.rottentomatoes.com/m/* 11 | // @include https://rottentomatoes.com/m/* 12 | // @include https://*.rottentomatoes.com/m/* 13 | // @run-at document-start 14 | // @grant none 15 | // ==/UserScript== 16 | 17 | // NOTE This file is generated from src/more-tomatoes.user.ts and should not be edited directly. 18 | 19 | "use strict"; 20 | (() => { 21 | // src/more-tomatoes.user.ts 22 | // @license GPL 23 | var run = () => { 24 | const synopsis = document.querySelector('[data-qa="section:media-scorecard"]'); 25 | if (!synopsis) { 26 | return; 27 | } 28 | const readLess = synopsis.querySelector('[slot="ctaClose"]'); 29 | if (readLess) { 30 | readLess.style.display = "none"; 31 | } 32 | const readMore = synopsis.querySelector('[slot="ctaOpen"]'); 33 | if (readMore) { 34 | readMore.click(); 35 | } 36 | }; 37 | window.addEventListener("load", run); 38 | })(); 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "userscripts", 3 | "version": "1.1.0", 4 | "description": "Userscripts for Greasemonkey, Tampermonkey etc.", 5 | "main": "index.js", 6 | "repository": "https://github.com/chocolateboy/userscripts", 7 | "author": "chocolateboy", 8 | "license": "GPL", 9 | "private": true, 10 | "sideEffects": false, 11 | "scripts": { 12 | "build": "make", 13 | "build:doc": "toc-md README.md", 14 | "clean": "make clean", 15 | "rebuild": "make clean build", 16 | "typecheck": "make typecheck" 17 | }, 18 | "browserslist": [ 19 | "Firefox ESR", 20 | "Last 2 Chrome versions" 21 | ], 22 | "devDependencies": { 23 | "@chocolateboy/uncommonjs": "^3.2.1", 24 | "@types/bun": "^1.0.8", 25 | "@types/greasemonkey": "^4.0.4", 26 | "@types/jquery": "^3.5.16", 27 | "@types/node": "^18.15.11", 28 | "@types/shelljs": "^0.8.11", 29 | "@types/tampermonkey": "^4.0.10", 30 | "cash-dom": "^8.1.4", 31 | "cross-env": "^7.0.3", 32 | "crypto-hash": "^2.0.1", 33 | "dayjs": "^1.11.7", 34 | "flru": "^1.0.2", 35 | "get-wild": "^3.0.2", 36 | "gm-storage": "^2.0.3", 37 | "little-emitter": "^0.3.5", 38 | "npm-run-all": "^4.1.5", 39 | "shx": "^0.3.4", 40 | "toc-md-alt": "^0.4.6", 41 | "tsc-files": "^1.1.3", 42 | "typescript": "^5.0.4" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/twitter-direct/util.ts: -------------------------------------------------------------------------------- 1 | export type Json = 2 | | null 3 | | boolean 4 | | number 5 | | string 6 | | Array 7 | | { [key: string]: Json }; 8 | 9 | export type Dict = Record; 10 | export type JsonObject = Dict | Array; 11 | 12 | type TypeMap = { 13 | 'bigint': bigint; 14 | 'boolean': boolean; 15 | 'function': Function; 16 | 'null': null; 17 | 'number': number; 18 | 'object': object; 19 | 'string': string; 20 | 'symbol': symbol; 21 | 'undefined': undefined; 22 | } 23 | 24 | /* 25 | * return true if the supplied value is an array or plain object, false otherwise 26 | */ 27 | export const isObject = (value: unknown): value is JsonObject => !!value && (typeof value === 'object') 28 | 29 | /* 30 | * return true if the supplied value is a plain object, false otherwise 31 | * 32 | * only used with JSON data, so doesn't need to be foolproof 33 | */ 34 | export const isPlainObject = (function () { 35 | const toString = {}.toString 36 | return (value: unknown): value is Dict => toString.call(value) === '[object Object]' 37 | })() 38 | 39 | const typeOf = (value: unknown) => value === null ? 'null' : typeof value 40 | 41 | const isType = (type: T) => { 42 | return (value: unknown): value is U => { 43 | return typeOf(value) === type 44 | } 45 | } 46 | 47 | export const isString = isType('string') 48 | export const isNumber = isType('number') 49 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "allowSyntheticDefaultImports": true, 5 | "alwaysStrict": true, 6 | "baseUrl": "./", 7 | "checkJs": true, 8 | "declarationMap": false, 9 | "declaration": true, 10 | "downlevelIteration": true, 11 | "esModuleInterop": true, 12 | "experimentalDecorators": true, 13 | "extendedDiagnostics": true, 14 | "isolatedModules": true, 15 | "lib": ["ESNext", "DOM", "DOM.Iterable"], 16 | "moduleDetection": "force", 17 | "module": "ESNext", 18 | "moduleResolution": "bundler", 19 | "noEmit": true, 20 | "newLine": "LF", 21 | "noFallthroughCasesInSwitch": true, 22 | "noImplicitAny": true, 23 | "noImplicitReturns": true, 24 | "noImplicitThis": true, 25 | "noUncheckedIndexedAccess": false, 26 | "noUnusedLocals": true, 27 | "noUnusedParameters": true, 28 | "outDir": "dist", 29 | "removeComments": false, 30 | "resolveJsonModule": true, 31 | "sourceMap": true, 32 | "strict": true, 33 | "target": "ESNext", 34 | "typeRoots": ["node_modules/@types"], 35 | "types": ["tampermonkey"], 36 | "useUnknownInCatchVariables": false 37 | }, 38 | "typeAcquisition": { 39 | "enable": false, 40 | "disableFilenameBasedTypeAcquisition": true 41 | }, 42 | "include": [ 43 | "src/**/*.ts", 44 | ] 45 | } 46 | -------------------------------------------------------------------------------- /src/highlight_digg.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Digg Highlighter 3 | // @description Highlight new stories on Digg 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.2.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://digg.com/ 10 | // @require https://code.jquery.com/jquery-3.6.0.slim.min.js 11 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-highlighter@63adeb7dea43c47e210fd17b0589e648239e97f0/dist/highlighter.min.js 12 | // @grant GM_deleteValue 13 | // @grant GM_getValue 14 | // @grant GM_listValues 15 | // @grant GM_registerMenuCommand 16 | // @grant GM_setValue 17 | // ==/UserScript== 18 | 19 | const PROMO_CHANNELS = [ 20 | '/advertising', 21 | 'apps-we-digg', 22 | 'digg-pick', 23 | 'digg-store', 24 | 'gift-guides', 25 | 'promotion', 26 | ] 27 | 28 | const PROMO_SELECTOR = PROMO_CHANNELS 29 | .map(name => { 30 | const href = name.startsWith('/') ? name : `/channel/${name}` 31 | return `a[itemprop="keywords"][href="${href}"]` 32 | }) 33 | .join(', ') 34 | 35 | /** 36 | * @this {JQuery} 37 | */ 38 | function isArticle () { 39 | return !$(this).find(PROMO_SELECTOR).length 40 | } 41 | 42 | $.highlight({ 43 | ttl: { days: 4 }, 44 | item () { 45 | return $('article[data-id]').has('[itemprop="headline"]').filter(isArticle) 46 | }, 47 | target: '[itemprop="headline"]', 48 | id: 'data-id' 49 | }) 50 | -------------------------------------------------------------------------------- /dist/imdb-full-summary.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name IMDb Full Summary 3 | // @description Automatically show the full plot summary on IMDb 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 3.1.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include /^https://www\.imdb\.com(/[^/]+)?/title/tt[0-9]+(/([#?].*)?)?$/ 10 | // @run-at document-start 11 | // @grant none 12 | // ==/UserScript== 13 | 14 | // NOTE This file is generated from src/imdb-full-summary.user.ts and should not be edited directly. 15 | 16 | "use strict"; 17 | (() => { 18 | // src/imdb-full-summary.user.ts 19 | // @license GPL 20 | var $ = document; 21 | var init = { childList: true }; 22 | var run = () => { 23 | let summary = ""; 24 | try { 25 | const { textContent: metadata } = $.getElementById("__NEXT_DATA__"); 26 | summary = JSON.parse(metadata).props.pageProps.aboveTheFoldData.plot.plotText.plainText; 27 | } catch (e) { 28 | console.warn("Can't extract summary from JSON metadata:", e.message); 29 | } 30 | if (!summary) { 31 | return; 32 | } 33 | for (const target of $.querySelectorAll('[data-testid="plot"] [data-testid^="plot-"]')) { 34 | const callback = () => { 35 | observer.disconnect(); 36 | target.textContent = summary; 37 | observer.observe(target, init); 38 | }; 39 | const observer = new MutationObserver(callback); 40 | callback(); 41 | } 42 | }; 43 | $.addEventListener("readystatechange", run, { once: true }); 44 | })(); 45 | -------------------------------------------------------------------------------- /src/lib/observer.ts: -------------------------------------------------------------------------------- 1 | import { constant } from './util' 2 | 3 | export type ObserverCallbackState = { 4 | mutations: MutationRecord[]; 5 | observer: MutationObserver; 6 | target: T; 7 | } 8 | 9 | export type ObserverCallback = (state: ObserverCallbackState) => unknown; 10 | 11 | interface Observe { 12 | (target: T, init: MutationObserverInit, callback: ObserverCallback): MutationObserver; 13 | (target: T, callback: ObserverCallback): MutationObserver; 14 | (init: MutationObserverInit, callback: ObserverCallback): MutationObserver; 15 | (callback: ObserverCallback): MutationObserver; 16 | } 17 | 18 | type ObserveArgs = 19 | | [Element, MutationObserverInit, ObserverCallback] 20 | | [Element, ObserverCallback] 21 | | [MutationObserverInit, ObserverCallback] 22 | | [ObserverCallback] 23 | 24 | const INIT: MutationObserverInit = { childList: true, subtree: true } 25 | 26 | export const done = constant(false) 27 | export const resume = constant(true) 28 | 29 | // a Mutation Observer wrapper without the boilerplate 30 | export const observe = ((...args: ObserveArgs) => { 31 | const [target, init, callback] = 32 | args.length === 3 ? args : 33 | args.length === 2 ? ( 34 | args[0] instanceof Element ? 35 | [args[0], INIT, args[1]] : 36 | [document.body, args[0], args[1]] 37 | ) : 38 | [document.body, INIT, args[0]] 39 | 40 | const onMutate: MutationCallback = (mutations, observer) => { 41 | observer.disconnect() 42 | 43 | const resume = callback({ mutations, observer, target }) 44 | 45 | if (resume !== false) { 46 | observer.observe(target, init) 47 | } 48 | } 49 | 50 | const observer = new MutationObserver(onMutate) 51 | 52 | queueMicrotask(() => onMutate([], observer)) 53 | 54 | return observer 55 | }) 56 | -------------------------------------------------------------------------------- /types/imdb-tomatoes.user.d.ts: -------------------------------------------------------------------------------- 1 | import DayJs from 'dayjs' 2 | import DayJsRelativeTime from 'dayjs/plugin/relativeTime' 3 | 4 | declare global { 5 | const dayjs: typeof DayJs; 6 | const dayjs_plugin_relativeTime: typeof DayJsRelativeTime; 7 | 8 | type DayJs = DayJs.Dayjs; 9 | 10 | interface JQuery { 11 | balloon: (options: any) => this; 12 | } 13 | 14 | type AsyncGetOptions = { 15 | params?: Record; 16 | title?: string; 17 | request?: Partial; 18 | }; 19 | 20 | type LinkTarget = '_self' | '_blank'; 21 | type Falsey = null | undefined | '' | false | 0; 22 | type Maybe = T | Falsey; 23 | type IsTruthy = (value: Maybe) => value is T; 24 | 25 | namespace WaitFor { 26 | type Callback = (timeout: () => boolean, id: string) => void; 27 | type Checker = (state: State) => Maybe; 28 | type Id = string | number | bigint; 29 | type State = { tick: number, time: number, id: string }; 30 | 31 | interface WaitFor { 32 | (id: Id, callback: Callback, checker: Checker): Promise; 33 | (callback: Callback, checker: Checker): Promise; 34 | (id: Id, checker: Checker): Promise; 35 | (checker: Checker): Promise; 36 | } 37 | } 38 | 39 | type RTResult = { 40 | title: string; 41 | vanity: string; 42 | releaseYear: string; 43 | updateDate: string; 44 | cast?: Array<{ name: string }>; 45 | rottenTomatoes?: { criticsScore?: number }; 46 | pageViews_popularity?: number; 47 | aka?: string[]; 48 | }; 49 | 50 | type RTDoc = JQuery & { 51 | meta: any; 52 | document: Document; 53 | }; 54 | 55 | type RTMatch = { 56 | rating: number | undefined; 57 | url: string; 58 | verify?: ($rt: RTDoc) => boolean; 59 | }; 60 | 61 | type RTTVResult = RTResult & { 62 | seasons: number[]; 63 | seriesFinale?: string; 64 | seriesPremiere?: string; 65 | }; 66 | 67 | type RTMovieResult = RTResult; 68 | 69 | type RTState = { 70 | targetUrl: string | null; 71 | url: string; 72 | }; 73 | } 74 | -------------------------------------------------------------------------------- /src/pagerize_ars_technica.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Pagerize Ars Technica 3 | // @description Mark up Ars Technica with pager metadata 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 0.6.3 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include http://arstechnica.com/* 10 | // @include http://*.arstechnica.com/* 11 | // @include https://arstechnica.com/* 12 | // @include https://*.arstechnica.com/* 13 | // @require https://code.jquery.com/jquery-3.5.1.slim.min.js 14 | // @require https://cdn.jsdelivr.net/gh/chocolateboy/jquery-pagerizer@v1.0.0/dist/pagerizer.min.js 15 | // @grant GM_log 16 | // ==/UserScript== 17 | 18 | // XXX note: the unused grant is a workaround for a Greasemonkey bug: 19 | // https://github.com/greasemonkey/greasemonkey/issues/1614 20 | 21 | /* 22 | https://arstechnica.com/information-technology/2010/01/video-editing-in-linux-a-look-at-pitivi-and-kdenlive/2/ 23 | 24 | 36 | */ 37 | 38 | var $navbar = $('nav.page-numbers span.numbers'); 39 | var $pageNumber = $navbar.contents().filter(function () { 40 | return this.nodeType === 3 && $.trim(this.nodeValue).match(/^\d+$/) 41 | }); 42 | 43 | if ($pageNumber.prev().length) { 44 | // remove the rel from the "Previous Story" link 45 | $('a[rel="prev"], a[rel="previous"]').removeRel('prev', 'previous'); 46 | // use "previous" rather than "prev" (or both) to work around a bug in Vimperator: 47 | // https://github.com/vimperator/vimperator-labs/pull/570 48 | $pageNumber.prev().addRel('previous'); 49 | } 50 | 51 | if ($pageNumber.next().length) { 52 | // remove the rel from the "Next Story" link 53 | $('a[rel="next"]').removeRel('next'); 54 | $pageNumber.next().addRel('next'); 55 | } 56 | -------------------------------------------------------------------------------- /src/imdb-full-summary.user.ts: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name IMDb Full Summary 3 | // @description Automatically show the full plot summary on IMDb 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 3.1.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include /^https://www\.imdb\.com(/[^/]+)?/title/tt[0-9]+(/([#?].*)?)?$/ 10 | // @run-at document-start 11 | // @grant none 12 | // ==/UserScript== 13 | 14 | /* 15 | * Tests: 16 | * 17 | * - movie: https://www.imdb.com/title/tt7638460/ 18 | * - TV show: https://www.imdb.com/title/tt0108983/ 19 | */ 20 | 21 | const $ = document 22 | const init: MutationObserverInit = { childList: true } 23 | 24 | const run = () => { 25 | let summary = '' 26 | 27 | // get the summary from the props (JSON) embedded in the page 28 | try { 29 | const { textContent: metadata } = $.getElementById('__NEXT_DATA__')! 30 | summary = JSON.parse(metadata!).props.pageProps.aboveTheFoldData.plot.plotText.plainText 31 | } catch (e: unknown) { 32 | console.warn("Can't extract summary from JSON metadata:", (e as Error).message) 33 | } 34 | 35 | if (!summary) { 36 | return 37 | } 38 | 39 | // each child of the plot element is a summary element which is displayed 40 | // for a different display size, e.g. plot-xl for desktop, plot-l for 41 | // tablets, and plot-xs_to_m for mobile. changing the display size selects a 42 | // different summary element. 43 | for (const target of $.querySelectorAll('[data-testid="plot"] [data-testid^="plot-"]')) { 44 | // replace the truncated summary with the full version and revert 45 | // React's attempts to reinstate the original (reconciliation) 46 | const callback = () => { 47 | observer.disconnect() 48 | target.textContent = summary 49 | observer.observe(target, init) 50 | } 51 | 52 | const observer = new MutationObserver(callback) 53 | 54 | callback() 55 | } 56 | } 57 | 58 | // the earliest event after the "static" parts of the page become visible. 59 | // this occurs when document.readyState transitions from "loading" to 60 | // "interactive", which should be the first readystatechange event a userscript 61 | // sees. on my system, this can occur up to 4 seconds before DOMContentLoaded. 62 | // 63 | // NOTE: this means we can't extract the summary from the (lazy) "storyline" 64 | // element as it's not available yet. 65 | $.addEventListener('readystatechange', run, { once: true }) 66 | -------------------------------------------------------------------------------- /dist/github-my-issues.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name GitHub My Issues 3 | // @description Add a contextual link to issues you've contributed to on GitHub 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 2.1.1 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://github.com/ 10 | // @include https://github.com/* 11 | // @require https://cdn.jsdelivr.net/npm/cash-dom@8.1.5/dist/cash.min.js 12 | // @grant GM_addStyle 13 | // @run-at document-start 14 | // ==/UserScript== 15 | 16 | // NOTE This file is generated from src/github-my-issues.user.ts and should not be edited directly. 17 | 18 | "use strict"; 19 | (() => { 20 | // src/github-my-issues.user.ts 21 | // @license GPL 22 | var ID = "my-issues-tab"; 23 | var ISSUES_LINK = "a#issues-tab"; 24 | var MY_ISSUES = "My Issues"; 25 | var MY_ISSUES_LINK = `li a#${ID}`; 26 | var run = () => { 27 | $(MY_ISSUES_LINK).closest("li").remove(); 28 | const $issuesLink = $(`li ${ISSUES_LINK}`); 29 | const $issues = $issuesLink.closest("li"); 30 | if ($issues.length !== 1) { 31 | return; 32 | } 33 | const self = $('meta[name="user-login"]').attr("content"); 34 | const repo = $("[data-current-repository]").data("currentRepository"); 35 | const user = repo?.split("/")?.at(0); 36 | if (!(self && repo && user)) { 37 | return; 38 | } 39 | const myIssues = `involves:${self}`; 40 | const subqueries = [myIssues, "sort:updated-desc"]; 41 | if (user === self) { 42 | subqueries.unshift("is:open", "archived:false"); 43 | } 44 | const query = subqueries.join("+"); 45 | const path = `/${repo}/issues`; 46 | const href = `${path}?q=${escape(query)}`; 47 | const $myIssues = $issues.clone(); 48 | const $link = $myIssues.find(`:scope ${ISSUES_LINK}`).removeClass("selected deselected").attr({ 49 | id: ID, 50 | role: "tab", 51 | href, 52 | "aria-current": null, 53 | "data-hotkey": "g I", 54 | "data-selected-links": null 55 | }); 56 | $link.find(':scope [data-content="Issues"]').text(MY_ISSUES); 57 | $link.find(':scope [id="issues-repo-tab-count"]').remove(); 58 | let q = null; 59 | if (location.pathname === path) { 60 | const params = new URLSearchParams(location.search); 61 | q = params.get("q"); 62 | } 63 | if (q && q.trim().split(/\s+/).includes(myIssues)) { 64 | $link.attr("aria-selected", "true"); 65 | $issuesLink.addClass("deselected"); 66 | } else { 67 | $link.attr("aria-selected", "false"); 68 | $issuesLink.removeClass("deselected"); 69 | } 70 | $issues.after($myIssues); 71 | }; 72 | GM_addStyle(` 73 | .deselected::after { 74 | background: transparent !important; 75 | } 76 | `); 77 | $(document).on("turbo:load", run); 78 | })(); 79 | -------------------------------------------------------------------------------- /src/iso_8601_dates.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name ISO 8601 Dates 3 | // @description Display US dates in the ISO 8601 YYYY-MM-DD format 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.2.3 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @exclude * 10 | // @grant GM_registerMenuCommand 11 | // ==/UserScript== 12 | 13 | var XPATH = '//body//text()'; 14 | var DATE = new RegExp( 15 | '(?:\\b(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])-(\\d{4}|\\d{2})\\b(?!-))' 16 | + '|' 17 | + '(?:\\b(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/(\\d{4}|\\d{2})\\b(?!/))', 18 | 'g' 19 | ); 20 | 21 | // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 22 | var days = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]; 23 | 24 | function leap_year (year) { 25 | if ((year % 400) === 0) { // multiples of 400 are leap years 26 | return true; 27 | } else if ((year % 100) === 0) { // the remaining multiples of 100 are not leap years 28 | return false; 29 | } else if ((year % 4) === 0) { // the remaining multiples of 4 are leap years 30 | return true; 31 | } else { // the rest are common years 32 | return false; 33 | } 34 | } 35 | 36 | // https://bugzilla.mozilla.org/show_bug.cgi?id=392378 37 | function replace (match, m1, d1, y1, m2, d2, y2, offset, string) { 38 | var year = y1 || y2; // depending on the above, non-matches are either empty or undefined, both of which are false 39 | var month = m1 || m2; 40 | var day = d1 || d2; 41 | 42 | // manual negative look-behind: see: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript 43 | if (offset > 0) { 44 | var prefix = string[offset - 1]; 45 | 46 | if ((prefix === '-') || (prefix === '/')) { 47 | return match; 48 | } 49 | } 50 | 51 | if (day > days[month - 1]) { 52 | return match; 53 | } 54 | 55 | if (year.length === 2) { 56 | // Internet Founding Fathers, forgive us. From the epoch to 1999, we knew not what to do... 57 | year = (((year >= 70) && (year <= 99)) ? '19' : '20') + year; 58 | } 59 | 60 | if ((month === '02') && (day === '29') && !leap_year(year)) { 61 | return match; 62 | } 63 | 64 | return year + '-' + month + '-' + day; 65 | } 66 | 67 | function fix_dates () { 68 | var nodes = document.evaluate(XPATH, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); 69 | 70 | for (var i = 0; i < nodes.snapshotLength; ++i) { 71 | var text = nodes.snapshotItem(i); 72 | text.data = text.data.replace(DATE, replace); 73 | } 74 | } 75 | 76 | // add a menu command for that pesky, hard-to-reach, lazily-loaded content 77 | GM_registerMenuCommand('ISO 8601 Dates', fix_dates); 78 | 79 | // run this script as late as possible to handle dynamically loaded content e.g. cracked.com 80 | window.addEventListener('load', fix_dates, false); 81 | -------------------------------------------------------------------------------- /dist/github-first-commit.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name GitHub First Commit 3 | // @description Add a link to a GitHub repo's first commit 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 4.0.3 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://github.com/ 10 | // @include https://github.com/* 11 | // @grant GM_log 12 | // @noframes 13 | // ==/UserScript== 14 | 15 | // NOTE This file is generated from src/github-first-commit.user.ts and should not be edited directly. 16 | 17 | "use strict"; 18 | (() => { 19 | // src/lib/util.ts 20 | var constant = (value) => (..._args) => value; 21 | 22 | // src/lib/observer.ts 23 | var INIT = { childList: true, subtree: true }; 24 | var done = constant(false); 25 | var resume = constant(true); 26 | var observe = (...args) => { 27 | const $2 = document; 28 | const [target, init, callback] = args.length === 3 ? args : args.length === 2 ? args[0] instanceof Element ? [args[0], INIT, args[1]] : [$2.body, args[0], args[1]] : [$2.body, INIT, args[0]]; 29 | const $callback = (mutations, observer2) => { 30 | observer2.disconnect(); 31 | const resume2 = callback({ mutations, observer: observer2, target, init }); 32 | if (resume2 !== false) { 33 | observer2.observe(target, init); 34 | } 35 | }; 36 | const observer = new MutationObserver($callback); 37 | queueMicrotask(() => $callback([], observer)); 38 | return observer; 39 | }; 40 | 41 | // src/github-first-commit.user.ts 42 | // @license GPL 43 | var ID = "first-commit"; 44 | var PATH = 'meta[name="analytics-location"][content]'; 45 | var REPO_PAGE = "//"; 46 | var USER_REPO = 'meta[name="octolytics-dimension-repository_network_root_nwo"][content]'; 47 | var $ = document; 48 | var openFirstCommit = (user, repo) => { 49 | return fetch(`https://api.github.com/repos/${user}/${repo}/commits`).then((res) => Promise.all([res.headers.get("link"), res.json()])).then(([link, commits]) => { 50 | if (!link) { 51 | return commits; 52 | } 53 | const lastPage = link.match(/^.+?<([^>]+)>;/)[1]; 54 | return fetch(lastPage).then((res) => res.json()); 55 | }).then((commits) => { 56 | if (Array.isArray(commits)) { 57 | location.href = commits.at(-1).html_url; 58 | } else { 59 | console.error(commits); 60 | } 61 | }); 62 | }; 63 | observe(() => { 64 | const path = $.querySelector(PATH)?.content; 65 | if (path !== REPO_PAGE) { 66 | return; 67 | } 68 | if ($.getElementById(ID)) { 69 | return; 70 | } 71 | const commitHistory = $.querySelector("div svg.octicon-history")?.closest("div"); 72 | if (!commitHistory) { 73 | return; 74 | } 75 | const firstCommit = commitHistory.cloneNode(true); 76 | const label = firstCommit.querySelector(':scope [data-component="text"] > *'); 77 | const header = firstCommit.querySelector(":scope h2"); 78 | const link = firstCommit.querySelector(":scope a[href]"); 79 | const [user, repo] = $.querySelector(USER_REPO).getAttribute("content").split("/"); 80 | firstCommit.id = ID; 81 | header.textContent = label.textContent = "1st Commit"; 82 | link.removeAttribute("href"); 83 | link.setAttribute("aria-label", "First commit"); 84 | const onClick = (e) => { 85 | e.preventDefault(); 86 | e.stopPropagation(); 87 | label.textContent = "Loading..."; 88 | openFirstCommit(user, repo); 89 | }; 90 | firstCommit.addEventListener("click", onClick, { once: true }); 91 | commitHistory.after(firstCommit); 92 | }); 93 | })(); 94 | -------------------------------------------------------------------------------- /dist/google-dwimages.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Google DWIMages 3 | // @description Direct links to images and pages on Google Images 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 3.1.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://www.google.tld/search?*tbm=isch* 10 | // @include https://www.google.tld/search?*udm=2* 11 | // @grant none 12 | // ==/UserScript== 13 | 14 | // NOTE This file is generated from src/google-dwimages.user.ts and should not be edited directly. 15 | 16 | "use strict"; 17 | (() => { 18 | // src/lib/util.ts 19 | var constant = (value) => (..._args) => value; 20 | 21 | // src/lib/observer.ts 22 | var INIT = { childList: true, subtree: true }; 23 | var done = constant(false); 24 | var resume = constant(true); 25 | var observe = (...args) => { 26 | const $ = document; 27 | const [target, init, callback] = args.length === 3 ? args : args.length === 2 ? args[0] instanceof Element ? [args[0], INIT, args[1]] : [$.body, args[0], args[1]] : [$.body, INIT, args[0]]; 28 | const $callback = (mutations, observer2) => { 29 | observer2.disconnect(); 30 | const resume2 = callback({ mutations, observer: observer2, target, init }); 31 | if (resume2 !== false) { 32 | observer2.observe(target, init); 33 | } 34 | }; 35 | const observer = new MutationObserver($callback); 36 | queueMicrotask(() => $callback([], observer)); 37 | return observer; 38 | }; 39 | 40 | // src/google-dwimages.user.ts 41 | // @license GPL 42 | var EVENTS = [ 43 | "auxclick", 44 | "click", 45 | "contextmenu", 46 | "focus", 47 | "focusin", 48 | "keydown", 49 | "mousedown", 50 | "touchstart" 51 | ]; 52 | var LINK_TARGET = "_blank"; 53 | var RESULT = ":scope > :is([data-lpage], [data-ri]):not([data-status])"; 54 | var RESULTS = ":has(> :is([data-lpage], [data-ri]))"; 55 | var stopPropagation = (e) => { 56 | e.stopPropagation(); 57 | }; 58 | var onImageLink = (link, result) => { 59 | const { searchParams: params } = new URL(link.href); 60 | const src = params.get("imgurl"); 61 | if (!src) { 62 | console.warn("Can't find image URL in result link:", { result, link, params }); 63 | return; 64 | } 65 | const image = link.querySelector(":scope img"); 66 | if (!image) { 67 | console.warn("Can't find image in result link:", { result, link }); 68 | return; 69 | } 70 | link.href = src; 71 | link.title = image.alt; 72 | link.target = LINK_TARGET; 73 | result.dataset.status = "fixed" /* FIXED */; 74 | image.parentElement.innerHTML = image.parentElement.innerHTML; 75 | }; 76 | var onResult = (result) => { 77 | result.dataset.status = "pending" /* PENDING */; 78 | for (const event of EVENTS) { 79 | result.addEventListener(event, stopPropagation); 80 | } 81 | const imageLink = result.querySelector(":scope a"); 82 | if (!imageLink) { 83 | console.warn("Can't find image link in result:", result); 84 | return; 85 | } 86 | observe(imageLink, { attributeFilter: ["href"] }, () => { 87 | return imageLink.href && done(onImageLink(imageLink, result)); 88 | }); 89 | }; 90 | var run = () => { 91 | const results = document.querySelector(RESULTS); 92 | if (!results) { 93 | console.warn("Can't find result container"); 94 | return; 95 | } 96 | observe(results, { childList: true }, () => { 97 | results.querySelectorAll(RESULT).forEach(onResult); 98 | }); 99 | }; 100 | run(); 101 | })(); 102 | -------------------------------------------------------------------------------- /src/github-my-issues.user.ts: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name GitHub My Issues 3 | // @description Add a contextual link to issues you've contributed to on GitHub 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 2.1.1 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://github.com/ 10 | // @include https://github.com/* 11 | // @require https://cdn.jsdelivr.net/npm/cash-dom@8.1.5/dist/cash.min.js 12 | // @grant GM_addStyle 13 | // @run-at document-start 14 | // ==/UserScript== 15 | 16 | /* 17 | * the ID of the "My Issues" link. 18 | */ 19 | const ID = 'my-issues-tab' 20 | 21 | /* 22 | * selector for the "Issues" link. we navigate up from this to its parent 23 | * tab, which we clone the "My Issues" tab from and append to. 24 | */ 25 | const ISSUES_LINK = 'a#issues-tab' 26 | 27 | /* 28 | * text of the "My Issues" link 29 | */ 30 | const MY_ISSUES = 'My Issues' 31 | 32 | /* 33 | * selector for the added "My Issues" link. used to identify an existing link so 34 | * it can be removed on pjax page loads 35 | */ 36 | const MY_ISSUES_LINK = `li a#${ID}` 37 | 38 | /* 39 | * add the "My Issues" link 40 | */ 41 | const run = () => { 42 | // if we're here via a pjax load, there may be an existing "My Issues" link 43 | // from a previous page load. we can't reuse it as it may no longer be 44 | // required or in a valid state, so we just replace it 45 | $(MY_ISSUES_LINK).closest('li').remove() 46 | 47 | const $issuesLink = $(`li ${ISSUES_LINK}`) 48 | const $issues = $issuesLink.closest('li') 49 | 50 | if ($issues.length !== 1) { 51 | return 52 | } 53 | 54 | const self = $('meta[name="user-login"]').attr('content') 55 | const repo = $('[data-current-repository]').data('currentRepository') 56 | const user = repo?.split('/')?.at(0) 57 | 58 | if (!(self && repo && user)) { 59 | return 60 | } 61 | 62 | const myIssues = `involves:${self}` 63 | const subqueries = [myIssues, 'sort:updated-desc'] 64 | 65 | if (user === self) { // own repo 66 | // is:open archived:false involves: ... 67 | subqueries.unshift('is:open', 'archived:false') 68 | } 69 | 70 | const query = subqueries.join('+') 71 | const path = `/${repo}/issues` 72 | const href = `${path}?q=${escape(query)}` 73 | const $myIssues = $issues.clone() 74 | const $link = $myIssues 75 | .find(`:scope ${ISSUES_LINK}`) 76 | .removeClass('selected deselected') 77 | .attr({ 78 | id: ID, 79 | role: 'tab', 80 | href, 81 | 'aria-current': null, 82 | 'data-hotkey': 'g I', 83 | 'data-selected-links': null, 84 | }) 85 | 86 | $link.find(':scope [data-content="Issues"]').text(MY_ISSUES) 87 | $link.find(':scope [id="issues-repo-tab-count"]').remove() 88 | 89 | let q: string | null = null 90 | 91 | if (location.pathname === path) { 92 | const params = new URLSearchParams(location.search) 93 | q = params.get('q') 94 | } 95 | 96 | if (q && q.trim().split(/\s+/).includes(myIssues)) { 97 | $link.attr('aria-selected', 'true') 98 | $issuesLink.addClass('deselected') 99 | } else { 100 | $link.attr('aria-selected', 'false') 101 | $issuesLink.removeClass('deselected') 102 | } 103 | 104 | $issues.after($myIssues) 105 | } 106 | 107 | GM_addStyle(` 108 | .deselected::after { 109 | background: transparent !important; 110 | } 111 | `) 112 | 113 | // run on navigation (including full page loads) 114 | $(document).on('turbo:load', run) 115 | -------------------------------------------------------------------------------- /src/reddit_toggle_custom_css.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Reddit Toggle Custom CSS 3 | // @description Persistently disable/re-enable custom subreddit styles via a userscript command 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.5.2 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: http://www.gnu.org/copyleft/gpl.html 9 | // @include http://reddit.com/r/* 10 | // @include https://reddit.com/r/* 11 | // @include http://*.reddit.com/r/* 12 | // @include https://*.reddit.com/r/* 13 | // @grant GM_deleteValue 14 | // @grant GM_getValue 15 | // @grant GM_setValue 16 | // @grant GM_registerMenuCommand 17 | // @run-at document-start 18 | // @inject-into auto 19 | // ==/UserScript== 20 | 21 | // inspired by: http://userscripts-mirror.org/scripts/show/109818 22 | 23 | // XXX the @inject-into directive is needed for the script to work on 24 | // Violentmonkey if JavaScript is disabled (i.e. not because of CSP): 25 | // https://github.com/violentmonkey/violentmonkey/issues/302#issuecomment-485271317 26 | 27 | const CUSTOM_CSS = 'link[ref^="applied_subreddit_"]' 28 | const DEFAULT_DISABLE_CSS = false 29 | const SUBREDDIT = location.pathname.match(/\/r\/(\w+)/)[1] 30 | const DISABLE_CSS = GM_getValue(SUBREDDIT, DEFAULT_DISABLE_CSS) 31 | 32 | function toggle (customCss) { 33 | const oldDisableCss = GM_getValue(SUBREDDIT, DEFAULT_DISABLE_CSS) 34 | const disableCss = !oldDisableCss 35 | 36 | customCss.disabled = disableCss 37 | 38 | if (disableCss === DEFAULT_DISABLE_CSS) { 39 | GM_deleteValue(SUBREDDIT) 40 | } else { 41 | GM_setValue(SUBREDDIT, disableCss) 42 | } 43 | } 44 | 45 | // the definition of document-start varies across userscript engines and may 46 | // vary for the same userscript engine across different browsers. currently, the 47 | // following userscript-engines/browsers all expose document.documentElement (in 48 | // fact, they all expose document.head as well, though that's not guaranteed [1] 49 | // [2]): 50 | // 51 | // - Greasemonkey 4 [3] 52 | // - Tampermonkey for Firefox 53 | // - Violentmonkey for Chrome 54 | // - Violentmonkey for Firefox 55 | // 56 | // [1] https://github.com/violentmonkey/violentmonkey/issues/420 57 | // [2] https://github.com/Tampermonkey/tampermonkey/issues/211#issuecomment-317116595 58 | // [3] Greasemonkey isn't supported as it doesn't support GM_registerMenuCommand 59 | const { style } = document.documentElement 60 | 61 | if (DISABLE_CSS) { 62 | // 1) hide the page 2) disable the stylesheet 3) unhide the page 63 | // 64 | // NOTE we need to use `display: none` rather than `visibility: hidden` as 65 | // the latter doesn't hide the background (which leads to a flash of styled 66 | // content (FOSC) on subreddits with a custom background color and/or image) 67 | // 68 | // XXX hide the HTML element rather than the BODY element as the latter 69 | // still results in a FOSC on some subreddits e.g. /r/firefox 70 | style.display = 'none' // 1) hide the page 71 | } 72 | 73 | document.addEventListener('DOMContentLoaded', () => { 74 | // the custom stylesheet (LINK element) doesn't exist on all subreddit 75 | // pages, e.g.: 76 | // 77 | // ✔ /r//about/rules/ 78 | // x /r//about/moderators/ 79 | const customCss = document.querySelector(CUSTOM_CSS) 80 | 81 | if (DISABLE_CSS) { 82 | if (customCss) { 83 | customCss.disabled = true // 2) disable the stylesheet 84 | } 85 | 86 | style.removeProperty('display') // 3) unhide the page 87 | } 88 | 89 | // don't show the toggle command if there's no custom stylesheet to toggle 90 | if (customCss) { 91 | GM_registerMenuCommand('Toggle Custom CSS', () => toggle(customCss)) 92 | } 93 | }) 94 | -------------------------------------------------------------------------------- /src/google-dwimages.user.ts: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Google DWIMages 3 | // @description Direct links to images and pages on Google Images 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 3.1.0 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://www.google.tld/search?*tbm=isch* 10 | // @include https://www.google.tld/search?*udm=2* 11 | // @grant none 12 | // ==/UserScript== 13 | 14 | import { done, observe } from './lib/observer' 15 | 16 | // property (data attribute) on image result elements used to distinguish them 17 | // from new/unprocessed results 18 | const enum ResultStatus { 19 | PENDING = 'pending', 20 | FIXED = 'fixed', 21 | } 22 | 23 | // events to intercept (stop propagating) in result elements 24 | const EVENTS = [ 25 | 'auxclick', 26 | 'click', 27 | 'contextmenu', 28 | 'focus', 29 | 'focusin', 30 | 'keydown', 31 | 'mousedown', 32 | 'touchstart' 33 | ] 34 | 35 | // the default target for image links (same as page links) 36 | const LINK_TARGET = '_blank' 37 | 38 | // selector for image result elements (relative to the result container) 39 | const RESULT = ':scope > :is([data-lpage], [data-ri]):not([data-status])' 40 | 41 | // selector for the image result container 42 | const RESULTS = ':has(> :is([data-lpage], [data-ri]))' 43 | 44 | /** 45 | * event handler for result elements which prevents their click/mousedown events 46 | * being intercepted to open the sidebar 47 | */ 48 | const stopPropagation = (e: Event): void => { 49 | e.stopPropagation() 50 | } 51 | 52 | /* 53 | * process an image link: 54 | * 55 | * 1) extract the image URL from the tracking URL and assign it, e.g. 56 | * 57 | * from: href="/imgres?imgurl=https%3A%2F%2Fexample.com%2Fimage.jpg&..." 58 | * to: href="https://example.com/image.jpg" 59 | * 60 | * 2) update the result element's status to indicate it has been processed 61 | */ 62 | const onImageLink = (link: HTMLAnchorElement, result: HTMLElement): void => { 63 | const { searchParams: params } = new URL(link.href) 64 | const src = params.get('imgurl') 65 | 66 | if (!src) { 67 | console.warn("Can't find image URL in result link:", { result, link, params }) 68 | return 69 | } 70 | 71 | const image = link.querySelector(':scope img') 72 | 73 | if (!image) { 74 | console.warn("Can't find image in result link:", { result, link }) 75 | return 76 | } 77 | 78 | link.href = src 79 | link.title = image.alt 80 | link.target = LINK_TARGET // make it consistent with the page link 81 | result.dataset.status = ResultStatus.FIXED 82 | 83 | // force a reflow (once) so the updated URL is immediately visible on hover 84 | // (XXX Firefox issue, not needed in Chrome) 85 | // 86 | // this no longer works (parent is a custom element (g-img)): 87 | // 88 | // image.parentElement!.replaceChild(image, image) 89 | image.parentElement!.innerHTML = image.parentElement!.innerHTML 90 | } 91 | 92 | /* 93 | * process an image result: 94 | * 95 | * 1) prevent its click event(s) being intercepted to open the sidebar 96 | * 2) wait for its image link to be assigned a URL (on the first hover) and 97 | * extract the direct image URL from it 98 | */ 99 | const onResult = (result: HTMLElement): void => { 100 | // tag the result so we don't process it again 101 | result.dataset.status = ResultStatus.PENDING 102 | 103 | // disable the click interceptors 104 | for (const event of EVENTS) { 105 | result.addEventListener(event, stopPropagation) 106 | } 107 | 108 | // grab the link to the image (first link) 109 | const imageLink = result.querySelector(':scope a') 110 | 111 | if (!imageLink) { 112 | console.warn("Can't find image link in result:", result) 113 | return 114 | } 115 | 116 | // wait for its href to be assigned (on the first hover) 117 | observe(imageLink, { attributeFilter: ['href'] }, () => { 118 | return imageLink.href && done(onImageLink(imageLink, result)) 119 | }) 120 | } 121 | 122 | const run = () => { 123 | const results = document.querySelector(RESULTS) 124 | 125 | if (!results) { 126 | console.warn("Can't find result container") 127 | return 128 | } 129 | 130 | observe(results, { childList: true }, () => { 131 | results.querySelectorAll(RESULT).forEach(onResult) 132 | }) 133 | } 134 | 135 | run() 136 | -------------------------------------------------------------------------------- /src/github-first-commit.user.ts: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name GitHub First Commit 3 | // @description Add a link to a GitHub repo's first commit 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 4.0.3 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://github.com/ 10 | // @include https://github.com/* 11 | // @grant GM_log 12 | // @noframes 13 | // ==/UserScript== 14 | 15 | import { observe } from './lib/observer.js' 16 | 17 | type Commit = { html_url: string }; 18 | 19 | /* unique ID assigned to the first-commit widget */ 20 | const ID = 'first-commit' 21 | 22 | /* 23 | * selector for the page-type identifier, e.g. "//" or 24 | * "///issues/index" 25 | */ 26 | const PATH = 'meta[name="analytics-location"][content]' 27 | 28 | /* 29 | * the page-type identifier for repo pages, e.g. 30 | * https://github.com/chocolateboy/userscripts 31 | */ 32 | const REPO_PAGE = '//' 33 | 34 | /* selector for the owner name/repo name, e.g. "chocolateboy/userscripts" */ 35 | const USER_REPO = 'meta[name="octolytics-dimension-repository_network_root_nwo"][content]' 36 | 37 | const $ = document 38 | 39 | /* 40 | * extract the URL of the repo's first commit and navigate to it. this is based 41 | * on code by several developers, a list of whom can be found here: 42 | * https://github.com/FarhadG/init#contributors 43 | * 44 | * XXX it doesn't work on private repos. a way to do that can be found here, but 45 | * it requires an authentication token: 46 | * https://gist.github.com/simonewebdesign/a70f6c89ffd71e6ba4f7dcf7cc74ccf8 47 | */ 48 | const openFirstCommit = (user: string, repo: string) => { 49 | return fetch(`https://api.github.com/repos/${user}/${repo}/commits`) 50 | // the `Link` header has additional URLs for paging. 51 | // parse the original JSON for the case where no other pages exist 52 | .then(res => Promise.all([res.headers.get('link'), res.json() as Promise])) 53 | 54 | .then(([link, commits]) => { 55 | if (!link) { 56 | // if there's no link, we know we're on the only page 57 | return commits 58 | } 59 | 60 | // the link header contains two URLs and has the following 61 | // format (wrapped for readability): 62 | // 63 | // ; rel="next", 64 | // ; rel="last" 65 | 66 | // extract the URL of the last page (commits are ordered in 67 | // reverse chronological order, like the git CLI, so the oldest 68 | // commit is on the last page) 69 | const lastPage = link.match(/^.+?<([^>]+)>;/)![1] 70 | 71 | // fetch the last page of results 72 | return fetch(lastPage).then(res => res.json()) 73 | }) 74 | 75 | // get the last commit and navigate to its target URL 76 | .then((commits: Commit[]) => { 77 | if (Array.isArray(commits)) { 78 | location.href = commits.at(-1)!.html_url 79 | } else { 80 | console.error(commits) 81 | } 82 | }) 83 | } 84 | 85 | observe(() => { 86 | const path = $.querySelector(PATH)?.content 87 | 88 | // bail if we're not on a repo page 89 | if (path !== REPO_PAGE) { 90 | return 91 | } 92 | 93 | // widget already exists 94 | if ($.getElementById(ID)) { 95 | return 96 | } 97 | 98 | // locate the commit-history widget (e.g. "1,234 Commits") via its clock icon 99 | const commitHistory = $.querySelector('div svg.octicon-history')?.closest('div') 100 | 101 | if (!commitHistory) { 102 | return 103 | } 104 | 105 | // clone and customize it 106 | const firstCommit = commitHistory.cloneNode(true) as typeof commitHistory 107 | const label = firstCommit.querySelector(':scope [data-component="text"] > *')! 108 | const header = firstCommit.querySelector(':scope h2')! 109 | const link = firstCommit.querySelector(':scope a[href]')! 110 | const [user, repo] = $.querySelector(USER_REPO)!.getAttribute('content')!.split('/') 111 | 112 | firstCommit.id = ID 113 | header.textContent = label.textContent = '1st Commit' 114 | link.removeAttribute('href') 115 | link.setAttribute('aria-label', 'First commit') 116 | 117 | // navigate to the first commit on click 118 | const onClick = (e: MouseEvent) => { 119 | e.preventDefault() 120 | e.stopPropagation() 121 | label.textContent = 'Loading...' 122 | openFirstCommit(user, repo) // async 123 | } 124 | 125 | firstCommit.addEventListener('click', onClick, { once: true }) 126 | 127 | // append to the commit-history widget 128 | commitHistory.after(firstCommit) 129 | }) 130 | -------------------------------------------------------------------------------- /src/last_picture_show.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Last Picture Show 3 | // @description Link last.fm artist/album images directly to the image page 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 1.2.4 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL: https://www.gnu.org/copyleft/gpl.html 9 | // @include http://*.last.fm/* 10 | // @include https://*.last.fm/* 11 | // @include http://*.lastfm.tld/* 12 | // @include https://*.lastfm.tld/* 13 | // @require https://code.jquery.com/jquery-3.5.1.slim.min.js 14 | // @require https://cdn.jsdelivr.net/gh/eclecto/jQuery-onMutate@79bbb2b8caccabfc9b9ade046fe63f15f593fef6/src/jquery.onmutate.min.js 15 | // @grant GM_log 16 | // @inject-into auto 17 | // ==/UserScript== 18 | 19 | // XXX note: the unused grant is a workaround for a Greasemonkey bug: 20 | // https://github.com/greasemonkey/greasemonkey/issues/1614 21 | 22 | /* 23 | Thumbnail: https://lastfm-img2.akamaized.net/i/u/300x300/{imageId}.jpg 24 | Picture page: https://www.last.fm/music/Artist+Name/+images/{imageId} 25 | 26 | before: 27 | 28 | 48 | 49 | after: 50 | 51 | 71 | */ 72 | 73 | // selector for the nearest parent element (div) which contains both the image 74 | // and a link to the artist/album 75 | const ITEM = '.grid-items-cover-image' 76 | 77 | // filter out "Similar Tracks" tiles (no way to determine the image page) and 78 | // tiles without an image 79 | function filterItems () { 80 | const $item = $(this) 81 | 82 | // XXX don't include the images in "Similar Tracks" grids. their pages are 83 | // located in album (or release) "subfolders" e.g.: 84 | // 85 | // - image: https://lastfm-img2.akamaized.net/i/u/300x300/fafc74a8f45241acc10158be6e2d8270.jpg 86 | // - track: https://www.last.fm/music/The+Beatles/_/Doctor+Robert 87 | // - image page: https://www.last.fm/music/The+Beatles/Revolver/+images/fafc74a8f45241acc10158be6e2d8270 88 | // 89 | // but last.fm doesn't include any additional data in the "Similar Tracks" 90 | // grids which can be used to identify the release (e.g. "Revolver"). 91 | // 92 | // XXX last.fm doesn't distinguish the "Similar Tracks" grid from the "Similar 93 | // Artists" grid in any way (same markup and CSS), so we have to identify 94 | // (and exclude) it as "section 1 of 2 in the similar-tracks-and-artists row" 95 | if ($item.is(`.similar-tracks-and-artists-row section:nth-of-type(1) ${ITEM}`)) 96 | return false 97 | 98 | // XXX we also need to exclude tiles with missing/default images. they have 99 | // an additional .grid-items-cover-default class on their image-container div 100 | // alongside .grid-items-cover-image-image 101 | if ($item.has('.grid-items-cover-default').length) 102 | return false 103 | 104 | return true 105 | } 106 | 107 | function onItems ($items) { 108 | $items.filter(filterItems).each(function () { 109 | const $item = $(this) 110 | const $image = $item.find('.grid-items-cover-image-image img[src]') 111 | const imageId = $image.attr('src').match(/\/([^/.]+)\.\w+$/)[1] 112 | const path = $item.find('a.link-block-target[href]').attr('href') 113 | 114 | $image.wrap(``) 115 | }) 116 | } 117 | 118 | $.onCreate(ITEM, onItems, true /* multi */) 119 | -------------------------------------------------------------------------------- /src/twitter-direct.user.ts: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Twitter Direct 3 | // @description Remove t.co tracking links from Twitter 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 3.1.2 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://mobile.twitter.com/ 10 | // @include https://mobile.twitter.com/* 11 | // @include https://twitter.com/ 12 | // @include https://twitter.com/* 13 | // @include https://x.com/ 14 | // @include https://x.com/* 15 | // @require https://unpkg.com/gm-compat@1.1.0/dist/index.iife.min.js 16 | // @run-at document-start 17 | // ==/UserScript== 18 | 19 | /// 20 | 21 | import Replacer from './twitter-direct/replacer' 22 | import { isObject } from './twitter-direct/util' 23 | 24 | /* 25 | * a list of document URIs (paths) which are known to not contain t.co URLs and 26 | * which therefore don't need to be transformed 27 | */ 28 | const URL_BLACKLIST = new Set([ 29 | '/hashflags.json', 30 | '/badge_count/badge_count.json', 31 | '/graphql/articleNudgeDomains', 32 | '/graphql/TopicToFollowSidebar', 33 | ]) 34 | 35 | /* 36 | * a pattern which matches the content-type header of responses we scan for 37 | * URLs: "application/json" or "application/json; charset=utf-8" 38 | */ 39 | const CONTENT_TYPE = /^application\/json\b/ 40 | 41 | /* 42 | * the minimum size (in bytes) of documents we deem to be "not small" 43 | * 44 | * we log (to the console) misses (i.e. no URLs ever found/replaced) in 45 | * documents whose size is greater than or equal to this value 46 | */ 47 | const LOG_THRESHOLD = 1024 48 | 49 | /* 50 | * a map from URI paths (strings) to the replacement count for each path. used 51 | * to keep a running total of the number of replacements in each document type 52 | */ 53 | const STATS: Record = {} 54 | 55 | /* 56 | * a pattern which matches the domain(s) we expect data (JSON) to come from. 57 | * responses which don't come from a matching domain are ignored. 58 | */ 59 | const TWITTER_API = /^(?:(?:api|mobile)\.)?(?:twitter|x)\.com$/ 60 | 61 | /* 62 | * replacement for the default handler for XHR requests. we transform the 63 | * response if it's a) JSON and b) contains URL data; otherwise, we leave it 64 | * unchanged 65 | */ 66 | const onResponse = (xhr: XMLHttpRequest, uri: string): void => { 67 | const contentType = xhr.getResponseHeader('Content-Type') 68 | 69 | if (!contentType || !CONTENT_TYPE.test(contentType)) { 70 | return 71 | } 72 | 73 | const url = new URL(uri) 74 | 75 | // exclude e.g. the config-.json file from pbs.twimg.com, which is the 76 | // second biggest document (~500K) after home_latest.json (~700K) 77 | if (!TWITTER_API.test(url.hostname)) { 78 | return 79 | } 80 | 81 | const json = xhr.responseText 82 | const size = json.length 83 | 84 | // fold paths which differ only in the API version, user ID or query 85 | // ID, e.g.: 86 | // 87 | // /2/timeline/profile/1234.json -> /timeline/profile.json 88 | // /i/api/graphql/abc123/UserTweets -> /graphql/UserTweets 89 | // 90 | const path = url.pathname 91 | .replace(/^\/i\/api\//, '/') 92 | .replace(/^\/\d+(\.\d+)*\//, '/') 93 | .replace(/(\/graphql\/)[^\/]+\/(.+)$/, '$1$2') 94 | .replace(/\/\d+\.json$/, '.json') 95 | 96 | if (URL_BLACKLIST.has(path)) { 97 | return 98 | } 99 | 100 | let data 101 | 102 | try { 103 | data = JSON.parse(json) 104 | } catch (e) { 105 | console.error(`Can't parse JSON for ${uri}:`, e) 106 | return 107 | } 108 | 109 | if (!isObject(data)) { 110 | return 111 | } 112 | 113 | const newPath = !(path in STATS) 114 | const count = Replacer.transform(data, path) 115 | 116 | STATS[path] = (STATS[path] || 0) + count 117 | 118 | if (!count) { 119 | if (STATS[path] === 0 && size > LOG_THRESHOLD) { 120 | console.debug(`no replacements in ${path} (${size} B)`) 121 | } 122 | 123 | return 124 | } 125 | 126 | const descriptor = { value: JSON.stringify(data) } 127 | const clone = GMCompat.export(descriptor) 128 | 129 | GMCompat.unsafeWindow.Object.defineProperty(xhr, 'responseText', clone) 130 | 131 | const replacements = 'replacement' + (count === 1 ? '' : 's') 132 | 133 | console.debug(`${count} ${replacements} in ${path} (${size} B)`) 134 | 135 | if (newPath) { 136 | console.log(STATS) 137 | } 138 | } 139 | 140 | /* 141 | * replace the built-in XHR#send method with a custom version which swaps 142 | * in our custom response handler. once done, we delegate to the original 143 | * handler (this.onreadystatechange) 144 | */ 145 | const hookXHRSend = (oldSend: XMLHttpRequest['send']): XMLHttpRequest['send'] => { 146 | return function send (this: XMLHttpRequest, body = null) { 147 | const oldOnReadyStateChange = this.onreadystatechange 148 | 149 | this.onreadystatechange = function (event) { 150 | if (this.readyState === this.DONE && this.responseURL && this.status === 200) { 151 | onResponse(this, this.responseURL) 152 | } 153 | 154 | if (oldOnReadyStateChange) { 155 | oldOnReadyStateChange.call(this, event) 156 | } 157 | } 158 | 159 | oldSend.call(this, body) 160 | } 161 | } 162 | 163 | // replace the default XHR#send method with our custom version, which scans 164 | // responses for t.co URLs and expands them 165 | const xhrProto = GMCompat.unsafeWindow.XMLHttpRequest.prototype 166 | const send = hookXHRSend(xhrProto.send) 167 | 168 | xhrProto.send = GMCompat.export(send) 169 | -------------------------------------------------------------------------------- /dist/twitter-linkify-trends.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Twitter Linkify Trends 3 | // @description Make Twitter trends links (again) 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 3.3.2 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://mobile.x.com/ 10 | // @include https://mobile.x.com/* 11 | // @include https://x.com/ 12 | // @include https://x.com/* 13 | // @require https://code.jquery.com/jquery-3.7.1.slim.min.js 14 | // @require https://unpkg.com/gm-compat@1.1.0/dist/index.iife.min.js 15 | // @require https://unpkg.com/@chocolateboy/uncommonjs@3.2.1/dist/polyfill.iife.min.js 16 | // @require https://unpkg.com/get-wild@3.0.2/dist/index.umd.min.js 17 | // @require https://unpkg.com/flru@1.0.2/dist/flru.min.js 18 | // @grant GM_log 19 | // @run-at document-start 20 | // ==/UserScript== 21 | 22 | // NOTE This file is generated from src/twitter-linkify-trends.user.ts and should not be edited directly. 23 | 24 | "use strict"; 25 | (() => { 26 | // src/lib/util.ts 27 | var constant = (value) => (..._args) => value; 28 | 29 | // src/lib/observer.ts 30 | var INIT = { childList: true, subtree: true }; 31 | var done = constant(false); 32 | var resume = constant(true); 33 | var observe = ((...args) => { 34 | const [target, init, callback] = args.length === 3 ? args : args.length === 2 ? args[0] instanceof Element ? [args[0], INIT, args[1]] : [document.body, args[0], args[1]] : [document.body, INIT, args[0]]; 35 | const onMutate = (mutations, observer2) => { 36 | observer2.disconnect(); 37 | const resume2 = callback({ mutations, observer: observer2, target }); 38 | if (resume2 !== false) { 39 | observer2.observe(target, init); 40 | } 41 | }; 42 | const observer = new MutationObserver(onMutate); 43 | queueMicrotask(() => onMutate([], observer)); 44 | return observer; 45 | }); 46 | 47 | // src/twitter-linkify-trends.user.ts 48 | // @license GPL 49 | var CACHE = exports.default(128); 50 | var DISABLED_EVENTS = "click touch"; 51 | var EVENT_DATA_HANDLERS = /* @__PURE__ */ new Map([ 52 | [ 53 | "ExplorePage", 54 | "data.explore_page.body.initialTimeline.timeline.timeline.instructions[-1].entries.*.content.items.*.item.itemContent" 55 | ], 56 | [ 57 | "GenericTimelineById", 58 | "data.timeline.timeline.instructions[-1].entries.*.content.items.*.item.itemContent" 59 | ], 60 | [ 61 | "SearchTimeline", 62 | "data.search_by_raw_query.search_timeline.timeline.instructions[-1].entries.*.content.items.*.item.itemContent" 63 | ], 64 | [ 65 | "useStoryTopicQuery", 66 | { 67 | path: "data.story_topic.stories.items.*.trend_results.result", 68 | handler: onSidebarEventData 69 | } 70 | ] 71 | ]); 72 | var CARET = '[data-testid="caret"]'; 73 | var IS_TREND = '[data-testid="trend"]'; 74 | var HAS_MENU = `:has(${CARET})`; 75 | var TIMELINE_EVENT = `${IS_TREND}:not(${HAS_MENU})`; 76 | var SIDEBAR_EVENT = '[data-testid^="news_sidebar_article_"]'; 77 | var EVENT = `:is(${TIMELINE_EVENT}, ${SIDEBAR_EVENT})`; 78 | var TREND = `${IS_TREND}${HAS_MENU}`; 79 | var SELECTOR = [EVENT, TREND].map((it) => `div[role="link"]${it}:not([data-linked])`).join(", "); 80 | function disableAll(e) { 81 | e.stopPropagation(); 82 | } 83 | function disableSome(e) { 84 | const $target = $(e.target); 85 | const $caret = $target.closest(CARET, this); 86 | if (!$caret.length) { 87 | e.stopPropagation(); 88 | } 89 | } 90 | function hookXHROpen(oldOpen) { 91 | return function open(_method, url) { 92 | const endpoint = URL.parse(url)?.pathname.split("/").at(-1) ?? ""; 93 | const $path = EVENT_DATA_HANDLERS.get(endpoint); 94 | if ($path) { 95 | const [path, handler] = typeof $path === "string" ? [$path, onTimelineEventData] : [$path.path, $path.handler]; 96 | this.addEventListener("load", () => handler(this.responseText, path)); 97 | } 98 | return GMCompat.apply(this, oldOpen, arguments); 99 | }; 100 | } 101 | function linkFor(href) { 102 | return $("").attr({ href, role: "link", "data-focusable": true }).css({ color: "inherit", textDecoration: "inherit" }); 103 | } 104 | function onElement(el) { 105 | const $el = $(el); 106 | let linked = true; 107 | if ($el.is(EVENT)) { 108 | $el.on(DISABLED_EVENTS, disableAll); 109 | linked = onEventElement($el); 110 | } else if ($el.is(TREND)) { 111 | $el.on(DISABLED_EVENTS, disableSome); 112 | onTrendElement($el); 113 | } 114 | if (linked) { 115 | $el.css("cursor", "auto"); 116 | $el.attr("data-linked", "true"); 117 | } 118 | } 119 | function onEventElement($event) { 120 | const { target, title } = targetFor($event); 121 | const url = CACHE.get(title); 122 | if (!url) { 123 | return false; 124 | } 125 | console.debug(`element (event):`, JSON.stringify(title)); 126 | const $link = linkFor(url); 127 | $(target).parent().wrap($link); 128 | return true; 129 | } 130 | function onSidebarEventData(json, path) { 131 | const data = JSON.parse(json); 132 | const events = exports.get(data, path, []); 133 | for (const event of events) { 134 | const { core: { name: title }, rest_id: id } = event; 135 | const url = `${location.origin}/i/trending/${id}`; 136 | console.debug("data (sidebar event):", { title, url }); 137 | CACHE.set(title, url); 138 | } 139 | } 140 | function onTimelineEventData(json, path) { 141 | const data = JSON.parse(json); 142 | const events = exports.get(data, path, []); 143 | for (const event of events) { 144 | if (event.itemType !== "TimelineTrend") { 145 | continue; 146 | } 147 | const { name: title, trend_url: { url: uri } } = event; 148 | const url = uri.replace(/^twitter:\/\//, `${location.origin}/i/`); 149 | console.debug("data (timeline event):", { title, url }); 150 | CACHE.set(title, url); 151 | } 152 | } 153 | function onTrendElement($trend) { 154 | const { target, title } = targetFor($trend); 155 | const trend = /\s/.test(title) ? `"${title.replace(/"/g, "")}"` : title; 156 | console.debug("element (trend):", trend); 157 | const query = encodeURIComponent(trend); 158 | const url = `${location.origin}/search?q=${query}&src=trend_click&vertical=trends`; 159 | $(target).wrap(linkFor(url)); 160 | } 161 | function targetFor($el) { 162 | const targets = $el.find('div[dir="ltr"] > span').filter((_, el) => { 163 | const fontWeight = Number($(el).parent().css("fontWeight") || 0); 164 | return fontWeight >= 700; 165 | }); 166 | const target = targets.get().pop(); 167 | const title = $(target).text().trim(); 168 | return { target, title }; 169 | } 170 | function run() { 171 | const target = document.getElementById("react-root"); 172 | if (!target) { 173 | console.warn("can't find react-root element"); 174 | return; 175 | } 176 | observe(target, () => { 177 | for (const el of $(SELECTOR)) { 178 | onElement(el); 179 | } 180 | }); 181 | } 182 | var xhrProto = GMCompat.unsafeWindow.XMLHttpRequest.prototype; 183 | xhrProto.open = GMCompat.export(hookXHROpen(xhrProto.open)); 184 | $(run); 185 | })(); 186 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # userscripts 2 | 3 | 4 | 5 | - [INSTALLATION](#installation) 6 | - [Compatibility](#compatibility) 7 | - [SCRIPTS](#scripts) 8 | - [Sites](#sites) 9 | - [Amazon](#amazon) 10 | - [GitHub](#github) 11 | - [Google](#google) 12 | - [Hacker News](#hacker-news) 13 | - [IMDb](#imdb) 14 | - [Last.fm](#lastfm) 15 | - [Reddit](#reddit) 16 | - [Rotten Tomatoes](#rotten-tomatoes) 17 | - [Twitter](#twitter) 18 | - [Highlighters](#highlighters) 19 | - [Pagerizers](#pagerizers) 20 | - [Misc](#misc) 21 | - [DEVELOPMENT](#development) 22 | - [Prerequisites](#prerequisites) 23 | - [NPM Scripts](#npm-scripts) 24 | - [SEE ALSO](#see-also) 25 | - [Addons](#addons) 26 | - [Libraries](#libraries) 27 | - [jQuery Plugins](#jquery-plugins) 28 | - [Sites](#sites-1) 29 | - [AUTHOR](#author) 30 | - [COPYRIGHT AND LICENSE](#copyright-and-license) 31 | 32 | 33 | 34 | # INSTALLATION 35 | 36 | Unless otherwise noted, each link below points to the userscript's homepage on 37 | [GreasyFork](https://greasyfork.org/en/users/23939-chocolateboy). 38 | 39 | Where possible, always install (or reinstall) these userscripts from 40 | GreasyFork, as this repo may contain development versions of these scripts that 41 | aren't ready for release and which may not even compile. In addition, the 42 | file/directory names here are subject to change, whereas the URLs on GreasyFork 43 | will always remain stable. 44 | 45 | ## Compatibility 46 | 47 | All of these scripts work in and are tested on 48 | [Violentmonkey](https://violentmonkey.github.io/), which is open source, cross 49 | browser, actively maintained, and highly recommended. If for some reason you 50 | can't use it — or don't want to — the following options are available: 51 | 52 | - [Greasemonkey](https://addons.mozilla.org/firefox/addon/greasemonkey/)[1](#fn1) 53 | - Tampermonkey ([closed source](https://github.com/Tampermonkey/tampermonkey/issues/214)) 54 | 55 | 1 The 56 | [Greasemonkey 4 API](https://www.greasespot.net/2017/09/greasemonkey-4-for-script-authors.html) 57 | is not [currently](https://github.com/chocolateboy/userscripts/issues/5) 58 | supported. Some scripts work, but most haven't been tested.
59 | 60 | # SCRIPTS 61 | 62 | ## Sites 63 | 64 | ### Amazon 65 | 66 | - [Amazon International Links](https://greasyfork.org/en/scripts/38639-amazon-international-links "Homepage") - add international links to Amazon product pages 67 | 68 | ### GitHub 69 | 70 | - [GitHub First Commit](https://greasyfork.org/en/scripts/38557-github-first-commit "Homepage") - add a link to a GitHub repo's first commit 71 | - [GitHub My Issues](https://greasyfork.org/en/scripts/411765-github-my-issues "Homepage") - add a link to issues you've contributed to in a GitHub repo 72 | 73 | ### Google 74 | 75 | - [Google DWIMages](https://greasyfork.org/scripts/29420-google-dwimages/ "Homepage") - direct links to images and pages on Google Images 76 | 77 | ### Hacker News 78 | 79 | - [Hacker News Date Tooltips](https://greasyfork.org/scripts/23432-hacker-news-date-tooltips/ "Homepage") - deobfuscate the "n days ago" dates on Hacker News with YYYY-MM-DD tooltips 80 | 81 | ### IMDb 82 | 83 | - [IMDb Full Summary](https://greasyfork.org/scripts/23433-imdb-full-summary "Homepage") - automatically show the full plot summary on IMDb 84 | - [IMDb Tomatoes](https://greasyfork.org/scripts/15222-imdb-tomatoes/ "Homepage") - add Rotten Tomatoes ratings to IMDb movie and TV show pages 85 | 86 | ### Last.fm 87 | 88 | - [Last Picture Show](https://greasyfork.org/scripts/31179-last-picture-show/ "Homepage") - link last.fm artist/album images directly to the image page 89 | 90 | ### Reddit 91 | 92 | - [Reddit Toggle Custom CSS](https://greasyfork.org/scripts/23434-reddit-toggle-custom-css/ "Homepage") - persistently disable/re-enable custom subreddit styles via a userscript command 93 | 94 | ### Rotten Tomatoes 95 | 96 | - [More Tomatoes](https://greasyfork.org/scripts/23435-more-tomatoes/ "Homepage") - automatically show the full "Movie Info" plot synopsis on Rotten Tomatoes 97 | 98 | ### Twitter 99 | 100 | - [Twitter Direct](https://greasyfork.org/en/scripts/404632-twitter-direct "Homepage") - remove t.co tracking links from Twitter 101 | - [Twitter Linkify Trends](https://greasyfork.org/en/scripts/405103-linkify-twitter-trends "Homepage") - make Twitter trends links (again) 102 | - [Twitter Zoom Cursor](https://greasyfork.org/en/scripts/413963-twitter-zoom-cursor "Homepage") - distinguish between images and links on Twitter (userstyle) 103 | 104 | ## Highlighters 105 | 106 | Highlight new stories since the last time a site was visited 107 | 108 | - [Hacker News](https://greasyfork.org/en/scripts/39311-hacker-news-highlighter "Homepage") 109 | - [Lobsters](https://greasyfork.org/en/scripts/40906-lobsters-highlighter "Homepage") 110 | - [Reddit](https://greasyfork.org/en/scripts/39312-reddit-highlighter "Homepage") 111 | 112 | ## Pagerizers 113 | 114 | These scripts mark up pages with missing/sane `rel="prev"` and `rel="next"` 115 | links which can be consumed by a pager, e.g. [[ and ]] in 116 | [Tridactyl](https://github.com/cmcaine/tridactyl), [Vim Vixen](https://github.com/ueokande/vim-vixen) 117 | etc. 118 | 119 | The following are all direct links, i.e. clicking them installs the script. 120 | 121 | - [Amazon](https://github.com/chocolateboy/userscripts/raw/master/src/pagerize_amazon.user.js "Install") 122 | - [Ars Technica](https://github.com/chocolateboy/userscripts/raw/master/src/pagerize_ars_technica.user.js "Install") 123 | - [eBay](https://github.com/chocolateboy/userscripts/raw/master/src/pagerize_ebay.user.js "Install") 124 | - [Metafilter](https://github.com/chocolateboy/userscripts/raw/master/src/pagerize_metafilter.user.js "Install") 125 | 126 | ## Misc 127 | 128 | - [ISO 8601 Dates](https://greasyfork.org/scripts/23436-iso-8601-dates/ "Homepage") - display US dates in the ISO 8601 YYYY-MM-DD format 129 | 130 | # DEVELOPMENT 131 | 132 |
133 | 134 | ## Prerequisites 135 | 136 | - awk 137 | - esbuild 138 | - make 139 | 140 | ## NPM Scripts 141 | 142 | - build - compile updated userscripts and save them to the `dist` directory 143 | - build:doc - generate the README's TOC (table of contents) 144 | - clean - remove the `dist` directory and other build artifacts 145 | - rebuild - clean the build artifacts and recompile the code 146 | 147 |
148 | 149 | # SEE ALSO 150 | 151 | ## Addons 152 | 153 | - [Google Direct](https://github.com/chocolateboy/google-direct) - a Firefox addon which removes tracking links from Google Search results 154 | 155 | ## Libraries 156 | 157 | - [gm-compat](https://github.com/chocolateboy/gm-compat) - portable monkey-patching for userscripts 158 | - [gm-storage](https://github.com/chocolateboy/gm-storage) - an ES6 Map wrapper for the synchronous userscript storage API 159 | - [UnCommonJS](https://github.com/chocolateboy/uncommonjs) - a minimum viable shim for `module.exports` 160 | 161 | ## jQuery Plugins 162 | 163 | - [jQuery Highlighter](https://github.com/chocolateboy/jquery-highlighter) - highlight new items since the last time a site was visited 164 | - [jQuery Pagerizer](https://github.com/chocolateboy/jquery-pagerizer) - mark up web pages with next/previous page annotations 165 | 166 | ## Sites 167 | 168 | - [GreasyFork](https://greasyfork.org/en/users/23939-chocolateboy) 169 | - [USO Mirror](https://userscripts-mirror.org/users/3169/scripts) 170 | 171 | # AUTHOR 172 | 173 | [chocolateboy](mailto:chocolate@cpan.org) 174 | 175 | # COPYRIGHT AND LICENSE 176 | 177 | Copyright © 2011-2025 by chocolateboy. 178 | 179 | These userscripts are free software; you can redistribute and/or modify them 180 | under the terms of the [GPL](https://www.gnu.org/copyleft/gpl.html). 181 | -------------------------------------------------------------------------------- /src/amazon-international-links.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Amazon International Links 3 | // @description Add international links to Amazon product pages 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 4.1.1 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://smile.amazon.tld/* 10 | // @include https://www.amazon.tld/* 11 | // @require https://code.jquery.com/jquery-3.7.1.slim.min.js 12 | // @require https://cdn.jsdelivr.net/gh/sizzlemctwizzle/GM_config@43fd0fe4de1166f343883511e53546e87840aeaf/gm_config.js 13 | // @grant GM_registerMenuCommand 14 | // @grant GM_getValue 15 | // @grant GM_setValue 16 | // ==/UserScript== 17 | 18 | // XXX GM_getValue and GM_setValue are used by GM_config 19 | 20 | /* 21 | * 22 | * further reading: 23 | * 24 | * https://helpful.knobs-dials.com/index.php/Amazon_notes#Links 25 | */ 26 | 27 | /*********************** Constants ********************************/ 28 | 29 | /* 30 | * a map from the Amazon TLD to the corresponding two-letter country code 31 | * 32 | * XXX technically, UK should be GB: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 33 | */ 34 | const SITES = { 35 | 'com.au': 'AU', // Australia 36 | 'com.be': 'BE', // Belgium 37 | 'com.br': 'BR', // Brazil 38 | 'ca': 'CA', // Canada 39 | 'cn': 'CN', // China 40 | 'fr': 'FR', // France 41 | 'de': 'DE', // Germany 42 | 'in': 'IN', // India 43 | 'ie': 'IE', // Ireland 44 | 'it': 'IT', // Italy 45 | 'co.jp': 'JP', // Japan 46 | 'com.mx': 'MX', // Mexico 47 | 'nl': 'NL', // Netherlands 48 | 'es': 'ES', // Spain 49 | 'se': 'SE', // Sweden 50 | 'com.tr': 'TR', // Turkey 51 | 'ae': 'AE', // UAE 52 | 'co.uk': 'UK', // UK 53 | 'com': 'US', // US 54 | } 55 | 56 | /* 57 | * Amazon TLDs which support the "smile.amazon" subdomain 58 | */ 59 | const SMILE = new Set(['com', 'co.uk', 'de']) 60 | 61 | /*********************** Functions and Classes ********************************/ 62 | 63 | /* 64 | * A class which encapsulates the logic for creating and updating cross-site links 65 | */ 66 | class Linker { 67 | /* 68 | * get the unique identifier (ASIN - Amazon Standard Identification Number) 69 | * for this product, or return a falsey value if it's not found 70 | */ 71 | static getASIN () { 72 | const $asin = $('input#ASIN, input[name="ASIN"], input[name="ASIN.0"]') 73 | let asin 74 | 75 | if ($asin.length) { 76 | asin = $asin.val() 77 | } else { // if there's a canonical link, try to retrieve the ASIN from its URI 78 | // 79 | const canonical = $('link[rel="canonical"][href]').attr('href') 80 | let match 81 | 82 | if (canonical && (match = canonical.match('/dp/(\\w+)$'))) { 83 | asin = match[1] 84 | } 85 | } 86 | 87 | return asin 88 | } 89 | 90 | constructor (asin) { 91 | // the unique Amazon identifier for this product 92 | this.asin = asin 93 | 94 | // the navbar to add the cross-site links to 95 | this.navbar = $('#nav-xshop .nav-ul') 96 | 97 | // an array of our added elements - jQuery wrappers of child elements of 98 | // the cross-site links navbar 99 | // 100 | // we keep a reference to these elements so we can easily remove them 101 | // from the DOM (and replace them with new elements) whenever the 102 | // country selection changes 103 | this.links = [] 104 | 105 | // extract and store 1) the subdomain (e.g. "www.amazon") and 2) the TLD 106 | // (e.g. "co.uk") of the current site 107 | const parts = location.hostname.split('.') 108 | 109 | // 1) the subdomain (part before the TLD) of the current site, e.g. 110 | // "www.amazon" or "smile.amazon" 111 | this.subdomain = parts.slice(0, 2).join('.') 112 | 113 | // 2) the TLD of the current site, e.g. "co.uk" or "com" 114 | this.tld = parts.slice(2).join('.') 115 | } 116 | 117 | /* 118 | * add a child element to the internal `links` array 119 | */ 120 | addLink (tld, country) { 121 | const attrs = { 122 | class: 'nav-a', 123 | title: `amazon.${tld}` 124 | } 125 | 126 | // XXX we can't always preserve the "smile.amazon" subdomain as it's not 127 | // available for most Amazon TLDs 128 | const subdomain = SMILE.has(tld) ? this.subdomain : 'www.amazon' 129 | 130 | let tag 131 | 132 | if (tld === this.tld) { 133 | tag = 'strong' 134 | } else { 135 | tag = 'a' 136 | attrs.href = `//${subdomain}.${tld}/dp/${this.asin}` 137 | } 138 | 139 | // serialize the attributes, e.g. { title: 'amazon.com' } -> `title="amazon.com"` 140 | const $attrs = Object.entries(attrs) 141 | .map(([key, value]) => `${key}=${JSON.stringify(value)}`) 142 | .join(' ') 143 | 144 | const link = 145 | `` 150 | 151 | this.links.push($(link)) 152 | } 153 | 154 | /* 155 | * populate the array of links and display them by prepending them to the 156 | * body of the cross-site navigation bar 157 | */ 158 | addLinks () { 159 | // create the subset of the TLD -> country-code map (SITES) 160 | // corresponding to the enabled sites 161 | const sites = Object.entries(SITES) 162 | .filter(([tld]) => GM_config.get(tld)) 163 | .reduce((obj, [key, val]) => { return obj[key] = val, obj }, {}) 164 | 165 | if ($.isEmptyObject(sites)) { 166 | return 167 | } 168 | 169 | // sort the sites by the country code (e.g. AU) rather than the TLD 170 | // (e.g. com.au) 171 | // const tlds = sortBy(Object.keys(sites), tld => sites[tld]) 172 | const tlds = Object.keys(sites).sort((a, b) => sites[a].localeCompare(sites[b])) 173 | 174 | // populate the `links` array with jQuery wrappers for each link 175 | // element (e.g.
  • ...
  • ) 176 | for (const tld of tlds) { 177 | this.addLink(tld, sites[tld]) 178 | } 179 | 180 | // prepend the cross-site links to the body of the navbar 181 | this.navbar.prepend(...this.links) 182 | } 183 | 184 | /* 185 | * build the underlying data model used by the GM_config utility 186 | */ 187 | initializeConfig () { 188 | const checkboxes = {} 189 | 190 | // sort by country code 191 | for (const tld of Object.keys(SITES).sort((a, b) => SITES[a].localeCompare(SITES[b]))) { 192 | const country = SITES[tld] 193 | 194 | checkboxes[tld] = { 195 | type: 'checkbox', 196 | label: country, 197 | title: `amazon.${tld}`, 198 | default: (country === 'UK' || country === 'US') 199 | } 200 | } 201 | 202 | // re-render the links when the settings are updated 203 | const save = () => { 204 | this.removeLinks() 205 | this.addLinks() 206 | GM_config.close() 207 | } 208 | 209 | const callbacks = { save } 210 | 211 | GM_config.init('Amazon International Links Settings', checkboxes, callbacks) 212 | } 213 | 214 | /* 215 | * remove all added links from the DOM and clear the array referencing them 216 | */ 217 | removeLinks () { 218 | const { links } = this 219 | 220 | for (const $link of links) { 221 | $link.remove() // remove from the DOM... 222 | } 223 | 224 | links.length = 0 // ...and empty the array 225 | } 226 | } 227 | 228 | /*********************** Main ********************************/ 229 | 230 | const run = () => { 231 | const asin = Linker.getASIN() 232 | 233 | if (!asin) { 234 | return 235 | } 236 | 237 | const showConfig = () => GM_config.open() // display the settings manager 238 | const linker = new Linker(asin) 239 | 240 | linker.initializeConfig() 241 | linker.addLinks() 242 | 243 | GM_registerMenuCommand('Configure Amazon International Links', showConfig) 244 | } 245 | 246 | run() 247 | -------------------------------------------------------------------------------- /src/twitter-linkify-trends.user.ts: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Twitter Linkify Trends 3 | // @description Make Twitter trends links (again) 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 3.3.2 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://mobile.x.com/ 10 | // @include https://mobile.x.com/* 11 | // @include https://x.com/ 12 | // @include https://x.com/* 13 | // @require https://code.jquery.com/jquery-3.7.1.slim.min.js 14 | // @require https://unpkg.com/gm-compat@1.1.0/dist/index.iife.min.js 15 | // @require https://unpkg.com/@chocolateboy/uncommonjs@3.2.1/dist/polyfill.iife.min.js 16 | // @require https://unpkg.com/get-wild@3.0.2/dist/index.umd.min.js 17 | // @require https://unpkg.com/flru@1.0.2/dist/flru.min.js 18 | // @grant GM_log 19 | // @run-at document-start 20 | // ==/UserScript== 21 | 22 | /// 23 | /// 24 | 25 | // XXX needed to appease esbuild 26 | export {} 27 | 28 | import { observe } from './lib/observer.js' 29 | 30 | declare const exports: { 31 | default: typeof import('flru').default; 32 | get: typeof import('get-wild').get; 33 | } 34 | 35 | type EventDataHandler = (json: string, path: string) => void; 36 | type EventDataHandlersValue = string | { path: string, handler: EventDataHandler }; 37 | 38 | type SidebarEvent = { 39 | core: { name: string }; 40 | rest_id: string; 41 | } 42 | 43 | type TimelineEvent = { 44 | itemType: string; 45 | name: string; 46 | trend_url: { url: string }; 47 | } 48 | 49 | /** 50 | * a map from event titles to their URLs. populated via the intercepted event 51 | * data (JSON) 52 | * 53 | * uses an LRU cache (flru) with up to 256 (128 * 2) entries 54 | */ 55 | const CACHE = exports.default(128) 56 | 57 | /* 58 | * DOM events to disable (stop propagating) on event and trend elements 59 | */ 60 | const DISABLED_EVENTS = 'click touch' 61 | 62 | /* 63 | * A map from the basename (e.g. "ExplorePage") of endpoints which return JSON 64 | * documents with event data (e.g. /i/api/graphql/abc123/ExplorePage) to the 65 | * path within those documents containing the event data. each event record 66 | * includes a title and target URI 67 | */ 68 | const EVENT_DATA_HANDLERS = new Map([ 69 | [ 70 | 'ExplorePage', 71 | 'data.explore_page.body.initialTimeline.timeline.timeline.instructions[-1].entries.*.content.items.*.item.itemContent', 72 | ], 73 | [ 74 | 'GenericTimelineById', 75 | 'data.timeline.timeline.instructions[-1].entries.*.content.items.*.item.itemContent', 76 | ], 77 | [ 78 | 'SearchTimeline', 79 | 'data.search_by_raw_query.search_timeline.timeline.instructions[-1].entries.*.content.items.*.item.itemContent', 80 | ], 81 | [ 82 | 'useStoryTopicQuery', 83 | { 84 | path: 'data.story_topic.stories.items.*.trend_results.result', 85 | handler: onSidebarEventData, 86 | } 87 | ], 88 | ]) 89 | 90 | /* 91 | * selectors for trend elements and event elements (i.e. Twitter's AI-curated 92 | * news links). works for trends/events in the "What's happening" panel in the 93 | * sidebar, on the dedicated trends pages (https://x.com/explore/tabs/*) and in 94 | * search results (https://x.com/search?q=foo) 95 | */ 96 | const CARET = '[data-testid="caret"]' 97 | const IS_TREND = '[data-testid="trend"]' 98 | const HAS_MENU = `:has(${CARET})` 99 | const TIMELINE_EVENT = `${IS_TREND}:not(${HAS_MENU})` 100 | const SIDEBAR_EVENT = '[data-testid^="news_sidebar_article_"]' 101 | const EVENT = `:is(${TIMELINE_EVENT}, ${SIDEBAR_EVENT})` 102 | const TREND = `${IS_TREND}${HAS_MENU}` 103 | 104 | // any trend/event element (distinguished in the element handler (onElement)), 105 | // excluding the ones we've already processed ([data-linked="true"]) 106 | const SELECTOR = [EVENT, TREND].map(it => `div[role="link"]${it}:not([data-linked])`).join(', ') 107 | 108 | /* 109 | * remove the onclick interceptors from event elements 110 | */ 111 | function disableAll (e: JQuery.Event) { 112 | // don't preventDefault: we still want links to work 113 | e.stopPropagation() 114 | } 115 | 116 | /** 117 | * remove the onclick interceptors from trend elements, apart from clicks on the 118 | * caret (which opens a drop-down menu) 119 | */ 120 | function disableSome (this: HTMLElement, e: JQueryEventObject) { 121 | const $target = $(e.target) 122 | const $caret = $target.closest(CARET, this) 123 | 124 | if (!$caret.length) { 125 | // don't preventDefault: we still want links to work 126 | e.stopPropagation() 127 | } 128 | } 129 | 130 | /** 131 | * intercept XMLHTTPRequest#open requests for event data and pass the response 132 | * to a custom handler which extracts the URLs for the event elements 133 | * 134 | * @param {XMLHttpRequest['open']} oldOpen 135 | * @returns {XMLHttpRequest['open']} 136 | */ 137 | function hookXHROpen (oldOpen: XMLHttpRequest['open']) { 138 | return function open (this: XMLHttpRequest, _method: string, url: string) { // preserve the arity 139 | const endpoint = URL.parse(url)?.pathname.split('/').at(-1) ?? '' 140 | const $path = EVENT_DATA_HANDLERS.get(endpoint) 141 | 142 | if ($path) { 143 | const [path, handler] = typeof $path === 'string' 144 | ? [$path, onTimelineEventData] 145 | : [$path.path, $path.handler] 146 | 147 | // register a new listener 148 | this.addEventListener('load', () => handler(this.responseText, path)) 149 | } 150 | 151 | // delegate to the original XHR#open handler 152 | return GMCompat.apply(this, oldOpen, arguments) 153 | } 154 | } 155 | 156 | /* 157 | * create a link (A) which targets the specified URL 158 | * 159 | * used to wrap the trend/event titles 160 | */ 161 | function linkFor (href: string) { 162 | return $('') 163 | .attr({ href, role: 'link', 'data-focusable': true }) 164 | .css({ color: 'inherit', textDecoration: 'inherit' }) 165 | } 166 | 167 | /* 168 | * process a newly-created trend or event element 169 | */ 170 | function onElement (el: HTMLElement) { 171 | const $el = $(el) 172 | 173 | let linked = true 174 | 175 | // determine the element's type and pass it to the appropriate handler 176 | if ($el.is(EVENT)) { 177 | $el.on(DISABLED_EVENTS, disableAll) 178 | linked = onEventElement($el) 179 | } else if ($el.is(TREND)) { 180 | $el.on(DISABLED_EVENTS, disableSome) 181 | onTrendElement($el) 182 | } 183 | 184 | // a link was added: tag the element so we don't select it again 185 | if (linked) { 186 | $el.css('cursor', 'auto') // remove the fake pointer 187 | $el.attr('data-linked', 'true') 188 | } 189 | } 190 | 191 | /* 192 | * linkify an event element: the target URL is (was) extracted from the 193 | * intercepted JSON 194 | * 195 | * returns true if the link has been added (i.e. the event data has been 196 | * loaded), false otherwise (i.e. try again on the next DOM update) 197 | */ 198 | function onEventElement ($event: JQuery): boolean { 199 | const { target, title } = targetFor($event) 200 | const url = CACHE.get(title) 201 | 202 | // the JSON may be loaded after the element is detected, so wait until the 203 | // target URL becomes available 204 | if (!url) { 205 | return false 206 | } 207 | 208 | console.debug(`element (event):`, JSON.stringify(title)) 209 | const $link = linkFor(url) 210 | $(target).parent().wrap($link) 211 | return true 212 | } 213 | 214 | /* 215 | * process the (JSON) data for events in the "Today's News" sidebar: extract 216 | * title/URL pairs for the event elements and store them in a cache 217 | */ 218 | function onSidebarEventData (json: string, path: string) { 219 | const data = JSON.parse(json) 220 | const events = exports.get(data, path, []) 221 | 222 | for (const event of events) { 223 | const { core: { name: title }, rest_id: id } = event 224 | const url = `${location.origin}/i/trending/${id}` 225 | console.debug('data (sidebar event):', { title, url }) 226 | CACHE.set(title, url) 227 | } 228 | } 229 | 230 | /* 231 | * process the (JSON) data for timeline events: extract title/URL pairs for the 232 | * event elements and store them in a cache 233 | */ 234 | function onTimelineEventData (json: string, path: string) { 235 | const data = JSON.parse(json) 236 | const events = exports.get(data, path, []) 237 | 238 | for (const event of events) { 239 | if (event.itemType !== 'TimelineTrend') { 240 | continue 241 | } 242 | 243 | const { name: title, trend_url: { url: uri } } = event 244 | const url = uri.replace(/^twitter:\/\//, `${location.origin}/i/`) 245 | console.debug('data (timeline event):', { title, url }) 246 | CACHE.set(title, url) 247 | } 248 | } 249 | 250 | /* 251 | * linkify a trend element: the target URL is derived from the title in the 252 | * element rather than from the JSON data 253 | */ 254 | function onTrendElement ($trend: JQuery) { 255 | const { target, title } = targetFor($trend) 256 | // use Twitter's quoting rule for compatibility 257 | const trend = /\s/.test(title) ? `"${title.replace(/"/g, '')}"` : title 258 | 259 | console.debug('element (trend):', trend) 260 | 261 | const query = encodeURIComponent(trend) 262 | const url = `${location.origin}/search?q=${query}&src=trend_click&vertical=trends` 263 | 264 | $(target).wrap(linkFor(url)) 265 | } 266 | 267 | /* 268 | * given a trend or event element, return its target element (the SPAN 269 | * containing the element's title) along with its title text 270 | */ 271 | function targetFor ($el: JQuery) { 272 | // the target element is the last bold SPAN (live events have a preceding 273 | // bold SPAN containing the word "LIVE" in the header) 274 | const targets = $el.find('div[dir="ltr"] > span').filter((_, el) => { 275 | // the class for this is currently r-b88u0q (700) or r-1vr29t4 for 276 | // hero images (800) 277 | const fontWeight = Number($(el).parent().css('fontWeight') || 0) 278 | return fontWeight >= 700 279 | }) 280 | 281 | const target = targets.get().pop()! 282 | const title = $(target).text().trim() 283 | 284 | return { target, title } 285 | } 286 | 287 | /******************************************************************************/ 288 | 289 | /* 290 | * monitor the creation of trend/event elements 291 | */ 292 | function run () { 293 | const target = document.getElementById('react-root') 294 | 295 | if (!target) { 296 | console.warn("can't find react-root element") 297 | return 298 | } 299 | 300 | observe(target, () => { 301 | for (const el of $(SELECTOR)) { 302 | onElement(el) 303 | } 304 | }) 305 | } 306 | 307 | // hook HMLHTTPRequest#open so we can extract event data from the JSON 308 | const xhrProto = GMCompat.unsafeWindow.XMLHttpRequest.prototype 309 | 310 | xhrProto.open = GMCompat.export(hookXHROpen(xhrProto.open)) 311 | 312 | // monitor the creation of trend/event elements after the page has loaded 313 | // 314 | // this script needs to be loaded early enough to intercept the JSON 315 | // (document-start), but run after the page has loaded (DOMContentLoaded). this 316 | // ensures the latter 317 | $(run) 318 | -------------------------------------------------------------------------------- /src/twitter-direct/replacer.ts: -------------------------------------------------------------------------------- 1 | import { 2 | isNumber, 3 | isObject, 4 | isPlainObject, 5 | isString, 6 | Dict, 7 | Json, 8 | JsonObject, 9 | } from './util' 10 | 11 | type FullTextContext = Dict & { 12 | entities?: any; 13 | lang?: string; 14 | } 15 | 16 | type Target = { target: Dict, key: string }; 17 | 18 | type URLData = { 19 | url: string; 20 | expanded_url: string; 21 | indices: [number, number]; 22 | } 23 | 24 | /* 25 | * document keys under which t.co URL nodes can be found when the document is a 26 | * plain object. not used when the document is an array. 27 | * 28 | * some densely-populated top-level paths don't contain t.co URLs, e.g. 29 | * $.timeline. 30 | */ 31 | const DOCUMENT_ROOTS = [ 32 | 'data', 33 | 'globalObjects', 34 | 'inbox_initial_state', 35 | 'users', 36 | ] 37 | 38 | /* 39 | * keys of "legacy" objects which URL data is known to be found in/under, e.g. 40 | * we're interested in legacy.user_refs.* and legacy.retweeted_status.*, but not 41 | * legacy.created_at or legacy.reply_count. 42 | * 43 | * legacy objects typically contain dozens of keys, but t.co URLs only exist in 44 | * a handful of them. typically this reduces the number of keys to traverse in a 45 | * legacy object from 30 on average (max 39) to 2 or 3. 46 | */ 47 | const LEGACY_KEYS = [ 48 | 'binding_values', 49 | 'entities', 50 | 'extended_entities', 51 | 'full_text', 52 | 'lang', 53 | 'quoted_status_permalink', 54 | 'retweeted_status', 55 | 'retweeted_status_result', 56 | 'user_refs', 57 | ] 58 | 59 | /* 60 | * nodes under these keys never contain t.co URLs so we can speed up traversal 61 | * by pruning (not descending) them 62 | */ 63 | const PRUNE_KEYS = new Set([ 64 | 'advertiser_account_service_levels', 65 | 'card_platform', 66 | 'clientEventInfo', 67 | 'ext', 68 | 'ext_media_color', 69 | 'features', 70 | 'feedbackInfo', 71 | 'hashtags', 72 | 'indices', 73 | 'original_info', 74 | 'player_image_color', 75 | 'profile_banner_extensions', 76 | 'profile_banner_extensions_media_color', 77 | 'profile_image_extensions', 78 | 'profile_image_extensions_media_color', 79 | 'responseObjects', 80 | 'sizes', 81 | 'user_mentions', 82 | 'video_info', 83 | ]) 84 | 85 | /* 86 | * return a truthy value (the URL itself) if the supplied value is a valid URL 87 | * (string), falsey otherwise 88 | */ 89 | const checkUrl = (function () { 90 | // this is faster than using the URL constructor (in v8), which incurs 91 | // the overhead of using a try/catch block 92 | const urlPattern = /^https?:\/\/\w/i 93 | 94 | // no need to coerce the value to a string as RegExp#test does that 95 | // automatically 96 | // 97 | // https://tc39.es/ecma262/#sec-regexp.prototype.test 98 | return (value: unknown) => urlPattern.test(value as string) && value as string 99 | })() 100 | 101 | /* 102 | * return true if the supplied value is a t.co URL (string), false otherwise 103 | */ 104 | const isTrackedUrl = (function () { 105 | // this is faster (in v8) than using the URL constructor (and a try/catch 106 | // block) 107 | const urlPattern = /^https?:\/\/t\.co\/\w+$/ 108 | 109 | // no need to coerce the value to a string as RegExp#test does that 110 | // automatically 111 | return (value: unknown): value is string => urlPattern.test(value as string) 112 | })() 113 | 114 | const isURLData = (value: unknown): value is URLData => { 115 | return isPlainObject(value) 116 | && isString(value.url) 117 | && isString(value.expanded_url) 118 | && Array.isArray(value.indices) 119 | && isNumber(value.indices[0]) 120 | && isNumber(value.indices[1]) 121 | } 122 | 123 | class Replacer { 124 | private readonly seen = new Map(); 125 | private readonly unresolved = new Map(); 126 | private count = 0; 127 | 128 | public static transform (data: JsonObject, path: string): number { 129 | const replacer = new Replacer() 130 | return replacer.transform(data, path) 131 | } 132 | 133 | /* 134 | * replace t.co URLs with the original URL in all locations in the document 135 | * which may contain them 136 | * 137 | * returns the number of substituted URLs 138 | */ 139 | protected transform (data: JsonObject, path: string): number { 140 | const { seen, unresolved } = this 141 | 142 | // [1] top-level tweet or user data (e.g. /favorites/create.json) 143 | if (Array.isArray(data) || ('id_str' in data) /* [1] */) { 144 | this.traverse(data) 145 | } else { 146 | for (const key of DOCUMENT_ROOTS) { 147 | if (key in data) { 148 | this.traverse(data[key]) 149 | } 150 | } 151 | } 152 | 153 | for (const [url, targets] of unresolved) { 154 | const expandedUrl = seen.get(url) 155 | 156 | if (expandedUrl) { 157 | for (const { target, key } of targets) { 158 | target[key] = expandedUrl 159 | ++this.count 160 | } 161 | 162 | unresolved.delete(url) 163 | } 164 | } 165 | 166 | if (unresolved.size) { 167 | console.warn(`unresolved URIs (${path}):`, Object.fromEntries(unresolved)) 168 | } 169 | 170 | return this.count 171 | } 172 | 173 | /* 174 | * reduce the large binding_values array/object to the one property we care 175 | * about (card_url) 176 | */ 177 | private onBindingValues (value: Json): Json { 178 | if (Array.isArray(value)) { 179 | const found = value.find(it => (it as Dict)?.key === 'card_url') 180 | return found ? [found] : 0 181 | } else if (isPlainObject(value) && isPlainObject(value.card_url)) { 182 | return [value.card_url] 183 | } else { 184 | return 0 185 | } 186 | } 187 | 188 | /* 189 | * handle cases where the t.co URL is already expanded, e.g.: 190 | * 191 | * { 192 | * "entities": { 193 | * "urls": [ 194 | * { 195 | * "display_url": "example.com", 196 | * "expanded_url": "https://www.example.com", 197 | * "url": "https://www.example.com", 198 | * "indices": [16, 39] 199 | * } 200 | * ] 201 | * }, 202 | * "full_text": "I'm on the bus! https://t.co/abcde12345" 203 | * } 204 | * 205 | * extract the corresponding t.co URLs from the text via the entities.urls 206 | * records and register the t.co -> expanded URL mappings so they can be 207 | * used later, e.g. https://t.co/abcde12345 -> https://www.example.com 208 | */ 209 | private onFullText (context: FullTextContext, message: string): string { 210 | const seen = this.seen 211 | const urls = context.entities?.urls 212 | 213 | if (!(Array.isArray(urls) && urls.length)) { 214 | return message 215 | } 216 | 217 | const $message = Array.from(message) 218 | 219 | for (let i = 0; i < urls.length; ++i) { 220 | const $url = urls[i] 221 | 222 | if (!isURLData($url)) { 223 | break 224 | } 225 | 226 | const { 227 | url, 228 | expanded_url: expandedUrl, 229 | indices: [start, end] 230 | } = $url 231 | 232 | const alreadyExpanded = !isTrackedUrl(url) && expandedUrl === url 233 | 234 | if (!alreadyExpanded) { 235 | continue 236 | } 237 | 238 | const trackedUrl = (context.lang === 'zxx') // just a URL 239 | ? message 240 | : $message.slice(start, end).join('') 241 | 242 | seen.set(trackedUrl, expandedUrl) 243 | } 244 | 245 | return message 246 | } 247 | 248 | /* 249 | * reduce the keys under $.legacy (typically around 30) to the 250 | * handful we care about 251 | */ 252 | private onLegacyObject (value: Dict): Dict { 253 | // XXX don't expand legacy.url: leaving it unexpanded results in media 254 | // URLs (e.g. YouTube URLs) appearing as clickable links in the tweet 255 | // (which we want) 256 | 257 | // we could use an array, but it doesn't appear to be faster (in v8) 258 | const filtered: Dict = {} 259 | 260 | for (let i = 0; i < LEGACY_KEYS.length; ++i) { 261 | const key = LEGACY_KEYS[i] 262 | 263 | if (key in value) { 264 | filtered[key] = value[key] 265 | } 266 | } 267 | 268 | return filtered 269 | } 270 | 271 | /* 272 | * expand t.co URL nodes in place, either $.url or $.string_value in 273 | * binding_values arrays/objects 274 | */ 275 | private onTrackedURL (context: Dict, key: string, url: string): string { 276 | const { seen, unresolved } = this 277 | 278 | let expandedUrl 279 | 280 | if ((expandedUrl = seen.get(url))) { 281 | context[key] = expandedUrl 282 | ++this.count 283 | } else if ((expandedUrl = checkUrl(context.expanded_url || context.expanded))) { 284 | seen.set(url, expandedUrl) 285 | context[key] = expandedUrl 286 | ++this.count 287 | } else { 288 | let targets = unresolved.get(url) 289 | 290 | if (!targets) { 291 | unresolved.set(url, targets = []) 292 | } 293 | 294 | targets.push({ target: context, key }) 295 | } 296 | 297 | return url 298 | } 299 | 300 | /* 301 | * traverse an object by hijacking JSON.stringify's visitor (replacer). 302 | * dispatches each node to the +visit+ method 303 | */ 304 | private traverse (data: Json): void { 305 | if (!isObject(data)) { 306 | return 307 | } 308 | 309 | const self = this 310 | const replacer = function (this: JsonObject, key: string, value: Json) { 311 | return Array.isArray(this) ? value : self.visit(this, key, value) 312 | } 313 | 314 | JSON.stringify(data, replacer) 315 | } 316 | 317 | /* 318 | * visitor callback which replaces a t.co +url+ property in an object with 319 | * its expanded URL 320 | */ 321 | private visit (context: Dict, key: string, value: Json): Json { 322 | // exclude subtrees which never contain t.co URLs 323 | if (PRUNE_KEYS.has(key)) { 324 | return 0 // a terminal value to stop traversal 325 | } 326 | 327 | switch (key) { 328 | case 'binding_values': 329 | // we only care about the "card_url" property in binding_values 330 | // objects/arrays. exclude the other 24 properties 331 | return this.onBindingValues(value) 332 | 333 | case 'full_text': 334 | // if a URL is already expanded, extract its t.co URL and link 335 | // it to the expansion 336 | if (isString(value)) { 337 | return this.onFullText(context, value) 338 | } 339 | break 340 | 341 | case 'legacy': 342 | // reduce the keys under $.legacy (typically around 30) to 343 | // the handful we care about 344 | if (isPlainObject(value)) { 345 | return this.onLegacyObject(value) 346 | } 347 | break 348 | 349 | case 'string_value': 350 | case 'url': 351 | // expand t.co URL nodes in place 352 | if (isTrackedUrl(value)) { 353 | return this.onTrackedURL(context, key, value) 354 | } 355 | break 356 | } 357 | 358 | return value 359 | } 360 | } 361 | 362 | export default Replacer 363 | -------------------------------------------------------------------------------- /dist/twitter-direct.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name Twitter Direct 3 | // @description Remove t.co tracking links from Twitter 4 | // @author chocolateboy 5 | // @copyright chocolateboy 6 | // @version 3.1.2 7 | // @namespace https://github.com/chocolateboy/userscripts 8 | // @license GPL 9 | // @include https://mobile.twitter.com/ 10 | // @include https://mobile.twitter.com/* 11 | // @include https://twitter.com/ 12 | // @include https://twitter.com/* 13 | // @include https://x.com/ 14 | // @include https://x.com/* 15 | // @require https://unpkg.com/gm-compat@1.1.0/dist/index.iife.min.js 16 | // @run-at document-start 17 | // ==/UserScript== 18 | 19 | // NOTE This file is generated from src/twitter-direct.user.ts and should not be edited directly. 20 | 21 | "use strict"; 22 | (() => { 23 | // src/twitter-direct/util.ts 24 | var isObject = (value) => !!value && typeof value === "object"; 25 | var isPlainObject = function() { 26 | const toString = {}.toString; 27 | return (value) => toString.call(value) === "[object Object]"; 28 | }(); 29 | var typeOf = (value) => value === null ? "null" : typeof value; 30 | var isType = (type) => { 31 | return (value) => { 32 | return typeOf(value) === type; 33 | }; 34 | }; 35 | var isString = isType("string"); 36 | var isNumber = isType("number"); 37 | 38 | // src/twitter-direct/replacer.ts 39 | var DOCUMENT_ROOTS = [ 40 | "data", 41 | "globalObjects", 42 | "inbox_initial_state", 43 | "users" 44 | ]; 45 | var LEGACY_KEYS = [ 46 | "binding_values", 47 | "entities", 48 | "extended_entities", 49 | "full_text", 50 | "lang", 51 | "quoted_status_permalink", 52 | "retweeted_status", 53 | "retweeted_status_result", 54 | "user_refs" 55 | ]; 56 | var PRUNE_KEYS = /* @__PURE__ */ new Set([ 57 | "advertiser_account_service_levels", 58 | "card_platform", 59 | "clientEventInfo", 60 | "ext", 61 | "ext_media_color", 62 | "features", 63 | "feedbackInfo", 64 | "hashtags", 65 | "indices", 66 | "original_info", 67 | "player_image_color", 68 | "profile_banner_extensions", 69 | "profile_banner_extensions_media_color", 70 | "profile_image_extensions", 71 | "profile_image_extensions_media_color", 72 | "responseObjects", 73 | "sizes", 74 | "user_mentions", 75 | "video_info" 76 | ]); 77 | var checkUrl = /* @__PURE__ */ function() { 78 | const urlPattern = /^https?:\/\/\w/i; 79 | return (value) => urlPattern.test(value) && value; 80 | }(); 81 | var isTrackedUrl = /* @__PURE__ */ function() { 82 | const urlPattern = /^https?:\/\/t\.co\/\w+$/; 83 | return (value) => urlPattern.test(value); 84 | }(); 85 | var isURLData = (value) => { 86 | return isPlainObject(value) && isString(value.url) && isString(value.expanded_url) && Array.isArray(value.indices) && isNumber(value.indices[0]) && isNumber(value.indices[1]); 87 | }; 88 | var Replacer = class _Replacer { 89 | seen = /* @__PURE__ */ new Map(); 90 | unresolved = /* @__PURE__ */ new Map(); 91 | count = 0; 92 | static transform(data, path) { 93 | const replacer = new _Replacer(); 94 | return replacer.transform(data, path); 95 | } 96 | /* 97 | * replace t.co URLs with the original URL in all locations in the document 98 | * which may contain them 99 | * 100 | * returns the number of substituted URLs 101 | */ 102 | transform(data, path) { 103 | const { seen, unresolved } = this; 104 | if (Array.isArray(data) || "id_str" in data) { 105 | this.traverse(data); 106 | } else { 107 | for (const key of DOCUMENT_ROOTS) { 108 | if (key in data) { 109 | this.traverse(data[key]); 110 | } 111 | } 112 | } 113 | for (const [url, targets] of unresolved) { 114 | const expandedUrl = seen.get(url); 115 | if (expandedUrl) { 116 | for (const { target, key } of targets) { 117 | target[key] = expandedUrl; 118 | ++this.count; 119 | } 120 | unresolved.delete(url); 121 | } 122 | } 123 | if (unresolved.size) { 124 | console.warn(`unresolved URIs (${path}):`, Object.fromEntries(unresolved)); 125 | } 126 | return this.count; 127 | } 128 | /* 129 | * reduce the large binding_values array/object to the one property we care 130 | * about (card_url) 131 | */ 132 | onBindingValues(value) { 133 | if (Array.isArray(value)) { 134 | const found = value.find((it) => it?.key === "card_url"); 135 | return found ? [found] : 0; 136 | } else if (isPlainObject(value) && isPlainObject(value.card_url)) { 137 | return [value.card_url]; 138 | } else { 139 | return 0; 140 | } 141 | } 142 | /* 143 | * handle cases where the t.co URL is already expanded, e.g.: 144 | * 145 | * { 146 | * "entities": { 147 | * "urls": [ 148 | * { 149 | * "display_url": "example.com", 150 | * "expanded_url": "https://www.example.com", 151 | * "url": "https://www.example.com", 152 | * "indices": [16, 39] 153 | * } 154 | * ] 155 | * }, 156 | * "full_text": "I'm on the bus! https://t.co/abcde12345" 157 | * } 158 | * 159 | * extract the corresponding t.co URLs from the text via the entities.urls 160 | * records and register the t.co -> expanded URL mappings so they can be 161 | * used later, e.g. https://t.co/abcde12345 -> https://www.example.com 162 | */ 163 | onFullText(context, message) { 164 | const seen = this.seen; 165 | const urls = context.entities?.urls; 166 | if (!(Array.isArray(urls) && urls.length)) { 167 | return message; 168 | } 169 | const $message = Array.from(message); 170 | for (let i = 0; i < urls.length; ++i) { 171 | const $url = urls[i]; 172 | if (!isURLData($url)) { 173 | break; 174 | } 175 | const { 176 | url, 177 | expanded_url: expandedUrl, 178 | indices: [start, end] 179 | } = $url; 180 | const alreadyExpanded = !isTrackedUrl(url) && expandedUrl === url; 181 | if (!alreadyExpanded) { 182 | continue; 183 | } 184 | const trackedUrl = context.lang === "zxx" ? message : $message.slice(start, end).join(""); 185 | seen.set(trackedUrl, expandedUrl); 186 | } 187 | return message; 188 | } 189 | /* 190 | * reduce the keys under $.legacy (typically around 30) to the 191 | * handful we care about 192 | */ 193 | onLegacyObject(value) { 194 | const filtered = {}; 195 | for (let i = 0; i < LEGACY_KEYS.length; ++i) { 196 | const key = LEGACY_KEYS[i]; 197 | if (key in value) { 198 | filtered[key] = value[key]; 199 | } 200 | } 201 | return filtered; 202 | } 203 | /* 204 | * expand t.co URL nodes in place, either $.url or $.string_value in 205 | * binding_values arrays/objects 206 | */ 207 | onTrackedURL(context, key, url) { 208 | const { seen, unresolved } = this; 209 | let expandedUrl; 210 | if (expandedUrl = seen.get(url)) { 211 | context[key] = expandedUrl; 212 | ++this.count; 213 | } else if (expandedUrl = checkUrl(context.expanded_url || context.expanded)) { 214 | seen.set(url, expandedUrl); 215 | context[key] = expandedUrl; 216 | ++this.count; 217 | } else { 218 | let targets = unresolved.get(url); 219 | if (!targets) { 220 | unresolved.set(url, targets = []); 221 | } 222 | targets.push({ target: context, key }); 223 | } 224 | return url; 225 | } 226 | /* 227 | * traverse an object by hijacking JSON.stringify's visitor (replacer). 228 | * dispatches each node to the +visit+ method 229 | */ 230 | traverse(data) { 231 | if (!isObject(data)) { 232 | return; 233 | } 234 | const self = this; 235 | const replacer = function(key, value) { 236 | return Array.isArray(this) ? value : self.visit(this, key, value); 237 | }; 238 | JSON.stringify(data, replacer); 239 | } 240 | /* 241 | * visitor callback which replaces a t.co +url+ property in an object with 242 | * its expanded URL 243 | */ 244 | visit(context, key, value) { 245 | if (PRUNE_KEYS.has(key)) { 246 | return 0; 247 | } 248 | switch (key) { 249 | case "binding_values": 250 | return this.onBindingValues(value); 251 | case "full_text": 252 | if (isString(value)) { 253 | return this.onFullText(context, value); 254 | } 255 | break; 256 | case "legacy": 257 | if (isPlainObject(value)) { 258 | return this.onLegacyObject(value); 259 | } 260 | break; 261 | case "string_value": 262 | case "url": 263 | if (isTrackedUrl(value)) { 264 | return this.onTrackedURL(context, key, value); 265 | } 266 | break; 267 | } 268 | return value; 269 | } 270 | }; 271 | var replacer_default = Replacer; 272 | 273 | // src/twitter-direct.user.ts 274 | // @license GPL 275 | var URL_BLACKLIST = /* @__PURE__ */ new Set([ 276 | "/hashflags.json", 277 | "/badge_count/badge_count.json", 278 | "/graphql/articleNudgeDomains", 279 | "/graphql/TopicToFollowSidebar" 280 | ]); 281 | var CONTENT_TYPE = /^application\/json\b/; 282 | var LOG_THRESHOLD = 1024; 283 | var STATS = {}; 284 | var TWITTER_API = /^(?:(?:api|mobile)\.)?(?:twitter|x)\.com$/; 285 | var onResponse = (xhr, uri) => { 286 | const contentType = xhr.getResponseHeader("Content-Type"); 287 | if (!contentType || !CONTENT_TYPE.test(contentType)) { 288 | return; 289 | } 290 | const url = new URL(uri); 291 | if (!TWITTER_API.test(url.hostname)) { 292 | return; 293 | } 294 | const json = xhr.responseText; 295 | const size = json.length; 296 | const path = url.pathname.replace(/^\/i\/api\//, "/").replace(/^\/\d+(\.\d+)*\//, "/").replace(/(\/graphql\/)[^\/]+\/(.+)$/, "$1$2").replace(/\/\d+\.json$/, ".json"); 297 | if (URL_BLACKLIST.has(path)) { 298 | return; 299 | } 300 | let data; 301 | try { 302 | data = JSON.parse(json); 303 | } catch (e) { 304 | console.error(`Can't parse JSON for ${uri}:`, e); 305 | return; 306 | } 307 | if (!isObject(data)) { 308 | return; 309 | } 310 | const newPath = !(path in STATS); 311 | const count = replacer_default.transform(data, path); 312 | STATS[path] = (STATS[path] || 0) + count; 313 | if (!count) { 314 | if (STATS[path] === 0 && size > LOG_THRESHOLD) { 315 | console.debug(`no replacements in ${path} (${size} B)`); 316 | } 317 | return; 318 | } 319 | const descriptor = { value: JSON.stringify(data) }; 320 | const clone = GMCompat.export(descriptor); 321 | GMCompat.unsafeWindow.Object.defineProperty(xhr, "responseText", clone); 322 | const replacements = "replacement" + (count === 1 ? "" : "s"); 323 | console.debug(`${count} ${replacements} in ${path} (${size} B)`); 324 | if (newPath) { 325 | console.log(STATS); 326 | } 327 | }; 328 | var hookXHRSend = (oldSend) => { 329 | return function send2(body = null) { 330 | const oldOnReadyStateChange = this.onreadystatechange; 331 | this.onreadystatechange = function(event) { 332 | if (this.readyState === this.DONE && this.responseURL && this.status === 200) { 333 | onResponse(this, this.responseURL); 334 | } 335 | if (oldOnReadyStateChange) { 336 | oldOnReadyStateChange.call(this, event); 337 | } 338 | }; 339 | oldSend.call(this, body); 340 | }; 341 | }; 342 | var xhrProto = GMCompat.unsafeWindow.XMLHttpRequest.prototype; 343 | var send = hookXHRSend(xhrProto.send); 344 | xhrProto.send = GMCompat.export(send); 345 | })(); 346 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ### GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this 9 | license document, but changing it is not allowed. 10 | 11 | ### Preamble 12 | 13 | The GNU General Public License is a free, copyleft license for 14 | software and other kinds of works. 15 | 16 | The licenses for most software and other practical works are designed 17 | to take away your freedom to share and change the works. By contrast, 18 | the GNU General Public License is intended to guarantee your freedom 19 | to share and change all versions of a program--to make sure it remains 20 | free software for all its users. We, the Free Software Foundation, use 21 | the GNU General Public License for most of our software; it applies 22 | also to any other work released this way by its authors. You can apply 23 | it to your programs, too. 24 | 25 | When we speak of free software, we are referring to freedom, not 26 | price. Our General Public Licenses are designed to make sure that you 27 | have the freedom to distribute copies of free software (and charge for 28 | them if you wish), that you receive source code or can get it if you 29 | want it, that you can change the software or use pieces of it in new 30 | free programs, and that you know you can do these things. 31 | 32 | To protect your rights, we need to prevent others from denying you 33 | these rights or asking you to surrender the rights. Therefore, you 34 | have certain responsibilities if you distribute copies of the 35 | software, or if you modify it: responsibilities to respect the freedom 36 | of others. 37 | 38 | For example, if you distribute copies of such a program, whether 39 | gratis or for a fee, you must pass on to the recipients the same 40 | freedoms that you received. You must make sure that they, too, receive 41 | or can get the source code. And you must show them these terms so they 42 | know their rights. 43 | 44 | Developers that use the GNU GPL protect your rights with two steps: 45 | (1) assert copyright on the software, and (2) offer you this License 46 | giving you legal permission to copy, distribute and/or modify it. 47 | 48 | For the developers' and authors' protection, the GPL clearly explains 49 | that there is no warranty for this free software. For both users' and 50 | authors' sake, the GPL requires that modified versions be marked as 51 | changed, so that their problems will not be attributed erroneously to 52 | authors of previous versions. 53 | 54 | Some devices are designed to deny users access to install or run 55 | modified versions of the software inside them, although the 56 | manufacturer can do so. This is fundamentally incompatible with the 57 | aim of protecting users' freedom to change the software. The 58 | systematic pattern of such abuse occurs in the area of products for 59 | individuals to use, which is precisely where it is most unacceptable. 60 | Therefore, we have designed this version of the GPL to prohibit the 61 | practice for those products. If such problems arise substantially in 62 | other domains, we stand ready to extend this provision to those 63 | domains in future versions of the GPL, as needed to protect the 64 | freedom of users. 65 | 66 | Finally, every program is threatened constantly by software patents. 67 | States should not allow patents to restrict development and use of 68 | software on general-purpose computers, but in those that do, we wish 69 | to avoid the special danger that patents applied to a free program 70 | could make it effectively proprietary. To prevent this, the GPL 71 | assures that patents cannot be used to render the program non-free. 72 | 73 | The precise terms and conditions for copying, distribution and 74 | modification follow. 75 | 76 | ### TERMS AND CONDITIONS 77 | 78 | #### 0. Definitions. 79 | 80 | "This License" refers to version 3 of the GNU General Public License. 81 | 82 | "Copyright" also means copyright-like laws that apply to other kinds 83 | of works, such as semiconductor masks. 84 | 85 | "The Program" refers to any copyrightable work licensed under this 86 | License. Each licensee is addressed as "you". "Licensees" and 87 | "recipients" may be individuals or organizations. 88 | 89 | To "modify" a work means to copy from or adapt all or part of the work 90 | in a fashion requiring copyright permission, other than the making of 91 | an exact copy. The resulting work is called a "modified version" of 92 | the earlier work or a work "based on" the earlier work. 93 | 94 | A "covered work" means either the unmodified Program or a work based 95 | on the Program. 96 | 97 | To "propagate" a work means to do anything with it that, without 98 | permission, would make you directly or secondarily liable for 99 | infringement under applicable copyright law, except executing it on a 100 | computer or modifying a private copy. Propagation includes copying, 101 | distribution (with or without modification), making available to the 102 | public, and in some countries other activities as well. 103 | 104 | To "convey" a work means any kind of propagation that enables other 105 | parties to make or receive copies. Mere interaction with a user 106 | through a computer network, with no transfer of a copy, is not 107 | conveying. 108 | 109 | An interactive user interface displays "Appropriate Legal Notices" to 110 | the extent that it includes a convenient and prominently visible 111 | feature that (1) displays an appropriate copyright notice, and (2) 112 | tells the user that there is no warranty for the work (except to the 113 | extent that warranties are provided), that licensees may convey the 114 | work under this License, and how to view a copy of this License. If 115 | the interface presents a list of user commands or options, such as a 116 | menu, a prominent item in the list meets this criterion. 117 | 118 | #### 1. Source Code. 119 | 120 | The "source code" for a work means the preferred form of the work for 121 | making modifications to it. "Object code" means any non-source form of 122 | a work. 123 | 124 | A "Standard Interface" means an interface that either is an official 125 | standard defined by a recognized standards body, or, in the case of 126 | interfaces specified for a particular programming language, one that 127 | is widely used among developers working in that language. 128 | 129 | The "System Libraries" of an executable work include anything, other 130 | than the work as a whole, that (a) is included in the normal form of 131 | packaging a Major Component, but which is not part of that Major 132 | Component, and (b) serves only to enable use of the work with that 133 | Major Component, or to implement a Standard Interface for which an 134 | implementation is available to the public in source code form. A 135 | "Major Component", in this context, means a major essential component 136 | (kernel, window system, and so on) of the specific operating system 137 | (if any) on which the executable work runs, or a compiler used to 138 | produce the work, or an object code interpreter used to run it. 139 | 140 | The "Corresponding Source" for a work in object code form means all 141 | the source code needed to generate, install, and (for an executable 142 | work) run the object code and to modify the work, including scripts to 143 | control those activities. However, it does not include the work's 144 | System Libraries, or general-purpose tools or generally available free 145 | programs which are used unmodified in performing those activities but 146 | which are not part of the work. For example, Corresponding Source 147 | includes interface definition files associated with source files for 148 | the work, and the source code for shared libraries and dynamically 149 | linked subprograms that the work is specifically designed to require, 150 | such as by intimate data communication or control flow between those 151 | subprograms and other parts of the work. 152 | 153 | The Corresponding Source need not include anything that users can 154 | regenerate automatically from other parts of the Corresponding Source. 155 | 156 | The Corresponding Source for a work in source code form is that same 157 | work. 158 | 159 | #### 2. Basic Permissions. 160 | 161 | All rights granted under this License are granted for the term of 162 | copyright on the Program, and are irrevocable provided the stated 163 | conditions are met. This License explicitly affirms your unlimited 164 | permission to run the unmodified Program. The output from running a 165 | covered work is covered by this License only if the output, given its 166 | content, constitutes a covered work. This License acknowledges your 167 | rights of fair use or other equivalent, as provided by copyright law. 168 | 169 | You may make, run and propagate covered works that you do not convey, 170 | without conditions so long as your license otherwise remains in force. 171 | You may convey covered works to others for the sole purpose of having 172 | them make modifications exclusively for you, or provide you with 173 | facilities for running those works, provided that you comply with the 174 | terms of this License in conveying all material for which you do not 175 | control copyright. Those thus making or running the covered works for 176 | you must do so exclusively on your behalf, under your direction and 177 | control, on terms that prohibit them from making any copies of your 178 | copyrighted material outside their relationship with you. 179 | 180 | Conveying under any other circumstances is permitted solely under the 181 | conditions stated below. Sublicensing is not allowed; section 10 makes 182 | it unnecessary. 183 | 184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 185 | 186 | No covered work shall be deemed part of an effective technological 187 | measure under any applicable law fulfilling obligations under article 188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 189 | similar laws prohibiting or restricting circumvention of such 190 | measures. 191 | 192 | When you convey a covered work, you waive any legal power to forbid 193 | circumvention of technological measures to the extent such 194 | circumvention is effected by exercising rights under this License with 195 | respect to the covered work, and you disclaim any intention to limit 196 | operation or modification of the work as a means of enforcing, against 197 | the work's users, your or third parties' legal rights to forbid 198 | circumvention of technological measures. 199 | 200 | #### 4. Conveying Verbatim Copies. 201 | 202 | You may convey verbatim copies of the Program's source code as you 203 | receive it, in any medium, provided that you conspicuously and 204 | appropriately publish on each copy an appropriate copyright notice; 205 | keep intact all notices stating that this License and any 206 | non-permissive terms added in accord with section 7 apply to the code; 207 | keep intact all notices of the absence of any warranty; and give all 208 | recipients a copy of this License along with the Program. 209 | 210 | You may charge any price or no price for each copy that you convey, 211 | and you may offer support or warranty protection for a fee. 212 | 213 | #### 5. Conveying Modified Source Versions. 214 | 215 | You may convey a work based on the Program, or the modifications to 216 | produce it from the Program, in the form of source code under the 217 | terms of section 4, provided that you also meet all of these 218 | conditions: 219 | 220 | - a) The work must carry prominent notices stating that you modified 221 | it, and giving a relevant date. 222 | - b) The work must carry prominent notices stating that it is 223 | released under this License and any conditions added under 224 | section 7. This requirement modifies the requirement in section 4 225 | to "keep intact all notices". 226 | - c) You must license the entire work, as a whole, under this 227 | License to anyone who comes into possession of a copy. This 228 | License will therefore apply, along with any applicable section 7 229 | additional terms, to the whole of the work, and all its parts, 230 | regardless of how they are packaged. This License gives no 231 | permission to license the work in any other way, but it does not 232 | invalidate such permission if you have separately received it. 233 | - d) If the work has interactive user interfaces, each must display 234 | Appropriate Legal Notices; however, if the Program has interactive 235 | interfaces that do not display Appropriate Legal Notices, your 236 | work need not make them do so. 237 | 238 | A compilation of a covered work with other separate and independent 239 | works, which are not by their nature extensions of the covered work, 240 | and which are not combined with it such as to form a larger program, 241 | in or on a volume of a storage or distribution medium, is called an 242 | "aggregate" if the compilation and its resulting copyright are not 243 | used to limit the access or legal rights of the compilation's users 244 | beyond what the individual works permit. Inclusion of a covered work 245 | in an aggregate does not cause this License to apply to the other 246 | parts of the aggregate. 247 | 248 | #### 6. Conveying Non-Source Forms. 249 | 250 | You may convey a covered work in object code form under the terms of 251 | sections 4 and 5, provided that you also convey the machine-readable 252 | Corresponding Source under the terms of this License, in one of these 253 | ways: 254 | 255 | - a) Convey the object code in, or embodied in, a physical product 256 | (including a physical distribution medium), accompanied by the 257 | Corresponding Source fixed on a durable physical medium 258 | customarily used for software interchange. 259 | - b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the Corresponding 269 | Source from a network server at no charge. 270 | - c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | - d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | - e) Convey the object code using peer-to-peer transmission, 288 | provided you inform other peers where the object code and 289 | Corresponding Source of the work are being offered to the general 290 | public at no charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, 298 | family, or household purposes, or (2) anything designed or sold for 299 | incorporation into a dwelling. In determining whether a product is a 300 | consumer product, doubtful cases shall be resolved in favor of 301 | coverage. For a particular product received by a particular user, 302 | "normally used" refers to a typical or common use of that class of 303 | product, regardless of the status of the particular user or of the way 304 | in which the particular user actually uses, or expects or is expected 305 | to use, the product. A product is a consumer product regardless of 306 | whether the product has substantial commercial, industrial or 307 | non-consumer uses, unless such uses represent the only significant 308 | mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to 312 | install and execute modified versions of a covered work in that User 313 | Product from a modified version of its Corresponding Source. The 314 | information must suffice to ensure that the continued functioning of 315 | the modified object code is in no case prevented or interfered with 316 | solely because modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or 331 | updates for a work that has been modified or installed by the 332 | recipient, or for the User Product in which it has been modified or 333 | installed. Access to a network may be denied when the modification 334 | itself materially and adversely affects the operation of the network 335 | or violates the rules and protocols for communication across the 336 | network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | #### 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders 364 | of that material) supplement the terms of this License with terms: 365 | 366 | - a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | - b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | - c) Prohibiting misrepresentation of the origin of that material, 372 | or requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | - d) Limiting the use for publicity purposes of names of licensors 375 | or authors of the material; or 376 | - e) Declining to grant rights under trademark law for use of some 377 | trade names, trademarks, or service marks; or 378 | - f) Requiring indemnification of licensors and authors of that 379 | material by anyone who conveys the material (or modified versions 380 | of it) with contractual assumptions of liability to the recipient, 381 | for any liability that these contractual assumptions directly 382 | impose on those licensors and authors. 383 | 384 | All other non-permissive additional terms are considered "further 385 | restrictions" within the meaning of section 10. If the Program as you 386 | received it, or any part of it, contains a notice stating that it is 387 | governed by this License along with a term that is a further 388 | restriction, you may remove that term. If a license document contains 389 | a further restriction but permits relicensing or conveying under this 390 | License, you may add to a covered work material governed by the terms 391 | of that license document, provided that the further restriction does 392 | not survive such relicensing or conveying. 393 | 394 | If you add terms to a covered work in accord with this section, you 395 | must place, in the relevant source files, a statement of the 396 | additional terms that apply to those files, or a notice indicating 397 | where to find the applicable terms. 398 | 399 | Additional terms, permissive or non-permissive, may be stated in the 400 | form of a separately written license, or stated as exceptions; the 401 | above requirements apply either way. 402 | 403 | #### 8. Termination. 404 | 405 | You may not propagate or modify a covered work except as expressly 406 | provided under this License. Any attempt otherwise to propagate or 407 | modify it is void, and will automatically terminate your rights under 408 | this License (including any patent licenses granted under the third 409 | paragraph of section 11). 410 | 411 | However, if you cease all violation of this License, then your license 412 | from a particular copyright holder is reinstated (a) provisionally, 413 | unless and until the copyright holder explicitly and finally 414 | terminates your license, and (b) permanently, if the copyright holder 415 | fails to notify you of the violation by some reasonable means prior to 416 | 60 days after the cessation. 417 | 418 | Moreover, your license from a particular copyright holder is 419 | reinstated permanently if the copyright holder notifies you of the 420 | violation by some reasonable means, this is the first time you have 421 | received notice of violation of this License (for any work) from that 422 | copyright holder, and you cure the violation prior to 30 days after 423 | your receipt of the notice. 424 | 425 | Termination of your rights under this section does not terminate the 426 | licenses of parties who have received copies or rights from you under 427 | this License. If your rights have been terminated and not permanently 428 | reinstated, you do not qualify to receive new licenses for the same 429 | material under section 10. 430 | 431 | #### 9. Acceptance Not Required for Having Copies. 432 | 433 | You are not required to accept this License in order to receive or run 434 | a copy of the Program. Ancillary propagation of a covered work 435 | occurring solely as a consequence of using peer-to-peer transmission 436 | to receive a copy likewise does not require acceptance. However, 437 | nothing other than this License grants you permission to propagate or 438 | modify any covered work. These actions infringe copyright if you do 439 | not accept this License. Therefore, by modifying or propagating a 440 | covered work, you indicate your acceptance of this License to do so. 441 | 442 | #### 10. Automatic Licensing of Downstream Recipients. 443 | 444 | Each time you convey a covered work, the recipient automatically 445 | receives a license from the original licensors, to run, modify and 446 | propagate that work, subject to this License. You are not responsible 447 | for enforcing compliance by third parties with this License. 448 | 449 | An "entity transaction" is a transaction transferring control of an 450 | organization, or substantially all assets of one, or subdividing an 451 | organization, or merging organizations. If propagation of a covered 452 | work results from an entity transaction, each party to that 453 | transaction who receives a copy of the work also receives whatever 454 | licenses to the work the party's predecessor in interest had or could 455 | give under the previous paragraph, plus a right to possession of the 456 | Corresponding Source of the work from the predecessor in interest, if 457 | the predecessor has it or can get it with reasonable efforts. 458 | 459 | You may not impose any further restrictions on the exercise of the 460 | rights granted or affirmed under this License. For example, you may 461 | not impose a license fee, royalty, or other charge for exercise of 462 | rights granted under this License, and you may not initiate litigation 463 | (including a cross-claim or counterclaim in a lawsuit) alleging that 464 | any patent claim is infringed by making, using, selling, offering for 465 | sale, or importing the Program or any portion of it. 466 | 467 | #### 11. Patents. 468 | 469 | A "contributor" is a copyright holder who authorizes use under this 470 | License of the Program or a work on which the Program is based. The 471 | work thus licensed is called the contributor's "contributor version". 472 | 473 | A contributor's "essential patent claims" are all patent claims owned 474 | or controlled by the contributor, whether already acquired or 475 | hereafter acquired, that would be infringed by some manner, permitted 476 | by this License, of making, using, or selling its contributor version, 477 | but do not include claims that would be infringed only as a 478 | consequence of further modification of the contributor version. For 479 | purposes of this definition, "control" includes the right to grant 480 | patent sublicenses in a manner consistent with the requirements of 481 | this License. 482 | 483 | Each contributor grants you a non-exclusive, worldwide, royalty-free 484 | patent license under the contributor's essential patent claims, to 485 | make, use, sell, offer for sale, import and otherwise run, modify and 486 | propagate the contents of its contributor version. 487 | 488 | In the following three paragraphs, a "patent license" is any express 489 | agreement or commitment, however denominated, not to enforce a patent 490 | (such as an express permission to practice a patent or covenant not to 491 | sue for patent infringement). To "grant" such a patent license to a 492 | party means to make such an agreement or commitment not to enforce a 493 | patent against the party. 494 | 495 | If you convey a covered work, knowingly relying on a patent license, 496 | and the Corresponding Source of the work is not available for anyone 497 | to copy, free of charge and under the terms of this License, through a 498 | publicly available network server or other readily accessible means, 499 | then you must either (1) cause the Corresponding Source to be so 500 | available, or (2) arrange to deprive yourself of the benefit of the 501 | patent license for this particular work, or (3) arrange, in a manner 502 | consistent with the requirements of this License, to extend the patent 503 | license to downstream recipients. "Knowingly relying" means you have 504 | actual knowledge that, but for the patent license, your conveying the 505 | covered work in a country, or your recipient's use of the covered work 506 | in a country, would infringe one or more identifiable patents in that 507 | country that you have reason to believe are valid. 508 | 509 | If, pursuant to or in connection with a single transaction or 510 | arrangement, you convey, or propagate by procuring conveyance of, a 511 | covered work, and grant a patent license to some of the parties 512 | receiving the covered work authorizing them to use, propagate, modify 513 | or convey a specific copy of the covered work, then the patent license 514 | you grant is automatically extended to all recipients of the covered 515 | work and works based on it. 516 | 517 | A patent license is "discriminatory" if it does not include within the 518 | scope of its coverage, prohibits the exercise of, or is conditioned on 519 | the non-exercise of one or more of the rights that are specifically 520 | granted under this License. You may not convey a covered work if you 521 | are a party to an arrangement with a third party that is in the 522 | business of distributing software, under which you make payment to the 523 | third party based on the extent of your activity of conveying the 524 | work, and under which the third party grants, to any of the parties 525 | who would receive the covered work from you, a discriminatory patent 526 | license (a) in connection with copies of the covered work conveyed by 527 | you (or copies made from those copies), or (b) primarily for and in 528 | connection with specific products or compilations that contain the 529 | covered work, unless you entered into that arrangement, or that patent 530 | license was granted, prior to 28 March 2007. 531 | 532 | Nothing in this License shall be construed as excluding or limiting 533 | any implied license or other defenses to infringement that may 534 | otherwise be available to you under applicable patent law. 535 | 536 | #### 12. No Surrender of Others' Freedom. 537 | 538 | If conditions are imposed on you (whether by court order, agreement or 539 | otherwise) that contradict the conditions of this License, they do not 540 | excuse you from the conditions of this License. If you cannot convey a 541 | covered work so as to satisfy simultaneously your obligations under 542 | this License and any other pertinent obligations, then as a 543 | consequence you may not convey it at all. For example, if you agree to 544 | terms that obligate you to collect a royalty for further conveying 545 | from those to whom you convey the Program, the only way you could 546 | satisfy both those terms and this License would be to refrain entirely 547 | from conveying the Program. 548 | 549 | #### 13. Use with the GNU Affero General Public License. 550 | 551 | Notwithstanding any other provision of this License, you have 552 | permission to link or combine any covered work with a work licensed 553 | under version 3 of the GNU Affero General Public License into a single 554 | combined work, and to convey the resulting work. The terms of this 555 | License will continue to apply to the part which is the covered work, 556 | but the special requirements of the GNU Affero General Public License, 557 | section 13, concerning interaction through a network will apply to the 558 | combination as such. 559 | 560 | #### 14. Revised Versions of this License. 561 | 562 | The Free Software Foundation may publish revised and/or new versions 563 | of the GNU General Public License from time to time. Such new versions 564 | will be similar in spirit to the present version, but may differ in 565 | detail to address new problems or concerns. 566 | 567 | Each version is given a distinguishing version number. If the Program 568 | specifies that a certain numbered version of the GNU General Public 569 | License "or any later version" applies to it, you have the option of 570 | following the terms and conditions either of that numbered version or 571 | of any later version published by the Free Software Foundation. If the 572 | Program does not specify a version number of the GNU General Public 573 | License, you may choose any version ever published by the Free 574 | Software Foundation. 575 | 576 | If the Program specifies that a proxy can decide which future versions 577 | of the GNU General Public License can be used, that proxy's public 578 | statement of acceptance of a version permanently authorizes you to 579 | choose that version for the Program. 580 | 581 | Later license versions may give you additional or different 582 | permissions. However, no additional obligations are imposed on any 583 | author or copyright holder as a result of your choosing to follow a 584 | later version. 585 | 586 | #### 15. Disclaimer of Warranty. 587 | 588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT 592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 596 | CORRECTION. 597 | 598 | #### 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR 602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES 604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT 605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR 606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM 607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER 608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 609 | 610 | #### 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | ### How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these 626 | terms. 627 | 628 | To do so, attach the following notices to the program. It is safest to 629 | attach them to the start of each source file to most effectively state 630 | the exclusion of warranty; and each file should have at least the 631 | "copyright" line and a pointer to where the full notice is found. 632 | 633 | 634 | Copyright (C) 635 | 636 | This program is free software: you can redistribute it and/or modify 637 | it under the terms of the GNU General Public License as published by 638 | the Free Software Foundation, either version 3 of the License, or 639 | (at your option) any later version. 640 | 641 | This program is distributed in the hope that it will be useful, 642 | but WITHOUT ANY WARRANTY; without even the implied warranty of 643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 644 | GNU General Public License for more details. 645 | 646 | You should have received a copy of the GNU General Public License 647 | along with this program. If not, see . 648 | 649 | Also add information on how to contact you by electronic and paper 650 | mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands \`show w' and \`show c' should show the 661 | appropriate parts of the General Public License. Of course, your 662 | program's commands might be different; for a GUI interface, you would 663 | use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or 666 | school, if any, to sign a "copyright disclaimer" for the program, if 667 | necessary. For more information on this, and how to apply and follow 668 | the GNU GPL, see . 669 | 670 | The GNU General Public License does not permit incorporating your 671 | program into proprietary programs. If your program is a subroutine 672 | library, you may consider it more useful to permit linking proprietary 673 | applications with the library. If this is what you want to do, use the 674 | GNU Lesser General Public License instead of this License. But first, 675 | please read . 676 | --------------------------------------------------------------------------------