urlmason 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,9 +8,9 @@ Turn URLs into values and values back into URLs, from one list of URL patterns.
8
8
 
9
9
  Describe each kind of URL once, as a template in the [RFC 6570](https://www.rfc-editor.org/rfc/rfc6570) URI Template syntax, and urlmason reads, builds and cleans up URLs from that one description:
10
10
 
11
- - Turn `https://example.com/@alice/feed` into `{ user: 'alice' }`.
12
- - Turn `{ user: 'alice' }` into `https://example.com/@alice/feed`.
13
- - Turn an old spelling, such as `http://example.com/u/alice/rss`, into `https://example.com/@alice/feed`.
11
+ - Turn `https://example.com/@alice/feed.xml` into `{ user: 'alice' }`.
12
+ - Turn `{ user: 'alice' }` into `https://example.com/@alice/feed.xml`.
13
+ - Turn an old spelling, such as `http://example.com/u/alice/rss`, into `https://example.com/@alice/feed.xml`.
14
14
 
15
15
  It has no dependencies and runs in any modern JavaScript runtime.
16
16
 
@@ -40,7 +40,10 @@ const feeds = defineTable(
40
40
  {
41
41
  key: 'user',
42
42
  main: 'https://example.com/@{user}/feed.xml{?page}',
43
- aliases: ['https://example.com/u/{user}/rss', 'https://old.example.com/{user}/feed'],
43
+ aliases: [
44
+ 'https://example.com/u/{user}/rss',
45
+ 'https://old.example.com/{user}/feed',
46
+ ],
44
47
  },
45
48
  { key: 'tag', main: 'https://example.com/tags{/tags*}.xml' },
46
49
  { key: 'post', main: 'https://example.com/@{user}/{id}/comments.xml' },
@@ -53,7 +56,25 @@ const feeds = defineTable(
53
56
 
54
57
  ```typescript
55
58
  feeds.readUrl('https://old.example.com/alice/feed')
56
- // { key: 'user', values: { user: 'alice' }, isAlias: true, isExact: true, row: {…} }
59
+ // {
60
+ // key: 'user',
61
+ // values: { user: 'alice' },
62
+ // row: {…},
63
+ // isAliasMatch: true,
64
+ // isExactMatch: true,
65
+ // isLenientMatch: false,
66
+ // }
67
+
68
+ // A list takes every segment it covers:
69
+ feeds.readUrl('https://example.com/tags/news/tech.xml')
70
+ // {
71
+ // key: 'tag',
72
+ // values: { tags: ['news', 'tech'] },
73
+ // row: {…},
74
+ // isAliasMatch: false,
75
+ // isExactMatch: true,
76
+ // isLenientMatch: false,
77
+ // }
57
78
 
58
79
  // No row matches, or a value fails its check:
59
80
  feeds.readUrl('https://example.com/@alice/abc/comments.xml')
@@ -83,12 +104,12 @@ feeds.buildUrls('user', { user: 'alice' })
83
104
 
84
105
  ```typescript
85
106
  // The row writes {?page}, so `page` stays and every other query parameter goes:
86
- feeds.getMainUrl('http://old.example.com/alice/feed?utm_source=newsletter')
87
- // 'https://example.com/@alice/feed.xml'
107
+ feeds.getMainUrl('http://old.example.com/alice/feed?page=2&utm_source=newsletter')
108
+ // 'https://example.com/@alice/feed.xml?page=2'
88
109
 
89
110
  // Already the main URL:
90
111
  feeds.getMainUrl('https://example.com/@alice/feed.xml')
91
- // undefined
112
+ // 'https://example.com/@alice/feed.xml'
92
113
  ```
93
114
 
94
115
  ### Encode strictly
@@ -103,7 +124,7 @@ feeds.buildUrl('tag', { tags: ['C++', 'web dev'] }, { encoding: 'strict' })
103
124
 
104
125
  ### Read a URL on any host
105
126
 
106
- A row on `{host}` can read software that runs on many sites, such as forums, under whatever folder the site sits in:
127
+ A row whose host is one placeholder can read software that runs on many sites, such as forums, under whatever folder the site sits in. The scheme and the host come back under the names the template gives them:
107
128
 
108
129
  ```typescript
109
130
  const forums = defineTable([
@@ -111,11 +132,57 @@ const forums = defineTable([
111
132
  { key: 'forum', main: '{scheme}://{host}{/base*}/feed.php' },
112
133
  ])
113
134
 
114
- forums.readUrl('https://board.example.org/community/viewtopic.php?t=42', { isAnyHost: true })
115
- // { key: 'topic', values: { topic: '42', scheme: 'https', host: 'board.example.org', base: ['community'] }, … }
135
+ forums.readUrl('https://example.org/community/viewtopic.php?t=42', { isAnyHost: true })
136
+ // {
137
+ // key: 'topic',
138
+ // values: {
139
+ // topic: '42',
140
+ // scheme: 'https',
141
+ // host: 'example.org',
142
+ // base: ['community'],
143
+ // },
144
+ // row: {…},
145
+ // isAliasMatch: false,
146
+ // isExactMatch: false,
147
+ // isLenientMatch: false,
148
+ // }
149
+
150
+ const site = forums.forSite('https://example.org/community/')
151
+
152
+ site?.buildUrl('forum', { base: ['community'] })
153
+ // 'https://example.org/community/feed.php'
154
+ ```
155
+
156
+ ### Read a URL inside a URL
157
+
158
+ ```typescript
159
+ const snapshots = defineTable([
160
+ { key: 'snapshot', main: 'https://archive.example.com/web/{time}/{+url}' },
161
+ ])
162
+
163
+ const snapshot = 'https://archive.example.com/web/2020/https://example.org/feed?page=2'
164
+
165
+ snapshots.readUrl(snapshot)?.values
166
+ // { time: '2020', url: 'https://example.org/feed?page=2' }
116
167
 
117
- forums.forSite('https://board.example.org/community/')?.buildUrl('forum', { base: ['community'] })
118
- // 'https://board.example.org/community/feed.php'
168
+ snapshots.buildUrl('snapshot', { time: '2020', url: 'https://example.org/feed?page=2' })
169
+ // 'https://archive.example.com/web/2020/https://example.org/feed?page=2'
170
+ ```
171
+
172
+ ### Read a fragment
173
+
174
+ ```typescript
175
+ const apps = defineTable([
176
+ { key: 'sheet', main: 'https://app.example.com/view#!/home/{book}/{sheet}' },
177
+ { key: 'home', main: 'https://app.example.com/view' },
178
+ ])
179
+
180
+ apps.readUrl('https://app.example.com/view#!/home/sales/q1')
181
+ // { key: 'sheet', values: { book: 'sales', sheet: 'q1' }, … }
182
+
183
+ // A row that writes no fragment reads a URL whatever its fragment:
184
+ apps.readUrl('https://app.example.com/view#about')?.key
185
+ // 'home'
119
186
  ```
120
187
 
121
188
  ### Read a tenant's URL
@@ -129,9 +196,11 @@ blogs.readUrl('https://alice.example.co.uk/feed')?.values
129
196
  // { blog: 'alice', domain: 'example.co.uk' }
130
197
  ```
131
198
 
199
+ The last label of a host of several is the tenant domain, whatever its name, so `https://{blog}.{tld}/feed` reads `tld` the same way.
200
+
132
201
  ## Templates
133
202
 
134
- A template is a full URL with placeholders. Each one reads from and builds into its own part of the URL:
203
+ A template is a full URL written in the [RFC 6570](https://www.rfc-editor.org/rfc/rfc6570) URI Template syntax. Builds follow the RFC and are checked against its own test suite, and the few places urlmason departs from it are [listed below](#where-it-differs-from-rfc-6570). Each placeholder reads from and builds into its own part of the URL:
135
204
 
136
205
  | Placeholder | Takes | Example |
137
206
  | --- | --- | --- |
@@ -139,13 +208,32 @@ A template is a full URL with placeholders. Each one reads from and builds into
139
208
  | `{/name*}` | One or more path segments | `https://example.com/docs{/path*}` |
140
209
  | `{?a,b}` | Query names a URL may carry, on a URL with no query | `https://example.com/feed{?page,limit}` |
141
210
  | `{&a,b}` | The same, behind a query the template writes | `https://example.com/feed?alt=rss{&page}` |
142
- | `{scheme}` | The URL's scheme | `{scheme}://example.com/feed` |
143
- | `{host}` | A host the table lists | `{scheme}://{host}/feed` |
144
- | `{domain}` | A tenant domain the table lists | `https://{blog}.{domain}/feed` |
145
- | `{/base*}` | The folder a site sits in, possibly empty | `{scheme}://{host}{/base*}/feed.php` |
146
- | `{/tail*}` | Any segments at the end of the path, possibly empty | `https://example.com/{user}{/tail*}` |
211
+ | `?name{id}` | A value inside the name of a flag, a pair with no value | `https://example.com/spip.php?article{id}` |
212
+ | `{?name*}` | Every pair no other part of the template names, as a map, or `{&name*}` behind a query the template writes | `https://example.com/search{?q,query*}` |
213
+ | `{name}` as the scheme | The URL's scheme | `{scheme}://example.com/feed` |
214
+ | `{name}` as the whole host | A host the table lists | `{scheme}://{host}/feed` |
215
+ | `{name}` as the last label of a host | A tenant domain the table lists | `https://{blog}.{domain}/feed` |
216
+ | `{/base*}` | Keyword: the folder a site sits in, possibly empty, which a read on the table's own hosts takes only empty | `{scheme}://{host}{/base*}/feed.php` |
217
+ | `{/tail*}` | Keyword: any segments at the end of the path, possibly empty | `https://example.com/{user}{/tail*}` |
218
+ | `{+name}` | Path or fragment text as written, slashes included, up to the next fixed text | `https://example.com/raw/{+path}/feed.xml` |
219
+ | `{+name}` | At the end of a template with no query or fragment, the rest of the URL | `https://example.com/proxy/{+url}` |
220
+ | `{#name}` | The whole fragment as written, at the end of a template | `https://example.com/{page}{#section}` |
221
+
222
+ A placeholder's job in the scheme, the host and the query comes from where it sits, so any name works there, as `{?extra*}` for a passed query, and a name like `host` in the path is an ordinary value. `base` and `tail` are the two keywords: `{/base*}` goes only right behind the host and `{/tail*}` only at the end of the path, and a template that writes either name anywhere else throws.
223
+
224
+ <details>
225
+ <summary>Values, lists and maps</summary>
147
226
 
148
- A value may be a string, a list or a map. A list in a slot of one value is written as its items joined by commas, and a map as its names and values joined by commas, as RFC 6570 writes them. A row reads a URL only when every value passes its checks, and builds a URL only from values that do.
227
+ A value may be a string, a list or a map. A list in a slot of one value is written as its items joined by commas, and a map as its names and values joined by commas, as RFC 6570 writes them. A name keeps one shape everywhere in a table, one value, a list or a map, so `{/path*}` in one row and `{path}` or `{?path}` in another throw when the table is defined, since values read from the first would build the second joined. A row reads a URL only when every value passes its checks, and builds a URL only from values that do.
228
+
229
+ </details>
230
+
231
+ <details>
232
+ <summary>Templates refused at define time</summary>
233
+
234
+ A template a table could not read back throws when the table is defined. Two values with no fixed text between them, as `{first}{second}`, have no place where one ends, so they throw, while `{slug}-{id}` and a value in front of a list, as `{user}{/tail*}`, read fine. Two lists with only values between them, as `{/a*}/{v}{/b*}`, throw for the same reason, while `{/base*}{/path*}` reads fine. A list in the query, a fixed `.` or `..` segment, a port or a user in the host, a host label that holds a value beside text outside ASCII, a brace outside a placeholder, and a name every object holds, as `{constructor}`, throw too. `{+name}` throws in the host or the query, beside `{/tail*}`, and beside a list other than `{/base*}` or one right in front of it, and `{/tail*}` throws in a path with a list other than `{/base*}`. `{/base*}` behind a host other than one placeholder throws, and so does a host of several labels that ends in a placeholder, on a table without `hosts.tenant`.
235
+
236
+ </details>
149
237
 
150
238
  ### Rows
151
239
 
@@ -162,49 +250,182 @@ const pages = defineTable(
162
250
  )
163
251
  ```
164
252
 
165
- Rows are read most specific first: a template without `{/tail*}` before one with it, then the one with more query names, then the earlier row. Two rows can share a key, such as an Atom and an RSS spelling of one feed, and a build uses the first one the values fill.
253
+ Rows are read most specific first, and a build goes through a key's rows in order and writes the first URL the values fill: a row's main URL, then its aliases, then the next row.
254
+
255
+ A row holds its `key`, its `main` URL and its `aliases`. `isBuildOnly` marks a row the table builds and never reads, and a row can add [its own `checks`](#row-checks-and-pattern-rules) beside the table's. Two rows can share a key, such as the Atom and the RSS feed of one blog. `variant` tells a row from another of its key with the same placeholders, and a build picks it through `select`, as `(row) => row.variant === 'rss'`. A row may carry fields of its own, such as a `format`, which `select` and a read's `row` see. `table.rows` holds a copy of each row, for code that walks a whole table.
256
+
257
+ <details>
258
+ <summary>How rows are ranked</summary>
259
+
260
+ A template without an open end, `{/tail*}` or a `{+name}` that takes the rest of the URL, goes before one with it, and of two with one, the one with more segments in front of it. Then the one that writes more query parameters, as `alt=rss`, `id={id}` or a flag with a value in the name, while `{?a,b}` names don't count. Then one that writes a fragment, then the one with more fixed text in its host, path and values, so `/posts` before `/{id}`, then the earlier row. The scheme and the parameter names don't count, since a read takes either scheme and a parameter by its name. [`isFallThrough`](#query-parameters-and-fall-through) sets this order aside.
261
+
262
+ </details>
263
+
264
+ ### Checks
265
+
266
+ A check says which values a placeholder takes. A value that fails its check is neither read nor built, and a list is checked as its segments joined by `/`, as `news/tech`:
267
+
268
+ ```typescript
269
+ const reserved = ['about', 'login', 'settings']
270
+ const locales = ['en', 'de', 'pl']
271
+
272
+ const pages = defineTable(
273
+ [
274
+ { key: 'docs', main: 'https://example.com/{locale}/docs' },
275
+ { key: 'user', main: 'https://example.com/{user}' },
276
+ ],
277
+ {
278
+ checks: {
279
+ // A pattern, anchored at both ends.
280
+ id: /^\d+$/,
281
+ // A list of the values a slot takes.
282
+ locale: (value) => locales.includes(value),
283
+ // A list of the values it never takes.
284
+ user: (value) => !reserved.includes(value),
285
+ },
286
+ },
287
+ )
288
+
289
+ pages.readUrl('https://example.com/login')
290
+ // undefined
291
+ ```
292
+
293
+ A list that only says yes or no to a value belongs here, in the table. A list that changes the URL, as a map from one name to another, stays in the code that calls the table.
294
+
295
+ <details>
296
+ <summary><a id="row-checks-and-pattern-rules"></a>Row checks and pattern rules</summary>
297
+
298
+ A row can add its own `checks` beside the table's, and a function there also gets the row's other values, as `(date, { host }) => …`. A value the URL or the build leaves out, such as an optional query name, is missing there. A row check or a value case mark that names a value none of the templates writes throws when the table is defined, while the table's checks may name more, so one set of checks can serve several tables. A pattern throws unless it's anchored at both ends with no `g` or `y` flag, and so does one with a backreference or a named group, since it is joined with the table's other patterns.
299
+
300
+ </details>
166
301
 
167
302
  ### Hosts
168
303
 
169
- `hosts.exact` lists the hosts a `{host}` placeholder stands for, and `hosts.tenant` the domains that `{domain}` stands for and that tenants live under. An entry is a string, a pattern anchored at both ends, or a function that takes a host. A fixed host matches with or without `www`.
304
+ `hosts.exact` lists the hosts a host of one placeholder stands for. `hosts.tenant` lists the domains that tenants live under, which the last label of a host of several stands for. `hosts.subdomain` lists domains that a host of one placeholder stands for together with every host under them, so `example.com` covers `player.eu.example.com` too. An entry is a string, a pattern anchored at both ends, or a function that takes a host.
305
+
306
+ <details>
307
+ <summary><code>www</code> and hosts outside ASCII</summary>
308
+
309
+ A fixed host matches with or without `www`. `isWwwTenant` lets `www` be a tenant, so `www.example.com` reads on `https://{user}.example.com/feed`, and `isWwwTenantPrefix` drops a `www` in front of a tenant, so `www.alice.example.com` reads as `alice.example.com`.
310
+
311
+ A host reads as a parsed URL spells it: in lowercase, with a label outside ASCII in punycode. A host in a template or a string entry can be written either way: a template on `bücher.example` reads `https://bücher.example/` and `https://xn--bcher-kva.example/` alike, and a build writes the punycode. A pattern or a function sees the host only in that form.
312
+
313
+ </details>
170
314
 
171
315
  ### Limits
172
316
 
173
- A URL part that holds two or more values, such as `{slug}-{id}` in one segment, is read only up to 1,000 characters. Values side by side can be split in many ways, and the limit keeps a crafted URL from taking long to read.
317
+ A URL part that holds two or more values, such as `{slug}-{id}` in one segment, is read only up to 1,000 characters.
318
+
319
+ <details>
320
+ <summary>Why reads stop at 1,000 characters</summary>
321
+
322
+ Values side by side can be split in many ways, and the limit keeps a crafted URL from taking long to read. The same limit holds for a path with two lists or a list and a `{+name}`, and for a path or a fragment with two `{+name}` values or a `{+name}` with a value behind it, as `{+path}.{format}`.
323
+
324
+ </details>
174
325
 
175
326
  ## Encoding
176
327
 
177
328
  Builds come in two spellings, picked per call with `{ encoding }`:
178
329
 
179
- - **`pretty`, the default,** decodes a value's valid escapes, then writes every character the part allows, so `Ann Lee!` builds `/@Ann%20Lee!/feed`.
330
+ - **`pretty`, the default,** decodes a value's valid escapes, then writes every character the part allows, so `Ann Lee!` builds `/@Ann%20Lee!/feed`. An escape that decodes to no character, as `%E0%A4` of a cut-off `अ`, stays as written, so a URL read and built again is the URL it was.
180
331
  - **`strict`** writes a value as RFC 6570 does, encoding everything outside the unreserved characters, so the same value builds `/@Ann%20Lee%21/feed`.
181
332
 
182
- `getMainUrl` takes the same option. Pretty keeps each value as the URL spelled it, and strict builds the main URL from the values it reads, so a strict main URL equals a strict build of the same values.
333
+ <details>
334
+ <summary>Main URLs under each encoding</summary>
335
+
336
+ `getMainUrl` takes the same option. Pretty keeps each value as the URL spelled it, and strict builds the main URL from the values it reads, so a strict main URL equals a strict build of the same values. A value that moves to another part of the URL, as from the query into the path, is written as a pretty build writes it there, so `?id=a%3Ab` moves into the path as `/a:b`.
337
+
338
+ </details>
339
+
340
+ <details>
341
+ <summary>Query order</summary>
342
+
343
+ A query is written in the order the template writes it, then every other pair in the order the URL or the passed map gives it. Two URLs that differ only in that order stay two spellings, and trousse's `normalizeUrl` with `sortQueryParams` gives them one.
344
+
345
+ </details>
183
346
 
184
347
  ### Where it differs from RFC 6570
185
348
 
186
349
  RFC 6570 defines how a template builds a URL. Reading one back is urlmason's own:
187
350
 
188
351
  - A template is a full URL, and each placeholder reads from one part of it.
189
- - A name may hold a hyphen, as `{?max-results}`, since platforms write them that way.
190
- - Query pairs are written sorted by name, so one URL has one spelling.
352
+ - A name in `{?a,b}` or `{&a,b}` may hold a hyphen, as `{?max-results}`, since platforms write them that way.
191
353
  - `{?a,b}` ends a URL with no query, and `{&a,b}` one behind a query.
192
- - A list slot given an empty list builds no URL, so a missing value never builds a URL that names nothing.
193
- - Operators beyond these, such as `{+x}`, `{#x}`, `{.x}`, `{;x}` and `{x:3}`, are refused when a table is defined.
354
+ - An empty value or a list with no item builds no URL, and an empty path segment is never read as a value.
355
+ - `{+x}` reads its value as written, and a list right in front of it shares its segments with it.
356
+ - A template may write a fragment, and then reads only a URL that carries it.
357
+ - A value inside the name of a flag stops at a slash.
358
+ - A name holds one value, even where a template or a URL gives it twice.
359
+ - `{?query*}` and `{&query*}` read every pair the template doesn't name into a map.
360
+ - Operators beyond these, such as `{.x}`, `{;x}` and `{x:3}`, are refused when a table is defined.
361
+
362
+ <details>
363
+ <summary>Empty values and empty segments</summary>
364
+
365
+ An empty value builds no URL in a host label, a path segment, a fixed query value, a flag or a `{+x}`, and neither does a list with no item, so a missing value never builds a URL that names nothing. A list leaves its empty items out, so `['a', '', 'b']` builds `/a/b` in `{/p*}` and `a,b` in `{p}`, and a string given to a list is read as segments joined by `/`.
366
+
367
+ An empty path segment is never read as a value. A doubled slash at the start of a path reads as one in front of fixed text, so `example.com//feed/12` reads as `/feed/{id}`, and reads nothing in front of a value, so `example.com//12` reads no `/{id}`. A `{+x}` keeps an empty segment as written, and a base or a list never holds one.
368
+
369
+ </details>
370
+
371
+ <details>
372
+ <summary><a id="reserved-values-and-lists-in-front-of-them"></a>Reserved values and lists in front of them</summary>
373
+
374
+ `{+x}` sits in the path or the fragment and reads its value as written, never decoded. In front of fixed text it takes the shortest text that lets the whole URL read. At the end of a template with no query and no fragment it takes the rest of the URL, query and fragment included, so a URL inside a URL comes back whole. It builds the same under both encodings, but for `|`, which pretty writes as it is and strict as `%7C`.
375
+
376
+ A `{x}` value reads `%7C` as `|`, but a `{+x}` or `{#x}` value reads as written, so `a%7Cb` and `a|b` are two values there. A strict build and a strict main URL write `|` as `%7C`, so a `{+x}` or `{#x}` value holding `|` gets neither, unless the table or the row sets `pipeEscape`. Under it a strict build writes `a|b` as `a%7Cb`, the strict main URL of `/p/a|b/feed` is `/p/a%7Cb/feed`, which reads back `a|b`, and the pretty main URL of `/p/a%7Cb/feed` is `/p/a|b/feed`, as a pretty build writes it.
377
+
378
+ A list right in front of a `{+x}`, as `{/options*}/{+source}`, shares its segments with it. A read takes the first split every check passes, and the value with the check takes all it can: a checked list its most segments, and the value behind an unchecked list the fewest list segments. A table throws where neither of the two has a check.
379
+
380
+ </details>
381
+
382
+ <details>
383
+ <summary>Fragments, flags and repeated names</summary>
384
+
385
+ A template may write a fragment, as `#!/video/{id}` or `{#x}`, and then reads only a URL that carries it. A value in it stops at a slash, as in a path, and `{+x}` and `{#x}` read as written. A template without a fragment reads a URL whatever its fragment.
386
+
387
+ A value inside the name of a flag stops at a slash, as in a path, so a value with a slash builds no URL. Two flags whose names start alike each read their own pair, and a flag given twice reads as not exact.
388
+
389
+ A name holds one value, as RFC 6570 builds it. A template may write a name twice, as `/{user}/{user}`, and a URL may give a query name the template takes twice, as `?q=cats&q=cats`. Either reads only when every copy holds the same value, so `/alice/bob` and `?q=cats&q=dogs` read nothing. Copies of a name the `valueCase` mark covers hold the same value in any letter case, so `/Alice/alice` reads `alice`. A list in place of the one value would build back as `/alice,bob/alice,bob`.
390
+
391
+ </details>
392
+
393
+ <details>
394
+ <summary>Query maps</summary>
395
+
396
+ `{?query*}` and `{&query*}` read every pair the template doesn't name into a map, a name given twice as a list of its values, so a URL read and built again keeps every pair.
397
+
398
+ A map that holds a name the template writes itself, or one a flag in it takes, builds no URL, since the table would read that pair into the template's own value.
399
+
400
+ </details>
194
401
 
195
402
  ## API
196
403
 
197
404
  ### `defineTable(rows, options?)`
198
405
 
199
- Compiles the rows and returns a table. A template it can't read throws here, so a table that defines reads and builds without throwing.
406
+ Compiles the rows and returns a table. A template it can't read throws here, so a table that defines reads without throwing, and builds without throwing for a key it holds.
200
407
 
201
408
  ```typescript
202
409
  const table = defineTable(rows, {
203
- hosts: { exact: ['example.com'], tenant: ['example.org'] },
410
+ hosts: {
411
+ exact: ['example.com'],
412
+ tenant: ['example.org'],
413
+ subdomain: ['example.net'],
414
+ },
415
+ // `www` as a tenant, and `www.` dropped in front of one.
416
+ isWwwTenant: true,
417
+ isWwwTenantPrefix: true,
204
418
  // A check per placeholder: a pattern anchored at both ends, or a function.
205
419
  checks: { id: /^\d+$/, locale: (value) => value.length === 2 },
206
- // Values read in any letter case, which a main URL writes in lowercase.
207
- lenient: { case: ['user'] },
420
+ // The spellings read beside the template's, each described below.
421
+ lenient: {
422
+ valueCase: ['user'],
423
+ fixedCase: true,
424
+ trailingSlash: true,
425
+ semicolonSeparator: true,
426
+ ampersandEntity: true,
427
+ pipeEscape: true,
428
+ },
208
429
  // A rewrite keeps no query parameter the row does not name.
209
430
  isQueryKept: false,
210
431
  // A row that refuses a URL passes it to the next row, read in the order written.
@@ -212,28 +433,94 @@ const table = defineTable(rows, {
212
433
  })
213
434
  ```
214
435
 
215
- Each option, and each field of a row, such as `variant` and its own `checks`, is documented on its type.
436
+ <details>
437
+ <summary><a id="query-parameters-and-fall-through"></a>Query parameters and fall-through</summary>
438
+
439
+ `isQueryKept` is `true` when left out, so a rewrite keeps every query parameter of a row that names none. A row that writes `{?a,b}` keeps only those names, and one with `{?query*}` keeps every pair.
440
+
441
+ `isFallThrough` is for page tables: a row that refuses a URL, by a check or by a parameter that tells rows apart, passes it to the next row that fits, of any shape. A table with `isFallThrough` reads its rows in the order written. Without it, a URL a check refuses goes on only to rows of the same shape. [`findHiddenRows`](#findhiddenrowstable) finds the rows that hides.
442
+
443
+ </details>
444
+
445
+ Each lenient mark reads another spelling of a URL as its template's. A read that needed a mark is a lenient match and never an exact one, and `getMainUrl` writes the template's spelling, or for `valueCase` the value in lowercase:
446
+
447
+ - `trailingSlash` reads a URL with or without a trailing slash, where the template's path ends in fixed text or one value. Without it, `/feed/` reads only where a template or an alias writes `/feed/`.
448
+ - `fixedCase` reads the fixed text of the templates, the path, query names, fixed values and the fragment, in any letter case as the template's, so `getMainUrl` respells `/Rss.aspx` as `/rss.aspx`, `format=RSS` as `format=rss` and `#!/Feed` as `#!/feed`. Without it, `/Rss.aspx` reads only where a template or an alias writes `/Rss.aspx`, since a server can treat path letters as case-sensitive.
449
+ - `valueCase` lists the values read in any letter case, which the main URL writes in lowercase, as `alice` for `/Alice/feed`.
450
+ - `semicolonSeparator` reads `;` between query pairs as `&`.
451
+ - `ampersandEntity` reads `&amp;` between query pairs as `&`, as a URL copied out of HTML spells it.
452
+ - `pipeEscape` reads `%7C` and `%7c` as `|` in a `{+x}` or `{#x}` value, which changes how [a strict build writes `|`](#reserved-values-and-lists-in-front-of-them).
453
+
454
+ <details>
455
+ <summary>How lenient marks combine</summary>
456
+
457
+ `trailingSlash` and `pipeEscape` also go on one row, and a row's mark wins over the table's, so `{ trailingSlash: false }` turns it off there. A mark that changes nothing, as `valueCase` on a value already in lowercase, leaves the read exact.
458
+
459
+ Under `trailingSlash`, a row reads the other slash in its turn, so `/feed/rss/` reads `/feed/rss` before a later `/feed{/path*}` does. Only a template of its shape that writes the URL's slash goes ahead of it, as `/p{id}/` does for `/p1/` behind `/p{id}`.
460
+
461
+ A `valueCase` mark on a value that shares its part of the URL with another value throws when the table is defined, and so does a row that writes `;` in its query under `semicolonSeparator`, or a name `ampersandEntity` would read as another, as `amp;b`.
462
+
463
+ </details>
216
464
 
217
465
  ### `table.readUrl(url, options?)`
218
466
 
219
- Returns the row a URL is and its values, or `undefined`. `isAlias` says the URL matched an alias, and `isExact` that it's written exactly as its template is. With `{ isAnyHost: true }`, a `{host}` row reads a URL on any host, under the folder its path shows, and `{ base }` names that folder.
467
+ Returns the row a URL is and its values, or `undefined`. A value reads decoded, but for a `{+x}` or `{#x}` value and an escape that decodes to no character, which read as written.
468
+
469
+ - `isAliasMatch` says the URL matched an alias.
470
+ - `isExactMatch` says the URL is written as the row writes it: in the same letter case, with the same trailing slash, each own parameter once and no mark needed.
471
+ - `isLenientMatch` says a lenient mark was needed, as for `/Alice/feed/` lowercased to `alice` by the `valueCase` mark, and such a read is never exact.
472
+
473
+ <details>
474
+ <summary>When a read is exact</summary>
475
+
476
+ A platform can answer any other spelling with another feed. A URL on `www`, with an escape such as `al%69ce`, or with pairs added or in another order can still be exact, and so can one on `https` where the row writes `http`. A URL on `http` where the row writes `https` is not, since its main URL writes `https`, and a read under any host or a base never is.
477
+
478
+ </details>
479
+
480
+ <details>
481
+ <summary>Reads on any host</summary>
482
+
483
+ With `{ isAnyHost: true }`, a row whose host is one placeholder reads a URL on any host, under the folder its path shows, and `{ base }` names that folder, as `'/forum'` or `['forum']`, in any letter case and with either trailing slash. The scheme and the host are read under the names the row's template gives them, so a row that writes `https` reads no scheme. The Quick start [reads a forum on any host](#read-a-url-on-any-host).
484
+
485
+ </details>
220
486
 
221
487
  ### `table.buildUrl(key, values, options?)`
222
488
 
223
- Builds the first URL of the key's rows that the values fill, or `undefined`. A value that would move the URL to another path, scheme or host returns `undefined`. `{ select }` limits the rows to the ones a function picks, and `{ encoding }` picks the spelling.
489
+ Builds the first URL the values fill, or `undefined`. The key's rows are tried in order, each row's main URL before its aliases. A value that would move the URL to another path, scheme or host returns `undefined`. `{ select }` limits the rows to the ones a function picks, and `{ encoding }` picks the spelling. A key no row holds throws, which the typecheck catches where the rows spell their keys out.
490
+
491
+ <details>
492
+ <summary>Values a build refuses</summary>
493
+
494
+ A built URL reads back the values it was built from, and the checks see each value as the URL writes it, so `a%20b` is checked as `a b`. A value that fails its check, one the URL would read back as another value, and one outside the types, such as a nested map or text cut inside an emoji, return `undefined`. The build doesn't fall back to an alias that has no place for the value, so a page that fails its check never builds the home feed. A value that only a row's own check refuses skips that row and moves on to the next one.
495
+
496
+ </details>
224
497
 
225
498
  ### `table.buildUrls(key, values, options?)`
226
499
 
227
- Builds every spelling of the first row the values fill: its main URL, then each alias.
500
+ Builds every spelling the values fill of the first row that has one: its main URL, then each alias, each URL once. It refuses the same values `buildUrl` does, with an empty list.
228
501
 
229
502
  ### `table.getMainUrl(url, options?)`
230
503
 
231
- Rewrites a URL to its row's main URL, or returns `undefined` where it's already the main URL or can't be rewritten safely, such as a URL with credentials.
504
+ Rewrites a URL to its row's main URL, and returns a main URL as itself, written as a URL parser writes it. It returns `undefined` for a URL the table doesn't hold or can't rewrite safely, such as a URL with credentials. It reads only the table's own hosts, as `readUrl` does without `isAnyHost`, so an alias whose host is one placeholder, on a table with no `hosts`, gets no main URL.
232
505
 
233
506
  ### `table.forSite(url)`
234
507
 
235
- Returns `buildUrl` and `buildUrls` with `{scheme}`, `{host}` and `{domain}` filled from a page's URL.
508
+ Returns `buildUrl` and `buildUrls` with the scheme, a host of one placeholder and the last label of a host of several filled from a page's URL, whatever their names.
509
+
510
+ <details>
511
+ <summary>Which values a page fills</summary>
512
+
513
+ The last label is the page's host or the nearest parent domain `hosts.tenant` lists, so a page on `example.com` itself fills it too. A placeholder elsewhere is left to the values given, whatever its name. A template whose check refuses a value the page filled in, and the values given leave alone, builds nothing, and the key's other templates still build, as a feed on a fixed host for a page on a host the check refuses.
514
+
515
+ </details>
516
+
517
+ ### `findHiddenRows(table)`
518
+
519
+ Returns the rows a check refusal hides in a table without `isFallThrough`: a row takes a URL first and its check refuses it, so a row of another shape that reads it is never tried. Each entry holds the `key`, the refusing `row` and its `template`, the `hiddenRow` and its `hiddenTemplate`, and the `url` that shows it, one per pair of rows. It reads one URL built from sample values per template, so it can miss a hidden row, and it runs only when called, so a test asserts `expect(findHiddenRows(table)).toEqual([])`.
236
520
 
237
521
  ## Thanks
238
522
 
239
- The [uritemplate-test](https://github.com/uri-templates/uritemplate-test) suite checks every build urlmason shares with RFC 6570, and [url-template](https://github.com/bramstein/url-template) checks builds on inputs the suite lacks. Both run in the tests only, since they build URLs and urlmason also reads them.
523
+ - [uritemplate-test](https://github.com/uri-templates/uritemplate-test) suite checks every build urlmason shares with RFC 6570,
524
+ - [url-template](https://github.com/bramstein/url-template) checks builds on inputs the suite lacks.
525
+
526
+ Both run in the tests only, since they build URLs and urlmason also reads them.
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { defineTable } from "./tables.mjs";
2
- import { UrlBuildOptions, UrlCheck, UrlEncoding, UrlHostCheck, UrlHosts, UrlKeyMatch, UrlLenient, UrlMap, UrlMatch, UrlReadOptions, UrlRow, UrlRowCheck, UrlTable, UrlTableOptions, UrlValue, UrlValues, UrlWriteOptions } from "./types.mjs";
3
- export { type UrlBuildOptions, type UrlCheck, type UrlEncoding, type UrlHostCheck, type UrlHosts, type UrlKeyMatch, type UrlLenient, type UrlMap, type UrlMatch, type UrlReadOptions, type UrlRow, type UrlRowCheck, type UrlTable, type UrlTableOptions, type UrlValue, type UrlValues, type UrlWriteOptions, defineTable };
1
+ import { defineTable, findHiddenRows } from "./tables.mjs";
2
+ import { UrlBuildOptions, UrlCheck, UrlEncoding, UrlHiddenRow, UrlHostCheck, UrlHosts, UrlKeyMatch, UrlLenient, UrlMap, UrlMatch, UrlReadOptions, UrlRow, UrlRowCheck, UrlTable, UrlTableOptions, UrlValue, UrlValues, UrlWriteOptions } from "./types.mjs";
3
+ export { type UrlBuildOptions, type UrlCheck, type UrlEncoding, type UrlHiddenRow, type UrlHostCheck, type UrlHosts, type UrlKeyMatch, type UrlLenient, type UrlMap, type UrlMatch, type UrlReadOptions, type UrlRow, type UrlRowCheck, type UrlTable, type UrlTableOptions, type UrlValue, type UrlValues, type UrlWriteOptions, defineTable, findHiddenRows };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { defineTable } from "./tables.mjs";
1
+ export { defineTable, findHiddenRows } from "./tables.mjs";
@@ -7,12 +7,29 @@ var errors = {
7
7
  "ampersandEntityName": "The {{key}} row sets {{name}}, which the ampersand mark reads as another parameter",
8
8
  "statefulCheckRegex": "The check of {{name}} is a pattern with a g or y flag, which answers differently on a second call",
9
9
  "unanchoredCheckRegex": "The check of {{name}} is a pattern without ^ at its start and $ at its end",
10
- "misplacedOpenTail": "The {{key}} row writes {/tail*} elsewhere than at the end of its path",
11
10
  "openTailBesideMultiSegment": "The {{key}} row writes {/tail*} in a path with {{name}}, which takes several segments, so the two are split by a guess",
12
- "openTailName": "The {{key}} row names a value tail, which {/tail*} is read as",
13
11
  "unsupportedTemplateExpression": "The template {{template}} writes {{expression}}, an operator or modifier no template takes",
14
- "unsupportedPassedQuery": "The template {{template}} writes {{expression}}, a passed query, which no template takes",
15
12
  "oldTemplateSpelling": "The template {{template}} writes {{expression}}, which is spelled {{spelling}}",
16
- "unbalancedBrace": "The template {{template}} writes a brace outside a complete expression"
13
+ "misplacedReserved": "The template {{template}} writes {{expression}} outside its path, or beside a list or an open tail",
14
+ "uncheckedListSplit": "The {{key}} row writes {{list}} in front of {{reserved}} with a check on neither, so the two are split by a guess",
15
+ "semicolonInQuery": "The {{key}} row writes ; in its query, which semicolonSeparator reads as a separator",
16
+ "mixedListName": "The {{key}} row writes {{name}} as {{shape}}, which another template writes as {{otherShape}}",
17
+ "unbalancedBrace": "The template {{template}} writes a brace outside a complete expression",
18
+ "adjacentValues": "The template {{template}} writes {{expression}}, two values with no fixed text between them, so the two are split by a guess",
19
+ "misplacedKeyword": "The template {{template}} writes {{expression}}, but base is only {/base*} right behind the host and tail only {/tail*} at the end of the path",
20
+ "hostPortOrUser": "The template {{template}} writes a port or a user in its host, which no URL reads",
21
+ "misplacedBase": "The template {{template}} writes {/base*} behind a host other than one placeholder, where no URL reads it",
22
+ "checkRegexGroup": "The check of {{name}} is a pattern with a backreference or a named group, which points at another group once joined with other patterns",
23
+ "unknownCaseName": "The valueCase mark names {{name}}, a value no template of the table writes",
24
+ "unknownRowCheckName": "The {{key}} row checks {{name}}, a value none of its templates writes",
25
+ "nonAsciiValueLabel": "The template {{template}} writes a host label with a value and text outside ASCII, which no URL reads",
26
+ "dotSegment": "The template {{template}} writes the segment {{segment}}, which a URL parser resolves away",
27
+ "adjacentLists": "The template {{template}} writes {{first}} and {{second}} with no fixed text between them, so the two are split by a guess",
28
+ "prototypeName": "The template {{template}} writes {{name}}, a name every object already holds"
17
29
  };
18
- export { errors };
30
+ var nameShapes = {
31
+ "value": "one value",
32
+ "list": "a list",
33
+ "map": "a map"
34
+ };
35
+ export { errors, nameShapes };
@@ -1,9 +1,14 @@
1
+ import { createTrimPredicate } from "./internal.mjs";
1
2
  import { isPresent } from "./is.mjs";
2
3
  // node_modules/trousse/dist/arrays.js
3
- const omitEmpty = (array) => {
4
+ const isFilled = (value) => {
5
+ return value !== "";
6
+ };
7
+ const trimArray = (array, options = {}) => {
8
+ const keep = createTrimPredicate(options, isFilled);
4
9
  const result = [];
5
- for (const item of array) if (isPresent(item) && item !== "") result.push(item);
10
+ for (const item of array) if (isPresent(item) && keep(item)) result.push(item);
6
11
  if (!result.length) return;
7
12
  return result;
8
13
  };
9
- export { omitEmpty };
14
+ export { trimArray };
@@ -0,0 +1,7 @@
1
+ import { isNullish } from "./is.mjs";
2
+ // node_modules/trousse/dist/coercions.js
3
+ const coerceArray = (value) => {
4
+ if (isNullish(value)) return [];
5
+ return Array.isArray(value) ? value : [value];
6
+ };
7
+ export { coerceArray };
@@ -0,0 +1,3 @@
1
+ // node_modules/trousse/dist/internal/blank.js
2
+ const blankCharacterClass = "[\\p{White_Space}\\uFEFF]";
3
+ export { blankCharacterClass };
@@ -0,0 +1,16 @@
1
+ import "./internal/blank.mjs";
2
+ import { isNonEmptyString, isNullish, isString } from "./is.mjs";
3
+ // node_modules/trousse/dist/internal.js
4
+ const toPatternList = (patterns) => {
5
+ return isString(patterns) || patterns instanceof RegExp ? [patterns] : patterns;
6
+ };
7
+ const createTrimPredicate = (options, fallback) => {
8
+ const keep = options.keep ?? fallback;
9
+ const isBlankDropped = options.blank;
10
+ return (value) => {
11
+ if (isNullish(value)) return false;
12
+ if (isBlankDropped && isString(value) && !isNonEmptyString(value)) return false;
13
+ return keep(value);
14
+ };
15
+ };
16
+ export { createTrimPredicate, toPatternList };
@@ -1,7 +1,14 @@
1
+ import { blankCharacterClass } from "./internal/blank.mjs";
1
2
  // node_modules/trousse/dist/is.js
2
3
  const isString = (value) => {
3
4
  return typeof value === "string";
4
5
  };
6
+ const isNumber = (value) => {
7
+ return typeof value === "number";
8
+ };
9
+ const isBoolean = (value) => {
10
+ return typeof value === "boolean";
11
+ };
5
12
  const isFunction = (value) => {
6
13
  return typeof value === "function";
7
14
  };
@@ -17,4 +24,11 @@ const isObject = (value) => {
17
24
  const isPlainObject = (value) => {
18
25
  return isObject(value) && Object.getPrototypeOf(value) === Object.prototype;
19
26
  };
20
- export { isFunction, isNullish, isObject, isPlainObject, isPresent, isString };
27
+ const whitespaceOnlyRegex = new RegExp(`^${blankCharacterClass}*$`, "u");
28
+ const isNonEmptyString = (value) => {
29
+ if (!isString(value) || !value) return false;
30
+ const code = value.charCodeAt(0);
31
+ if (code > 32 && code < 127) return true;
32
+ return !whitespaceOnlyRegex.test(value);
33
+ };
34
+ export { isBoolean, isFunction, isNonEmptyString, isNullish, isNumber, isObject, isPlainObject, isPresent, isString };