-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
43 lines (34 loc) · 1.14 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Copyright 2023-latest the httpland authors. All rights reserved. MIT license.
// This module is browser compatible.
import { isString, Item, Parameters, stringifySfv, Token } from "./deps.ts";
import type { EmbedderPolicy } from "./types.ts";
const enum Param {
ReportTo = "report-to",
}
/** Serialize {@link EmbedderPolicy} into string.
* @param Any {@link COEP}.
*
* @throws {TypeError} If the {@link EmbedderPolicy} is invalid.
*/
export function stringifyEmbedderPolicy(policy: EmbedderPolicy): string {
const item = policy2Item(policy);
try {
const string = stringifySfv(item);
return string;
} catch (cause) {
throw TypeError(`invalid ${displayEmbedderPolicy(policy)}.`, { cause });
}
}
function displayEmbedderPolicy(policy: EmbedderPolicy): string {
return `EmbedderPolicy ${JSON.stringify(policy, null, 2)}`;
}
export function policy2Item(policy: EmbedderPolicy): Item {
const { value, reportTo } = policy;
const parameters = isString(reportTo)
? new Parameters({
[Param.ReportTo]: new Token(reportTo),
})
: new Parameters();
const item = new Item([new Token(value), parameters]);
return item;
}