tempest-react-sdk 0.76.0 → 0.78.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.
Files changed (173) hide show
  1. package/README.md +2 -2
  2. package/bin/create-tempest-app.e2e.test.mjs +112 -0
  3. package/bin/create-tempest-app.mjs +69 -28
  4. package/bin/lib/alias/collect.mjs +20 -3
  5. package/bin/lib/alias/index.mjs +12 -1
  6. package/bin/lib/alias/index.test.mjs +24 -0
  7. package/bin/lib/component/generate.mjs +191 -0
  8. package/bin/lib/component/generate.test.mjs +336 -0
  9. package/bin/lib/css/analyze.test.mjs +21 -1
  10. package/bin/lib/css/collect.mjs +14 -0
  11. package/bin/lib/css/extract.mjs +63 -5
  12. package/bin/lib/css/extract.test.mjs +110 -1
  13. package/bin/lib/css/fix.e2e.test.mjs +50 -0
  14. package/bin/lib/css/index.mjs +6 -1
  15. package/bin/lib/fs/contain.mjs +50 -0
  16. package/bin/lib/icons/generate.mjs +28 -3
  17. package/bin/lib/icons/generate.test.mjs +57 -1
  18. package/bin/lib/openapi/escape.mjs +224 -0
  19. package/bin/lib/openapi/generate.encode.test.mjs +120 -0
  20. package/bin/lib/openapi/generate.hostile.test.mjs +621 -0
  21. package/bin/lib/openapi/generate.mjs +129 -18
  22. package/bin/lib/openapi/generate.test.mjs +7 -2
  23. package/bin/lib/openapi/schema-to-zod.mjs +43 -4
  24. package/bin/tempest-gen.test.mjs +188 -0
  25. package/bin/tempest.mjs +263 -6
  26. package/dist/auth/create-tempest-auth.cjs +1 -1
  27. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  28. package/dist/auth/create-tempest-auth.js +203 -58
  29. package/dist/auth/create-tempest-auth.js.map +1 -1
  30. package/dist/auth/refresh-queue.cjs +1 -1
  31. package/dist/auth/refresh-queue.cjs.map +1 -1
  32. package/dist/auth/refresh-queue.js +13 -6
  33. package/dist/auth/refresh-queue.js.map +1 -1
  34. package/dist/br/pix.cjs +1 -1
  35. package/dist/br/pix.cjs.map +1 -1
  36. package/dist/br/pix.js +85 -72
  37. package/dist/br/pix.js.map +1 -1
  38. package/dist/br.d.ts +19 -4
  39. package/dist/components/Chat/ChatAttachments.cjs +1 -1
  40. package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
  41. package/dist/components/Chat/ChatAttachments.js +46 -38
  42. package/dist/components/Chat/ChatAttachments.js.map +1 -1
  43. package/dist/components/CodeBlock/CodeBlock.cjs +1 -1
  44. package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
  45. package/dist/components/CodeBlock/CodeBlock.js +1 -1
  46. package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
  47. package/dist/components/CodeBlock/tokenize.cjs +1 -1
  48. package/dist/components/CodeBlock/tokenize.cjs.map +1 -1
  49. package/dist/components/CodeBlock/tokenize.js +54 -25
  50. package/dist/components/CodeBlock/tokenize.js.map +1 -1
  51. package/dist/components/Markdown/markdown-parse.cjs +7 -5
  52. package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
  53. package/dist/components/Markdown/markdown-parse.js +171 -90
  54. package/dist/components/Markdown/markdown-parse.js.map +1 -1
  55. package/dist/components/Toast/Toast.module.cjs +1 -1
  56. package/dist/components/Toast/Toast.module.cjs.map +1 -1
  57. package/dist/components/Toast/Toast.module.js +7 -3
  58. package/dist/components/Toast/Toast.module.js.map +1 -1
  59. package/dist/components/Toast/ToastProvider.cjs +1 -1
  60. package/dist/components/Toast/ToastProvider.cjs.map +1 -1
  61. package/dist/components/Toast/ToastProvider.js +77 -51
  62. package/dist/components/Toast/ToastProvider.js.map +1 -1
  63. package/dist/data/create-data-provider.cjs +1 -1
  64. package/dist/data/create-data-provider.cjs.map +1 -1
  65. package/dist/data/create-data-provider.js +32 -21
  66. package/dist/data/create-data-provider.js.map +1 -1
  67. package/dist/http/api-client.cjs +1 -1
  68. package/dist/http/api-client.cjs.map +1 -1
  69. package/dist/http/api-client.js +81 -73
  70. package/dist/http/api-client.js.map +1 -1
  71. package/dist/http/errors.cjs +1 -1
  72. package/dist/http/errors.cjs.map +1 -1
  73. package/dist/http/errors.js +39 -35
  74. package/dist/http/errors.js.map +1 -1
  75. package/dist/http/resumable-upload.cjs +1 -1
  76. package/dist/http/resumable-upload.cjs.map +1 -1
  77. package/dist/http/resumable-upload.js +141 -105
  78. package/dist/http/resumable-upload.js.map +1 -1
  79. package/dist/http/retry.cjs +1 -1
  80. package/dist/http/retry.cjs.map +1 -1
  81. package/dist/http/retry.js +5 -6
  82. package/dist/http/retry.js.map +1 -1
  83. package/dist/oauth/callback.cjs +2 -0
  84. package/dist/oauth/callback.cjs.map +1 -0
  85. package/dist/oauth/callback.js +42 -0
  86. package/dist/oauth/callback.js.map +1 -0
  87. package/dist/oauth/use-oauth-callback.cjs +1 -1
  88. package/dist/oauth/use-oauth-callback.cjs.map +1 -1
  89. package/dist/oauth/use-oauth-callback.js +13 -20
  90. package/dist/oauth/use-oauth-callback.js.map +1 -1
  91. package/dist/push/use-push-subscription.cjs +1 -1
  92. package/dist/push/use-push-subscription.cjs.map +1 -1
  93. package/dist/push/use-push-subscription.js +42 -42
  94. package/dist/push/use-push-subscription.js.map +1 -1
  95. package/dist/push/web-push-client.cjs +1 -1
  96. package/dist/push/web-push-client.cjs.map +1 -1
  97. package/dist/push/web-push-client.js +23 -3
  98. package/dist/push/web-push-client.js.map +1 -1
  99. package/dist/query/offline-persistence.cjs +1 -1
  100. package/dist/query/offline-persistence.cjs.map +1 -1
  101. package/dist/query/offline-persistence.js +68 -23
  102. package/dist/query/offline-persistence.js.map +1 -1
  103. package/dist/styles/component/Toast.css +6 -1
  104. package/dist/styles/feedback.css +6 -1
  105. package/dist/styles.css +1 -1
  106. package/dist/sw/background-sync.cjs +1 -1
  107. package/dist/sw/background-sync.cjs.map +1 -1
  108. package/dist/sw/background-sync.js +272 -60
  109. package/dist/sw/background-sync.js.map +1 -1
  110. package/dist/sw/cache-inspect.cjs.map +1 -1
  111. package/dist/sw/cache-inspect.js.map +1 -1
  112. package/dist/sw/cache.cjs +1 -1
  113. package/dist/sw/cache.cjs.map +1 -1
  114. package/dist/sw/cache.js +91 -64
  115. package/dist/sw/cache.js.map +1 -1
  116. package/dist/sw/credential-headers.cjs +2 -0
  117. package/dist/sw/credential-headers.cjs.map +1 -0
  118. package/dist/sw/credential-headers.js +17 -0
  119. package/dist/sw/credential-headers.js.map +1 -0
  120. package/dist/sw/session-data.cjs +2 -0
  121. package/dist/sw/session-data.cjs.map +1 -0
  122. package/dist/sw/session-data.js +17 -0
  123. package/dist/sw/session-data.js.map +1 -0
  124. package/dist/sw.cjs +1 -1
  125. package/dist/sw.d.ts +309 -23
  126. package/dist/sw.js +7 -5
  127. package/dist/telemetry/app-error-queue.cjs +1 -1
  128. package/dist/telemetry/app-error-queue.cjs.map +1 -1
  129. package/dist/telemetry/app-error-queue.js +19 -14
  130. package/dist/telemetry/app-error-queue.js.map +1 -1
  131. package/dist/telemetry/app-error-reporter.cjs +1 -1
  132. package/dist/telemetry/app-error-reporter.cjs.map +1 -1
  133. package/dist/telemetry/app-error-reporter.js +75 -34
  134. package/dist/telemetry/app-error-reporter.js.map +1 -1
  135. package/dist/telemetry/app-error-transport.cjs +1 -1
  136. package/dist/telemetry/app-error-transport.cjs.map +1 -1
  137. package/dist/telemetry/app-error-transport.js +16 -3
  138. package/dist/telemetry/app-error-transport.js.map +1 -1
  139. package/dist/tempest-react-sdk.cjs +1 -1
  140. package/dist/tempest-react-sdk.d.ts +1183 -64
  141. package/dist/tempest-react-sdk.js +160 -156
  142. package/dist/utils/csv.cjs +3 -3
  143. package/dist/utils/csv.cjs.map +1 -1
  144. package/dist/utils/csv.js +18 -14
  145. package/dist/utils/csv.js.map +1 -1
  146. package/dist/utils/owner-fingerprint.cjs +2 -0
  147. package/dist/utils/owner-fingerprint.cjs.map +1 -0
  148. package/dist/utils/owner-fingerprint.js +18 -0
  149. package/dist/utils/owner-fingerprint.js.map +1 -0
  150. package/dist/utils/safe-url.cjs +2 -0
  151. package/dist/utils/safe-url.cjs.map +1 -0
  152. package/dist/utils/safe-url.js +39 -0
  153. package/dist/utils/safe-url.js.map +1 -0
  154. package/dist/vite/tempest-csp.cjs +2 -2
  155. package/dist/vite/tempest-csp.cjs.map +1 -1
  156. package/dist/vite/tempest-csp.js +130 -64
  157. package/dist/vite/tempest-csp.js.map +1 -1
  158. package/dist/vite.d.ts +23 -5
  159. package/dist/webrtc/peer-link.cjs +1 -1
  160. package/dist/webrtc/peer-link.cjs.map +1 -1
  161. package/dist/webrtc/peer-link.js +2 -10
  162. package/dist/webrtc/peer-link.js.map +1 -1
  163. package/dist/webrtc/peer-mesh.cjs +1 -1
  164. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  165. package/dist/webrtc/peer-mesh.js +110 -72
  166. package/dist/webrtc/peer-mesh.js.map +1 -1
  167. package/package.json +1 -1
  168. package/template-pwa/src/pwa.tsx +22 -0
  169. package/template-pwa/src/sw.ts +27 -14
  170. package/dist/components/Markdown/markdown-url.cjs +0 -2
  171. package/dist/components/Markdown/markdown-url.cjs.map +0 -1
  172. package/dist/components/Markdown/markdown-url.js +0 -28
  173. package/dist/components/Markdown/markdown-url.js.map +0 -1
@@ -8,13 +8,43 @@ var t = /* @__PURE__ */ new Set([
8
8
  module: /[\\/]forms[\\/]use-viacep\.(?:[cm]?js|tsx?)$/,
9
9
  origin: "https://viacep.com.br",
10
10
  from: "tempest-react-sdk useViaCEP"
11
- }], r = /^(?:https?|wss?):\/\//i, i = /^((?:https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?)(?:[/?#].*)?$/i;
12
- function a(e, t) {
11
+ }], r = {
12
+ "script-src-elem": ["script-src", "default-src"],
13
+ "script-src-attr": ["script-src", "default-src"],
14
+ "style-src-elem": ["style-src", "default-src"],
15
+ "style-src-attr": ["style-src", "default-src"],
16
+ "worker-src": [
17
+ "child-src",
18
+ "script-src",
19
+ "default-src"
20
+ ],
21
+ "frame-src": ["child-src", "default-src"],
22
+ "fenced-frame-src": [
23
+ "frame-src",
24
+ "child-src",
25
+ "default-src"
26
+ ],
27
+ "child-src": ["default-src"],
28
+ "connect-src": ["default-src"],
29
+ "font-src": ["default-src"],
30
+ "img-src": ["default-src"],
31
+ "manifest-src": ["default-src"],
32
+ "media-src": ["default-src"],
33
+ "object-src": ["default-src"],
34
+ "prefetch-src": ["default-src"],
35
+ "script-src": ["default-src"],
36
+ "style-src": ["default-src"]
37
+ };
38
+ function i(e, t) {
39
+ for (let n of r[t] ?? []) if (n in e) return e[n];
40
+ }
41
+ var a = /^(?:https?|wss?):\/\//i, o = /^((?:https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?)(?:[/?#].*)?$/i;
42
+ function s(e, t) {
13
43
  let n = e.trim();
14
44
  if (n.startsWith("/") && !n.startsWith("//")) return;
15
- let a = i.exec(n);
16
- if (a) return a[1].toLowerCase();
17
- if (r.test(n)) try {
45
+ let r = o.exec(n);
46
+ if (r) return r[1].toLowerCase();
47
+ if (a.test(n)) try {
18
48
  let e = new URL(n);
19
49
  return `${e.protocol}//${e.host}`;
20
50
  } catch {
@@ -22,7 +52,7 @@ function a(e, t) {
22
52
  }
23
53
  throw Error(`tempestCsp: ${t} must be an absolute http(s)/ws(s) URL or a root-relative path, got "${e}"`);
24
54
  }
25
- function o(e) {
55
+ function c(e) {
26
56
  let t = {};
27
57
  for (let n of e.split(";")) {
28
58
  let [e, ...r] = n.trim().split(/\s+/);
@@ -32,97 +62,106 @@ function o(e) {
32
62
  }
33
63
  return t;
34
64
  }
35
- function s(e, n) {
65
+ function l(e, n) {
36
66
  return Object.entries(e).filter(([e]) => n === "header" || !t.has(e)).map(([e, t]) => [e, ...t].join(" ")).join("; ");
37
67
  }
38
- function c(e, t) {
39
- let n = e.filter((e) => e !== "'none'" || t.length === 0);
68
+ function u(e, t) {
69
+ return e.toLowerCase() === t;
70
+ }
71
+ function d(e) {
72
+ return e.every((e) => u(e, "'none'"));
73
+ }
74
+ function f(e) {
75
+ return e.replace(/^'(?:sha\d{3}|nonce)-/i, (e) => e.toLowerCase());
76
+ }
77
+ function p(e, t) {
78
+ let n = e.filter((e) => !u(e, "'none'") || t.length === 0);
40
79
  for (let e of t) n.includes(e) || n.push(e);
41
80
  return n.length === 0 ? ["'none'"] : n;
42
81
  }
43
- function l(t) {
82
+ function m(t) {
44
83
  return `'sha256-${e("sha256").update(t, "utf8").digest("base64")}'`;
45
84
  }
46
- function u(e) {
85
+ function h(e) {
47
86
  return e.replace(/'|'|'/gi, "'").replace(/"/gi, "\"").replace(/&/gi, "&");
48
87
  }
49
- function d(e) {
88
+ function g(e) {
50
89
  let t = {};
51
- for (let n of e.matchAll(/([^\s=<>/]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)) t[n[1].toLowerCase()] = u(n[2] ?? n[3] ?? n[4] ?? "");
90
+ for (let n of e.matchAll(/([^\s=<>/]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)) t[n[1].toLowerCase()] = h(n[2] ?? n[3] ?? n[4] ?? "");
52
91
  return t;
53
92
  }
54
- function f(e) {
55
- let t = [...e.matchAll(/<meta\b[^>]*>/gi)].filter((e) => d(e[0])["http-equiv"]?.toLowerCase() === "content-security-policy");
93
+ function _(e) {
94
+ let t = [...e.matchAll(/<meta\b[^>]*>/gi)].filter((e) => g(e[0])["http-equiv"]?.toLowerCase() === "content-security-policy");
56
95
  if (t.length === 0) return { html: e };
57
96
  if (t.length > 1) throw Error("tempestCsp: index.html declares more than one Content-Security-Policy <meta>; merge them into one");
58
97
  let n = t[0];
59
98
  return {
60
99
  html: e.slice(0, n.index) + e.slice(n.index + n[0].length).replace(/^[ \t]*\r?\n/, ""),
61
- declared: o(d(n[0]).content ?? "")
100
+ declared: c(g(n[0]).content ?? "")
62
101
  };
63
102
  }
64
- function p(e, t) {
103
+ function v(e, t) {
65
104
  let n = RegExp(`<${t}\\b([^>]*)>([\\s\\S]*?)</${t}>`, "gi"), r = [];
66
105
  for (let i of e.matchAll(n)) {
67
- let e = d(`<x ${i[1]}>`);
106
+ let e = g(`<x ${i[1]}>`);
68
107
  if (t === "script" && "src" in e || i[2].length === 0) continue;
69
- let n = l(i[2]);
108
+ let n = m(i[2]);
70
109
  r.includes(n) || r.push(n);
71
110
  }
72
111
  return r;
73
112
  }
74
- function m(e, t) {
113
+ function y(e, t) {
75
114
  let n = `<meta http-equiv="Content-Security-Policy" content="${t.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}" />`, r = /<meta\b[^>]*\bcharset\s*=[^>]*>/i.exec(e), i = /<head\b[^>]*>/i.exec(e), a = r !== null && i !== null && /<(?:script|link|style)\b/i.test(e.slice(i.index, r.index)), o = r && i && r.index > i.index && !a ? r : i;
76
115
  if (!o) return `${n}\n${e}`;
77
116
  let s = o.index + o[0].length;
78
117
  return `${e.slice(0, s)}\n ${n}${e.slice(s)}`;
79
118
  }
80
- function h(e) {
119
+ function b(e) {
81
120
  let t = [];
82
121
  for (let n of Object.values(e.bundle ?? {})) n.type === "chunk" && t.push(...n.moduleIds ?? Object.keys(n.modules ?? {}));
83
122
  return t;
84
123
  }
85
- function g(e = {}) {
86
- let { connect: t = [], env: i = !0, sockets: o = !0, wasm: l = !0, inlineStyles: u = !0, directives: d = {}, dev: g = !0, log: _ = !0, onPolicy: v } = e, y, b = [], x = "";
87
- function S(e, t, n) {
124
+ function x(e = {}) {
125
+ let { connect: t = [], env: r = !0, sockets: o = !0, wasm: c = !0, inlineStyles: m = !0, directives: h = {}, dev: g = !0, log: x = !0, onPolicy: S } = e, C = Object.fromEntries(Object.entries(h).map(([e, t]) => [e.toLowerCase(), t])), w, T = [], E = "";
126
+ function D(e, t, n) {
88
127
  t === void 0 || e.some((e) => e.origin === t) || e.push({
89
128
  origin: t,
90
129
  from: n
91
130
  });
92
131
  }
93
- function C(e) {
94
- let n = [], o = e.env ?? {}, s = [e.envPrefix ?? "VITE_"].flat();
95
- if (i === !0) for (let [e, t] of Object.entries(o)) s.some((t) => e.startsWith(t)) && typeof t == "string" && r.test(t.trim()) && S(n, a(t, `env ${e}`), `env ${e}`);
96
- else if (Array.isArray(i)) for (let t of i) {
97
- let r = o[t];
132
+ function O(e) {
133
+ let n = [], i = e.env ?? {}, o = [e.envPrefix ?? "VITE_"].flat();
134
+ if (r === !0) for (let [e, t] of Object.entries(i)) o.some((t) => e.startsWith(t)) && typeof t == "string" && a.test(t.trim()) && D(n, s(t, `env ${e}`), `env ${e}`);
135
+ else if (Array.isArray(r)) for (let t of r) {
136
+ let r = i[t];
98
137
  if (typeof r != "string" || r.trim() === "") {
99
138
  e.logger.warn(`tempestCsp: env ${t} is empty — nothing added to connect-src`);
100
139
  continue;
101
140
  }
102
- S(n, a(r, `env ${t}`), `env ${t}`);
141
+ D(n, s(r, `env ${t}`), `env ${t}`);
103
142
  }
104
143
  return t.forEach((t, r) => {
105
144
  if (!t || t.trim() === "") {
106
145
  e.logger.warn(`tempestCsp: connect[${r}] is empty — skipped, nothing added to connect-src`);
107
146
  return;
108
147
  }
109
- S(n, a(t, `connect[${r}]`), `connect[${r}]`);
148
+ D(n, s(t, `connect[${r}]`), `connect[${r}]`);
110
149
  }), n;
111
150
  }
112
- function w(e) {
151
+ function k(e) {
113
152
  let t = [...e];
114
153
  if (!o) return t;
115
154
  for (let { origin: n } of e) {
116
155
  let e = n.replace(/^http(s?):/i, "ws$1:");
117
- e !== n && S(t, e, `sockets (${n})`);
156
+ e !== n && D(t, e, `sockets (${n})`);
118
157
  }
119
158
  return t;
120
159
  }
121
- function T(e, t) {
160
+ function A(e, t) {
122
161
  let n = e ? ["'self'", e] : ["'self'"], r = {
123
162
  "default-src": [...n],
124
- "script-src": l ? [...n, "'wasm-unsafe-eval'"] : [...n],
125
- "style-src": u || t ? [...n, "'unsafe-inline'"] : [...n],
163
+ "script-src": c ? [...n, "'wasm-unsafe-eval'"] : [...n],
164
+ "style-src": m || t ? [...n, "'unsafe-inline'"] : [...n],
126
165
  "img-src": [
127
166
  ...n,
128
167
  "data:",
@@ -141,49 +180,76 @@ function g(e = {}) {
141
180
  "base-uri": ["'self'"],
142
181
  "form-action": ["'self'"]
143
182
  };
144
- for (let [e, t] of Object.entries(d)) {
145
- let n = e.toLowerCase();
146
- t === !1 ? delete r[n] : r[n] = c(r[n] ?? [], t);
147
- }
183
+ for (let [e, t] of Object.entries(C)) t === !1 ? delete r[e] : r[e] = p(r[e] ?? [], t);
148
184
  return r;
149
185
  }
186
+ function j(e, t) {
187
+ let n = {};
188
+ for (let [r, a] of Object.entries(e)) {
189
+ if (r in t) {
190
+ n[r] = t[r];
191
+ continue;
192
+ }
193
+ let e = i(t, r), o = C[r];
194
+ e === void 0 ? n[r] = a : Array.isArray(o) ? n[r] = p(e, o) : a.length > 0 && d(a) && (n[r] = a);
195
+ }
196
+ for (let [e, r] of Object.entries(t)) n[e] ??= r;
197
+ for (let [e, r] of Object.entries(C)) {
198
+ if (!(e in t)) continue;
199
+ if (r === !1) {
200
+ delete n[e];
201
+ continue;
202
+ }
203
+ let i = r.filter((n) => !t[e].includes(n));
204
+ i.length > 0 && w?.logger.warn(`tempestCsp: index.html declares ${e}, so directives["${e}"] is not added to it (${i.join(" ")}); the plugin never loosens a declared policy — add them to the <meta> instead`);
205
+ }
206
+ return n;
207
+ }
208
+ function M(e, t, n) {
209
+ if (!n || !w) return;
210
+ let r = n.map(f);
211
+ if (n.some((e) => u(e, "'unsafe-inline'")) && !r.some((e) => /^'(?:sha\d{3}|nonce)-/.test(e))) return;
212
+ let i = v(e, "script").filter((e) => !r.includes(e));
213
+ i.length !== 0 && w.logger.warn(`tempestCsp: the Content-Security-Policy declared in index.html blocks ${i.length} inline <script> (${t} ${n.join(" ")}); the plugin never loosens a declared policy, so add ${i.join(" ")} to ${t}`);
214
+ }
150
215
  return {
151
216
  name: "tempest-csp",
152
217
  configResolved(e) {
153
- y = e, b = C(e);
218
+ w = e, T = O(e);
154
219
  },
155
220
  transformIndexHtml: {
156
221
  order: "post",
157
222
  handler(e, t) {
158
- let i = y?.command === "serve";
159
- if (i && !g) return e;
160
- let o = w(b), l = y?.base ?? "/", u = r.test(l) ? a(l, "base") : void 0;
161
- u && S(o, u, "base");
162
- let d = i ? [] : h(t);
163
- for (let e of n) (i || d.some((t) => e.module.test(t))) && S(o, e.origin, e.from);
164
- let C = o, { html: E, declared: D = {} } = f(e), O = T(u, i);
165
- "script-src" in D || (O["script-src"] = c(O["script-src"] ?? [], p(E, "script"))), !("style-src" in D) && !O["style-src"]?.includes("'unsafe-inline'") && (O["style-src"] = c(O["style-src"] ?? [], p(E, "style")));
166
- let k = { ...O };
167
- for (let [e, t] of Object.entries(D)) k[e] = t;
168
- k["connect-src"] = c(k["connect-src"] ?? ["'self'"], C.map((e) => e.origin));
169
- let A = {
170
- directives: k,
171
- meta: s(k, "meta"),
172
- header: s(k, "header"),
173
- connect: C,
174
- command: i ? "serve" : "build"
223
+ let r = w?.command === "serve";
224
+ if (r && !g) return e;
225
+ let o = k(T), c = w?.base ?? "/", f = a.test(c) ? s(c, "base") : void 0;
226
+ f && D(o, f, "base");
227
+ let m = r ? [] : b(t);
228
+ for (let e of n) (r || m.some((t) => e.module.test(t))) && D(o, e.origin, e.from);
229
+ let h = o, { html: C, declared: O = {} } = _(e), N = A(f, r), P = (e) => !(e in O) && i(O, e) === void 0;
230
+ P("script-src") && !("script-src-elem" in O) && (N["script-src"] = p(N["script-src"] ?? [], v(C, "script"))), P("style-src") && !("style-src-elem" in O) && !N["style-src"]?.some((e) => u(e, "'unsafe-inline'")) && (N["style-src"] = p(N["style-src"] ?? [], v(C, "style")));
231
+ let F = j(N, O), I = h.map((e) => e.origin), L = i(O, "connect-src"), R = F["connect-src"] ?? L;
232
+ R !== void 0 && d(R) && ("connect-src" in O || L !== void 0) ? I.length > 0 && w?.logger.warn(`tempestCsp: index.html declares connect-src ${R.join(" ") || "with no source"}${"connect-src" in O ? "" : " (through default-src)"}, so these origins stay out and requests to them will be blocked: ${I.join(" ")}`) : ("connect-src" in F || I.length > 0 || L === void 0) && (F["connect-src"] = p(R ?? ["'self'"], I));
233
+ let z = "script-src-elem" in O ? "script-src-elem" : "script-src";
234
+ M(C, z, F[z] ?? i(O, z));
235
+ let B = {
236
+ directives: F,
237
+ meta: l(F, "meta"),
238
+ header: l(F, "header"),
239
+ connect: h,
240
+ command: r ? "serve" : "build"
175
241
  };
176
- if (_ && y && A.header !== x) {
177
- x = A.header;
178
- let e = C.map((e) => ` ${e.origin} ← ${e.from}`);
179
- y.logger.info([`tempest-csp: connect-src ${k["connect-src"].join(" ")}`, ...e.length > 0 ? e : [" (no cross-origin endpoint: only 'self')"]].join("\n"));
242
+ if (x && w && B.header !== E) {
243
+ E = B.header;
244
+ let e = h.map((e) => ` ${e.origin} ← ${e.from}`);
245
+ w.logger.info([`tempest-csp: connect-src ${(F["connect-src"] ?? L ?? []).join(" ")}`, ...e.length > 0 ? e : [" (no cross-origin endpoint: only 'self')"]].join("\n"));
180
246
  }
181
- return v?.(A), m(E, A.meta);
247
+ return S?.(B), y(C, B.meta);
182
248
  }
183
249
  }
184
250
  };
185
251
  }
186
252
  //#endregion
187
- export { a as cspOrigin, o as parseCsp, s as serializeCsp, g as tempestCsp };
253
+ export { s as cspOrigin, c as parseCsp, l as serializeCsp, x as tempestCsp };
188
254
 
189
255
  //# sourceMappingURL=tempest-csp.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tempest-csp.js","names":[],"sources":["../../src/vite/tempest-csp.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { IndexHtmlTransformContext, Plugin, ResolvedConfig } from \"vite\";\n\nimport type { TempestVitePlugin } from \"./tempest-pwa-manifest\";\n\n/** Options for {@link tempestCsp}. */\nexport interface TempestCspOptions {\n /**\n * Endpoints the app calls at runtime, as full URLs. Only the origin\n * (`scheme://host[:port]`) enters `connect-src`: a source expression with a path\n * matches that path alone, so `https://idp/realms/x` would still block\n * `https://idp/realms/x/protocol/openid-connect/token`.\n *\n * Empty entries (`undefined`, `null`, `false`, `\"\"`) are skipped with a build\n * warning instead of leaving a hole in the directive, so passing an env var\n * that is not set is safe. A root-relative path (`/api`) is same-origin and\n * already covered by `'self'`. Anything else that is not an absolute\n * `http(s)`/`ws(s)` URL throws at config time — failing the build, not\n * production. A wildcard host (`https://*.example.com`) is kept as written.\n */\n connect?: ReadonlyArray<string | null | undefined | false>;\n /**\n * Read origins from the same environment the runtime reads. `true` (the\n * default) adds every variable Vite exposes to `import.meta.env` (the\n * `envPrefix` ones, `VITE_` by default) whose value is an absolute\n * `http(s)`/`ws(s)` URL. This is the structural bridge: an origin added to\n * `.env` for a new runtime call lands in the policy with no second list to\n * keep in sync. Pass a list of names to include exactly those — a name that\n * resolves to nothing is reported as a build warning — or `false` to rely on\n * {@link TempestCspOptions.connect} alone.\n */\n env?: boolean | readonly string[];\n /**\n * Also allow the WebSocket twin of every `http(s)` origin (`https://api` →\n * `wss://api`). Measured in Chromium (23/09/2026): `connect-src https://api`\n * blocks `new WebSocket(\"wss://api\")`, while `'self'` does cover a same-origin\n * `ws:` — so an app that derives its socket URL from the API URL breaks\n * without this. Default `true`.\n */\n sockets?: boolean;\n /**\n * Add `'wasm-unsafe-eval'` to `script-src`, which `onnxruntime-web` (the\n * `/vision` and `/tabular` subpaths) needs to compile its WebAssembly. Without\n * it `WebAssembly.compile` throws a `CompileError` naming `script-src`.\n * It grants WebAssembly compilation only, not `eval`. Default `true`.\n */\n wasm?: boolean;\n /**\n * Add `'unsafe-inline'` to `style-src`. React's `style` prop does **not** need\n * it — it writes through the CSSOM, which CSP does not govern (measured in\n * Chromium, 23/09/2026). What needs it is a `<style>` element or a `style=\"\"`\n * attribute, and the SDK's own `applyTheme` injects a `<style>`. Pass `false`\n * when the app never calls `applyTheme`; inline `<style>` blocks in\n * `index.html` are then hashed instead. Always on under `vite dev`, whose CSS\n * injection is a `<style>` element. Default `true`.\n */\n inlineStyles?: boolean;\n /**\n * Extra sources per directive, merged into the defaults (`{ \"img-src\":\n * [\"https://tiles.example.com\"] }`), or `false` to drop a directive.\n * `frame-ancestors`, `report-uri` and `sandbox` are ignored by browsers when\n * delivered by `<meta>`, so they reach {@link TempestCspPolicy.header} only.\n */\n directives?: Readonly<Record<string, readonly string[] | false>>;\n /**\n * Apply the policy under `vite dev` too. Default `true`: the failure this\n * plugin exists for is \"works in dev, blocked in production\", and a policy\n * enforced in dev moves every missing origin to the first page load on the\n * developer's machine. Dev differs from build only in `style-src\n * 'unsafe-inline'` and in allowing every SDK-known origin (see\n * {@link TempestCspPolicy.connect}), because the dev server cannot know which\n * modules the page will load.\n */\n dev?: boolean;\n /** Print the resolved `connect-src` and where each origin came from. Default `true`. */\n log?: boolean;\n /**\n * Receive the resolved policy — for asserting it in a test, or for writing the\n * same policy as an HTTP header (the only channel for `frame-ancestors`).\n */\n onPolicy?: (policy: TempestCspPolicy) => void;\n}\n\n/** One origin in `connect-src` and the input that put it there. */\nexport interface TempestCspSource {\n /** The source expression, e.g. `https://api.example.com`. */\n origin: string;\n /** Where it came from: `env VITE_API_URL`, `connect[0]`, `sockets`, `base` or an SDK module. */\n from: string;\n}\n\n/** The policy {@link tempestCsp} resolved for one `index.html`. */\nexport interface TempestCspPolicy {\n /** Every directive and its sources, including the header-only ones. */\n directives: Record<string, string[]>;\n /** The policy as written into the `<meta http-equiv>` tag. */\n meta: string;\n /** The full policy for a `Content-Security-Policy` response header. */\n header: string;\n /** Every origin added to `connect-src`, with its provenance. */\n connect: TempestCspSource[];\n /** `\"serve\"` under `vite dev`, `\"build\"` under `vite build`. */\n command: \"serve\" | \"build\";\n}\n\n/**\n * Directives a browser ignores when the policy arrives by `<meta>` (CSP3 §3.3),\n * printing a console warning for each.\n */\nconst HEADER_ONLY_DIRECTIVES: ReadonlySet<string> = new Set([\n \"frame-ancestors\",\n \"report-uri\",\n \"sandbox\",\n]);\n\n/**\n * Origins the SDK itself calls, keyed by the module that calls them. In a build\n * the origin enters only when the module is in the bundle; in dev always.\n */\nconst SDK_ORIGINS: ReadonlyArray<{ module: RegExp; origin: string; from: string }> = [\n {\n module: /[\\\\/]forms[\\\\/]use-viacep\\.(?:[cm]?js|tsx?)$/,\n origin: \"https://viacep.com.br\",\n from: \"tempest-react-sdk useViaCEP\",\n },\n];\n\nconst ABSOLUTE_URL = /^(?:https?|wss?):\\/\\//i;\nconst WILDCARD_SOURCE = /^((?:https?|wss?):\\/\\/\\*\\.[a-z0-9.-]+(?::\\d+)?)(?:[/?#].*)?$/i;\n\n/**\n * Reduce a URL to the origin a CSP source expression should carry.\n *\n * @param value - The URL as the app configured it.\n * @param from - Its provenance, quoted in the error.\n * @returns The origin, or `undefined` for a root-relative path (covered by `'self'`).\n * @throws {Error} When the value is neither an absolute `http(s)`/`ws(s)` URL nor a path.\n */\nexport function cspOrigin(value: string, from: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.startsWith(\"/\") && !trimmed.startsWith(\"//\")) return undefined;\n const wildcard = WILDCARD_SOURCE.exec(trimmed);\n if (wildcard) return wildcard[1]!.toLowerCase();\n if (ABSOLUTE_URL.test(trimmed)) {\n try {\n const url = new URL(trimmed);\n return `${url.protocol}//${url.host}`;\n } catch {\n throw new Error(`tempestCsp: ${from} is not a valid URL: \"${value}\"`);\n }\n }\n throw new Error(\n `tempestCsp: ${from} must be an absolute http(s)/ws(s) URL or a root-relative path, got \"${value}\"`,\n );\n}\n\n/**\n * Parse a serialized policy into directives, lowercasing names. A repeated\n * directive keeps its first occurrence, as browsers do.\n *\n * @param policy - A `Content-Security-Policy` value.\n * @returns Directive name → sources.\n */\nexport function parseCsp(policy: string): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const part of policy.split(\";\")) {\n const [name, ...sources] = part.trim().split(/\\s+/);\n if (!name) continue;\n const key = name.toLowerCase();\n if (!(key in out)) out[key] = sources;\n }\n return out;\n}\n\n/**\n * Serialize directives into a policy string, dropping header-only directives\n * when the target is a `<meta>` tag.\n *\n * @param directives - Directive name → sources.\n * @param target - `\"meta\"` or `\"header\"`.\n * @returns The policy value.\n */\nexport function serializeCsp(\n directives: Readonly<Record<string, readonly string[]>>,\n target: \"meta\" | \"header\",\n): string {\n return Object.entries(directives)\n .filter(([name]) => target === \"header\" || !HEADER_ONLY_DIRECTIVES.has(name))\n .map(([name, sources]) => [name, ...sources].join(\" \"))\n .join(\"; \");\n}\n\nfunction union(base: readonly string[], extra: readonly string[]): string[] {\n const out = base.filter((source) => source !== \"'none'\" || extra.length === 0);\n for (const source of extra) if (!out.includes(source)) out.push(source);\n return out.length === 0 ? [\"'none'\"] : out;\n}\n\nfunction sha256(content: string): string {\n return `'sha256-${createHash(\"sha256\").update(content, \"utf8\").digest(\"base64\")}'`;\n}\n\nfunction decodeEntities(value: string): string {\n return value\n .replace(/&#39;|&#x27;|&apos;/gi, \"'\")\n .replace(/&quot;/gi, '\"')\n .replace(/&amp;/gi, \"&\");\n}\n\nfunction readAttributes(tag: string): Record<string, string> {\n const out: Record<string, string> = {};\n const pattern = /([^\\s=<>/]+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/g;\n for (const match of tag.matchAll(pattern)) {\n out[match[1]!.toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n return out;\n}\n\n/**\n * Find the policy `index.html` already declares and remove its tag, so the merged\n * policy replaces it instead of stacking a second one (two policies are\n * intersected by the browser, so the stricter would win silently).\n *\n * @throws {Error} When the page declares more than one CSP `<meta>`: merging an\n * intersection into a union would weaken it, so the plugin refuses.\n */\nfunction extractMetaPolicy(html: string): { html: string; declared?: Record<string, string[]> } {\n const tags = [...html.matchAll(/<meta\\b[^>]*>/gi)].filter(\n (match) =>\n readAttributes(match[0])[\"http-equiv\"]?.toLowerCase() === \"content-security-policy\",\n );\n if (tags.length === 0) return { html };\n if (tags.length > 1) {\n throw new Error(\n \"tempestCsp: index.html declares more than one Content-Security-Policy <meta>; merge them into one\",\n );\n }\n const tag = tags[0]!;\n return {\n html:\n html.slice(0, tag.index) +\n html.slice(tag.index! + tag[0].length).replace(/^[ \\t]*\\r?\\n/, \"\"),\n declared: parseCsp(readAttributes(tag[0]).content ?? \"\"),\n };\n}\n\nfunction inlineHashes(html: string, element: \"script\" | \"style\"): string[] {\n const pattern = new RegExp(`<${element}\\\\b([^>]*)>([\\\\s\\\\S]*?)</${element}>`, \"gi\");\n const hashes: string[] = [];\n for (const match of html.matchAll(pattern)) {\n const attributes = readAttributes(`<x ${match[1]}>`);\n if (element === \"script\" && \"src\" in attributes) continue;\n if (match[2]!.length === 0) continue;\n const hash = sha256(match[2]!);\n if (!hashes.includes(hash)) hashes.push(hash);\n }\n return hashes;\n}\n\n/**\n * Write the policy tag where it governs the whole page. A `<meta>` CSP applies\n * only to what follows it, so it goes right after `<meta charset>` — unless a\n * resource precedes the charset, as the React Refresh preamble does under\n * `vite dev` (`head-prepend`), in which case it goes right after `<head>`.\n */\nfunction insertMeta(html: string, policy: string): string {\n const escaped = policy.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n const tag = `<meta http-equiv=\"Content-Security-Policy\" content=\"${escaped}\" />`;\n const charset = /<meta\\b[^>]*\\bcharset\\s*=[^>]*>/i.exec(html);\n const head = /<head\\b[^>]*>/i.exec(html);\n const resourceFirst =\n charset !== null &&\n head !== null &&\n /<(?:script|link|style)\\b/i.test(html.slice(head.index, charset.index));\n const anchor = charset && head && charset.index > head.index && !resourceFirst ? charset : head;\n if (!anchor) return `${tag}\\n${html}`;\n const at = anchor.index + anchor[0].length;\n return `${html.slice(0, at)}\\n ${tag}${html.slice(at)}`;\n}\n\nfunction bundleModuleIds(ctx: IndexHtmlTransformContext): string[] {\n const ids: string[] = [];\n for (const output of Object.values(ctx.bundle ?? {})) {\n if (output.type !== \"chunk\") continue;\n ids.push(...(output.moduleIds ?? Object.keys(output.modules ?? {})));\n }\n return ids;\n}\n\n/**\n * Vite plugin that writes a Content-Security-Policy `<meta>` into `index.html`\n * and derives `connect-src` from the origins the app actually calls.\n *\n * It exists because of how a missing origin fails: the request is blocked\n * before a connection opens, so there is no entry in the Network tab, nothing in\n * the server log, `curl` succeeds, and the app sees `TypeError: Failed to\n * fetch` — indistinguishable from offline, DNS or CORS. And a hand-written CSP\n * plugin is usually `apply: \"build\"`, so it only fails in production. This\n * plugin closes both ends:\n *\n * - origins come from the same `import.meta.env` the runtime reads\n * ({@link TempestCspOptions.env}), reduced to `scheme://host[:port]`, with\n * empty values skipped — no second list to drift;\n * - the policy is enforced under `vite dev` as well ({@link TempestCspOptions.dev});\n * - the build prints every origin and its provenance.\n *\n * Defaults cover what the SDK's stack needs and nothing more: `'self'`\n * everywhere, `'wasm-unsafe-eval'` for ONNX Runtime, `blob:` for workers, object\n * URLs and media, `data:` for images and fonts, `object-src 'none'`,\n * `base-uri 'self'`, `form-action 'self'`. Inline `<script>` blocks left in\n * `index.html` (a `themeInitScript()` anti-flash script, say) are allowed by\n * SHA-256 hash, never by `'unsafe-inline'`.\n *\n * An existing CSP `<meta>` in `index.html` is merged, not overwritten: every\n * directive it declares is kept verbatim — the plugin never loosens a choice the\n * app wrote — except `connect-src`, which gains the resolved origins, since\n * that is the list the plugin exists to maintain. Directives it does not declare\n * come from the defaults.\n *\n * @param options - See {@link TempestCspOptions}.\n * @returns A Vite plugin, to be placed in `plugins`. It runs as a `post` HTML\n * transform, so a plugin that rewrites inline scripts after it would\n * invalidate the hashes.\n *\n * @example\n * // vite.config.ts\n * import { createViteConfig, tempestCsp } from \"tempest-react-sdk/vite\";\n *\n * export default createViteConfig({\n * plugins: [tempestCsp({ connect: [\"https://sso.example.com/realms/app\"] })],\n * });\n */\nexport function tempestCsp(options: TempestCspOptions = {}): TempestVitePlugin {\n const {\n connect = [],\n env = true,\n sockets = true,\n wasm = true,\n inlineStyles = true,\n directives: extra = {},\n dev = true,\n log = true,\n onPolicy,\n } = options;\n\n let config: ResolvedConfig | undefined;\n let resolved: TempestCspSource[] = [];\n let lastLogged = \"\";\n\n function add(list: TempestCspSource[], origin: string | undefined, from: string): void {\n if (origin === undefined || list.some((source) => source.origin === origin)) return;\n list.push({ origin, from });\n }\n\n function resolveSources(resolvedConfig: ResolvedConfig): TempestCspSource[] {\n const list: TempestCspSource[] = [];\n const values: Record<string, unknown> = resolvedConfig.env ?? {};\n const prefixes = [resolvedConfig.envPrefix ?? \"VITE_\"].flat();\n if (env === true) {\n for (const [name, value] of Object.entries(values)) {\n if (!prefixes.some((prefix) => name.startsWith(prefix))) continue;\n if (typeof value !== \"string\" || !ABSOLUTE_URL.test(value.trim())) continue;\n add(list, cspOrigin(value, `env ${name}`), `env ${name}`);\n }\n } else if (Array.isArray(env)) {\n for (const name of env) {\n const value = values[name];\n if (typeof value !== \"string\" || value.trim() === \"\") {\n resolvedConfig.logger.warn(\n `tempestCsp: env ${name} is empty — nothing added to connect-src`,\n );\n continue;\n }\n add(list, cspOrigin(value, `env ${name}`), `env ${name}`);\n }\n }\n connect.forEach((value, index) => {\n if (!value || value.trim() === \"\") {\n resolvedConfig.logger.warn(\n `tempestCsp: connect[${index}] is empty — skipped, nothing added to connect-src`,\n );\n return;\n }\n add(list, cspOrigin(value, `connect[${index}]`), `connect[${index}]`);\n });\n return list;\n }\n\n function withSockets(list: readonly TempestCspSource[]): TempestCspSource[] {\n const out = [...list];\n if (!sockets) return out;\n for (const { origin } of list) {\n const twin = origin.replace(/^http(s?):/i, \"ws$1:\");\n if (twin !== origin) add(out, twin, `sockets (${origin})`);\n }\n return out;\n }\n\n function defaults(baseOrigin: string | undefined, serve: boolean): Record<string, string[]> {\n const self = baseOrigin ? [\"'self'\", baseOrigin] : [\"'self'\"];\n const policy: Record<string, string[]> = {\n \"default-src\": [...self],\n \"script-src\": wasm ? [...self, \"'wasm-unsafe-eval'\"] : [...self],\n \"style-src\": inlineStyles || serve ? [...self, \"'unsafe-inline'\"] : [...self],\n \"img-src\": [...self, \"data:\", \"blob:\"],\n \"font-src\": [...self, \"data:\"],\n \"media-src\": [...self, \"blob:\"],\n \"connect-src\": [\"'self'\", \"blob:\", \"data:\"],\n \"worker-src\": [...self, \"blob:\"],\n \"manifest-src\": [...self],\n \"object-src\": [\"'none'\"],\n \"base-uri\": [\"'self'\"],\n \"form-action\": [\"'self'\"],\n };\n for (const [name, sources] of Object.entries(extra)) {\n const key = name.toLowerCase();\n if (sources === false) delete policy[key];\n else policy[key] = union(policy[key] ?? [], sources);\n }\n return policy;\n }\n\n const plugin: Plugin = {\n name: \"tempest-csp\",\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n resolved = resolveSources(resolvedConfig);\n },\n transformIndexHtml: {\n order: \"post\",\n handler(source, ctx) {\n const serve = config?.command === \"serve\";\n if (serve && !dev) return source;\n\n const connectSources = withSockets(resolved);\n const base = config?.base ?? \"/\";\n const baseOrigin = ABSOLUTE_URL.test(base) ? cspOrigin(base, \"base\") : undefined;\n if (baseOrigin) add(connectSources, baseOrigin, \"base\");\n const moduleIds = serve ? [] : bundleModuleIds(ctx);\n for (const known of SDK_ORIGINS) {\n if (serve || moduleIds.some((id) => known.module.test(id))) {\n add(connectSources, known.origin, known.from);\n }\n }\n const allSources = connectSources;\n\n const { html, declared = {} } = extractMetaPolicy(source);\n const policy = defaults(baseOrigin, serve);\n if (!(\"script-src\" in declared)) {\n policy[\"script-src\"] = union(\n policy[\"script-src\"] ?? [],\n inlineHashes(html, \"script\"),\n );\n }\n if (\n !(\"style-src\" in declared) &&\n !policy[\"style-src\"]?.includes(\"'unsafe-inline'\")\n ) {\n policy[\"style-src\"] = union(\n policy[\"style-src\"] ?? [],\n inlineHashes(html, \"style\"),\n );\n }\n const merged: Record<string, string[]> = { ...policy };\n for (const [name, sources] of Object.entries(declared)) merged[name] = sources;\n merged[\"connect-src\"] = union(\n merged[\"connect-src\"] ?? [\"'self'\"],\n allSources.map((entry) => entry.origin),\n );\n\n const result: TempestCspPolicy = {\n directives: merged,\n meta: serializeCsp(merged, \"meta\"),\n header: serializeCsp(merged, \"header\"),\n connect: allSources,\n command: serve ? \"serve\" : \"build\",\n };\n\n if (log && config && result.header !== lastLogged) {\n lastLogged = result.header;\n const lines = allSources.map((entry) => ` ${entry.origin} ← ${entry.from}`);\n config.logger.info(\n [\n `tempest-csp: connect-src ${merged[\"connect-src\"].join(\" \")}`,\n ...(lines.length > 0\n ? lines\n : [\" (no cross-origin endpoint: only 'self')\"]),\n ].join(\"\\n\"),\n );\n }\n onPolicy?.(result);\n return insertMeta(html, result.meta);\n },\n },\n };\n\n return plugin as TempestVitePlugin;\n}\n"],"mappings":";;AA6GA,IAAM,oBAA8C,IAAI,IAAI;CACxD;CACA;CACA;AACJ,CAAC,GAMK,IAA+E,CACjF;CACI,QAAQ;CACR,QAAQ;CACR,MAAM;AACV,CACJ,GAEM,IAAe,0BACf,IAAkB;AAUxB,SAAgB,EAAU,GAAe,GAAkC;CACvE,IAAM,IAAU,EAAM,KAAK;CAC3B,IAAI,EAAQ,WAAW,GAAG,KAAK,CAAC,EAAQ,WAAW,IAAI,GAAG;CAC1D,IAAM,IAAW,EAAgB,KAAK,CAAO;CAC7C,IAAI,GAAU,OAAO,EAAS,EAAE,CAAE,YAAY;CAC9C,IAAI,EAAa,KAAK,CAAO,GACzB,IAAI;EACA,IAAM,IAAM,IAAI,IAAI,CAAO;EAC3B,OAAO,GAAG,EAAI,SAAS,IAAI,EAAI;CACnC,QAAQ;EACJ,MAAU,MAAM,eAAe,EAAK,wBAAwB,EAAM,EAAE;CACxE;CAEJ,MAAU,MACN,eAAe,EAAK,uEAAuE,EAAM,EACrG;AACJ;AASA,SAAgB,EAAS,GAA0C;CAC/D,IAAM,IAAgC,CAAC;CACvC,KAAK,IAAM,KAAQ,EAAO,MAAM,GAAG,GAAG;EAClC,IAAM,CAAC,GAAM,GAAG,KAAW,EAAK,KAAK,CAAC,CAAC,MAAM,KAAK;EAClD,IAAI,CAAC,GAAM;EACX,IAAM,IAAM,EAAK,YAAY;EAC7B,AAAM,KAAO,MAAM,EAAI,KAAO;CAClC;CACA,OAAO;AACX;AAUA,SAAgB,EACZ,GACA,GACM;CACN,OAAO,OAAO,QAAQ,CAAU,CAAC,CAC5B,QAAQ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AAQ,EAAW,KAAK,MAAU,KAAK,EAAM,OAAO,MAAM,EAAM,MAAM;KAC5E,EAAO,OAAO,KACV,CACI,4BAA4B,EAAO,cAAc,CAAC,KAAK,GAAG,KAC1D,GAAI,EAAM,SAAS,IACb,IACA,CAAC,2CAA2C,CACtD,CAAC,CAAC,KAAK,IAAI,CACf;IACJ;IAEA,OADA,IAAW,CAAM,GACV,EAAW,GAAM,EAAO,IAAI;GACvC;EACJ;CAGG;AACX"}
1
+ {"version":3,"file":"tempest-csp.js","names":[],"sources":["../../src/vite/tempest-csp.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { IndexHtmlTransformContext, Plugin, ResolvedConfig } from \"vite\";\n\nimport type { TempestVitePlugin } from \"./tempest-pwa-manifest\";\n\n/** Options for {@link tempestCsp}. */\nexport interface TempestCspOptions {\n /**\n * Endpoints the app calls at runtime, as full URLs. Only the origin\n * (`scheme://host[:port]`) enters `connect-src`: a source expression with a path\n * matches that path alone, so `https://idp/realms/x` would still block\n * `https://idp/realms/x/protocol/openid-connect/token`.\n *\n * Empty entries (`undefined`, `null`, `false`, `\"\"`) are skipped with a build\n * warning instead of leaving a hole in the directive, so passing an env var\n * that is not set is safe. A root-relative path (`/api`) is same-origin and\n * already covered by `'self'`. Anything else that is not an absolute\n * `http(s)`/`ws(s)` URL throws at config time — failing the build, not\n * production. A wildcard host (`https://*.example.com`) is kept as written.\n */\n connect?: ReadonlyArray<string | null | undefined | false>;\n /**\n * Read origins from the same environment the runtime reads. `true` (the\n * default) adds every variable Vite exposes to `import.meta.env` (the\n * `envPrefix` ones, `VITE_` by default) whose value is an absolute\n * `http(s)`/`ws(s)` URL. This is the structural bridge: an origin added to\n * `.env` for a new runtime call lands in the policy with no second list to\n * keep in sync. Pass a list of names to include exactly those — a name that\n * resolves to nothing is reported as a build warning — or `false` to rely on\n * {@link TempestCspOptions.connect} alone.\n */\n env?: boolean | readonly string[];\n /**\n * Also allow the WebSocket twin of every `http(s)` origin (`https://api` →\n * `wss://api`). Measured in Chromium (23/09/2026): `connect-src https://api`\n * blocks `new WebSocket(\"wss://api\")`, while `'self'` does cover a same-origin\n * `ws:` — so an app that derives its socket URL from the API URL breaks\n * without this. Default `true`.\n */\n sockets?: boolean;\n /**\n * Add `'wasm-unsafe-eval'` to `script-src`, which `onnxruntime-web` (the\n * `/vision` and `/tabular` subpaths) needs to compile its WebAssembly. Without\n * it `WebAssembly.compile` throws a `CompileError` naming `script-src`.\n * It grants WebAssembly compilation only, not `eval`. Default `true`.\n */\n wasm?: boolean;\n /**\n * Add `'unsafe-inline'` to `style-src`. React's `style` prop does **not** need\n * it — it writes through the CSSOM, which CSP does not govern (measured in\n * Chromium, 23/09/2026). What needs it is a `<style>` element or a `style=\"\"`\n * attribute, and the SDK's own `applyTheme` injects a `<style>`. Pass `false`\n * when the app never calls `applyTheme`; inline `<style>` blocks in\n * `index.html` are then hashed instead. Always on under `vite dev`, whose CSS\n * injection is a `<style>` element. Default `true`.\n */\n inlineStyles?: boolean;\n /**\n * Extra sources per directive, merged into the defaults (`{ \"img-src\":\n * [\"https://tiles.example.com\"] }`), or `false` to drop a directive.\n * `frame-ancestors`, `report-uri` and `sandbox` are ignored by browsers when\n * delivered by `<meta>`, so they reach {@link TempestCspPolicy.header} only.\n */\n directives?: Readonly<Record<string, readonly string[] | false>>;\n /**\n * Apply the policy under `vite dev` too. Default `true`: the failure this\n * plugin exists for is \"works in dev, blocked in production\", and a policy\n * enforced in dev moves every missing origin to the first page load on the\n * developer's machine. Dev differs from build only in `style-src\n * 'unsafe-inline'` and in allowing every SDK-known origin (see\n * {@link TempestCspPolicy.connect}), because the dev server cannot know which\n * modules the page will load.\n */\n dev?: boolean;\n /** Print the resolved `connect-src` and where each origin came from. Default `true`. */\n log?: boolean;\n /**\n * Receive the resolved policy — for asserting it in a test, or for writing the\n * same policy as an HTTP header (the only channel for `frame-ancestors`).\n */\n onPolicy?: (policy: TempestCspPolicy) => void;\n}\n\n/** One origin in `connect-src` and the input that put it there. */\nexport interface TempestCspSource {\n /** The source expression, e.g. `https://api.example.com`. */\n origin: string;\n /** Where it came from: `env VITE_API_URL`, `connect[0]`, `sockets`, `base` or an SDK module. */\n from: string;\n}\n\n/** The policy {@link tempestCsp} resolved for one `index.html`. */\nexport interface TempestCspPolicy {\n /** Every directive and its sources, including the header-only ones. */\n directives: Record<string, string[]>;\n /** The policy as written into the `<meta http-equiv>` tag. */\n meta: string;\n /** The full policy for a `Content-Security-Policy` response header. */\n header: string;\n /** Every origin added to `connect-src`, with its provenance. */\n connect: TempestCspSource[];\n /** `\"serve\"` under `vite dev`, `\"build\"` under `vite build`. */\n command: \"serve\" | \"build\";\n}\n\n/**\n * Directives a browser ignores when the policy arrives by `<meta>` (CSP3 §3.3),\n * printing a console warning for each.\n */\nconst HEADER_ONLY_DIRECTIVES: ReadonlySet<string> = new Set([\n \"frame-ancestors\",\n \"report-uri\",\n \"sandbox\",\n]);\n\n/**\n * Origins the SDK itself calls, keyed by the module that calls them. In a build\n * the origin enters only when the module is in the bundle; in dev always.\n */\nconst SDK_ORIGINS: ReadonlyArray<{ module: RegExp; origin: string; from: string }> = [\n {\n module: /[\\\\/]forms[\\\\/]use-viacep\\.(?:[cm]?js|tsx?)$/,\n origin: \"https://viacep.com.br\",\n from: \"tempest-react-sdk useViaCEP\",\n },\n];\n\n/**\n * Where each fetch directive falls back when a policy does not declare it, in\n * order. Ported from CSP3 §6.8.3, \"Get fetch directive fallback list\"\n * (https://w3c.github.io/webappsec-csp/#directive-fallback-list, checked\n * 11/10/2026), which lists twelve effective directives: `script-src-elem`,\n * `script-src-attr`, `style-src-elem`, `style-src-attr`, `worker-src`,\n * `connect-src`, `manifest-src`, `object-src`, `frame-src`, `media-src`,\n * `font-src` and `img-src`. Four more are listed here on purpose:\n *\n * - `script-src`, `style-src` and `child-src` are never an effective directive,\n * but every chain that reaches them continues to `default-src`;\n * - `fenced-frame-src` comes from the Fenced Frame spec, which extends the\n * `frame-src` chain;\n * - `prefetch-src` was in earlier CSP3 drafts (→ `default-src`) and is gone from\n * the current one; a browser that still resolves it does so through\n * `default-src`, so it is treated as inherited.\n *\n * A directive absent from this map does not fall back at all (`base-uri`,\n * `form-action`, `frame-ancestors`, …): leaving it out of a policy allows\n * everything, so adding it only ever restricts.\n */\nconst CSP_FALLBACK: Readonly<Record<string, readonly string[]>> = {\n \"script-src-elem\": [\"script-src\", \"default-src\"],\n \"script-src-attr\": [\"script-src\", \"default-src\"],\n \"style-src-elem\": [\"style-src\", \"default-src\"],\n \"style-src-attr\": [\"style-src\", \"default-src\"],\n \"worker-src\": [\"child-src\", \"script-src\", \"default-src\"],\n \"frame-src\": [\"child-src\", \"default-src\"],\n \"fenced-frame-src\": [\"frame-src\", \"child-src\", \"default-src\"],\n \"child-src\": [\"default-src\"],\n \"connect-src\": [\"default-src\"],\n \"font-src\": [\"default-src\"],\n \"img-src\": [\"default-src\"],\n \"manifest-src\": [\"default-src\"],\n \"media-src\": [\"default-src\"],\n \"object-src\": [\"default-src\"],\n \"prefetch-src\": [\"default-src\"],\n \"script-src\": [\"default-src\"],\n \"style-src\": [\"default-src\"],\n};\n\n/**\n * The sources a declared policy already applies to a directive it does not\n * name, by walking {@link CSP_FALLBACK}.\n *\n * @param declared - The policy the app declared.\n * @param name - A directive the app did not declare.\n * @returns The inherited sources, or `undefined` when nothing governs the directive.\n */\nfunction inheritedSources(\n declared: Readonly<Record<string, string[]>>,\n name: string,\n): string[] | undefined {\n for (const parent of CSP_FALLBACK[name] ?? []) {\n if (parent in declared) return declared[parent];\n }\n return undefined;\n}\n\nconst ABSOLUTE_URL = /^(?:https?|wss?):\\/\\//i;\nconst WILDCARD_SOURCE = /^((?:https?|wss?):\\/\\/\\*\\.[a-z0-9.-]+(?::\\d+)?)(?:[/?#].*)?$/i;\n\n/**\n * Reduce a URL to the origin a CSP source expression should carry.\n *\n * @param value - The URL as the app configured it.\n * @param from - Its provenance, quoted in the error.\n * @returns The origin, or `undefined` for a root-relative path (covered by `'self'`).\n * @throws {Error} When the value is neither an absolute `http(s)`/`ws(s)` URL nor a path.\n */\nexport function cspOrigin(value: string, from: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.startsWith(\"/\") && !trimmed.startsWith(\"//\")) return undefined;\n const wildcard = WILDCARD_SOURCE.exec(trimmed);\n if (wildcard) return wildcard[1]!.toLowerCase();\n if (ABSOLUTE_URL.test(trimmed)) {\n try {\n const url = new URL(trimmed);\n return `${url.protocol}//${url.host}`;\n } catch {\n throw new Error(`tempestCsp: ${from} is not a valid URL: \"${value}\"`);\n }\n }\n throw new Error(\n `tempestCsp: ${from} must be an absolute http(s)/ws(s) URL or a root-relative path, got \"${value}\"`,\n );\n}\n\n/**\n * Parse a serialized policy into directives, lowercasing names. A repeated\n * directive keeps its first occurrence, as browsers do.\n *\n * @param policy - A `Content-Security-Policy` value.\n * @returns Directive name → sources.\n */\nexport function parseCsp(policy: string): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const part of policy.split(\";\")) {\n const [name, ...sources] = part.trim().split(/\\s+/);\n if (!name) continue;\n const key = name.toLowerCase();\n if (!(key in out)) out[key] = sources;\n }\n return out;\n}\n\n/**\n * Serialize directives into a policy string, dropping header-only directives\n * when the target is a `<meta>` tag.\n *\n * @param directives - Directive name → sources.\n * @param target - `\"meta\"` or `\"header\"`.\n * @returns The policy value.\n */\nexport function serializeCsp(\n directives: Readonly<Record<string, readonly string[]>>,\n target: \"meta\" | \"header\",\n): string {\n return Object.entries(directives)\n .filter(([name]) => target === \"header\" || !HEADER_ONLY_DIRECTIVES.has(name))\n .map(([name, sources]) => [name, ...sources].join(\" \"))\n .join(\"; \");\n}\n\n/**\n * Compare a source with a CSP keyword (`'self'`, `'none'`, `'unsafe-inline'`…).\n * Keywords are ASCII case-insensitive (CSP3 §2.3.1), so `'NONE'` is `'none'`.\n *\n * @param source - A source expression as written.\n * @param keyword - The keyword, quoted and lowercase.\n * @returns Whether the source is that keyword.\n */\nfunction isKeyword(source: string, keyword: string): boolean {\n return source.toLowerCase() === keyword;\n}\n\n/**\n * Whether a source list matches nothing: CSP3 §6.7.2.5 gives \"does not match\"\n * for an empty list and for one that holds only `'none'` — in any letter case.\n *\n * @param sources - The directive's sources.\n * @returns `true` for `[]`, `['none']`, `['NONE']`, `['none', 'None']`.\n */\nfunction matchesNothing(sources: readonly string[]): boolean {\n return sources.every((source) => isKeyword(source, \"'none'\"));\n}\n\n/**\n * Lowercase the algorithm (or `nonce`) prefix of a hash or nonce source,\n * leaving the case-sensitive base64 value alone, so `'SHA256-…'` compares\n * equal to the `'sha256-…'` the plugin computes.\n *\n * @param source - A source expression as written.\n * @returns The source with a normalized prefix.\n */\nfunction normalizeHashSource(source: string): string {\n return source.replace(/^'(?:sha\\d{3}|nonce)-/i, (prefix) => prefix.toLowerCase());\n}\n\nfunction union(base: readonly string[], extra: readonly string[]): string[] {\n const out = base.filter((source) => !isKeyword(source, \"'none'\") || extra.length === 0);\n for (const source of extra) if (!out.includes(source)) out.push(source);\n return out.length === 0 ? [\"'none'\"] : out;\n}\n\nfunction sha256(content: string): string {\n return `'sha256-${createHash(\"sha256\").update(content, \"utf8\").digest(\"base64\")}'`;\n}\n\nfunction decodeEntities(value: string): string {\n return value\n .replace(/&#39;|&#x27;|&apos;/gi, \"'\")\n .replace(/&quot;/gi, '\"')\n .replace(/&amp;/gi, \"&\");\n}\n\nfunction readAttributes(tag: string): Record<string, string> {\n const out: Record<string, string> = {};\n const pattern = /([^\\s=<>/]+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/g;\n for (const match of tag.matchAll(pattern)) {\n out[match[1]!.toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n return out;\n}\n\n/**\n * Find the policy `index.html` already declares and remove its tag, so the merged\n * policy replaces it instead of stacking a second one (two policies are\n * intersected by the browser, so the stricter would win silently).\n *\n * @throws {Error} When the page declares more than one CSP `<meta>`: merging an\n * intersection into a union would weaken it, so the plugin refuses.\n */\nfunction extractMetaPolicy(html: string): { html: string; declared?: Record<string, string[]> } {\n const tags = [...html.matchAll(/<meta\\b[^>]*>/gi)].filter(\n (match) =>\n readAttributes(match[0])[\"http-equiv\"]?.toLowerCase() === \"content-security-policy\",\n );\n if (tags.length === 0) return { html };\n if (tags.length > 1) {\n throw new Error(\n \"tempestCsp: index.html declares more than one Content-Security-Policy <meta>; merge them into one\",\n );\n }\n const tag = tags[0]!;\n return {\n html:\n html.slice(0, tag.index) +\n html.slice(tag.index! + tag[0].length).replace(/^[ \\t]*\\r?\\n/, \"\"),\n declared: parseCsp(readAttributes(tag[0]).content ?? \"\"),\n };\n}\n\nfunction inlineHashes(html: string, element: \"script\" | \"style\"): string[] {\n const pattern = new RegExp(`<${element}\\\\b([^>]*)>([\\\\s\\\\S]*?)</${element}>`, \"gi\");\n const hashes: string[] = [];\n for (const match of html.matchAll(pattern)) {\n const attributes = readAttributes(`<x ${match[1]}>`);\n if (element === \"script\" && \"src\" in attributes) continue;\n if (match[2]!.length === 0) continue;\n const hash = sha256(match[2]!);\n if (!hashes.includes(hash)) hashes.push(hash);\n }\n return hashes;\n}\n\n/**\n * Write the policy tag where it governs the whole page. A `<meta>` CSP applies\n * only to what follows it, so it goes right after `<meta charset>` — unless a\n * resource precedes the charset, as the React Refresh preamble does under\n * `vite dev` (`head-prepend`), in which case it goes right after `<head>`.\n */\nfunction insertMeta(html: string, policy: string): string {\n const escaped = policy.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n const tag = `<meta http-equiv=\"Content-Security-Policy\" content=\"${escaped}\" />`;\n const charset = /<meta\\b[^>]*\\bcharset\\s*=[^>]*>/i.exec(html);\n const head = /<head\\b[^>]*>/i.exec(html);\n const resourceFirst =\n charset !== null &&\n head !== null &&\n /<(?:script|link|style)\\b/i.test(html.slice(head.index, charset.index));\n const anchor = charset && head && charset.index > head.index && !resourceFirst ? charset : head;\n if (!anchor) return `${tag}\\n${html}`;\n const at = anchor.index + anchor[0].length;\n return `${html.slice(0, at)}\\n ${tag}${html.slice(at)}`;\n}\n\nfunction bundleModuleIds(ctx: IndexHtmlTransformContext): string[] {\n const ids: string[] = [];\n for (const output of Object.values(ctx.bundle ?? {})) {\n if (output.type !== \"chunk\") continue;\n ids.push(...(output.moduleIds ?? Object.keys(output.modules ?? {})));\n }\n return ids;\n}\n\n/**\n * Vite plugin that writes a Content-Security-Policy `<meta>` into `index.html`\n * and derives `connect-src` from the origins the app actually calls.\n *\n * It exists because of how a missing origin fails: the request is blocked\n * before a connection opens, so there is no entry in the Network tab, nothing in\n * the server log, `curl` succeeds, and the app sees `TypeError: Failed to\n * fetch` — indistinguishable from offline, DNS or CORS. And a hand-written CSP\n * plugin is usually `apply: \"build\"`, so it only fails in production. This\n * plugin closes both ends:\n *\n * - origins come from the same `import.meta.env` the runtime reads\n * ({@link TempestCspOptions.env}), reduced to `scheme://host[:port]`, with\n * empty values skipped — no second list to drift;\n * - the policy is enforced under `vite dev` as well ({@link TempestCspOptions.dev});\n * - the build prints every origin and its provenance.\n *\n * Defaults cover what the SDK's stack needs and nothing more: `'self'`\n * everywhere, `'wasm-unsafe-eval'` for ONNX Runtime, `blob:` for workers, object\n * URLs and media, `data:` for images and fonts, `object-src 'none'`,\n * `base-uri 'self'`, `form-action 'self'`. Inline `<script>` blocks left in\n * `index.html` (a `themeInitScript()` anti-flash script, say) are allowed by\n * SHA-256 hash, never by `'unsafe-inline'`.\n *\n * An existing CSP `<meta>` in `index.html` is merged, not overwritten, and the\n * merge never loosens what the app wrote:\n *\n * - a directive it declares is kept verbatim, except `connect-src`, which gains\n * the resolved origins (the list the plugin exists to maintain) unless it\n * matches nothing — `'none'` in any letter case, or an empty list, declared or\n * inherited from `default-src` — in which case the origins stay out and each\n * one is reported as a build warning. Keywords are compared case-insensitively\n * throughout, as browsers do. Sources in\n * {@link TempestCspOptions.directives} for a declared directive are not added\n * (a build warning names them); `false` there removes it;\n * - a fetch directive it does not declare but already governs through the CSP3\n * fallback chain (§6.8.3 — `img-src` → `default-src`,\n * `worker-src` → `child-src` → `script-src` → `default-src`) is left out, so it\n * keeps falling back. Filling it from the defaults would replace a\n * `default-src 'none'` with `'self' data: blob:`. No inline-script hash and no\n * `'wasm-unsafe-eval'` is added to it, and an inline `<script>` is judged by a\n * declared `script-src-elem` before `script-src`; `connect-src` starts from the inherited\n * value, and so does any directive passed in {@link TempestCspOptions.directives};\n * - a default that is exactly `'none'` (`object-src`), or a directive that does\n * not fall back (`base-uri`, `form-action`), is still added: it can only\n * restrict;\n * - a directive nothing in the declared policy governs comes from the defaults.\n *\n * @param options - See {@link TempestCspOptions}.\n * @returns A Vite plugin, to be placed in `plugins`. It runs as a `post` HTML\n * transform, so a plugin that rewrites inline scripts after it would\n * invalidate the hashes.\n *\n * @example\n * // vite.config.ts\n * import { createViteConfig, tempestCsp } from \"tempest-react-sdk/vite\";\n *\n * export default createViteConfig({\n * plugins: [tempestCsp({ connect: [\"https://sso.example.com/realms/app\"] })],\n * });\n */\nexport function tempestCsp(options: TempestCspOptions = {}): TempestVitePlugin {\n const {\n connect = [],\n env = true,\n sockets = true,\n wasm = true,\n inlineStyles = true,\n directives: extra = {},\n dev = true,\n log = true,\n onPolicy,\n } = options;\n\n const configured: Record<string, readonly string[] | false> = Object.fromEntries(\n Object.entries(extra).map(([name, sources]) => [name.toLowerCase(), sources]),\n );\n let config: ResolvedConfig | undefined;\n let resolved: TempestCspSource[] = [];\n let lastLogged = \"\";\n\n function add(list: TempestCspSource[], origin: string | undefined, from: string): void {\n if (origin === undefined || list.some((source) => source.origin === origin)) return;\n list.push({ origin, from });\n }\n\n function resolveSources(resolvedConfig: ResolvedConfig): TempestCspSource[] {\n const list: TempestCspSource[] = [];\n const values: Record<string, unknown> = resolvedConfig.env ?? {};\n const prefixes = [resolvedConfig.envPrefix ?? \"VITE_\"].flat();\n if (env === true) {\n for (const [name, value] of Object.entries(values)) {\n if (!prefixes.some((prefix) => name.startsWith(prefix))) continue;\n if (typeof value !== \"string\" || !ABSOLUTE_URL.test(value.trim())) continue;\n add(list, cspOrigin(value, `env ${name}`), `env ${name}`);\n }\n } else if (Array.isArray(env)) {\n for (const name of env) {\n const value = values[name];\n if (typeof value !== \"string\" || value.trim() === \"\") {\n resolvedConfig.logger.warn(\n `tempestCsp: env ${name} is empty — nothing added to connect-src`,\n );\n continue;\n }\n add(list, cspOrigin(value, `env ${name}`), `env ${name}`);\n }\n }\n connect.forEach((value, index) => {\n if (!value || value.trim() === \"\") {\n resolvedConfig.logger.warn(\n `tempestCsp: connect[${index}] is empty — skipped, nothing added to connect-src`,\n );\n return;\n }\n add(list, cspOrigin(value, `connect[${index}]`), `connect[${index}]`);\n });\n return list;\n }\n\n function withSockets(list: readonly TempestCspSource[]): TempestCspSource[] {\n const out = [...list];\n if (!sockets) return out;\n for (const { origin } of list) {\n const twin = origin.replace(/^http(s?):/i, \"ws$1:\");\n if (twin !== origin) add(out, twin, `sockets (${origin})`);\n }\n return out;\n }\n\n function defaults(baseOrigin: string | undefined, serve: boolean): Record<string, string[]> {\n const self = baseOrigin ? [\"'self'\", baseOrigin] : [\"'self'\"];\n const policy: Record<string, string[]> = {\n \"default-src\": [...self],\n \"script-src\": wasm ? [...self, \"'wasm-unsafe-eval'\"] : [...self],\n \"style-src\": inlineStyles || serve ? [...self, \"'unsafe-inline'\"] : [...self],\n \"img-src\": [...self, \"data:\", \"blob:\"],\n \"font-src\": [...self, \"data:\"],\n \"media-src\": [...self, \"blob:\"],\n \"connect-src\": [\"'self'\", \"blob:\", \"data:\"],\n \"worker-src\": [...self, \"blob:\"],\n \"manifest-src\": [...self],\n \"object-src\": [\"'none'\"],\n \"base-uri\": [\"'self'\"],\n \"form-action\": [\"'self'\"],\n };\n for (const [name, sources] of Object.entries(configured)) {\n if (sources === false) delete policy[name];\n else policy[name] = union(policy[name] ?? [], sources);\n }\n return policy;\n }\n\n /**\n * Merge the defaults, the declared policy and the configured\n * {@link TempestCspOptions.directives}, never loosening what was declared. A\n * declared directive is kept verbatim: configured sources for it are not\n * added — adding would loosen the app's policy — and each ignored source is\n * reported as a build warning, while a configured `false` removes it, since\n * removing is an explicit choice. An inherited directive (see\n * {@link inheritedSources}) is omitted unless the default is `'none'` or the\n * config adds sources, which then extend the inherited value instead of the\n * defaults.\n */\n function mergePolicy(\n policy: Readonly<Record<string, string[]>>,\n declared: Readonly<Record<string, string[]>>,\n ): Record<string, string[]> {\n const merged: Record<string, string[]> = {};\n for (const [name, sources] of Object.entries(policy)) {\n if (name in declared) {\n merged[name] = declared[name]!;\n continue;\n }\n const inherited = inheritedSources(declared, name);\n const added = configured[name];\n if (inherited === undefined) merged[name] = sources;\n else if (Array.isArray(added)) merged[name] = union(inherited, added);\n else if (sources.length > 0 && matchesNothing(sources)) merged[name] = sources;\n }\n for (const [name, sources] of Object.entries(declared)) merged[name] ??= sources;\n for (const [name, sources] of Object.entries(configured)) {\n if (!(name in declared)) continue;\n if (sources === false) {\n delete merged[name];\n continue;\n }\n const ignored = sources.filter((source) => !declared[name]!.includes(source));\n if (ignored.length > 0) {\n config?.logger.warn(\n `tempestCsp: index.html declares ${name}, so directives[\"${name}\"] is not added to it ` +\n `(${ignored.join(\" \")}); the plugin never loosens a declared policy — add them to the <meta> instead`,\n );\n }\n }\n return merged;\n }\n\n /**\n * Report every inline `<script>` the final policy blocks. It only happens when\n * the app's declared policy governs `script-src` — directly or through\n * `default-src` — since the plugin then adds no hash, and the symptom would\n * otherwise be a script that silently never runs (under `vite dev`, the React\n * Refresh preamble, which takes the page down with it).\n *\n * `<script>` elements are governed by `script-src-elem` when the policy has\n * one, so that is the directive judged and named.\n *\n * @param html - The page, without its CSP `<meta>`.\n * @param directive - `\"script-src-elem\"` when declared, else `\"script-src\"`.\n * @param effective - The sources the browser will apply to inline `<script>`\n * elements, or `undefined` when no directive governs them.\n */\n function warnBlockedInlineScripts(\n html: string,\n directive: string,\n effective: readonly string[] | undefined,\n ): void {\n if (!effective || !config) return;\n const normalized = effective.map(normalizeHashSource);\n const unsafeInline =\n effective.some((source) => isKeyword(source, \"'unsafe-inline'\")) &&\n !normalized.some((source) => /^'(?:sha\\d{3}|nonce)-/.test(source));\n if (unsafeInline) return;\n const blocked = inlineHashes(html, \"script\").filter((hash) => !normalized.includes(hash));\n if (blocked.length === 0) return;\n config.logger.warn(\n `tempestCsp: the Content-Security-Policy declared in index.html blocks ${blocked.length} inline <script> ` +\n `(${directive} ${effective.join(\" \")}); the plugin never loosens a declared policy, so add ${blocked.join(\" \")} to ${directive}`,\n );\n }\n\n const plugin: Plugin = {\n name: \"tempest-csp\",\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n resolved = resolveSources(resolvedConfig);\n },\n transformIndexHtml: {\n order: \"post\",\n handler(source, ctx) {\n const serve = config?.command === \"serve\";\n if (serve && !dev) return source;\n\n const connectSources = withSockets(resolved);\n const base = config?.base ?? \"/\";\n const baseOrigin = ABSOLUTE_URL.test(base) ? cspOrigin(base, \"base\") : undefined;\n if (baseOrigin) add(connectSources, baseOrigin, \"base\");\n const moduleIds = serve ? [] : bundleModuleIds(ctx);\n for (const known of SDK_ORIGINS) {\n if (serve || moduleIds.some((id) => known.module.test(id))) {\n add(connectSources, known.origin, known.from);\n }\n }\n const allSources = connectSources;\n\n const { html, declared = {} } = extractMetaPolicy(source);\n const policy = defaults(baseOrigin, serve);\n const filled = (name: string): boolean =>\n !(name in declared) && inheritedSources(declared, name) === undefined;\n if (filled(\"script-src\") && !(\"script-src-elem\" in declared)) {\n policy[\"script-src\"] = union(\n policy[\"script-src\"] ?? [],\n inlineHashes(html, \"script\"),\n );\n }\n if (\n filled(\"style-src\") &&\n !(\"style-src-elem\" in declared) &&\n !policy[\"style-src\"]?.some((source) => isKeyword(source, \"'unsafe-inline'\"))\n ) {\n policy[\"style-src\"] = union(\n policy[\"style-src\"] ?? [],\n inlineHashes(html, \"style\"),\n );\n }\n const merged = mergePolicy(policy, declared);\n const origins = allSources.map((entry) => entry.origin);\n const inheritedConnect = inheritedSources(declared, \"connect-src\");\n const declaredConnect = merged[\"connect-src\"] ?? inheritedConnect;\n const declaredNone =\n declaredConnect !== undefined &&\n matchesNothing(declaredConnect) &&\n (\"connect-src\" in declared || inheritedConnect !== undefined);\n if (declaredNone) {\n if (origins.length > 0) {\n config?.logger.warn(\n `tempestCsp: index.html declares connect-src ${declaredConnect.join(\" \") || \"with no source\"}${\"connect-src\" in declared ? \"\" : \" (through default-src)\"}, ` +\n `so these origins stay out and requests to them will be blocked: ${origins.join(\" \")}`,\n );\n }\n } else if (\n \"connect-src\" in merged ||\n origins.length > 0 ||\n inheritedConnect === undefined\n ) {\n merged[\"connect-src\"] = union(declaredConnect ?? [\"'self'\"], origins);\n }\n\n const scriptElem = \"script-src-elem\" in declared ? \"script-src-elem\" : \"script-src\";\n warnBlockedInlineScripts(\n html,\n scriptElem,\n merged[scriptElem] ?? inheritedSources(declared, scriptElem),\n );\n\n const result: TempestCspPolicy = {\n directives: merged,\n meta: serializeCsp(merged, \"meta\"),\n header: serializeCsp(merged, \"header\"),\n connect: allSources,\n command: serve ? \"serve\" : \"build\",\n };\n\n if (log && config && result.header !== lastLogged) {\n lastLogged = result.header;\n const lines = allSources.map((entry) => ` ${entry.origin} ← ${entry.from}`);\n config.logger.info(\n [\n `tempest-csp: connect-src ${(merged[\"connect-src\"] ?? inheritedConnect ?? []).join(\" \")}`,\n ...(lines.length > 0\n ? lines\n : [\" (no cross-origin endpoint: only 'self')\"]),\n ].join(\"\\n\"),\n );\n }\n onPolicy?.(result);\n return insertMeta(html, result.meta);\n },\n },\n };\n\n return plugin as TempestVitePlugin;\n}\n"],"mappings":";;AA6GA,IAAM,oBAA8C,IAAI,IAAI;CACxD;CACA;CACA;AACJ,CAAC,GAMK,IAA+E,CACjF;CACI,QAAQ;CACR,QAAQ;CACR,MAAM;AACV,CACJ,GAuBM,IAA4D;CAC9D,mBAAmB,CAAC,cAAc,aAAa;CAC/C,mBAAmB,CAAC,cAAc,aAAa;CAC/C,kBAAkB,CAAC,aAAa,aAAa;CAC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AAG,KAAK,GAAG,KACtF,GAAI,EAAM,SAAS,IACb,IACA,CAAC,2CAA2C,CACtD,CAAC,CAAC,KAAK,IAAI,CACf;IACJ;IAEA,OADA,IAAW,CAAM,GACV,EAAW,GAAM,EAAO,IAAI;GACvC;EACJ;CAGG;AACX"}
package/dist/vite.d.ts CHANGED
@@ -113,11 +113,29 @@ export declare interface StyleManifest {
113
113
  * `index.html` (a `themeInitScript()` anti-flash script, say) are allowed by
114
114
  * SHA-256 hash, never by `'unsafe-inline'`.
115
115
  *
116
- * An existing CSP `<meta>` in `index.html` is merged, not overwritten: every
117
- * directive it declares is kept verbatim — the plugin never loosens a choice the
118
- * app wrote — except `connect-src`, which gains the resolved origins, since
119
- * that is the list the plugin exists to maintain. Directives it does not declare
120
- * come from the defaults.
116
+ * An existing CSP `<meta>` in `index.html` is merged, not overwritten, and the
117
+ * merge never loosens what the app wrote:
118
+ *
119
+ * - a directive it declares is kept verbatim, except `connect-src`, which gains
120
+ * the resolved origins (the list the plugin exists to maintain) unless it
121
+ * matches nothing — `'none'` in any letter case, or an empty list, declared or
122
+ * inherited from `default-src` — in which case the origins stay out and each
123
+ * one is reported as a build warning. Keywords are compared case-insensitively
124
+ * throughout, as browsers do. Sources in
125
+ * {@link TempestCspOptions.directives} for a declared directive are not added
126
+ * (a build warning names them); `false` there removes it;
127
+ * - a fetch directive it does not declare but already governs through the CSP3
128
+ * fallback chain (§6.8.3 — `img-src` → `default-src`,
129
+ * `worker-src` → `child-src` → `script-src` → `default-src`) is left out, so it
130
+ * keeps falling back. Filling it from the defaults would replace a
131
+ * `default-src 'none'` with `'self' data: blob:`. No inline-script hash and no
132
+ * `'wasm-unsafe-eval'` is added to it, and an inline `<script>` is judged by a
133
+ * declared `script-src-elem` before `script-src`; `connect-src` starts from the inherited
134
+ * value, and so does any directive passed in {@link TempestCspOptions.directives};
135
+ * - a default that is exactly `'none'` (`object-src`), or a directive that does
136
+ * not fall back (`base-uri`, `form-action`), is still added: it can only
137
+ * restrict;
138
+ * - a directive nothing in the declared policy governs comes from the defaults.
121
139
  *
122
140
  * @param options - See {@link TempestCspOptions}.
123
141
  * @returns A Vite plugin, to be placed in `plugins`. It runs as a `post` HTML
@@ -1,2 +1,2 @@
1
- function e(e){return new RTCPeerConnection({iceServers:e,bundlePolicy:`max-bundle`,rtcpMuxPolicy:`require`})}function t(e,t,n){let r=Number(e.mid);if(e.mid!==null&&Number.isInteger(r)&&n[r])return n[r];let i=t.transceivers.indexOf(e);return i>=0?n[i]??null:null}async function n(e){let t=e.pendingCandidates.splice(0,e.pendingCandidates.length);for(let n of t)try{await e.pc.addIceCandidate(n)}catch{}}async function r(e,t){if(!e.remoteReady){e.pendingCandidates.push(t);return}try{await e.pc.addIceCandidate(t)}catch{}}async function i(e,t,n){for(let[r,i]of t.entries()){let t=e.transceivers[r],a=n.get(i.name)??null;if(t&&a)try{await t.sender.replaceTrack(a)}catch{}}}function a(e){e.transceivers=e.pc.getTransceivers().filter(e=>e.mid!==null).sort((e,t)=>Number(e.mid)-Number(t.mid));for(let t of e.transceivers)t.direction!==`sendrecv`&&(t.direction=`sendrecv`)}exports.acceptCandidate=r,exports.adoptTransceivers=a,exports.attachLocalTracks=i,exports.createPeerConnection=e,exports.drainCandidates=n,exports.slotOf=t;
1
+ function e(e){return new RTCPeerConnection({iceServers:e,bundlePolicy:`max-bundle`,rtcpMuxPolicy:`require`})}function t(e,t,n){let r=Number(e.mid);if(e.mid!==null&&Number.isInteger(r)&&n[r])return n[r];let i=t.transceivers.indexOf(e);return i>=0?n[i]??null:null}async function n(e){let t=e.pendingCandidates.splice(0,e.pendingCandidates.length);for(let n of t)try{await e.pc.addIceCandidate(n)}catch{}}async function r(e,t){if(!e.remoteReady){e.pendingCandidates.push(t);return}try{await e.pc.addIceCandidate(t)}catch{}}function i(e){e.transceivers=e.pc.getTransceivers().filter(e=>e.mid!==null).sort((e,t)=>Number(e.mid)-Number(t.mid));for(let t of e.transceivers)t.direction!==`sendrecv`&&(t.direction=`sendrecv`)}exports.acceptCandidate=r,exports.adoptTransceivers=i,exports.createPeerConnection=e,exports.drainCandidates=n,exports.slotOf=t;
2
2
  //# sourceMappingURL=peer-link.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"peer-link.cjs","names":[],"sources":["../../src/webrtc/peer-link.ts"],"sourcesContent":["import type { MeshSlot } from \"./mesh-types\";\n\n/** One remote peer's connection and everything the mesh tracks about it. */\nexport interface PeerLink {\n peerId: string;\n pc: RTCPeerConnection;\n /**\n * Transceivers in slot order.\n *\n * Held explicitly rather than re-read from `getTransceivers()` so slot\n * lookup stays O(1) and cannot drift if a browser reorders.\n */\n transceivers: RTCRtpTransceiver[];\n /** Candidates that arrived before the remote description they belong to. */\n pendingCandidates: RTCIceCandidateInit[];\n /** Whether `setRemoteDescription` has landed, which gates the queue. */\n remoteReady: boolean;\n /** Whether an offer is in flight, so a re-entrant call does not stack one. */\n makingOffer: boolean;\n /** Whether this side offers. Exactly one side of a link does. */\n isOfferer: boolean;\n}\n\n/** Open a connection with the policies a mesh needs. */\nexport function createPeerConnection(iceServers: RTCIceServer[]): RTCPeerConnection {\n return new RTCPeerConnection({\n iceServers,\n bundlePolicy: \"max-bundle\",\n rtcpMuxPolicy: \"require\",\n });\n}\n\n/**\n * Resolve which slot a transceiver carries.\n *\n * The offerer allocates the m-lines in slot order, so a transceiver's `mid` is\n * its ordinal and both ends read the same one. That makes `mid` the slot's wire\n * identity, and the **only** identifier correct on both sides of a link.\n *\n * Position in the link's own array is a fallback for a `mid` that is not a plain\n * ordinal, and never the primary: a browser answering an offer appends the\n * negotiated transceivers *after* any it already held, so positional lookup\n * silently resolves to the wrong slot — the camera arriving in the screen tile —\n * or to none at all, dropping the track.\n *\n * @param transceiver - The transceiver a track arrived on.\n * @param link - The link it belongs to.\n * @param slots - The mesh's slot list.\n * @returns The slot, or `null` when neither route names one.\n */\nexport function slotOf(\n transceiver: RTCRtpTransceiver,\n link: PeerLink,\n slots: readonly MeshSlot[],\n): MeshSlot | null {\n const ordinal = Number(transceiver.mid);\n if (transceiver.mid !== null && Number.isInteger(ordinal) && slots[ordinal]) {\n return slots[ordinal];\n }\n const index = link.transceivers.indexOf(transceiver);\n return index >= 0 ? (slots[index] ?? null) : null;\n}\n\n/**\n * Feed a link every candidate that arrived before its remote description.\n *\n * `addIceCandidate` throws while `remoteDescription` is `null`, and candidates\n * routinely beat the offer or answer they belong to. Without the queue the\n * connection loses them and sits in `checking` until it times out — a failure\n * with no error anywhere.\n *\n * @param link - The link whose queue is drained.\n */\nexport async function drainCandidates(link: PeerLink): Promise<void> {\n const queued = link.pendingCandidates.splice(0, link.pendingCandidates.length);\n for (const candidate of queued) {\n try {\n await link.pc.addIceCandidate(candidate);\n } catch {\n /* a candidate the browser rejects is not fatal to the connection */\n }\n }\n}\n\n/**\n * Hand a candidate to the connection, or park it until the description lands.\n *\n * @param link - The link the candidate belongs to.\n * @param init - The candidate, already in `RTCIceCandidateInit` shape.\n */\nexport async function acceptCandidate(link: PeerLink, init: RTCIceCandidateInit): Promise<void> {\n if (!link.remoteReady) {\n link.pendingCandidates.push(init);\n return;\n }\n try {\n await link.pc.addIceCandidate(init);\n } catch {\n /* a candidate the browser rejects is not fatal to the connection */\n }\n}\n\n/**\n * Publish every held local track onto a link's slots.\n *\n * Called once the transceivers exist — up front for the offerer, after the offer\n * lands for the answerer — so a microphone that was already live when the peer\n * joined starts flowing without waiting for a toggle.\n *\n * @param link - The link to publish onto.\n * @param slots - The mesh's slot list.\n * @param tracks - The current local track per slot name.\n */\nexport async function attachLocalTracks(\n link: PeerLink,\n slots: readonly MeshSlot[],\n tracks: Map<string, MediaStreamTrack | null>,\n): Promise<void> {\n for (const [index, slot] of slots.entries()) {\n const transceiver = link.transceivers[index];\n const track = tracks.get(slot.name) ?? null;\n if (!transceiver || !track) continue;\n try {\n await transceiver.sender.replaceTrack(track);\n } catch {\n /* the browser refused the track; the slot simply stays silent */\n }\n }\n}\n\n/**\n * Adopt the transceivers a remote offer created, in `mid` order.\n *\n * The answering side allocates **nothing** up front, and that is the whole\n * subtlety: applying a remote offer creates one transceiver per m-line, in\n * m-line order, and browsers do not reuse transceivers the answerer made\n * beforehand. Pre-allocating leaves dead, never-negotiated transceivers sitting\n * in front of the live ones, which is how slot lookup ends up pointing at the\n * wrong media or at nothing.\n *\n * Each adopted transceiver is switched to `sendrecv` so this side may publish on\n * it too; without that a peer that answered could hear but never be heard.\n *\n * @param link - The link that just applied a remote offer.\n */\nexport function adoptTransceivers(link: PeerLink): void {\n link.transceivers = link.pc\n .getTransceivers()\n .filter((transceiver) => transceiver.mid !== null)\n .sort((a, b) => Number(a.mid) - Number(b.mid));\n for (const transceiver of link.transceivers) {\n if (transceiver.direction !== \"sendrecv\") transceiver.direction = \"sendrecv\";\n }\n}\n"],"mappings":"AAwBA,SAAgB,EAAqB,EAA+C,CAChF,OAAO,IAAI,kBAAkB,CACzB,aACA,aAAc,aACd,cAAe,SACnB,CAAC,CACL,CAoBA,SAAgB,EACZ,EACA,EACA,EACe,CACf,IAAM,EAAU,OAAO,EAAY,GAAG,EACtC,GAAI,EAAY,MAAQ,MAAQ,OAAO,UAAU,CAAO,GAAK,EAAM,GAC/D,OAAO,EAAM,GAEjB,IAAM,EAAQ,EAAK,aAAa,QAAQ,CAAW,EACnD,OAAO,GAAS,EAAK,EAAM,IAAU,KAAQ,IACjD,CAYA,eAAsB,EAAgB,EAA+B,CACjE,IAAM,EAAS,EAAK,kBAAkB,OAAO,EAAG,EAAK,kBAAkB,MAAM,EAC7E,IAAK,IAAM,KAAa,EACpB,GAAI,CACA,MAAM,EAAK,GAAG,gBAAgB,CAAS,CAC3C,MAAQ,CAER,CAER,CAQA,eAAsB,EAAgB,EAAgB,EAA0C,CAC5F,GAAI,CAAC,EAAK,YAAa,CACnB,EAAK,kBAAkB,KAAK,CAAI,EAChC,MACJ,CACA,GAAI,CACA,MAAM,EAAK,GAAG,gBAAgB,CAAI,CACtC,MAAQ,CAER,CACJ,CAaA,eAAsB,EAClB,EACA,EACA,EACa,CACb,IAAK,GAAM,CAAC,EAAO,KAAS,EAAM,QAAQ,EAAG,CACzC,IAAM,EAAc,EAAK,aAAa,GAChC,EAAQ,EAAO,IAAI,EAAK,IAAI,GAAK,KACnC,GAAC,GAAgB,EACrB,GAAI,CACA,MAAM,EAAY,OAAO,aAAa,CAAK,CAC/C,MAAQ,CAER,CACJ,CACJ,CAiBA,SAAgB,EAAkB,EAAsB,CACpD,EAAK,aAAe,EAAK,GACpB,gBAAgB,CAAC,CACjB,OAAQ,GAAgB,EAAY,MAAQ,IAAI,CAAC,CACjD,MAAM,EAAG,IAAM,OAAO,EAAE,GAAG,EAAI,OAAO,EAAE,GAAG,CAAC,EACjD,IAAK,IAAM,KAAe,EAAK,aACvB,EAAY,YAAc,aAAY,EAAY,UAAY,WAE1E"}
1
+ {"version":3,"file":"peer-link.cjs","names":[],"sources":["../../src/webrtc/peer-link.ts"],"sourcesContent":["import type { MeshSlot } from \"./mesh-types\";\n\n/** One remote peer's connection and everything the mesh tracks about it. */\nexport interface PeerLink {\n peerId: string;\n pc: RTCPeerConnection;\n /**\n * Transceivers in slot order.\n *\n * Held explicitly rather than re-read from `getTransceivers()` so slot\n * lookup stays O(1) and cannot drift if a browser reorders.\n */\n transceivers: RTCRtpTransceiver[];\n /** Candidates that arrived before the remote description they belong to. */\n pendingCandidates: RTCIceCandidateInit[];\n /** Whether `setRemoteDescription` has landed, which gates the queue. */\n remoteReady: boolean;\n /** Whether an offer is in flight, so a re-entrant call does not stack one. */\n makingOffer: boolean;\n /** Whether this side offers. Exactly one side of a link does. */\n isOfferer: boolean;\n}\n\n/** Open a connection with the policies a mesh needs. */\nexport function createPeerConnection(iceServers: RTCIceServer[]): RTCPeerConnection {\n return new RTCPeerConnection({\n iceServers,\n bundlePolicy: \"max-bundle\",\n rtcpMuxPolicy: \"require\",\n });\n}\n\n/**\n * Resolve which slot a transceiver carries.\n *\n * The offerer allocates the m-lines in slot order, so a transceiver's `mid` is\n * its ordinal and both ends read the same one. That makes `mid` the slot's wire\n * identity, and the **only** identifier correct on both sides of a link.\n *\n * Position in the link's own array is a fallback for a `mid` that is not a plain\n * ordinal, and never the primary: a browser answering an offer appends the\n * negotiated transceivers *after* any it already held, so positional lookup\n * silently resolves to the wrong slot — the camera arriving in the screen tile —\n * or to none at all, dropping the track.\n *\n * @param transceiver - The transceiver a track arrived on.\n * @param link - The link it belongs to.\n * @param slots - The mesh's slot list.\n * @returns The slot, or `null` when neither route names one.\n */\nexport function slotOf(\n transceiver: RTCRtpTransceiver,\n link: PeerLink,\n slots: readonly MeshSlot[],\n): MeshSlot | null {\n const ordinal = Number(transceiver.mid);\n if (transceiver.mid !== null && Number.isInteger(ordinal) && slots[ordinal]) {\n return slots[ordinal];\n }\n const index = link.transceivers.indexOf(transceiver);\n return index >= 0 ? (slots[index] ?? null) : null;\n}\n\n/**\n * Feed a link every candidate that arrived before its remote description.\n *\n * `addIceCandidate` throws while `remoteDescription` is `null`, and candidates\n * routinely beat the offer or answer they belong to. Without the queue the\n * connection loses them and sits in `checking` until it times out — a failure\n * with no error anywhere.\n *\n * @param link - The link whose queue is drained.\n */\nexport async function drainCandidates(link: PeerLink): Promise<void> {\n const queued = link.pendingCandidates.splice(0, link.pendingCandidates.length);\n for (const candidate of queued) {\n try {\n await link.pc.addIceCandidate(candidate);\n } catch {\n /* a candidate the browser rejects is not fatal to the connection */\n }\n }\n}\n\n/**\n * Hand a candidate to the connection, or park it until the description lands.\n *\n * @param link - The link the candidate belongs to.\n * @param init - The candidate, already in `RTCIceCandidateInit` shape.\n */\nexport async function acceptCandidate(link: PeerLink, init: RTCIceCandidateInit): Promise<void> {\n if (!link.remoteReady) {\n link.pendingCandidates.push(init);\n return;\n }\n try {\n await link.pc.addIceCandidate(init);\n } catch {\n /* a candidate the browser rejects is not fatal to the connection */\n }\n}\n\n/**\n * Adopt the transceivers a remote offer created, in `mid` order.\n *\n * The answering side allocates **nothing** up front, and that is the whole\n * subtlety: applying a remote offer creates one transceiver per m-line, in\n * m-line order, and browsers do not reuse transceivers the answerer made\n * beforehand. Pre-allocating leaves dead, never-negotiated transceivers sitting\n * in front of the live ones, which is how slot lookup ends up pointing at the\n * wrong media or at nothing.\n *\n * Each adopted transceiver is switched to `sendrecv` so this side may publish on\n * it too; without that a peer that answered could hear but never be heard.\n *\n * @param link - The link that just applied a remote offer.\n */\nexport function adoptTransceivers(link: PeerLink): void {\n link.transceivers = link.pc\n .getTransceivers()\n .filter((transceiver) => transceiver.mid !== null)\n .sort((a, b) => Number(a.mid) - Number(b.mid));\n for (const transceiver of link.transceivers) {\n if (transceiver.direction !== \"sendrecv\") transceiver.direction = \"sendrecv\";\n }\n}\n"],"mappings":"AAwBA,SAAgB,EAAqB,EAA+C,CAChF,OAAO,IAAI,kBAAkB,CACzB,aACA,aAAc,aACd,cAAe,SACnB,CAAC,CACL,CAoBA,SAAgB,EACZ,EACA,EACA,EACe,CACf,IAAM,EAAU,OAAO,EAAY,GAAG,EACtC,GAAI,EAAY,MAAQ,MAAQ,OAAO,UAAU,CAAO,GAAK,EAAM,GAC/D,OAAO,EAAM,GAEjB,IAAM,EAAQ,EAAK,aAAa,QAAQ,CAAW,EACnD,OAAO,GAAS,EAAK,EAAM,IAAU,KAAQ,IACjD,CAYA,eAAsB,EAAgB,EAA+B,CACjE,IAAM,EAAS,EAAK,kBAAkB,OAAO,EAAG,EAAK,kBAAkB,MAAM,EAC7E,IAAK,IAAM,KAAa,EACpB,GAAI,CACA,MAAM,EAAK,GAAG,gBAAgB,CAAS,CAC3C,MAAQ,CAER,CAER,CAQA,eAAsB,EAAgB,EAAgB,EAA0C,CAC5F,GAAI,CAAC,EAAK,YAAa,CACnB,EAAK,kBAAkB,KAAK,CAAI,EAChC,MACJ,CACA,GAAI,CACA,MAAM,EAAK,GAAG,gBAAgB,CAAI,CACtC,MAAQ,CAER,CACJ,CAiBA,SAAgB,EAAkB,EAAsB,CACpD,EAAK,aAAe,EAAK,GACpB,gBAAgB,CAAC,CACjB,OAAQ,GAAgB,EAAY,MAAQ,IAAI,CAAC,CACjD,MAAM,EAAG,IAAM,OAAO,EAAE,GAAG,EAAI,OAAO,EAAE,GAAG,CAAC,EACjD,IAAK,IAAM,KAAe,EAAK,aACvB,EAAY,YAAc,aAAY,EAAY,UAAY,WAE1E"}
@@ -27,19 +27,11 @@ async function r(e, t) {
27
27
  await e.pc.addIceCandidate(t);
28
28
  } catch {}
29
29
  }
30
- async function i(e, t, n) {
31
- for (let [r, i] of t.entries()) {
32
- let t = e.transceivers[r], a = n.get(i.name) ?? null;
33
- if (t && a) try {
34
- await t.sender.replaceTrack(a);
35
- } catch {}
36
- }
37
- }
38
- function a(e) {
30
+ function i(e) {
39
31
  e.transceivers = e.pc.getTransceivers().filter((e) => e.mid !== null).sort((e, t) => Number(e.mid) - Number(t.mid));
40
32
  for (let t of e.transceivers) t.direction !== "sendrecv" && (t.direction = "sendrecv");
41
33
  }
42
34
  //#endregion
43
- export { r as acceptCandidate, a as adoptTransceivers, i as attachLocalTracks, e as createPeerConnection, n as drainCandidates, t as slotOf };
35
+ export { r as acceptCandidate, i as adoptTransceivers, e as createPeerConnection, n as drainCandidates, t as slotOf };
44
36
 
45
37
  //# sourceMappingURL=peer-link.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"peer-link.js","names":[],"sources":["../../src/webrtc/peer-link.ts"],"sourcesContent":["import type { MeshSlot } from \"./mesh-types\";\n\n/** One remote peer's connection and everything the mesh tracks about it. */\nexport interface PeerLink {\n peerId: string;\n pc: RTCPeerConnection;\n /**\n * Transceivers in slot order.\n *\n * Held explicitly rather than re-read from `getTransceivers()` so slot\n * lookup stays O(1) and cannot drift if a browser reorders.\n */\n transceivers: RTCRtpTransceiver[];\n /** Candidates that arrived before the remote description they belong to. */\n pendingCandidates: RTCIceCandidateInit[];\n /** Whether `setRemoteDescription` has landed, which gates the queue. */\n remoteReady: boolean;\n /** Whether an offer is in flight, so a re-entrant call does not stack one. */\n makingOffer: boolean;\n /** Whether this side offers. Exactly one side of a link does. */\n isOfferer: boolean;\n}\n\n/** Open a connection with the policies a mesh needs. */\nexport function createPeerConnection(iceServers: RTCIceServer[]): RTCPeerConnection {\n return new RTCPeerConnection({\n iceServers,\n bundlePolicy: \"max-bundle\",\n rtcpMuxPolicy: \"require\",\n });\n}\n\n/**\n * Resolve which slot a transceiver carries.\n *\n * The offerer allocates the m-lines in slot order, so a transceiver's `mid` is\n * its ordinal and both ends read the same one. That makes `mid` the slot's wire\n * identity, and the **only** identifier correct on both sides of a link.\n *\n * Position in the link's own array is a fallback for a `mid` that is not a plain\n * ordinal, and never the primary: a browser answering an offer appends the\n * negotiated transceivers *after* any it already held, so positional lookup\n * silently resolves to the wrong slot — the camera arriving in the screen tile —\n * or to none at all, dropping the track.\n *\n * @param transceiver - The transceiver a track arrived on.\n * @param link - The link it belongs to.\n * @param slots - The mesh's slot list.\n * @returns The slot, or `null` when neither route names one.\n */\nexport function slotOf(\n transceiver: RTCRtpTransceiver,\n link: PeerLink,\n slots: readonly MeshSlot[],\n): MeshSlot | null {\n const ordinal = Number(transceiver.mid);\n if (transceiver.mid !== null && Number.isInteger(ordinal) && slots[ordinal]) {\n return slots[ordinal];\n }\n const index = link.transceivers.indexOf(transceiver);\n return index >= 0 ? (slots[index] ?? null) : null;\n}\n\n/**\n * Feed a link every candidate that arrived before its remote description.\n *\n * `addIceCandidate` throws while `remoteDescription` is `null`, and candidates\n * routinely beat the offer or answer they belong to. Without the queue the\n * connection loses them and sits in `checking` until it times out — a failure\n * with no error anywhere.\n *\n * @param link - The link whose queue is drained.\n */\nexport async function drainCandidates(link: PeerLink): Promise<void> {\n const queued = link.pendingCandidates.splice(0, link.pendingCandidates.length);\n for (const candidate of queued) {\n try {\n await link.pc.addIceCandidate(candidate);\n } catch {\n /* a candidate the browser rejects is not fatal to the connection */\n }\n }\n}\n\n/**\n * Hand a candidate to the connection, or park it until the description lands.\n *\n * @param link - The link the candidate belongs to.\n * @param init - The candidate, already in `RTCIceCandidateInit` shape.\n */\nexport async function acceptCandidate(link: PeerLink, init: RTCIceCandidateInit): Promise<void> {\n if (!link.remoteReady) {\n link.pendingCandidates.push(init);\n return;\n }\n try {\n await link.pc.addIceCandidate(init);\n } catch {\n /* a candidate the browser rejects is not fatal to the connection */\n }\n}\n\n/**\n * Publish every held local track onto a link's slots.\n *\n * Called once the transceivers exist — up front for the offerer, after the offer\n * lands for the answerer — so a microphone that was already live when the peer\n * joined starts flowing without waiting for a toggle.\n *\n * @param link - The link to publish onto.\n * @param slots - The mesh's slot list.\n * @param tracks - The current local track per slot name.\n */\nexport async function attachLocalTracks(\n link: PeerLink,\n slots: readonly MeshSlot[],\n tracks: Map<string, MediaStreamTrack | null>,\n): Promise<void> {\n for (const [index, slot] of slots.entries()) {\n const transceiver = link.transceivers[index];\n const track = tracks.get(slot.name) ?? null;\n if (!transceiver || !track) continue;\n try {\n await transceiver.sender.replaceTrack(track);\n } catch {\n /* the browser refused the track; the slot simply stays silent */\n }\n }\n}\n\n/**\n * Adopt the transceivers a remote offer created, in `mid` order.\n *\n * The answering side allocates **nothing** up front, and that is the whole\n * subtlety: applying a remote offer creates one transceiver per m-line, in\n * m-line order, and browsers do not reuse transceivers the answerer made\n * beforehand. Pre-allocating leaves dead, never-negotiated transceivers sitting\n * in front of the live ones, which is how slot lookup ends up pointing at the\n * wrong media or at nothing.\n *\n * Each adopted transceiver is switched to `sendrecv` so this side may publish on\n * it too; without that a peer that answered could hear but never be heard.\n *\n * @param link - The link that just applied a remote offer.\n */\nexport function adoptTransceivers(link: PeerLink): void {\n link.transceivers = link.pc\n .getTransceivers()\n .filter((transceiver) => transceiver.mid !== null)\n .sort((a, b) => Number(a.mid) - Number(b.mid));\n for (const transceiver of link.transceivers) {\n if (transceiver.direction !== \"sendrecv\") transceiver.direction = \"sendrecv\";\n }\n}\n"],"mappings":";AAwBA,SAAgB,EAAqB,GAA+C;CAChF,OAAO,IAAI,kBAAkB;EACzB;EACA,cAAc;EACd,eAAe;CACnB,CAAC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MeshSlot } from \"./mesh-types\";\n\n/** One remote peer's connection and everything the mesh tracks about it. */\nexport interface PeerLink {\n peerId: string;\n pc: RTCPeerConnection;\n /**\n * Transceivers in slot order.\n *\n * Held explicitly rather than re-read from `getTransceivers()` so slot\n * lookup stays O(1) and cannot drift if a browser reorders.\n */\n transceivers: RTCRtpTransceiver[];\n /** Candidates that arrived before the remote description they belong to. */\n pendingCandidates: RTCIceCandidateInit[];\n /** Whether `setRemoteDescription` has landed, which gates the queue. */\n remoteReady: boolean;\n /** Whether an offer is in flight, so a re-entrant call does not stack one. */\n makingOffer: boolean;\n /** Whether this side offers. Exactly one side of a link does. */\n isOfferer: boolean;\n}\n\n/** Open a connection with the policies a mesh needs. */\nexport function createPeerConnection(iceServers: RTCIceServer[]): RTCPeerConnection {\n return new RTCPeerConnection({\n iceServers,\n bundlePolicy: \"max-bundle\",\n rtcpMuxPolicy: \"require\",\n });\n}\n\n/**\n * Resolve which slot a transceiver carries.\n *\n * The offerer allocates the m-lines in slot order, so a transceiver's `mid` is\n * its ordinal and both ends read the same one. That makes `mid` the slot's wire\n * identity, and the **only** identifier correct on both sides of a link.\n *\n * Position in the link's own array is a fallback for a `mid` that is not a plain\n * ordinal, and never the primary: a browser answering an offer appends the\n * negotiated transceivers *after* any it already held, so positional lookup\n * silently resolves to the wrong slot — the camera arriving in the screen tile —\n * or to none at all, dropping the track.\n *\n * @param transceiver - The transceiver a track arrived on.\n * @param link - The link it belongs to.\n * @param slots - The mesh's slot list.\n * @returns The slot, or `null` when neither route names one.\n */\nexport function slotOf(\n transceiver: RTCRtpTransceiver,\n link: PeerLink,\n slots: readonly MeshSlot[],\n): MeshSlot | null {\n const ordinal = Number(transceiver.mid);\n if (transceiver.mid !== null && Number.isInteger(ordinal) && slots[ordinal]) {\n return slots[ordinal];\n }\n const index = link.transceivers.indexOf(transceiver);\n return index >= 0 ? (slots[index] ?? null) : null;\n}\n\n/**\n * Feed a link every candidate that arrived before its remote description.\n *\n * `addIceCandidate` throws while `remoteDescription` is `null`, and candidates\n * routinely beat the offer or answer they belong to. Without the queue the\n * connection loses them and sits in `checking` until it times out — a failure\n * with no error anywhere.\n *\n * @param link - The link whose queue is drained.\n */\nexport async function drainCandidates(link: PeerLink): Promise<void> {\n const queued = link.pendingCandidates.splice(0, link.pendingCandidates.length);\n for (const candidate of queued) {\n try {\n await link.pc.addIceCandidate(candidate);\n } catch {\n /* a candidate the browser rejects is not fatal to the connection */\n }\n }\n}\n\n/**\n * Hand a candidate to the connection, or park it until the description lands.\n *\n * @param link - The link the candidate belongs to.\n * @param init - The candidate, already in `RTCIceCandidateInit` shape.\n */\nexport async function acceptCandidate(link: PeerLink, init: RTCIceCandidateInit): Promise<void> {\n if (!link.remoteReady) {\n link.pendingCandidates.push(init);\n return;\n }\n try {\n await link.pc.addIceCandidate(init);\n } catch {\n /* a candidate the browser rejects is not fatal to the connection */\n }\n}\n\n/**\n * Adopt the transceivers a remote offer created, in `mid` order.\n *\n * The answering side allocates **nothing** up front, and that is the whole\n * subtlety: applying a remote offer creates one transceiver per m-line, in\n * m-line order, and browsers do not reuse transceivers the answerer made\n * beforehand. Pre-allocating leaves dead, never-negotiated transceivers sitting\n * in front of the live ones, which is how slot lookup ends up pointing at the\n * wrong media or at nothing.\n *\n * Each adopted transceiver is switched to `sendrecv` so this side may publish on\n * it too; without that a peer that answered could hear but never be heard.\n *\n * @param link - The link that just applied a remote offer.\n */\nexport function adoptTransceivers(link: PeerLink): void {\n link.transceivers = link.pc\n .getTransceivers()\n .filter((transceiver) => transceiver.mid !== null)\n .sort((a, b) => Number(a.mid) - Number(b.mid));\n for (const transceiver of link.transceivers) {\n if (transceiver.direction !== \"sendrecv\") transceiver.direction = \"sendrecv\";\n }\n}\n"],"mappings":";AAwBA,SAAgB,EAAqB,GAA+C;CAChF,OAAO,IAAI,kBAAkB;EACzB;EACA,cAAc;EACd,eAAe;CACnB,CAAC;AACL;AAoBA,SAAgB,EACZ,GACA,GACA,GACe;CACf,IAAM,IAAU,OAAO,EAAY,GAAG;CACtC,IAAI,EAAY,QAAQ,QAAQ,OAAO,UAAU,CAAO,KAAK,EAAM,IAC/D,OAAO,EAAM;CAEjB,IAAM,IAAQ,EAAK,aAAa,QAAQ,CAAW;CACnD,OAAO,KAAS,IAAK,EAAM,MAAU,OAAQ;AACjD;AAYA,eAAsB,EAAgB,GAA+B;CACjE,IAAM,IAAS,EAAK,kBAAkB,OAAO,GAAG,EAAK,kBAAkB,MAAM;CAC7E,KAAK,IAAM,KAAa,GACpB,IAAI;EACA,MAAM,EAAK,GAAG,gBAAgB,CAAS;CAC3C,QAAQ,CAER;AAER;AAQA,eAAsB,EAAgB,GAAgB,GAA0C;CAC5F,IAAI,CAAC,EAAK,aAAa;EACnB,EAAK,kBAAkB,KAAK,CAAI;EAChC;CACJ;CACA,IAAI;EACA,MAAM,EAAK,GAAG,gBAAgB,CAAI;CACtC,QAAQ,CAER;AACJ;AAiBA,SAAgB,EAAkB,GAAsB;CACpD,EAAK,eAAe,EAAK,GACpB,gBAAgB,CAAC,CACjB,QAAQ,MAAgB,EAAY,QAAQ,IAAI,CAAC,CACjD,MAAM,GAAG,MAAM,OAAO,EAAE,GAAG,IAAI,OAAO,EAAE,GAAG,CAAC;CACjD,KAAK,IAAM,KAAe,EAAK,cAC3B,AAAI,EAAY,cAAc,eAAY,EAAY,YAAY;AAE1E"}