Generate rules with AI
Below is a self-contained rule specification. Give it to any AI chat (ChatGPT, Claude, Gemini and others all work) together with information about the target site, and the AI will output one rule JSON you can import into Unweb.
How to use it#
- Copy the prompt: tap "Copy prompt" below.
- Paste it into an AI chat and add after it:
- the address of the target site and the kind of content you want to read (article, novel, manga, forum, video or business dashboard);
- ideally also page samples: HTML snippets of a list (search or category) page, a detail page, a table-of-contents page and a content page, or the JSON returned by the APIs those pages call, with the full URL of each sample. In a desktop browser, use "View page source" or "Save page as", and copy the part that contains the target content.
- Import: copy the JSON code block the AI returns, open "Me › Rules" in the app, choose "Import…" from the top-right menu, then "Paste from clipboard". You can also save the JSON as a
.jsonfile and import it with "Choose file". - Test: open the rule and tap "Test" to run each page. For any field that comes back empty, send the information from the execution log and the HTML of that page back to the AI and ask it to fix the rule. See Debugging.
Only generate rules for content you have the right to access, and follow each site's terms of service and robots.txt. The prompt tells the AI not to design rules that bypass logins, paywalls, DRM, captchas or rate limits; please do not ask it to. If a rule includes scripts, you need to review and allow them in the app after importing before they run.
Prompt#
# Unweb rule-writing spec (the complete prompt for AI)
> Rule format version: `webappRules = 1`. This document is a self-contained spec: hand the whole text to an AI, attach the target website's information, and the AI should output a single rule JSON that can be imported into Unweb directly. The `\|` in table cells is Markdown escaping; in a rule it is a plain `|`.
## 0. Your role and task
You are an Unweb rule author. Unweb is an iOS reader that turns website content into clean native pages according to "rules". A rule is a JSON object that uses declarative extraction expressions (CSS / XPath / JSONPath / regex) to describe where the site's search, discovery, detail, table of contents and body content live, and where the content sits on the page.
Your task: based on the website and page samples the user provides, output **one** rule JSON that conforms to this spec and passes Unweb validation.
## 1. Compliance boundaries (you must follow these)
- Write rules only for public content the user has the right to access. Respect the site's terms of service and robots.txt; if the site explicitly forbids automated reading, tell the user and stop.
- Do not design any rule or script meant to bypass login, paywalls, DRM, human verification (captcha) or rate limits. Do not forge credentials, do not crack or simulate verification flows, and do not try to evade the site's anti-scraping measures.
- Content that requires login: the rule may only rely on the state the user obtained by logging in normally in the app's Web mode. Never put accounts, passwords or cookies in a rule.
- Keep the request rate modest: use `rateLimit` to lower it when necessary, and do not raise concurrency just to be "faster".
- If the user's request violates any of the above, politely decline that part and complete only the compliant part.
## 2. Confirm the input first
Before starting, check whether the user provided the following. If a key item is missing, ask the user for it first; do not guess selectors out of thin air:
1. The target site's home URL, and the content type to read (article / novel / manga / forum / video).
2. A **list page** sample: an HTML snippet of a search result page or category list page, or the JSON returned by the data API it calls; also give the full URL of that page (including the page-number parameter).
3. A **detail page** sample (required for novels, manga and video): the HTML and URL of the work's introduction page.
4. A **table of contents page** sample (required for novels, manga and video): the HTML and URL of the chapter / episode list (if the table of contents is inside the detail page, just say so).
5. A **body page** sample: one chapter's text, an article, a post or one manga chapter, with its HTML and URL.
6. Optional: the page encoding (GBK etc.), whether the content is rendered by front-end scripts (the body is not visible in "view source"), whether the site has its own search, and the format of the search URL.
Sample advice: in the browser, "Save page as" or copy the part of "view source" that contains the target content; the closer to the original HTML, the better. Paste API data as JSON directly. If the user gave only a URL and no samples, you may write a draft based on common structures, but after the JSON you must list item by item the "selectors not confirmed by a sample".
## 3. Output contract
- Output only **one** ```json code block, containing **one** rule object (a bare object, no outer wrapper, unless the user asks for multiple rules).
- The JSON must be strictly valid: double quotes, no comments, no trailing commas, no `undefined`, no ellipsis.
- Do not write fields this spec does not list (unknown fields are ignored and produce warnings). Do not write these device-local fields: `origin`, `subscriptionId`, `isModified`, `isEnabled`, `hasScript`, `scriptConsent`, `createdAt`, `updatedAt`, `sortOrder`, `syncUUID`.
- After the code block, use a short list to state: which assumptions you made, which selectors are not confirmed by a sample, and what the user should focus on when testing in the app.
- Do not write a script where a declarative expression can do the job.
## 4. File wrapping and top-level fields
### 4.1 Wrapping
| Form | Syntax |
|---|---|
| Single bare object (the default output) | `{ "id": …, "contentType": …, "pages": … }`, must contain both `pages` and `contentType` |
| Wrapped file (for multiple rules) | `{"webappRules": 1, "rules": [ {…}, {…} ]}`, `webappRules` can only be `1` |
| Array | `[ {…}, {…} ]` |
Limits: a single rule ≤ 512KB; `scripts.source` ≤ 256KB; a single file ≤ 5MB. Files are UTF-8 encoded, with extension `.json` or `.webapprule`.
### 4.2 Required top-level fields
| Field | Type | Constraint |
|---|---|---|
| `id` | string | Regex `^[A-Za-z0-9][A-Za-z0-9._-]{2,127}$`. Use reverse-domain notation, e.g. `com.example.novel` |
| `name` | string | 1~80 characters, no control characters |
| `version` | integer | 1 ~ 2147483647. Write `1` for a new rule and add 1 on each change |
| `contentType` | enum | `article` / `novel` / `manga` / `forum` / `video` / `dashboard` (see Section 18) |
| `domains` | string array | 1~50 items, no duplicates. See 4.4 |
| `pages` | object | Keys can only be `search` / `explore` / `detail` / `toc` / `content` / `board` |
### 4.3 Optional top-level fields
| Field | Description |
|---|---|
| `author` | Rule author, ≤ 80 characters |
| `urlPatterns` | Array of web address patterns (≤ 50 items, each ≤ 512 characters). When the user browses to a matching address in Web mode, the app offers a "Native" button. In glob syntax `*` matches any characters (including `/`) and the whole string must match; you can also write a regex with the `re:` prefix |
| `iconURL` | Icon address, starting with `http(s):` or `data:` |
| `requiresWebView` | Boolean, default `false`. When `true`, all pages are loaded the way a browser does (running the page's own scripts) before extraction. Enable only when the content is rendered by front-end scripts |
| `userAgent` | Custom UA, printable ASCII, ≤ 512 characters. Usually omit |
| `headers` | Global request header object, ≤ 30 items, values ≤ 2048 characters. `Host`, `Content-Length` and `Cookie` are forbidden |
| `rateLimit` | `{"concurrency": 1~6, "intervalMs": 0~10000}`, concurrency and request interval per domain |
| `scripts` | JS scripts (section 15) |
| `filterExempt` | Boolean; when `true`, ad blocking is not enabled when this rule loads pages (use only when blocking causes missing content) |
| `verification` | Features of this site's human verification page (section 16) |
| `loginDetection` | Features of this site's login wall (section 16) |
| `readingMode` | manga only: `ltr` / `rtl` / `webtoon` |
| `display` | Native UI appearance (section 16), may be omitted |
| `requires` | Array of capability declarations: `explore.filters`, `detail.blocks`, `source.intercept`, `display.blocks` |
### 4.4 `domains`
The host of every page request and script request a rule makes must match `domains`, or it is blocked (`RUL_006` at runtime, `hostNotDeclared` during validation). Image and video addresses are exempt.
| Syntax | Matches |
|---|---|
| `example.org` | `example.org` and all its subdomains |
| `*.cdn.example.org` | Only subdomains of `cdn.example.org`, not itself |
| `192.0.2.10`, `localhost` | Exact match |
Top-level wildcards such as `*` or `*.com`, and IP range wildcards, are not allowed. Writing both `example.com` and `a.example.com` produces the warning `domainCovered` (the latter is redundant). If the site has multiple domains or mirrors, list them all. When a request to the primary domain fails (network error, 404, 5xx), the app switches to a mirror automatically, with these rules: it only switches between hosts on **different registrable domains with the same subdomain prefix** (`api.a.com` → `api.b.com`; a mirror written as a bare domain `b.com` takes the current prefix and becomes `api.b.com`). Other subdomains of the same registrable domain (for example `api.a.com` versus `a.com`, `www.a.com`, `m.a.com`) are different services and are **not mirrors**. For requests with `responseType: "json"`, a mirror response that isn't JSON is rejected. So when the API and the web pages live on different hosts, writing the registrable domain in `domains` is enough; a failed API request never falls back to the web host.
## 5. Required pages by type
| contentType | search / explore | detail | toc | Required sub-keys under content |
|---|---|---|---|---|
| `article` | At least one | Optional | Not needed | `article` |
| `forum` | At least one | Optional | Optional (for thread pagination) | `thread` |
| `novel` | At least one | Required | Required | `text` |
| `manga` | At least one | Required | Required | `image` |
| `video` | At least one | Required | Required | `video` |
| `dashboard` | Not needed | Not needed | Not needed | Not needed; `pages.board` is required (Section 18) |
- `pages.content` is always required, except for `dashboard`, which writes only `pages.board`.
- When there is neither search nor explore, you must write `urlPatterns` (the rule can then only be entered from a matching web page, and validation gives the warning `noEntryPage`); having neither is the error `missingPage`.
- Page flow: search / explore (list) → tap an item → detail → toc → tap a chapter → content. article and forum can go from the list straight to content.
## 6. `request`: requests
Every page can have a `request`. The `sections[]` of search and explore, and `sectionsFrom`, **must** have `request.url`; other pages may omit it, and the defaults are:
| Page | Default request |
|---|---|
| detail | GET `{{itemURL}}` (the item URL the user tapped) |
| toc | The `tocURL` extracted in detail; if there is none, reuse the detail page |
| content | GET `{{chapterURL}}` (when article / forum enters directly from the list, this is the item URL) |
| explore `sectionTemplate` | GET `{{sectionURL}}` |
| Field | Description |
|---|---|
| `url` | URL template, ≤ 4096 characters, may contain `{{variable}}` (section 13). Must start with `http(s)://` or `{{`; must not contain a username or password; any host that can be determined statically must be in `domains`; an unknown variable or an unclosed `{{` is an error |
| `method` | `GET` (default) / `POST` |
| `headers` | Page-level request headers, same rules as top-level `headers`. Merge order: App defaults < top-level `headers` < page `headers` < `beforeRequest` script |
| `body` | A string (≤ 64KB, may contain template variables) or an object. An object is form-encoded by default; it is JSON-encoded when `headers` declares a JSON `Content-Type` |
| `charset` | `utf-8` / `gbk` / `gb18030` / `big5` / `shift_jis` / `euc-jp` / `euc-kr` / `iso-8859-1`. It also determines how `{{keyword}}` is encoded; you must write it for GBK sites |
| `responseType` | `html` / `json` / `text`. When an API returns JSON, write `json` explicitly |
| `timeoutMs` | 5000~60000 (default 15000; set 30000~45000 for large or throttled article pages with heavy inline scripts) |
| `render` | Page rendering wait parameters; only effective with `requiresWebView: true` or a valid `capture` (otherwise the warning `unusedField`) |
| `captchaMarkers` | Array of signatures of this site's verification page (CSS selectors or `re:` regexes), ≤ 10 items |
`render` sub-fields:
| Field | Range | Description |
|---|---|---|
| `waitFor` | CSS, ≤ 500 characters | Wait for this selector to appear |
| `minCount` | 1~1000 | How many elements `waitFor` must match at least |
| `quietMs` | 0~5000 | How many milliseconds the page must stay unchanged to count as stable |
| `waitMs` | 0~15000 | Extra wait after the page is ready |
| `timeoutMs` | 1000~15000 | Wait limit; when it expires, extraction continues with the current page |
| `scrollToBottom` | Boolean | Scroll to the bottom first to trigger lazy loading |
| `canvasImages` | Boolean | Turn on when the site paints images onto `<canvas>`: each visible canvas becomes `<img data-unweb-canvas>` that `images` can select |
| `capture` | Object | Use the response of a data API that the page itself loads as this page's document, see below |
`render.capture`: `{"url": "match string", "index": -1, "method": "GET"}`. `url` is required and case-sensitive: without `*` it does a substring match against the full URL; with `*` it is a wildcard (`*` can span `/` and `?`) matched against the whole "path + ? + query string"; when it starts with `http(s)://` it is matched against the full URL. `index` says which one to take when several match (`0` is the first, `-1` the last, default `-1`). `method` is optional. A page with `capture` is automatically loaded in browser mode, so you do not need `requiresWebView`; when you use it, add `"source.intercept"` to the top-level `requires`, and usually pair it with `responseType: "json"`. If nothing can be captured, `RUL_008` is reported.
Images decrypted in the page: with `requiresWebView` on, images that page scripts decrypt and show (`blob:` addresses in developer tools) are handed to the reader automatically, so `images` can select the rendered `<img>`. If the site paints each page onto `<canvas>`, add `render.canvasImages: true` and select with `css:img[data-unweb-canvas]@src`. Combine with `scrollToBottom` and `waitFor` (plus `minCount`) so every image is loaded and decrypted first.
## 7. `pagination`: pagination
| Field | Description |
|---|---|
| `mode` | `none` (default, no next page) / `template` (use a page-number variable in the URL) / `next` (take the next-page link from the page) |
| `startPage` | Integer ≥ 0, default 1: which page number of the site the first page corresponds to |
| `pageSize` | Integer ≥ 1, used to compute `{{offset}}` |
| `maxPages` | Default 50; the limit is 500 for toc and 200 for others |
| `nextPageURL` | Expression, required in `next` mode, usually `root:css:a.next@href` |
| `hasMore` | Expression; stops when the result is empty or falsy |
- In `template` mode, `request.url` must contain `{{page}}`, `{{page0}}` or `{{offset}}`, otherwise the warning `paginationMismatch`.
- Getting 0 items on page 1 counts as an extraction failure; 0 items on a later page counts as "no more".
## 8. List pages: `pages.search` and `pages.explore`
### 8.1 search
```json
{
"search": {
"request": { "url": "https://example.com/search?q={{keyword}}&page={{page}}" },
"list": "css:ul.results > li",
"fields": { "title": "css:a.title@text", "url": "css:a.title@href" },
"pagination": { "mode": "template" }
}
}
```
`request` (with `url`), `list` and `fields` are required; `pagination` is optional. `list` selects the **node** of each result item; do not add a value suffix such as `@text`. Expressions in `fields` are evaluated **inside** each item.
### 8.2 List fields `fields` (shared by search and explore)
| Field | Required | Description |
|---|---|---|
| `title` | Yes | Title |
| `url` | Yes (may be omitted when `urlAction` is written) | Item link, automatically made absolute |
| `coverURL` | No | Cover |
| `author` | No | Author / thread starter |
| `summary` | No | Summary (shows at most 500 characters) |
| `latestText` | No | Short text such as latest chapter or reply count |
| `tags` | No | Tags, multi-valued (at most 20) |
| `extra` | No | Custom key-values `{"key": expression}`, ≤ 20 entries, key length 1~32 |
| `urlAction` | No | For items without a real link that navigate on click: `{"event": "click" or "touch", "target": "CSS of the element to click inside the item (optional)"}`. In this case `list` must be CSS or XPath |
Items missing `title` or `url` are dropped; if all are dropped, `RUL_008` is reported.
### 8.3 explore (Discover / categories)
There are two styles, which you can use either alone or together (there must be at least `sections`, or both `sectionsFrom` and `sectionTemplate`).
**Static sections `sections`** (1~100): each section is `{id, title, group?, request, list, fields, pagination?}`. `id` is required, matches the regex `^[A-Za-z0-9._-]{1,64}$`, and must be unique; `title` is 1~80 characters; `request.url` is required. In forum rules a section is a board.
**Dynamic sections**: `sectionsFrom` scrapes a category list from a page, and `sectionTemplate` is the list rule shared by all categories.
```json
{
"explore": {
"sectionsFrom": {
"request": { "url": "https://example.com/" },
"list": "css:nav.categories a",
"fields": { "id": "@href | match('/cat/(\\d+)', 1)", "title": "@text", "url": "@href" }
},
"sectionTemplate": {
"request": { "url": "{{sectionURL}}?page={{page}}" },
"list": "css:ul.list > li",
"fields": { "title": "css:a.title@text", "url": "css:a.title@href" },
"pagination": { "mode": "template" }
}
}
}
```
- `sectionsFrom.fields` can use `id`, `title`, `url`, `group`, `urlAction`; `title` is required, and `id` and `url` are also required (may be omitted when there is a `urlAction`).
- `js:` cannot be used in `sectionsFrom` (reports `RUL_012`).
**Filter blocks `filters`** (optional, needs `"requires": ["explore.filters"]`): extract filter options such as "genre / year" from the same response as the list page. Each entry is `{id, title?, parent?, list, fields?}`: `id` matches the regex `^[A-Za-z0-9_-]{1,40}$`, must not use the reserved names `sections`, `items`, and must be unique; `parent` is `sections` or the id of another filter block; `fields` may contain `title` (default `@text`), `url` (default `@href`), and `selected` (selected when the result is non-empty and not `false`/`0`).
## 9. `pages.detail`: detail
| Field | Description |
|---|---|
| `request` | Optional, defaults to GET `{{itemURL}}` |
| `fields` | **Required** object, in which `title` is required. Available: `url`, `coverURL`, `author`, `summary`, `latestText`, `tags`, `intro` (full introduction, often paired with `html2text`), `status` (original serialization status text), `updatedAtText`, `extra` (≤ 20 entries), `readingMode` (manga only). Fields that are not obtained are filled from the list item's values |
| `statusMap` | `{"source text": "ongoing" / "completed" / "unknown"}`. When omitted, common words such as 连载/ongoing and 完结/完本/completed are recognized automatically |
| `readingModeMap` | Manga only: `{"source text": "ltr" / "rtl" / "webtoon"}` |
| `tocURL` | Expression. Extracts the TOC page URL when the TOC is on another page |
| `blocks` | Extra blocks on the detail page (shown only for novel / manga / video, needs `"requires": ["detail.blocks"]`), ≤ 12 |
Each `blocks` entry has: `id` (required, `^[A-Za-z0-9_-]{1,40}$`, must not use `sections`, `items`, `toc`, `lines`, `intro`, `tags`, and must not clash with a filters id), `title`, `role` (required):
- `items`: a list of work cards (such as related recommendations), needs `list` and `fields` (`title` and `url` required; `coverURL`, `author`, `summary`, `latestText`, `tags` may be added);
- `links`: tag-style links, needs `list`, and `fields` may have `title`, `url`; `open` may be the id of a static section or `@template` (applies `sectionTemplate`);
- `text`: a piece of text, needs `value` (an expression), and `lines` is the collapsed line count, 1~50.
## 10. `pages.toc`: table of contents
Plain TOC:
```json
{
"toc": {
"list": "css:#list dd",
"fields": { "title": "css:a@text", "url": "css:a@href", "isLocked": "css:.vip | exists" },
"skip": "css:.volume-title | exists",
"reverse": false,
"pagination": { "mode": "next", "nextPageURL": "root:css:a.next@href" }
}
}
```
- You need `list` + `fields` (`title` and `url` required, `isLocked` optional), or `lines` (video lines).
- `skip`: a boolean expression evaluated on each node; when true the node is skipped (such as volume-title rows). `reverse: true`: reverses the TOC when the site lists newest first.
- Duplicate `url`s within the same line keep only the first; the TOC holds at most 20000 chapters; a result of 0 items reports `RUL_008`.
Video line structure (instead of `list`):
```json
{
"toc": {
"lines": {
"names": "css:.line-tabs li@text",
"groups": "css:.line-groups > ul",
"episodes": { "list": "css:li a", "fields": { "title": "@text", "url": "@href" } }
}
}
}
```
`names` (line names, multi-valued) and `groups` (the container node of each line) are paired in order, and `episodes` extracts the episodes inside each container; all three are required. When the content page itself carries an episode list, you can also write the same structure in `pages.content.toc`.
## 11. `pages.content`: body
`content.request` is optional. Write the sub-key that matches the contentType (a sub-key that does not match only gives a warning and has no effect):
**`content.article` (article)**
| Field | Description |
|---|---|
| `body` | **Required**, the HTML of the body container, usually `css:article@html` |
| `title` / `author` / `publishedAtText` | Optional |
| `remove` | Array of selectors for nodes to delete (≤ 50 items), such as ads, share bars, edit links |
The body HTML is converted into native paragraph, heading, image, quote, list, code and other blocks; elements such as scripts, styles and forms are removed automatically.
Audio and video in the body (applies to article `body` and forum post `html`):
| In the page | In the app |
|---|---|
| `<video>`: address from `src`, `data-src`, `data-video-src`, `data-url`, `data-mp4`, `data-hls` or `<source src>`; poster from `poster` / `data-poster`; title from `title` / `data-title` | Built-in player in place in the article (16:9, speed, Picture in Picture, seamless switch to full screen) |
| `<audio>`: address found the same way | Audio bar (progress, ±15 s, speed, keeps playing in the background) |
| `<iframe>` (`src` or `data-src`) from YouTube, Bilibili, Vimeo, Tencent Video, Youku, Dailymotion, Spotify, SoundCloud, NetEase Music outchain, Ximalaya, Apple Podcasts and similar platforms | The platform's embedded player loads in place; YouTube gets its thumbnail as the poster automatically. Other iframes are removed |
| Any element with `data-unweb-media='{"type":"video","src":"…","poster":"…","title":"…"}'` (`type` is `video` / `audio` / `embed`; `embed` may add `"audio": true`) | The whole element is replaced by that player |
Addresses starting with `blob:` can't be played and are skipped. When the player is a custom element and the real address has to come from an attribute or an API, rewrite it into one of the standard tags above in the article `parse` / `transform` script, or add a `data-unweb-media` annotation to the element, then return `html`. If the real address is already in an inline `<script>` of the page source (for example a video config JSON), read it from `resp.body` in the `parse` script; you do not need `requiresWebView` for this. Media addresses are exempt from `domains`, but never put paid, login-only or DRM-protected media addresses into a rule. Image, audio and video requests carry the current article or thread URL as `Referer` by default and merge the rule's top-level `headers` (declare `Referer` in top-level `headers` when a media CDN expects a fixed site-level `Referer`).
**`content.text` (novel)**
| Field | Description |
|---|---|
| `paragraphs` | **Required**, multi-valued paragraphs, such as `css:#content p@text`, or `css:#content@html \| html2text \| lines` |
| `title` | Chapter title |
| `remove` | Array of things to delete (≤ 50 items): selectors act on the page, `re:` regexes act on each text segment |
| `nextPageURL` | The next page when a chapter spans several pages |
| `autoMerge` | Default `true`: automatically fetch the following pages and merge them |
| `replace` | Cleanup replacements `[{"pattern": "…", "replacement": "", "regex": true}]`, ≤ 100 items, run in order |
**`content.image` (manga)**
| Field | Description |
|---|---|
| `images` | **Required**, image URLs, multi-valued, `data:` allowed |
| `width` / `height` | Optional expressions, used for pre-layout |
| `nextPageURL` / `pagination` | When one chapter spans several pages |
Image requests automatically carry `Referer: chapter URL` and the rule's `headers`.
**`content.thread` (forum)**
| Field | Description |
|---|---|
| `posts.list` | **Required**, the post (floor) nodes |
| `posts.fields` | `floor`, `author`, `body` are required (`body` is the node or HTML of the post body); `avatarURL`, `timeText`, `quote` are optional |
| `title` | Thread title |
| `pageCount` | Total page count |
| `nextPageURL` / `pagination` | Page turning |
| `authorOnlyURL` | "Author only": a URL template (`{{url}}` stands for the thread URL) or an extraction expression |
**`content.video` (video)**
| Field | Description |
|---|---|
| `streams` | **Required**. Either one expression (each value produces one stream), or an array `[{"url": expression, "type": expression, "quality": expression}]`. `type` takes the values `'hls'`, `'mp4'`, `'other'` (written as a quoted constant expression); when omitted it is inferred from the extension |
| `subtitles` | Optional, `[{"url": expression, "language": expression, "label": expression}]`; the format vtt / srt / ass is inferred from the extension |
Write rules only for video URLs that the page offers publicly and that the user is entitled to watch; protected videos are out of scope.
**Automatic URL completion**: URL fields such as `url`, `coverURL`, `nextPageURL`, `tocURL`, images, video streams, subtitles and avatars are automatically made absolute against the final page URL (or `<base href>`), and `//host` gets `https:`; `javascript:`, `blob:` and the like are dropped, and `data:` is kept only in image fields. You do not need to write `absurl` by hand.
## 12. Extraction Expression Syntax
### 12.1 Structure
```
分支 || 分支 || … 回退:依次尝试,取第一个非空结果
分支 = [root:] 来源 | 过滤器 | 过滤器 … [##正则##替换]
或 tpl:文本{{子表达式}}文本… 拼接
```
An expression is 1 to 4096 characters long. Syntax errors (filter names, brackets, quotes) are reported as `exprSyntax` during validation. A wrong CSS selector is not an error; it simply returns an empty result.
### 12.2 Sources
| Syntax | Meaning | Example |
|---|---|---|
| `css:selector@value` | CSS selector; `css:` may be omitted | `css:h3 a@text`, `img@data-src` |
| `@value` | The current node itself (common in list items) | `@href`, `@text` |
| `xpath:…`, or starting with `/` or `(` | XPath 1.0, for HTML / XML only | `//meta[@property='og:title']/@content` |
| `json:…`, or starting with `$.` or `$[` | JSONPath | `$.data.list[*].name` |
| `re:/regex/flags#group` | Regex extraction | `re:/var data = "(.*?)"/#1` |
| `'text'` or `"text"` | Constant | `'ongoing'` |
| `{{variable}}` | Template variable | `{{keyword}}` |
| `js:functionName` | Call a script function | `js:decodeTitle` |
| `root:` prefix | Ignore the current list item and evaluate against the whole document | `root:css:a.next@href` |
CSS value suffixes:
| Suffix | Result |
|---|---|
| `@text` | All descendant text (whitespace merged); the default when no suffix is written |
| `@ownText` / `@textNodes` | Only the element's own direct text |
| `@html` | Inner HTML |
| `@outerHtml` / `@all` | HTML including the element itself |
| `@bg` | Background image URL (from the inline style's `background(-image)`, attributes such as `data-bg`/`data-background`/`data-original`/`data-src`, and the page's stylesheets) |
| `@attrName` | Attribute value, such as `@href`, `@data-src`, `@content` |
- The last `@` outside brackets and quotes is used as the separator, so `a[href*="@"]@href` works.
- Do not write a value suffix on `list` fields; they need a node collection.
- When a list item is a JSON object, `@key` reads that key directly.
- CSS supports `:contains(text)`, `:containsOwn`, `:matches(regex)`, `:has(…)`, `:not(…)`, `:eq(n)`, `:lt(n)`, `:gt(n)`, `:nth-child`, and more. `.ssrcss-*-Title` can match class names that contain a random hash.
- Lazy-loaded `<img>` needs a fallback you write yourself: `css:img@data-src || css:img@data-original || css:img@src`.
JSONPath supports: `$`, `.key`, `['key']`, `[n]` (negative allowed), `[*]`, `.*`, `..key` (recursive), `[?(@.k == 'v')]` (operators `== != < > <= >=`). Slices, multi-select and script expressions are not supported. Writing `list` as `$.data.list` or `$.data.list[*]` both expand to one entry per element, and a child field `$.title` is evaluated relative to each element. XPath on a JSON response returns an empty result.
Regex source: flags can be `i`, `m`, `s`, `x`; `#n` takes group n. When omitted, group 1 is used if the pattern has a capture group, otherwise the whole match; only the first match is taken; inside a list item it runs on that item's outerHTML, otherwise on the entire raw response; write a literal `/` as `\/`.
### 12.3 Filters (chained with `|`, case-sensitive; quote string arguments, leave integers unquoted)
| Filter | Effect |
|---|---|
| `trim` / `lower` / `upper` | Trim whitespace / lowercase / uppercase |
| `replace('regex','replacement'[,'flags'])` | Replace all matches; the replacement can use `$1` |
| `replaceFirst('regex','replacement')` | Replace only the first match |
| `match('regex'[, group])` | Take the group of the first match (group 1 by default). **If there is no match, the value is discarded** |
| `split('separator')` / `join('separator')` | Split into multiple values / join into one |
| `first` / `last` / `index(n)` / `slice(a[,b])` | Take the first, the last, the nth, or a range (0-based; negative counts from the end) |
| `prepend('s')` / `append('s')` | Add a prefix / suffix |
| `default('s')` | Use `s` when the result is empty |
| `absurl` | Convert to an absolute URL (done automatically for URL fields) |
| `int` | Take the first integer |
| `lines` | Split on newlines into multiple values and drop empty lines |
| `unique` | Remove duplicates |
| `exists` | Output `"true"` / `"false"`, for boolean fields |
| `html2text` | Convert `<br>` and `<p>` to line breaks, strip tags, decode entities |
| `decodeEntities` / `urlDecode` | Decode HTML entities / percent-encoding |
| `js:functionName` | Call a script function |
| `re:/…/#n` | Regex extraction |
`first`, `last`, `index`, `slice` and `exists` keep the node form and can still be used as a `list`; all other filters convert nodes to text.
### 12.4 Fallback, concatenation, and replace shorthand
| Feature | Syntax | Notes |
|---|---|---|
| Fallback | `img@data-src \|\| img@src` | The right side is evaluated only if the left side is empty |
| Default value | `css:.status@text \| default('unknown')` | |
| Concatenation | `tpl:https://example.com/book/{{@data-id}}.html` | Each `{{ }}` is evaluated independently; an empty result becomes an empty string |
| Replace shorthand | `css:.author@text##^作者[::]\s*##` | Equivalent to `\| replace(…)`; must be placed at the end of a branch; ending with `###` replaces only the first match; write a literal `#` as `\#` |
"Empty" means: the selector matches nothing, the attribute does not exist, or the value is all whitespace or an empty string.
### 12.5 Common pitfalls (always check)
1. **Backslashes in JSON must be escaped once more**: every `\` in an expression is written as `\\` inside a JSON string. For example, the expression `match('/book/(\d+)', 1)` is written in JSON as `"match('/book/(\\d+)', 1)"`, and a literal bracket `\[` in a regex is written as `"\\["`.
2. A top-level `|` is always a filter separator; only a `|` inside quotes, `()`, `[]`, `{{ }}` or `re:/…/` does not count. Wrap an XPath union in parentheses: `(//a | //b)`.
3. `tpl:` cannot be followed by more filters (they would be treated as plain text); to process the result, put the filter inside `{{ }}`.
4. A misspelled variable name in `tpl:` does not raise an error; it is treated as a CSS selector and silently returns empty.
5. `match` with no match empties the field; add `| default('…')` when you need a safety net.
6. Use single quotes for string constants and filter arguments inside expressions, to avoid clashing with JSON's double quotes.
## 13. Template Variables
| Variable | Where available | Notes |
|---|---|---|
| `{{keyword}}` | search | The keyword the user typed, percent-encoded in URLs according to `charset` |
| `{{keyword\|raw}}` | search | As is, not encoded |
| `{{page}}` / `{{page0}}` / `{{offset}}` | Pagination | Page number (starting from `startPage`) / page number − 1 / (page number − 1) × `pageSize` |
| `{{sectionId}}` / `{{sectionURL}}` | explore | The current section's id / URL |
| `{{itemURL}}` | detail, toc | The work's URL |
| `{{chapterURL}}` | content | The chapter's URL |
| `{{url}}` | `authorOnlyURL` | The post's URL |
| `{{host}}` | All | The first non-wildcard domain in `domains` |
| `{{baseURL}}` | All | The current base URL |
| `{{storage.key}}` | All | A value stored by a script (requires a script and authorization); an empty string if it does not exist |
| `{{js:functionName}}` | **`request.url` only** | Calls a script function with no arguments; the return value is substituted into the URL |
A variable not listed in the table above appearing in `request.url` or in a string `body` is the error `invalidURL`. `{{js:…}}` written in `headers` is not substituted; use a `beforeRequest` script when you need dynamic headers or a dynamic request body.
## 14. When to Use `requiresWebView` / `render` / `capture` / Scripts
Choose in the following order; earlier is better:
1. **The site has a public JSON API** (for example, the search API that the list page calls): request the API directly, set `responseType: "json"`, and extract values with JSONPath. This is the fastest and most stable option.
2. **The content is in the raw HTML** (you can see the body text in "View Source"): use a normal request with CSS/XPath, and do not turn on `requiresWebView`.
3. **The content is rendered by front-end scripts** (not in the source, but visible in developer tools): set top-level `requiresWebView: true`, use `waitFor` in the relevant `request.render` to wait for a key element, and add `scrollToBottom` if needed. If unsure, leave it off first; the app will tell you during a trial run whether it is needed. Note: if page scripts only draw the player or images but the data they need (body text, media addresses) is already in an inline `<script>` of the source, this case does not apply. Use a normal request as in item 2 and parse it with a `parse` script; do not turn on `requiresWebView`. Browser-mode loading is much slower, and large pages tend to time out (`RUL_013`).
4. **The data comes from an API the page loads itself, and requesting that API directly does not work**: specify a match string for the API URL in that page's `request.render.capture`, and add `"source.intercept"` to the top-level `requires`.
5. **Declarative expressions truly cannot do it** (the response is Base64 or another encoding, the structure needs reorganizing, or the request needs parameters computed by the site's public rules): only then write a script (Section 15). Scripts must not be used for any purpose prohibited in Section 1.
## 15. Scripts (Only When Necessary)
```json
{
"scripts": {
"source": "function decode(resp, ctx) { resp.body = util.base64Decode(resp.body); return resp; }",
"hooks": { "content": { "afterResponse": "decode" } }
}
}
```
- Write all functions in the `scripts.source` string (≤ 256KB). They must be **top-level** `function` or `async function` declarations (`const f = () => …` will not be found). Referencing a function that does not exist reports `missingFunction`; a syntax error reports `scriptSyntax`.
- `hooks` keys: `search` / `explore` / `detail` / `toc` / `content`. Each can have `beforeRequest`, `afterResponse`, `parse` and `transform`, and the value is a function name.
- `fieldTimeoutMs`, `hookTimeoutMs`: 100 to 30000.
- Field level: `"title": "js:fn"` (the argument is the current node's outerHTML) or `"title": "css:a@text | js:fn"` (the argument is the previous step's result). The signature is `fn(value, ctx)`, returning a string, an array of strings, or `null`.
- Page level: `beforeRequest(req, ctx) → req` (`req = {url, method, headers, body}`; the returned headers replace the original headers entirely); `afterResponse(resp, ctx) → resp` (`resp = {status, url, headers, body}`; only `status` and `body` are used); `parse(resp, ctx) → result object` (takes over parsing completely); `transform(output, ctx) → result object` (post-processing; must return the complete object).
- `parse`/`transform` results: search/explore `{items:[{title,url,coverURL?,author?,summary?,latestText?,tags?}], nextPageURL?, hasMore?}`; detail `{title, coverURL?, author?, intro?, status?, tags?, extra?, tocURL?}`; toc `{chapters:[{title,url,isLocked?}], nextPageURL?, hasMore?}`, and for video `{lines:[{name, episodes:[…]}]}`; novel `{title?, paragraphs:[…], nextPageURL?}`; manga `{images:[url]}`; video `{streams:[{url,type?,quality?}], subtitles?}`; article `{title, author?, publishedAtText?, html}`; forum `{title, posts:[{floor?, author, avatarURL?, timeText?, quote?, html}], pageCount?}`. Even when `parse` is used, search's `list`/`fields` are still required.
- `ctx`: `rule {id,name,version,domains}`, `step`, `env` (`jsc` default environment / `webview` page environment), `url`, `baseURL`, `page`, `keyword`, `sectionId`, `itemURL`, `chapter`, `doc`.
- Available APIs (there is no `fetch`, `XMLHttpRequest` or timers; the default environment also has no DOM):
- `http.get(url, opts?)` / `http.post(url, body, opts?)` → `Promise<{status, url, headers, body}>`; `http.getSync` / `http.postSync` are the synchronous versions (default environment only). `opts: {headers?, charset?, timeoutMs?, responseType?: 'text'|'json'|'base64'}`. The target host must be within `domains`; a non-2xx response does not reject; at most 20 requests per page step.
- `cookie.get(url[, name])` → Promise, read-only, limited to URLs within `domains`.
- `storage.get/set/remove/keys/clear` → Promise, a rule-private key-value store on the device (values must be JSON-serializable, ≤ 64KB per value, ≤ 1MB in total).
- `log.debug/info/warn/error(...)`, `console.log/...`: output to the execution log.
- `util`: `base64Encode/base64Decode`, `hexEncode/hexDecode`, `md5/sha1/sha256`, `hmacSHA256(key,msg)`, `aesEncrypt/aesDecrypt(params)`, `absURL(base,rel)`, `urlEncode/urlDecode(s, charset?)`, `jsonPath(obj,path)`, `decodeCharset(base64Bytes, charset)`.
- `dom.parse(html, baseURL?)` → document; `select(css)`, `selectOne(css)`, `xpath(expr)`, `text()`, `ownText()`, `html()`, `outerHtml()`, `attr(name)`, `absURL(attr)`, `eval('css:h1@text')`.
- After a rule containing scripts is imported, the user must manually "Allow" it in the app before it runs; until allowed, pages that use scripts report `RUL_012`.
## 16. Verification, Login, Appearance, Capability Declarations (Usually Omit)
- `verification` (write it only when the app cannot recognize the site's captcha page): `statusCodes` (≤ 10 integers), `bodyContains`, `selectorExists`, `urlContains` (each ≤ 10 items), `successSelector`, `successURLPattern` (regex), `successCookie`, `stableMs` (500 to 5000), `disableBuiltInDetection` (boolean). Its only purpose is to **recognize** the verification page so the user can complete it personally in the web view; do not try to pass it automatically.
- `loginDetection`: `statusCodes`, `urlContains`, `bodyContains`, `selectorExists`, `loginURL` (http(s); the host should be within `domains`). When it matches, the user is prompted to log in in Web mode (`RUL_LOGIN_REQUIRED`).
- `display`: optional; the app picks a default appearance by type. Common forms: `{"list": {"style": "poster"|"book"|"story"|"text"|"card", "columns": 2~4, "coverAspect": "3:4"|"2:3"|"16:9"|"1:1", "density": "comfortable"|"compact"}}`, `{"detail": {"header": "cover"|"immersive", "introLines": 1~8}}`, `{"toc": {"style": "list"|"grid", "descending": true}}`, `{"immersive": true}` (full screen on scroll: native pages hide the status bar and buttons while you scroll down, and bring them back when you scroll up or reach the top; off by default). Invalid values are ignored.
- `requires`: declare it when you use `explore.filters`, `detail.blocks`, `request.render.capture` (write `source.intercept`), `display.blocks`, `pages.board.blocks` (write `board.blocks`) or a `chart:` source (write `source.chart`); omitting `source.intercept` or `detail.blocks` produces the warning `missingCapability`.
## 17. Complete Example (Wikisource, novel type, ready to import)
The site provides a public MediaWiki search API, so search uses JSON; detail, toc and content parse the HTML directly.
```json
{
"id": "org.wikisource.sample",
"name": "Wikisource",
"version": 2,
"author": "Unweb",
"contentType": "novel",
"domains": ["wikisource.org", "wikimedia.org"],
"urlPatterns": ["https://en.wikisource.org/wiki/*"],
"iconURL": "https://en.wikisource.org/static/favicon/wikisource.ico",
"requiresWebView": false,
"rateLimit": {"concurrency": 2, "intervalMs": 200},
"pages": {
"search": {
"request": {
"url": "https://en.wikisource.org/w/rest.php/v1/search/page?q={{keyword}}%20incategory%3A%22Novels%22&limit=20",
"responseType": "json"
},
"list": "$.pages[*]",
"fields": {
"title": "$.title",
"url": "tpl:https://en.wikisource.org/wiki/{{$.key}}",
"coverURL": "$.thumbnail.url",
"summary": "$.description || $.excerpt | html2text"
},
"pagination": {"mode": "none"}
},
"detail": {
"fields": {
"title": "css:#firstHeading@text",
"coverURL": "css:meta[property='og:image']@content",
"author": "css:#ws-author@text || css:#header_author_text a@text",
"intro": "css:meta[property='og:description']@content || tpl:{{css:#firstHeading@text}} · Wikisource"
}
},
"toc": {
"list": "css:table.ws-summary a[href*='/Chapter']",
"fields": {"title": "@text", "url": "@href"}
},
"content": {
"text": {
"title": "css:#firstHeading@text",
"paragraphs": "css:.prp-pages-output@html | html2text | lines",
"remove": [
"css:.pagenum", "css:.mw-editsection", "css:style",
"css:section[data-mw-section-id='-1'] > h2"
]
}
}
}
}
```
Key points:
- `search` uses the JSON API, and `tpl:` builds the work URL from the `key` returned by the API; `html2text` strips HTML tags from the summary.
- `detail.fields.title` is required; `intro` falls back with `||` to text built by `tpl:`.
- `toc` uses the attribute-contains selector `a[href*='/Chapter']` to select only chapter links.
- `content.text.paragraphs` uses `@html | html2text | lines` to split the body container into paragraphs, and `remove` strips page numbers and edit links.
- `domains` uses the registered domain `wikisource.org`, which covers `en.wikisource.org`.
## 18. Dashboard Rules `contentType: "dashboard"`: `pages.board`
Use this type when the user wants a **data page** from a business back-office / ops / sales / OA system (metrics, charts, tables, approval progress) rather than an article, novel, manga, forum or video. Dashboards are read-only by default (add actions / forms / embeds per 18.1 only when needed) and use **only `pages.board`**; do not write search / explore / detail / toc / content (they only produce the warning `unusedField`). Rules of the other five types are unaffected.
- Write `"board.blocks"` in `requires`; add `"source.chart"` when you use a `chart:` source and `"display.blocks"` when you use `display.blocks`.
- If the page needs a login or is rendered by front-end scripts: top-level `requiresWebView: true`, and use `waitFor` in `request.render` to wait for a key element (such as `#kpis .kpi-card` or a table row). `request.url` is required when there is no `urlPatterns`.
- Do not combine `render.capture` with `chart:` sources (capture returns API JSON, and the page's chart objects are not there).
`pages.board` fields: `request` (as in Section 6), `title` (an expression), `filters` (same as `explore.filters`; picking one reloads the whole page from that item's URL), `blocks` (required, 1 to 24).
Common block fields: `id` (required, `^[A-Za-z0-9_-]{1,40}$`, unique, must not equal a `filters` id, must not be `sections` `items` `toc` `lines` `intro` `tags`), `title` (≤ 80), `role` (required), `source`, `from` (only `"table"`), `list`, `fields`, `columns` (`[{title, value, numeric?}]`, ≤ 30 columns), `value` (text only), `unit`, `states` (steps only).
| role | Required | Optional | Notes |
|---|---|---|---|
| `metrics` | `fields.label`, `fields.value` | `delta` `trend` `unit` `higherIsBetter` `url` | One metric card per `list` node (one metric if there is no `list`); `delta` is the change text, `trend` a string of numbers or several values; ≤ 24 |
| `series` | One of: `from: "table"`; `columns` + `fields.label`; `fields.label` + `fields.value`; `source: "chart:…"` | `fields.series` `unit` | A chart. With `from: "table"` the first non-numeric column is the category and each other numeric column is a series; ≤ 20 series × 500 points |
| `table` | `from: "table"`; or `list` + `columns` | `fields.url` | A table; `numeric` is detected when omitted; ≤ 30 columns × 500 rows |
| `progress` | `fields.label`, `fields.value` | `total` `text` | `value` may be `68 / 100` or `68%`; ≤ 60 |
| `steps` | `list` | `fields.title` (default `@text`) `subtitle` `state` | Approval steps; `state` reads a status word or `@class`, classified as done / current / pending / rejected; `states` keys can only be those four, values are `\|`-separated substrings; ≤ 60 |
| `items` | `list`, `fields.title`, `fields.url` | `coverURL` `author` `summary` `latestText` `tags` | An item list; URLs must be inside `domains`; ≤ 60 |
| `text` | `value` | — | Text, ≤ 20,000 characters |
Key points:
- Number text needs no pre-cleaning: `¥12,480`, `3.2万`, `(1,234)` and `98.2%` all parse. A `delta` containing `%` may carry a direction word (`↓ ▼ down` negative); without `%` only a bare number is accepted. A table column whose cells parse as numbers with almost no surrounding text is treated as numeric (`12 orders`, `Q1` and dates are not).
- Chart `source`: `chart:echarts#0` (library `echarts` / `highcharts` / `chartjs` / `apexcharts`, index from 0, default 0), `chart:auto#1` (all libraries together, in DOM order), `chart:css(#c-region)` (the container is inside, or contains, an element matched by the selector; an optional `#index` may follow; prefer it when the chart order can change). Only on `series` blocks; `list` / `fields` / `columns` / `from` on such a block are ignored. If the chart is not found the block is not shown. Combo charts (bars + line) keep every series.
- `from: "table"` works only on HTML documents; for API JSON use `list` + `columns` (JSONPath).
- `display.blocks.<block id>`: `show` (series: `column` `stackedColumn` `bar` `stackedBar` `line` `area` `pie` `donut`; metrics: `grid` `row`; progress: `bar` `ring`; steps: `vertical` `horizontal`; items: `list` `rail` `grid`; table / text only have their own name), `span` (`full` / `half`), `fallback`, `hidden`. A chart source usually already suggests a good kind; write `show` only to change it, for example to a donut or a bar chart.
- One failing block drops only that block; if every block is empty the runtime error is `RUL_008`.
Validation: a missing `pages.board`, missing / empty `blocks`, an illegal / duplicate / reserved block id or one clashing with a filter, a missing `role`, a missing required field of a role, and a column without `title` / `value` are errors (V-38). An unknown role, fields used on a role that does not use them, a malformed `source`, `requires` missing `board.blocks` / `source.chart`, and more than 24 blocks are warnings (V-39). Using a `chart:` source without `requiresWebView: true` (or with `render.capture`) is the warning `needsRendering` (V-40).
Example (fictional site `ops.example.com`, data read after rendering; `chart:echarts#n` picks the n-th chart on the page, so `requiresWebView: true` and `source.chart` are required):
```json
{
"id": "com.example.ops.sales",
"name": "Example Ops Board",
"version": 1,
"contentType": "dashboard",
"domains": ["ops.example.com"],
"requiresWebView": true,
"requires": ["board.blocks", "display.blocks", "source.chart"],
"pages": {
"board": {
"request": {
"url": "https://ops.example.com/sales.html?range=30d",
"render": {"waitFor": "#kpis .kpi-card", "timeoutMs": 15000}
},
"title": "css:h1@text",
"filters": [
{
"id": "range",
"title": "Time range",
"list": "css:#range a",
"fields": {"selected": "@class | match('is-selected')"}
}
],
"blocks": [
{
"id": "kpi",
"title": "Key metrics",
"role": "metrics",
"list": "css:#kpis .kpi-card",
"fields": {
"label": "css:.kpi-label@text",
"value": "css:.kpi-value@text",
"delta": "css:.kpi-delta@text",
"trend": "css:svg.sp@data-points"
}
},
{
"id": "revenue",
"title": "Monthly revenue vs target",
"role": "series",
"source": "chart:echarts#0"
},
{
"id": "region",
"title": "Sales by region",
"role": "series",
"source": "chart:echarts#1"
},
{
"id": "top",
"title": "Top products",
"role": "table",
"from": "table",
"list": "css:table#top"
},
{
"id": "orders",
"title": "Latest orders",
"role": "table",
"list": "css:.order-row",
"columns": [
{"title": "Order no.", "value": "css:.no@text"},
{"title": "Amount", "value": "css:.amt@text", "numeric": true}
],
"fields": {"url": "css:a@href"}
},
{
"id": "quota",
"title": "Quota attainment",
"role": "progress",
"list": "css:.quota",
"fields": {
"label": "css:.name@text",
"value": "css:.done@text",
"total": "css:.target@text"
}
}
]
}
},
"display": {
"defaults": 1,
"blocks": {"region": {"show": "donut", "span": "half"}, "quota": {"show": "ring"}}
}
}
```
Common pitfalls:
- An empty chart block: usually `requiresWebView: true` is missing, or `waitFor` matches an element that appears before the chart data arrives (wait for something like a table row instead).
- Index-based chart picking is fragile: use `chart:css(selector)`.
- Using `from: "table"` on API JSON; putting `chart:` on a non-series block; steps whose state lives in the class but no `"state": "@class"`.
- Forgetting `request.url` when there is no `urlPatterns`.
- Actions without `success` / `error`, item actions without `"scope": "row"` and `fields.key`, selectors that did not come from the page samples.
### 18.1 Actions, forms and embedded pages (write actions; write them only when the user explicitly wants to approve / submit inside the dashboard)
- Block-level `actions` (any role) and item-level `itemActions` (only `items` / `table`; at most 8 each per block). Action fields: `id` (required, unique within the block), `title`, `style` (`primary` / `normal` / `destructive`), `icon`, `confirm`, `mutates` (default true), `inputs` (≤ 20; each has `id` / `label` / `kind` / `required` / `placeholder` / `options` / `value`), `run` (required), `success`, `error`, `after` (`refresh` / `open` / `none`), `timeout` (1000 to 60000). Every action that changes data shows a native confirmation before it runs and a rule cannot turn that off; a rule with write actions needs the user's one-time authorization.
- `run` is one of three: **prefer `steps` (the page runner)**, then `request`, and use `js` last (it needs a function in `scripts.source`).
- `steps` verbs (one per step): `{"fill": css, "from": inputId}`, `{"select": css, "from"}`, `{"check": css, "from"}`, `{"upload": css, "from"}`, `{"click": css}`, `{"waitFor": css | "navigation", "timeout": ms}`, `{"acceptDialog": true}`, `{"wait": ms}`; options `from` / `value` (a template) / `timeout` / `optional` / `scope` (`row` / `page`). At most 40 steps. An item action writes `"run": {"scope": "row", …}` so selectors are relative to that row, and elements inside a dialog add `"scope": "page"`; the block needs `fields.key` (for example `"@data-id"`) to locate the row.
- `request`: `{method, url, headers?, body?, json?, csrf?, csrfHeader?}`; `url` / `body` may use `{{inputs.x}}` `{{item.key}}` `{{item.url}}` `{{board.url}}` `{{csrf}}`.
- **Always write both `success` and `error`**: `success` is one of `{text: CSS or "re:regex"}`, `{gone: CSS}`, `{url: regex}`, `{json: "$.ok == true"}` (request only); `error` is the CSS of the page's error message. Without them the app can only judge by "page settled and no new error", which can mistake a failure for success.
- **Never invent selectors**: every CSS must come from the page samples the user provided. If a button / input is not in the samples, do not write that action; say in your notes that the user needs to supply a sample.
- Form block: `{"id": …, "role": "form", "from": "form", "list": "css:form#id", "submit": {"id": "submit", "title": "Submit", "success": …, "error": …, "after": "open"}}` reads the page form's inputs automatically; you may also write explicit `fields: [{id, kind, label, selector}]`. Add `board.forms` to `requires`.
- Embed block: `{"role": "embed", "embed": "html", "html": "<template>", "data": {name: expression}, "height": 220}` or `{"role": "embed", "embed": "fragment", "url": "/page", "selector": "CSS", "height": 260}` (a fragment reuses the site login). In an html template `{{x}}` escapes, `{{{x}}}` sanitizes site HTML and `{{json:x}}` emits JSON; scripts are off by default and run only with `scripts: true` (needs authorization). The page can use `window.unweb.data` / `open(url)` / `refresh()` / `toast(text)` / `action(id, inputs)` (still confirmed natively) / `theme` / `holdScroll(bool)`, and the theme variables `--ui-bg --ui-surface --ui-surface2 --ui-fill --ui-text --ui-text2 --ui-text3 --ui-accent --ui-on-accent --ui-separator --ui-success --ui-warning --ui-danger --ui-font --ui-font-serif --ui-font-mono --ui-radius`. Do not write html embed scripts unless the user asks.
- Add `board.actions` (any action), `board.forms` and `board.embed` to `requires`.
- Validation: V-41 (error) malformed actions, unknown verbs, references to undeclared inputs, `run` not exactly one of three; V-42 (warning) too many, `scope` / `itemActions` in the wrong place, select without `options`; V-43 (error) form / embed missing required fields (html without `html`, fragment without `selector`, a bad `data` expression); V-44 (warning / info) keys that do not apply, missing capabilities, and the info `writeActions` for rules with write actions (authorization needed).
Form example (fictional site; after submitting it goes to the detail page):
```json
{
"id": "com.example.ops.expense",
"name": "Example Expense Request",
"version": 1,
"contentType": "dashboard",
"domains": ["ops.example.com"],
"requiresWebView": true,
"requires": ["board.blocks", "board.forms"],
"urlPatterns": ["https://ops.example.com/expense.html*"],
"pages": {
"board": {
"request": {
"url": "https://ops.example.com/expense.html",
"render": {"waitFor": "form#expense", "timeoutMs": 15000}
},
"title": "css:h1@text",
"blocks": [
{
"id": "expense",
"title": "Expense request",
"role": "form",
"from": "form",
"list": "css:form#expense",
"submit": {
"id": "submit",
"title": "Submit request",
"success": {"url": "approval\\.html\\?id="},
"error": "#form-error",
"after": "open"
}
}
]
}
}
}
```
## 19. Pre-Output Self-Check List (check each item; it matches the app's validation)
1. The output is one valid JSON object; no comments, trailing commas or ellipses; only one code block.
2. `id` matches `^[A-Za-z0-9][A-Za-z0-9._-]{2,127}$`; `name` is 1 to 80 characters; `version` is an integer ≥ 1.
3. `contentType` is one of `article` / `novel` / `manga` / `forum` / `video` / `dashboard`.
4. `domains` is non-empty, ≤ 50, has no duplicates, and has no `*` or top-level-domain wildcard; no subdomain is already covered by another entry.
5. Every `request.url` starts with `http(s)://` or `{{`, its host matches `domains`, has no username or password, and uses only the variables listed in Section 13.
6. (Non-dashboard) `pages` contains only `search` / `explore` / `detail` / `toc` / `content`; there is at least search or explore (otherwise `urlPatterns` is required); `content` exists and contains the sub-key for the type (article→`article`, novel→`text`, manga→`image`, forum→`thread`, video→`video`); novel / manga / video have `detail` and `toc`. A dashboard has only `pages.board`, with a non-empty `blocks`, each block having a legal `id`, a `role` and that role's required fields (Section 18); if a `chart:` source is used, `requiresWebView: true` is present; every action has `success` and `error`, prefers `steps`, and uses only selectors from the samples; write actions / forms / embeds have `board.actions` / `board.forms` / `board.embed` in `requires`.
7. search: has `request.url`, `list`, `fields.title`, `fields.url` (or `urlAction`). explore: has `sections` (each with `id`, `title`, `request.url`, `list`, `fields`), or has both `sectionsFrom` and `sectionTemplate`; section ids are unique.
8. detail has `fields.title`; toc has `list`+`fields.title`+`fields.url` or `lines` (`names`, `groups`, `episodes.list`, `episodes.fields.title/url`).
9. Required body fields: article `body`; novel `paragraphs`; manga `images`; forum `posts.list` and `posts.fields.floor/author/body`; video `streams`.
10. When `pagination.mode` is `template`, the URL contains `{{page}}` / `{{page0}}` / `{{offset}}`; when it is `next`, `nextPageURL` is written; `maxPages` does not exceed the limit.
11. Expressions: `list` has no `@` value suffix; every filter name is in the 12.3 table and its argument types are correct (strings quoted, integers not); regexes compile; backslashes in JSON are doubled; `tpl:` is not followed by a filter.
12. `headers` has no `Host` / `Content-Length` / `Cookie`; the values of `charset`, `responseType` and `method` are valid.
13. `render` appears only when `requiresWebView: true` or there is a `capture`; if `capture` is used, write `source.intercept` in `requires`; if `detail.blocks` is used, write `detail.blocks`; if `filters` is used, writing `explore.filters` is recommended; if `pages.board` is used, write `board.blocks`, and add `source.chart` for `chart:` sources.
14. If there are scripts: functions are top-level `function` declarations and every referenced function exists; they are not used to bypass login, payment, verification or rate limits.
15. There are no fields outside this spec and no device-local fields.
16. The rule covers only public content the user is entitled to access, in line with Section 1.Plain-text files#
If your AI tool can read URLs, send it one of the links below directly. It is easier than pasting:
ai-rule-spec.md: exactly the same prompt as above, in Markdown.llms.txt: the index of this wiki (llms.txt convention), listing all pages and the spec file.
Tips for better results#
- If the site has a public search or list API (you can see requests that return JSON in the browser developer tools "Network" panel), give the AI the API address and a sample of the response. The generated rule is usually the most stable this way.
- If the content does not appear in "View page source" and only shows up in the developer tools Elements panel, tell the AI that "the content is rendered by the front end"; it will use
requiresWebViewandrender.waitFor. - Do one content type at a time. For several sites, generate one rule per site.
- If validation errors appear on import, send the error code and path to the AI unchanged. The self-check list in the prompt matches the app's validation rules.