urlmason 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +239 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +1 -0
- package/dist/locales.json.mjs +18 -0
- package/dist/node_modules/trousse/dist/arrays.mjs +9 -0
- package/dist/node_modules/trousse/dist/is.mjs +20 -0
- package/dist/node_modules/trousse/dist/locales.mjs +8 -0
- package/dist/node_modules/trousse/dist/matching.mjs +52 -0
- package/dist/node_modules/trousse/dist/objects.mjs +32 -0
- package/dist/node_modules/trousse/dist/urls.mjs +218 -0
- package/dist/queries.mjs +92 -0
- package/dist/tables.d.mts +2 -0
- package/dist/tables.mjs +799 -0
- package/dist/templates.mjs +407 -0
- package/dist/types.d.mts +77 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Maciej Lamberski
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# urlmason
|
|
2
|
+
|
|
3
|
+
[](https://codecov.io/gh/macieklamberski/urlmason)
|
|
4
|
+
[](https://www.npmjs.com/package/urlmason)
|
|
5
|
+
[](https://github.com/macieklamberski/urlmason/blob/main/LICENSE)
|
|
6
|
+
|
|
7
|
+
Turn URLs into values and values back into URLs, from one list of URL patterns.
|
|
8
|
+
|
|
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
|
+
|
|
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`.
|
|
14
|
+
|
|
15
|
+
It has no dependencies and runs in any modern JavaScript runtime.
|
|
16
|
+
|
|
17
|
+
[Quick start](#quick-start)
|
|
18
|
+
·
|
|
19
|
+
[Templates](#templates)
|
|
20
|
+
·
|
|
21
|
+
[Encoding](#encoding)
|
|
22
|
+
·
|
|
23
|
+
[API](#api)
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## Quick start
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install urlmason
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Define a table of rows. Each row has a key, its main URL, and other URLs that serve the same thing:
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import { defineTable } from 'urlmason'
|
|
37
|
+
|
|
38
|
+
const feeds = defineTable(
|
|
39
|
+
[
|
|
40
|
+
{
|
|
41
|
+
key: 'user',
|
|
42
|
+
main: 'https://example.com/@{user}/feed.xml{?page}',
|
|
43
|
+
aliases: ['https://example.com/u/{user}/rss', 'https://old.example.com/{user}/feed'],
|
|
44
|
+
},
|
|
45
|
+
{ key: 'tag', main: 'https://example.com/tags{/tags*}.xml' },
|
|
46
|
+
{ key: 'post', main: 'https://example.com/@{user}/{id}/comments.xml' },
|
|
47
|
+
],
|
|
48
|
+
{ checks: { id: /^\d+$/ } },
|
|
49
|
+
)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Read a URL
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
feeds.readUrl('https://old.example.com/alice/feed')
|
|
56
|
+
// { key: 'user', values: { user: 'alice' }, isAlias: true, isExact: true, row: {…} }
|
|
57
|
+
|
|
58
|
+
// No row matches, or a value fails its check:
|
|
59
|
+
feeds.readUrl('https://example.com/@alice/abc/comments.xml')
|
|
60
|
+
// undefined
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Build a URL
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
feeds.buildUrl('user', { user: 'alice', page: '2' })
|
|
67
|
+
// 'https://example.com/@alice/feed.xml?page=2'
|
|
68
|
+
|
|
69
|
+
// A value is missing:
|
|
70
|
+
feeds.buildUrl('post', { user: 'alice' })
|
|
71
|
+
// undefined
|
|
72
|
+
|
|
73
|
+
// Every spelling of the row, its main URL first:
|
|
74
|
+
feeds.buildUrls('user', { user: 'alice' })
|
|
75
|
+
// [
|
|
76
|
+
// 'https://example.com/@alice/feed.xml',
|
|
77
|
+
// 'https://example.com/u/alice/rss',
|
|
78
|
+
// 'https://old.example.com/alice/feed',
|
|
79
|
+
// ]
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Rewrite a URL to its main URL
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
// 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'
|
|
88
|
+
|
|
89
|
+
// Already the main URL:
|
|
90
|
+
feeds.getMainUrl('https://example.com/@alice/feed.xml')
|
|
91
|
+
// undefined
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Encode strictly
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
feeds.buildUrl('tag', { tags: ['C++', 'web dev'] })
|
|
98
|
+
// 'https://example.com/tags/C++/web%20dev.xml'
|
|
99
|
+
|
|
100
|
+
feeds.buildUrl('tag', { tags: ['C++', 'web dev'] }, { encoding: 'strict' })
|
|
101
|
+
// 'https://example.com/tags/C%2B%2B/web%20dev.xml'
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Read a URL on any host
|
|
105
|
+
|
|
106
|
+
A row on `{host}` can read software that runs on many sites, such as forums, under whatever folder the site sits in:
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
const forums = defineTable([
|
|
110
|
+
{ key: 'topic', main: '{scheme}://{host}{/base*}/viewtopic.php?t={topic}' },
|
|
111
|
+
{ key: 'forum', main: '{scheme}://{host}{/base*}/feed.php' },
|
|
112
|
+
])
|
|
113
|
+
|
|
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'] }, … }
|
|
116
|
+
|
|
117
|
+
forums.forSite('https://board.example.org/community/')?.buildUrl('forum', { base: ['community'] })
|
|
118
|
+
// 'https://board.example.org/community/feed.php'
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Read a tenant's URL
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
const blogs = defineTable([{ key: 'blog', main: 'https://{blog}.{domain}/feed' }], {
|
|
125
|
+
hosts: { tenant: ['example.com', 'example.co.uk'] },
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
blogs.readUrl('https://alice.example.co.uk/feed')?.values
|
|
129
|
+
// { blog: 'alice', domain: 'example.co.uk' }
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## Templates
|
|
133
|
+
|
|
134
|
+
A template is a full URL with placeholders. Each one reads from and builds into its own part of the URL:
|
|
135
|
+
|
|
136
|
+
| Placeholder | Takes | Example |
|
|
137
|
+
| --- | --- | --- |
|
|
138
|
+
| `{name}` | One host label, path segment or query value | `https://{blog}.example.com/posts/{id}` |
|
|
139
|
+
| `{/name*}` | One or more path segments | `https://example.com/docs{/path*}` |
|
|
140
|
+
| `{?a,b}` | Query names a URL may carry, on a URL with no query | `https://example.com/feed{?page,limit}` |
|
|
141
|
+
| `{&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*}` |
|
|
147
|
+
|
|
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.
|
|
149
|
+
|
|
150
|
+
### Rows
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
const pages = defineTable(
|
|
154
|
+
[
|
|
155
|
+
{ key: 'post', main: 'https://example.com/{year}/{slug}' },
|
|
156
|
+
// A row the table builds but never reads.
|
|
157
|
+
{ key: 'home', main: 'https://example.com/', isBuildOnly: true },
|
|
158
|
+
],
|
|
159
|
+
{
|
|
160
|
+
checks: { year: /^\d{4}$/ },
|
|
161
|
+
},
|
|
162
|
+
)
|
|
163
|
+
```
|
|
164
|
+
|
|
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.
|
|
166
|
+
|
|
167
|
+
### Hosts
|
|
168
|
+
|
|
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`.
|
|
170
|
+
|
|
171
|
+
### Limits
|
|
172
|
+
|
|
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.
|
|
174
|
+
|
|
175
|
+
## Encoding
|
|
176
|
+
|
|
177
|
+
Builds come in two spellings, picked per call with `{ encoding }`:
|
|
178
|
+
|
|
179
|
+
- **`pretty`, the default,** decodes a value's valid escapes, then writes every character the part allows, so `Ann Lee!` builds `/@Ann%20Lee!/feed`.
|
|
180
|
+
- **`strict`** writes a value as RFC 6570 does, encoding everything outside the unreserved characters, so the same value builds `/@Ann%20Lee%21/feed`.
|
|
181
|
+
|
|
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.
|
|
183
|
+
|
|
184
|
+
### Where it differs from RFC 6570
|
|
185
|
+
|
|
186
|
+
RFC 6570 defines how a template builds a URL. Reading one back is urlmason's own:
|
|
187
|
+
|
|
188
|
+
- 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.
|
|
191
|
+
- `{?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.
|
|
194
|
+
|
|
195
|
+
## API
|
|
196
|
+
|
|
197
|
+
### `defineTable(rows, options?)`
|
|
198
|
+
|
|
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.
|
|
200
|
+
|
|
201
|
+
```typescript
|
|
202
|
+
const table = defineTable(rows, {
|
|
203
|
+
hosts: { exact: ['example.com'], tenant: ['example.org'] },
|
|
204
|
+
// A check per placeholder: a pattern anchored at both ends, or a function.
|
|
205
|
+
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'] },
|
|
208
|
+
// A rewrite keeps no query parameter the row does not name.
|
|
209
|
+
isQueryKept: false,
|
|
210
|
+
// A row that refuses a URL passes it to the next row, read in the order written.
|
|
211
|
+
isFallThrough: true,
|
|
212
|
+
})
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Each option, and each field of a row, such as `variant` and its own `checks`, is documented on its type.
|
|
216
|
+
|
|
217
|
+
### `table.readUrl(url, options?)`
|
|
218
|
+
|
|
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.
|
|
220
|
+
|
|
221
|
+
### `table.buildUrl(key, values, options?)`
|
|
222
|
+
|
|
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.
|
|
224
|
+
|
|
225
|
+
### `table.buildUrls(key, values, options?)`
|
|
226
|
+
|
|
227
|
+
Builds every spelling of the first row the values fill: its main URL, then each alias.
|
|
228
|
+
|
|
229
|
+
### `table.getMainUrl(url, options?)`
|
|
230
|
+
|
|
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.
|
|
232
|
+
|
|
233
|
+
### `table.forSite(url)`
|
|
234
|
+
|
|
235
|
+
Returns `buildUrl` and `buildUrls` with `{scheme}`, `{host}` and `{domain}` filled from a page's URL.
|
|
236
|
+
|
|
237
|
+
## Thanks
|
|
238
|
+
|
|
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.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +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 };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { defineTable } from "./tables.mjs";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// src/locales.json
|
|
2
|
+
var errors = {
|
|
3
|
+
"invalidTemplate": "Not a URL template: {{template}}",
|
|
4
|
+
"unknownKey": "No row for {{key}}",
|
|
5
|
+
"missingHosts": "No hosts for the {{key}} row",
|
|
6
|
+
"sharedCaseMark": "The {{key}} row marks the case of {{name}}, which shares a part of its URL with another value",
|
|
7
|
+
"ampersandEntityName": "The {{key}} row sets {{name}}, which the ampersand mark reads as another parameter",
|
|
8
|
+
"statefulCheckRegex": "The check of {{name}} is a pattern with a g or y flag, which answers differently on a second call",
|
|
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
|
+
"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
|
+
"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
|
+
"oldTemplateSpelling": "The template {{template}} writes {{expression}}, which is spelled {{spelling}}",
|
|
16
|
+
"unbalancedBrace": "The template {{template}} writes a brace outside a complete expression"
|
|
17
|
+
};
|
|
18
|
+
export { errors };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { isPresent } from "./is.mjs";
|
|
2
|
+
// node_modules/trousse/dist/arrays.js
|
|
3
|
+
const omitEmpty = (array) => {
|
|
4
|
+
const result = [];
|
|
5
|
+
for (const item of array) if (isPresent(item) && item !== "") result.push(item);
|
|
6
|
+
if (!result.length) return;
|
|
7
|
+
return result;
|
|
8
|
+
};
|
|
9
|
+
export { omitEmpty };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// node_modules/trousse/dist/is.js
|
|
2
|
+
const isString = (value) => {
|
|
3
|
+
return typeof value === "string";
|
|
4
|
+
};
|
|
5
|
+
const isFunction = (value) => {
|
|
6
|
+
return typeof value === "function";
|
|
7
|
+
};
|
|
8
|
+
const isPresent = (value) => {
|
|
9
|
+
return value != null;
|
|
10
|
+
};
|
|
11
|
+
const isNullish = (value) => {
|
|
12
|
+
return value == null;
|
|
13
|
+
};
|
|
14
|
+
const isObject = (value) => {
|
|
15
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
16
|
+
};
|
|
17
|
+
const isPlainObject = (value) => {
|
|
18
|
+
return isObject(value) && Object.getPrototypeOf(value) === Object.prototype;
|
|
19
|
+
};
|
|
20
|
+
export { isFunction, isNullish, isObject, isPlainObject, isPresent, isString };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// node_modules/trousse/dist/locales.js
|
|
2
|
+
const placeholderRegex = /\{\{(\w+)\}\}/g;
|
|
3
|
+
const t = (template, params) => {
|
|
4
|
+
return template.replace(placeholderRegex, (placeholder, key) => {
|
|
5
|
+
return Object.hasOwn(params, key) ? String(params[key]) : placeholder;
|
|
6
|
+
});
|
|
7
|
+
};
|
|
8
|
+
export { t };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { isNullish, isString } from "./is.mjs";
|
|
2
|
+
// node_modules/trousse/dist/matching.js
|
|
3
|
+
const regexSyntaxCharsRegex = /[.*+?^${}()|[\]\\/]/;
|
|
4
|
+
const regexEscapableCharsRegex = /[.*+?^${}()|[\]\\/&!#%,:;<=>@`~-]/g;
|
|
5
|
+
const testRegex = (regex, value) => {
|
|
6
|
+
regex.lastIndex = 0;
|
|
7
|
+
return regex.test(value);
|
|
8
|
+
};
|
|
9
|
+
const testRegexAnyCase = (regex, lowerValue, value) => {
|
|
10
|
+
return testRegex(regex, lowerValue) || lowerValue !== value && testRegex(regex, value);
|
|
11
|
+
};
|
|
12
|
+
const toPatternList = (patterns) => {
|
|
13
|
+
return isString(patterns) || patterns instanceof RegExp ? [patterns] : patterns;
|
|
14
|
+
};
|
|
15
|
+
const escapeRegex = (value) => {
|
|
16
|
+
return value.replace(regexEscapableCharsRegex, (char) => {
|
|
17
|
+
if (regexSyntaxCharsRegex.test(char)) return `\\${char}`;
|
|
18
|
+
return `\\x${char.charCodeAt(0).toString(16)}`;
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
const isAnyOf = (value, patterns, parser) => {
|
|
22
|
+
if (isNullish(value)) return false;
|
|
23
|
+
const parsedValue = parser ? parser(value) : value.toLowerCase().trim();
|
|
24
|
+
if (isString(patterns)) return parsedValue === (parser ? patterns : patterns.toLowerCase().trim());
|
|
25
|
+
let originalValue;
|
|
26
|
+
for (const pattern of toPatternList(patterns)) {
|
|
27
|
+
if (pattern instanceof RegExp) {
|
|
28
|
+
if (originalValue === void 0) originalValue = parser ? parsedValue : value.trim();
|
|
29
|
+
if (testRegexAnyCase(pattern, parsedValue, originalValue)) return true;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (parsedValue === (parser ? pattern : pattern.toLowerCase().trim())) return true;
|
|
33
|
+
}
|
|
34
|
+
return false;
|
|
35
|
+
};
|
|
36
|
+
const isSameText = (value, other) => {
|
|
37
|
+
if (isNullish(value) || isNullish(other)) return false;
|
|
38
|
+
return value.toLowerCase().trim() === other.toLowerCase().trim();
|
|
39
|
+
};
|
|
40
|
+
const startsWithAnyOf = (value, patterns) => {
|
|
41
|
+
if (isNullish(value)) return false;
|
|
42
|
+
const lowerValue = value.toLowerCase();
|
|
43
|
+
for (const pattern of toPatternList(patterns)) {
|
|
44
|
+
if (pattern instanceof RegExp) {
|
|
45
|
+
if (testRegexAnyCase(pattern, lowerValue, value)) return true;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (pattern && lowerValue.startsWith(pattern.toLowerCase())) return true;
|
|
49
|
+
}
|
|
50
|
+
return false;
|
|
51
|
+
};
|
|
52
|
+
export { escapeRegex, isAnyOf, isSameText, startsWithAnyOf, toPatternList };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { isPresent } from "./is.mjs";
|
|
2
|
+
// node_modules/trousse/dist/objects.js
|
|
3
|
+
const setKey = (object, key, value) => {
|
|
4
|
+
if (key === "__proto__") {
|
|
5
|
+
Object.defineProperty(object, key, {
|
|
6
|
+
value,
|
|
7
|
+
enumerable: true,
|
|
8
|
+
writable: true,
|
|
9
|
+
configurable: true
|
|
10
|
+
});
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
object[key] = value;
|
|
14
|
+
};
|
|
15
|
+
const trimObject = (object, keep = isPresent) => {
|
|
16
|
+
let hasKept = false;
|
|
17
|
+
let hasDropped = false;
|
|
18
|
+
for (const key in object) {
|
|
19
|
+
if (keep(object[key])) hasKept = true;
|
|
20
|
+
else hasDropped = true;
|
|
21
|
+
if (hasKept && hasDropped) break;
|
|
22
|
+
}
|
|
23
|
+
if (!hasKept) return;
|
|
24
|
+
if (!hasDropped) return object;
|
|
25
|
+
const result = {};
|
|
26
|
+
for (const key in object) {
|
|
27
|
+
const value = object[key];
|
|
28
|
+
if (keep(value)) setKey(result, key, value);
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
};
|
|
32
|
+
export { trimObject };
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { isNullish, isString } from "./is.mjs";
|
|
2
|
+
import { isAnyOf, toPatternList } from "./matching.mjs";
|
|
3
|
+
// node_modules/trousse/dist/urls.js
|
|
4
|
+
const httpSchemes = ["http:", "https:"];
|
|
5
|
+
const parseUrl = (value, base) => {
|
|
6
|
+
if (isNullish(value)) return;
|
|
7
|
+
if (value instanceof URL && base === void 0) return value;
|
|
8
|
+
if (URL.parse) return URL.parse(value, base) ?? void 0;
|
|
9
|
+
try {
|
|
10
|
+
return new URL(value, base);
|
|
11
|
+
} catch {}
|
|
12
|
+
};
|
|
13
|
+
const getHostname = (url) => {
|
|
14
|
+
const hostname = parseUrl(url)?.hostname;
|
|
15
|
+
if (!hostname) return;
|
|
16
|
+
return hostname.endsWith(".") ? hostname.slice(0, -1) : hostname;
|
|
17
|
+
};
|
|
18
|
+
const nonAsciiRegex = /[\u0080-\uffff]/;
|
|
19
|
+
const normalizeDomain = (domain) => {
|
|
20
|
+
const trimmed = domain.trim();
|
|
21
|
+
const bare = trimmed.endsWith(".") ? trimmed.slice(0, -1).trimEnd() : trimmed;
|
|
22
|
+
if (!nonAsciiRegex.test(bare)) return bare;
|
|
23
|
+
return parseUrl(`http://${bare}`)?.hostname ?? bare;
|
|
24
|
+
};
|
|
25
|
+
const keepValue = (value) => value;
|
|
26
|
+
const isHostOf = (url, hosts) => {
|
|
27
|
+
const hostname = getHostname(url);
|
|
28
|
+
if (!hostname) return false;
|
|
29
|
+
const lowerHostname = hostname.toLowerCase();
|
|
30
|
+
for (const host of toPatternList(hosts)) {
|
|
31
|
+
if (host instanceof RegExp) {
|
|
32
|
+
if (isAnyOf(hostname, host)) return true;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (isAnyOf(lowerHostname, normalizeDomain(host).toLowerCase(), keepValue)) return true;
|
|
36
|
+
}
|
|
37
|
+
return false;
|
|
38
|
+
};
|
|
39
|
+
const isHttpUrl = (url) => {
|
|
40
|
+
const scheme = parseUrl(url)?.protocol;
|
|
41
|
+
if (!scheme) return false;
|
|
42
|
+
return httpSchemes.includes(scheme);
|
|
43
|
+
};
|
|
44
|
+
const escapeRunRegex = /(?:%[0-9A-Fa-f]{2})+/g;
|
|
45
|
+
const getSequenceLength = (byte) => {
|
|
46
|
+
if (byte < 128) return 1;
|
|
47
|
+
if (byte >= 194 && byte < 224) return 2;
|
|
48
|
+
if (byte >= 224 && byte < 240) return 3;
|
|
49
|
+
if (byte >= 240 && byte < 245) return 4;
|
|
50
|
+
return 0;
|
|
51
|
+
};
|
|
52
|
+
const decodeEscapeRun = (run) => {
|
|
53
|
+
try {
|
|
54
|
+
return decodeURIComponent(run);
|
|
55
|
+
} catch {}
|
|
56
|
+
const count = run.length / 3;
|
|
57
|
+
let decoded = "";
|
|
58
|
+
let index = 0;
|
|
59
|
+
while (index < count) {
|
|
60
|
+
const start = index * 3;
|
|
61
|
+
const length = getSequenceLength(Number.parseInt(run.slice(start + 1, start + 3), 16));
|
|
62
|
+
if (length && index + length <= count) try {
|
|
63
|
+
decoded += decodeURIComponent(run.slice(start, start + length * 3));
|
|
64
|
+
index += length;
|
|
65
|
+
continue;
|
|
66
|
+
} catch {}
|
|
67
|
+
decoded += run.slice(start, start + 3);
|
|
68
|
+
index += 1;
|
|
69
|
+
}
|
|
70
|
+
return decoded;
|
|
71
|
+
};
|
|
72
|
+
const decodePercent = (value) => {
|
|
73
|
+
return value.replace(escapeRunRegex, decodeEscapeRun);
|
|
74
|
+
};
|
|
75
|
+
const pathSegmentEscapeRegex = /[/?#\\\s]/g;
|
|
76
|
+
const encodePathSegment = (value) => {
|
|
77
|
+
return value.replace(pathSegmentEscapeRegex, (character) => encodeURIComponent(character));
|
|
78
|
+
};
|
|
79
|
+
const readRawPairs = (text, prefix) => {
|
|
80
|
+
if (text === void 0) return;
|
|
81
|
+
const pairs = [];
|
|
82
|
+
const body = text.startsWith(prefix) ? text.slice(1) : text;
|
|
83
|
+
for (const pair of body.split("&")) {
|
|
84
|
+
if (!pair) continue;
|
|
85
|
+
const separator = pair.indexOf("=");
|
|
86
|
+
if (separator === -1) {
|
|
87
|
+
pairs.push([decodePercent(pair.replaceAll("+", " ")), ""]);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const name = decodePercent(pair.slice(0, separator).replaceAll("+", " "));
|
|
91
|
+
pairs.push([name, pair.slice(separator + 1)]);
|
|
92
|
+
}
|
|
93
|
+
return pairs;
|
|
94
|
+
};
|
|
95
|
+
const readQuerySource = (source, options) => {
|
|
96
|
+
if (options?.decodeValues === false) return readRawPairs(source instanceof URL ? source.search : source?.toString(), "?");
|
|
97
|
+
if (source instanceof URL) return source.searchParams;
|
|
98
|
+
if (isString(source)) return new URLSearchParams(source);
|
|
99
|
+
return source;
|
|
100
|
+
};
|
|
101
|
+
const readParamValues = (params, name, options) => {
|
|
102
|
+
const values = [];
|
|
103
|
+
if (!params) return values;
|
|
104
|
+
const lowercaseName = name.toLowerCase();
|
|
105
|
+
for (const [key, value] of params) {
|
|
106
|
+
if (key.toLowerCase() !== lowercaseName) continue;
|
|
107
|
+
const read = options?.trimValues === false ? value : value.trim();
|
|
108
|
+
if (read || options?.preserveEmptyValues) values.push(read);
|
|
109
|
+
}
|
|
110
|
+
return values;
|
|
111
|
+
};
|
|
112
|
+
const getQueryParamValues = (source, name, options) => {
|
|
113
|
+
return readParamValues(readQuerySource(source, options), name, options);
|
|
114
|
+
};
|
|
115
|
+
const getQueryParam = (source, name, options) => {
|
|
116
|
+
return getQueryParamValues(source, name, options)[0];
|
|
117
|
+
};
|
|
118
|
+
const queryPartEscapeRegex = /[&#%+\s]/g;
|
|
119
|
+
const composePairs = (params) => {
|
|
120
|
+
const escapePart = (part) => {
|
|
121
|
+
return part.replace(queryPartEscapeRegex, (character) => encodeURIComponent(character));
|
|
122
|
+
};
|
|
123
|
+
const pairs = [];
|
|
124
|
+
for (const [name, value] of Object.entries(params ?? {})) {
|
|
125
|
+
if (value === true) {
|
|
126
|
+
pairs.push(escapePart(name));
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const text = String(value);
|
|
130
|
+
if (!text) continue;
|
|
131
|
+
pairs.push(`${escapePart(name)}=${escapePart(text)}`);
|
|
132
|
+
}
|
|
133
|
+
return pairs.join("&");
|
|
134
|
+
};
|
|
135
|
+
const composeQuery = (params) => {
|
|
136
|
+
const pairs = composePairs(params);
|
|
137
|
+
return pairs ? `?${pairs}` : "";
|
|
138
|
+
};
|
|
139
|
+
const ipv4Regex = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
|
140
|
+
const ipv6Regex = /^([0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$/i;
|
|
141
|
+
const wwwPrefixRegex = /^(?:www\.)+(?=.*\.)/;
|
|
142
|
+
const ipv6BracketsRegex = /^\[|\]$/g;
|
|
143
|
+
const schemeSeparator = String.raw`\.*[:\s=\\/][:\s=.\\/]*`;
|
|
144
|
+
const separatorChar = String.raw`(?:[:\s=.\\/]|%20|%c2%a0)`;
|
|
145
|
+
const leadingSchemeSeparator = String.raw`\.*(?::${separatorChar}*|[\s=\\/]${separatorChar}+)`;
|
|
146
|
+
String.raw`^\/?[htps]{2,7}${leadingSchemeSeparator}([htps]{2,7})(?!:\d|[^/?#\\]*@)(${schemeSeparator})(www[./]+)?`;
|
|
147
|
+
String.raw`^\/?(h[htps():]{1,10}|t{1,2}ps?)(${leadingSchemeSeparator})(www[./]+)?`;
|
|
148
|
+
const segmentEdgeSpace = "(?:\\s|%(?:09|0A|0D|20))";
|
|
149
|
+
const valueEdgeSpace = "(?:\\s|\\+|%(?:09|0A|0D|20))";
|
|
150
|
+
new RegExp(`^${segmentEdgeSpace}+|(?<!${segmentEdgeSpace})${segmentEdgeSpace}+$`, "gi");
|
|
151
|
+
new RegExp(`^${valueEdgeSpace}+|(?<!${valueEdgeSpace})${valueEdgeSpace}+$`, "gi");
|
|
152
|
+
const stripWww = (hostname) => {
|
|
153
|
+
return hostname.replace(wwwPrefixRegex, "");
|
|
154
|
+
};
|
|
155
|
+
const isIpAddress = (hostname) => {
|
|
156
|
+
return ipv4Regex.test(hostname) || ipv6Regex.test(hostname.replace(ipv6BracketsRegex, ""));
|
|
157
|
+
};
|
|
158
|
+
const genericSecondLevels = [
|
|
159
|
+
"ac",
|
|
160
|
+
"co",
|
|
161
|
+
"com",
|
|
162
|
+
"edu",
|
|
163
|
+
"go",
|
|
164
|
+
"gob",
|
|
165
|
+
"gov",
|
|
166
|
+
"id",
|
|
167
|
+
"ne",
|
|
168
|
+
"net",
|
|
169
|
+
"or",
|
|
170
|
+
"org"
|
|
171
|
+
];
|
|
172
|
+
const suffixRulesCache = /* @__PURE__ */ new WeakMap();
|
|
173
|
+
const getSuffixRules = (suffixes) => {
|
|
174
|
+
let cached = suffixRulesCache.get(suffixes);
|
|
175
|
+
if (cached) return cached;
|
|
176
|
+
cached = {
|
|
177
|
+
names: /* @__PURE__ */ new Set(),
|
|
178
|
+
wildcards: /* @__PURE__ */ new Set(),
|
|
179
|
+
exceptions: /* @__PURE__ */ new Set()
|
|
180
|
+
};
|
|
181
|
+
for (const entry of suffixes) {
|
|
182
|
+
const rule = entry.toLowerCase();
|
|
183
|
+
if (rule.startsWith("!")) {
|
|
184
|
+
cached.exceptions.add(normalizeDomain(rule.slice(1)));
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (rule.startsWith("*.")) {
|
|
188
|
+
cached.wildcards.add(normalizeDomain(rule.slice(2)));
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
cached.names.add(normalizeDomain(rule));
|
|
192
|
+
}
|
|
193
|
+
suffixRulesCache.set(suffixes, cached);
|
|
194
|
+
return cached;
|
|
195
|
+
};
|
|
196
|
+
const getPublicSuffixLength = (labels, rules) => {
|
|
197
|
+
for (let index = 0; index < labels.length; index++) if (rules.exceptions.has(labels.slice(index).join("."))) return labels.length - index - 1;
|
|
198
|
+
for (let index = 0; index < labels.length; index++) {
|
|
199
|
+
if (rules.names.has(labels.slice(index).join("."))) return labels.length - index;
|
|
200
|
+
if (index + 1 < labels.length && rules.wildcards.has(labels.slice(index + 1).join("."))) return labels.length - index;
|
|
201
|
+
}
|
|
202
|
+
return 1;
|
|
203
|
+
};
|
|
204
|
+
const getRegistrableDomain = (url, options) => {
|
|
205
|
+
const hostname = getHostname(url)?.toLowerCase();
|
|
206
|
+
if (!hostname) return;
|
|
207
|
+
if (isIpAddress(hostname)) return hostname;
|
|
208
|
+
const parts = hostname.split(".");
|
|
209
|
+
if (options?.suffixes) {
|
|
210
|
+
const suffixLength = getPublicSuffixLength(parts, getSuffixRules(options.suffixes));
|
|
211
|
+
return parts.slice(-Math.min(suffixLength + 1, parts.length)).join(".");
|
|
212
|
+
}
|
|
213
|
+
if (parts.length <= 2) return hostname;
|
|
214
|
+
const [secondLevel, topLevel] = parts.slice(-2);
|
|
215
|
+
const labels = topLevel.length === 2 && genericSecondLevels.includes(secondLevel) ? 3 : 2;
|
|
216
|
+
return parts.slice(-labels).join(".");
|
|
217
|
+
};
|
|
218
|
+
export { composeQuery, decodePercent, encodePathSegment, getQueryParam, getQueryParamValues, getRegistrableDomain, isHostOf, isHttpUrl, isIpAddress, parseUrl, stripWww };
|