@parrel/ledger 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +793 -2
  3. package/dist/cli/commands.d.ts +51 -0
  4. package/dist/cli/commands.d.ts.map +1 -0
  5. package/dist/cli/commands.js +968 -0
  6. package/dist/cli/commands.js.map +1 -0
  7. package/dist/cli/index.d.ts +24 -0
  8. package/dist/cli/index.d.ts.map +1 -0
  9. package/dist/cli/index.js +35 -0
  10. package/dist/cli/index.js.map +1 -0
  11. package/dist/cli/parrel.d.ts +3 -0
  12. package/dist/cli/parrel.d.ts.map +1 -0
  13. package/dist/cli/parrel.js +5 -0
  14. package/dist/cli/parrel.js.map +1 -0
  15. package/dist/cli/utils/angular-setup.d.ts +14 -0
  16. package/dist/cli/utils/angular-setup.d.ts.map +1 -0
  17. package/dist/cli/utils/angular-setup.js +96 -0
  18. package/dist/cli/utils/angular-setup.js.map +1 -0
  19. package/dist/cli/utils/api-tree-builder.d.ts +24 -0
  20. package/dist/cli/utils/api-tree-builder.d.ts.map +1 -0
  21. package/dist/cli/utils/api-tree-builder.js +146 -0
  22. package/dist/cli/utils/api-tree-builder.js.map +1 -0
  23. package/dist/cli/utils/bundle-reader.d.ts +185 -0
  24. package/dist/cli/utils/bundle-reader.d.ts.map +1 -0
  25. package/dist/cli/utils/bundle-reader.js +518 -0
  26. package/dist/cli/utils/bundle-reader.js.map +1 -0
  27. package/dist/cli/utils/collision-detector.d.ts +21 -0
  28. package/dist/cli/utils/collision-detector.d.ts.map +1 -0
  29. package/dist/cli/utils/collision-detector.js +53 -0
  30. package/dist/cli/utils/collision-detector.js.map +1 -0
  31. package/dist/cli/utils/map-fields.d.ts +42 -0
  32. package/dist/cli/utils/map-fields.d.ts.map +1 -0
  33. package/dist/cli/utils/map-fields.js +90 -0
  34. package/dist/cli/utils/map-fields.js.map +1 -0
  35. package/dist/cli/utils/map-validator.d.ts +42 -0
  36. package/dist/cli/utils/map-validator.d.ts.map +1 -0
  37. package/dist/cli/utils/map-validator.js +119 -0
  38. package/dist/cli/utils/map-validator.js.map +1 -0
  39. package/dist/cli/utils/media-file.d.ts +41 -0
  40. package/dist/cli/utils/media-file.d.ts.map +1 -0
  41. package/dist/cli/utils/media-file.js +72 -0
  42. package/dist/cli/utils/media-file.js.map +1 -0
  43. package/dist/cli/utils/media-validator.d.ts +10 -0
  44. package/dist/cli/utils/media-validator.d.ts.map +1 -0
  45. package/dist/cli/utils/media-validator.js +85 -0
  46. package/dist/cli/utils/media-validator.js.map +1 -0
  47. package/dist/cli/utils/mock-augmenter.d.ts +19 -0
  48. package/dist/cli/utils/mock-augmenter.d.ts.map +1 -0
  49. package/dist/cli/utils/mock-augmenter.js +102 -0
  50. package/dist/cli/utils/mock-augmenter.js.map +1 -0
  51. package/dist/cli/utils/mock-validator.d.ts +27 -0
  52. package/dist/cli/utils/mock-validator.d.ts.map +1 -0
  53. package/dist/cli/utils/mock-validator.js +214 -0
  54. package/dist/cli/utils/mock-validator.js.map +1 -0
  55. package/dist/cli/utils/project-dir.d.ts +24 -0
  56. package/dist/cli/utils/project-dir.d.ts.map +1 -0
  57. package/dist/cli/utils/project-dir.js +32 -0
  58. package/dist/cli/utils/project-dir.js.map +1 -0
  59. package/dist/cli/utils/schema-loader.d.ts +19 -0
  60. package/dist/cli/utils/schema-loader.d.ts.map +1 -0
  61. package/dist/cli/utils/schema-loader.js +101 -0
  62. package/dist/cli/utils/schema-loader.js.map +1 -0
  63. package/dist/cli/utils/server-entry.d.ts +34 -0
  64. package/dist/cli/utils/server-entry.d.ts.map +1 -0
  65. package/dist/cli/utils/server-entry.js +111 -0
  66. package/dist/cli/utils/server-entry.js.map +1 -0
  67. package/dist/cli/utils/sync.d.ts +116 -0
  68. package/dist/cli/utils/sync.d.ts.map +1 -0
  69. package/dist/cli/utils/sync.js +134 -0
  70. package/dist/cli/utils/sync.js.map +1 -0
  71. package/dist/client/index.d.ts +39 -0
  72. package/dist/client/index.d.ts.map +1 -0
  73. package/dist/client/index.js +88 -0
  74. package/dist/client/index.js.map +1 -0
  75. package/dist/core/browser-session.d.ts +5 -0
  76. package/dist/core/browser-session.d.ts.map +1 -0
  77. package/dist/core/browser-session.js +12 -0
  78. package/dist/core/browser-session.js.map +1 -0
  79. package/dist/core/cache.d.ts +80 -0
  80. package/dist/core/cache.d.ts.map +1 -0
  81. package/dist/core/cache.js +95 -0
  82. package/dist/core/cache.js.map +1 -0
  83. package/dist/core/client.d.ts +64 -0
  84. package/dist/core/client.d.ts.map +1 -0
  85. package/dist/core/client.js +281 -0
  86. package/dist/core/client.js.map +1 -0
  87. package/dist/core/config.d.ts +20 -0
  88. package/dist/core/config.d.ts.map +1 -0
  89. package/dist/core/config.js +32 -0
  90. package/dist/core/config.js.map +1 -0
  91. package/dist/core/copy-read.d.ts +25 -0
  92. package/dist/core/copy-read.d.ts.map +1 -0
  93. package/dist/core/copy-read.js +123 -0
  94. package/dist/core/copy-read.js.map +1 -0
  95. package/dist/core/define-ledger.d.ts +38 -0
  96. package/dist/core/define-ledger.d.ts.map +1 -0
  97. package/dist/core/define-ledger.js +65 -0
  98. package/dist/core/define-ledger.js.map +1 -0
  99. package/dist/core/deprecated.d.ts +16 -0
  100. package/dist/core/deprecated.d.ts.map +1 -0
  101. package/dist/core/deprecated.js +14 -0
  102. package/dist/core/deprecated.js.map +1 -0
  103. package/dist/core/env.d.ts +103 -0
  104. package/dist/core/env.d.ts.map +1 -0
  105. package/dist/core/env.js +208 -0
  106. package/dist/core/env.js.map +1 -0
  107. package/dist/core/error-codes.generated.d.ts +12 -0
  108. package/dist/core/error-codes.generated.d.ts.map +1 -0
  109. package/dist/core/error-codes.generated.js +3 -0
  110. package/dist/core/error-codes.generated.js.map +1 -0
  111. package/dist/core/get-content.d.ts +62 -0
  112. package/dist/core/get-content.d.ts.map +1 -0
  113. package/dist/core/get-content.js +86 -0
  114. package/dist/core/get-content.js.map +1 -0
  115. package/dist/core/get-media.d.ts +58 -0
  116. package/dist/core/get-media.d.ts.map +1 -0
  117. package/dist/core/get-media.js +89 -0
  118. package/dist/core/get-media.js.map +1 -0
  119. package/dist/core/manifest.d.ts +38 -0
  120. package/dist/core/manifest.d.ts.map +1 -0
  121. package/dist/core/manifest.js +93 -0
  122. package/dist/core/manifest.js.map +1 -0
  123. package/dist/core/media-proxy.d.ts +41 -0
  124. package/dist/core/media-proxy.d.ts.map +1 -0
  125. package/dist/core/media-proxy.js +219 -0
  126. package/dist/core/media-proxy.js.map +1 -0
  127. package/dist/core/package-info.d.ts +34 -0
  128. package/dist/core/package-info.d.ts.map +1 -0
  129. package/dist/core/package-info.js +39 -0
  130. package/dist/core/package-info.js.map +1 -0
  131. package/dist/core/parrel-error.d.ts +160 -0
  132. package/dist/core/parrel-error.d.ts.map +1 -0
  133. package/dist/core/parrel-error.js +198 -0
  134. package/dist/core/parrel-error.js.map +1 -0
  135. package/dist/core/transform-content.d.ts +42 -0
  136. package/dist/core/transform-content.d.ts.map +1 -0
  137. package/dist/core/transform-content.js +185 -0
  138. package/dist/core/transform-content.js.map +1 -0
  139. package/dist/core/types.d.ts +406 -0
  140. package/dist/core/types.d.ts.map +1 -0
  141. package/dist/core/types.js +11 -0
  142. package/dist/core/types.js.map +1 -0
  143. package/dist/errors/error-messages.generated.d.ts +5 -0
  144. package/dist/errors/error-messages.generated.d.ts.map +1 -0
  145. package/dist/errors/error-messages.generated.js +971 -0
  146. package/dist/errors/error-messages.generated.js.map +1 -0
  147. package/dist/errors/get-error-info.d.ts +29 -0
  148. package/dist/errors/get-error-info.d.ts.map +1 -0
  149. package/dist/errors/get-error-info.js +43 -0
  150. package/dist/errors/get-error-info.js.map +1 -0
  151. package/dist/errors/index.d.ts +4 -0
  152. package/dist/errors/index.d.ts.map +1 -0
  153. package/dist/errors/index.js +4 -0
  154. package/dist/errors/index.js.map +1 -0
  155. package/dist/errors/types.d.ts +19 -0
  156. package/dist/errors/types.d.ts.map +1 -0
  157. package/dist/errors/types.js +2 -0
  158. package/dist/errors/types.js.map +1 -0
  159. package/dist/generated.d.ts +29 -0
  160. package/dist/generated.d.ts.map +1 -0
  161. package/dist/generated.js +29 -0
  162. package/dist/generated.js.map +1 -0
  163. package/dist/index.d.ts +19 -0
  164. package/dist/index.d.ts.map +1 -0
  165. package/dist/index.js +16 -0
  166. package/dist/index.js.map +1 -0
  167. package/dist/mock/dev-media.d.ts +15 -0
  168. package/dist/mock/dev-media.d.ts.map +1 -0
  169. package/dist/mock/dev-media.js +52 -0
  170. package/dist/mock/dev-media.js.map +1 -0
  171. package/dist/mock/file-store.d.ts +44 -0
  172. package/dist/mock/file-store.d.ts.map +1 -0
  173. package/dist/mock/file-store.js +170 -0
  174. package/dist/mock/file-store.js.map +1 -0
  175. package/dist/mock/index.d.ts +4 -0
  176. package/dist/mock/index.d.ts.map +1 -0
  177. package/dist/mock/index.js +3 -0
  178. package/dist/mock/index.js.map +1 -0
  179. package/dist/mock/media-fields.d.ts +25 -0
  180. package/dist/mock/media-fields.d.ts.map +1 -0
  181. package/dist/mock/media-fields.js +54 -0
  182. package/dist/mock/media-fields.js.map +1 -0
  183. package/dist/mock/mock-adapter.d.ts +65 -0
  184. package/dist/mock/mock-adapter.d.ts.map +1 -0
  185. package/dist/mock/mock-adapter.js +431 -0
  186. package/dist/mock/mock-adapter.js.map +1 -0
  187. package/dist/mock/mock-errors.d.ts +18 -0
  188. package/dist/mock/mock-errors.d.ts.map +1 -0
  189. package/dist/mock/mock-errors.js +56 -0
  190. package/dist/mock/mock-errors.js.map +1 -0
  191. package/dist/mock/node-import.d.ts +13 -0
  192. package/dist/mock/node-import.d.ts.map +1 -0
  193. package/dist/mock/node-import.js +16 -0
  194. package/dist/mock/node-import.js.map +1 -0
  195. package/dist/mock/seed-mock-store.d.ts +14 -0
  196. package/dist/mock/seed-mock-store.d.ts.map +1 -0
  197. package/dist/mock/seed-mock-store.js +106 -0
  198. package/dist/mock/seed-mock-store.js.map +1 -0
  199. package/dist/mock/shared-memory-store.d.ts +35 -0
  200. package/dist/mock/shared-memory-store.d.ts.map +1 -0
  201. package/dist/mock/shared-memory-store.js +46 -0
  202. package/dist/mock/shared-memory-store.js.map +1 -0
  203. package/dist/next/dev-rendering-helpers.d.ts +78 -0
  204. package/dist/next/dev-rendering-helpers.d.ts.map +1 -0
  205. package/dist/next/dev-rendering-helpers.js +103 -0
  206. package/dist/next/dev-rendering-helpers.js.map +1 -0
  207. package/dist/next/index.d.ts +35 -0
  208. package/dist/next/index.d.ts.map +1 -0
  209. package/dist/next/index.js +33 -0
  210. package/dist/next/index.js.map +1 -0
  211. package/dist/next/next-cache-adapter.d.ts +11 -0
  212. package/dist/next/next-cache-adapter.d.ts.map +1 -0
  213. package/dist/next/next-cache-adapter.js +12 -0
  214. package/dist/next/next-cache-adapter.js.map +1 -0
  215. package/dist/nuxt/index.d.ts +22 -0
  216. package/dist/nuxt/index.d.ts.map +1 -0
  217. package/dist/nuxt/index.js +57 -0
  218. package/dist/nuxt/index.js.map +1 -0
  219. package/dist/sveltekit/index.d.ts +35 -0
  220. package/dist/sveltekit/index.d.ts.map +1 -0
  221. package/dist/sveltekit/index.js +56 -0
  222. package/dist/sveltekit/index.js.map +1 -0
  223. package/dist/ui/content-editor.d.ts +9 -0
  224. package/dist/ui/content-editor.d.ts.map +1 -0
  225. package/dist/ui/content-editor.js +27 -0
  226. package/dist/ui/content-editor.js.map +1 -0
  227. package/dist/ui/index.d.ts +8 -0
  228. package/dist/ui/index.d.ts.map +1 -0
  229. package/dist/ui/index.js +8 -0
  230. package/dist/ui/index.js.map +1 -0
  231. package/dist/ui/ledger-overlay.d.ts +10 -0
  232. package/dist/ui/ledger-overlay.d.ts.map +1 -0
  233. package/dist/ui/ledger-overlay.js +27 -0
  234. package/dist/ui/ledger-overlay.js.map +1 -0
  235. package/dist/ui/media-uploader.d.ts +9 -0
  236. package/dist/ui/media-uploader.d.ts.map +1 -0
  237. package/dist/ui/media-uploader.js +27 -0
  238. package/dist/ui/media-uploader.js.map +1 -0
  239. package/package.json +134 -6
@@ -0,0 +1,219 @@
1
+ import { getParrelLedgerConfig } from "./config.js";
2
+ import { resolveParrelApiOrigin, resolveParrelSiteOrigin } from "./env.js";
3
+ import { copyTimes } from "./cache.js";
4
+ import { ManifestCache, mediaHash } from "./manifest.js";
5
+ import { parrelHandshakeHeader } from "./package-info.js";
6
+ import { ParrelError } from "./parrel-error.js";
7
+ /** The most bytes of media that the proxy keeps in memory unless `cache.mediaCacheMaxBytes` says otherwise: 50 MB. */
8
+ export const DEFAULT_MEDIA_CACHE_MAX_BYTES = 52_428_800;
9
+ /** Proxied media by service, name and hash. A `Map` keeps the order of insertion, so the first key is the oldest. */
10
+ const mediaCache = new Map();
11
+ let mediaCacheBytes = 0;
12
+ /** Empties the memory cache of the media proxy. Meant for tests. */
13
+ export function clearLedgerMediaCache() {
14
+ mediaCache.clear();
15
+ mediaCacheBytes = 0;
16
+ }
17
+ function storeMedia(key, entry, maxBytes) {
18
+ const previous = mediaCache.get(key);
19
+ if (previous) {
20
+ mediaCacheBytes -= previous.bytes.byteLength;
21
+ mediaCache.delete(key);
22
+ }
23
+ if (entry.bytes.byteLength > maxBytes)
24
+ return;
25
+ while (mediaCacheBytes + entry.bytes.byteLength > maxBytes) {
26
+ const oldest = mediaCache.keys().next();
27
+ if (oldest.done)
28
+ break;
29
+ mediaCacheBytes -= mediaCache.get(oldest.value).bytes.byteLength;
30
+ mediaCache.delete(oldest.value);
31
+ }
32
+ mediaCache.set(key, entry);
33
+ mediaCacheBytes += entry.bytes.byteLength;
34
+ }
35
+ /** `cms/v1/read/{slug}/media/{name}` gives the slug and the media name; any other path is not cached. */
36
+ function parseMediaSegments(segments) {
37
+ if (segments.length !== 6)
38
+ return null;
39
+ const [product, version, read, slug, media, name] = segments;
40
+ if (product !== "cms" || version !== "v1" || read !== "read" || media !== "media")
41
+ return null;
42
+ try {
43
+ return { slug: decodeURIComponent(slug), name: decodeURIComponent(name) };
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ /**
50
+ * The manifest of a service for the media proxy, kept for `manifestTtlSeconds`. `null` when it cannot be read. The
51
+ * manifest is a read, not media, so it carries the `Origin` of the site when one is set; without one it is sent
52
+ * without, and a refusal only means that the file is not kept in memory.
53
+ */
54
+ async function readProxyManifest(origin, slug, ttlSeconds, siteOrigin) {
55
+ try {
56
+ const site = resolveParrelSiteOrigin(siteOrigin);
57
+ return await ManifestCache.getManifest(async () => {
58
+ const response = await fetch(`${origin}/cms/v1/read/${encodeURIComponent(slug)}/manifest`, {
59
+ cache: "no-store",
60
+ headers: { ...parrelHandshakeHeader(), ...(site ? { Origin: site } : {}) },
61
+ });
62
+ if (!response.ok)
63
+ throw new Error(`manifest answered ${response.status}`);
64
+ return (await response.json());
65
+ }, { key: slug, ttlSeconds });
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ /** True when an `If-None-Match` header names `etag` (or `*`), so the browser already has this file. */
72
+ function matchesEtag(ifNoneMatch, etag) {
73
+ if (!ifNoneMatch)
74
+ return false;
75
+ return ifNoneMatch
76
+ .split(",")
77
+ .map((value) => value.trim().replace(/^W[/]/, ""))
78
+ .some((value) => value === etag || value === "*");
79
+ }
80
+ function mediaResponse(body, contentType, etag) {
81
+ const headers = {
82
+ "Content-Type": contentType,
83
+ "Content-Disposition": "inline",
84
+ "X-Frame-Options": "SAMEORIGIN",
85
+ "Cache-Control": "public, max-age=300, stale-while-revalidate=60",
86
+ };
87
+ if (etag)
88
+ headers.ETag = etag;
89
+ return new Response(body, { headers });
90
+ }
91
+ /**
92
+ * Framework-neutral production media proxy.
93
+ *
94
+ * Fetches a media asset from the locked Ledger backend server-side and returns a
95
+ * Web `Response` with headers that let the browser embed every media type
96
+ * (pdf, svg, image, video) same-origin — stripping `X-Frame-Options`/CORS
97
+ * problems. Used by the per-framework media routes (`@parrel/ledger/next`,
98
+ * `/sveltekit`, `/nuxt`). The upstream origin is the Parrel API origin: `options.apiOrigin`, the `apiOrigin`
99
+ * of `defineParrelLedger`, `PARREL_API_ORIGIN` or `https://api.parrel.dev`, in this order.
100
+ *
101
+ * @param segments The path segments after the proxy route
102
+ * Media that the manifest lists is kept in memory by name and hash (up to `cache.mediaCacheMaxBytes` of
103
+ * `defineParrelLedger`, default 50 MB, `0` turns it off, the oldest file goes first). The manifest is read at most once per
104
+ * `cache.manifestTtlSeconds`. While the hash of a file is unchanged the file is served from memory and the service is not
105
+ * asked again. The answer carries `ETag: "<hash>"`, and a request with a matching `If-None-Match` gets `304`.
106
+ *
107
+ * @param options `apiOrigin` overrides the origin for this call. `request` is the request of the route: its `If-None-Match`
108
+ * header is checked against the hash of the file, and `ifNoneMatch` does the same for a framework that has no `Request`.
109
+ * @returns The file. When Ledger answers with an error, the same status, the same Parrel error body and the same
110
+ * content type, so the browser sees the real error code (for example `LE02500001`). When Ledger cannot be reached, a `502` with a JSON
111
+ * body in the Parrel error shape and the code `SD01000003`. A path that is not a media path answers `400`.
112
+ * @throws {ParrelError} `SD00100008` when the origin is not an allowed origin
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * // app/api/cms-media/[...path]/route.ts
117
+ * export async function GET(_request: Request, { params }: { params: Promise<{ path: string[] }> }) {
118
+ * return proxyLedgerMedia((await params).path, { apiOrigin: "http://localhost:18700" });
119
+ * }
120
+ * ```
121
+ */
122
+ export async function proxyLedgerMedia(segments, options = {}) {
123
+ // The upstream origin is the Parrel API origin, so a segment must never be able to climb out of the media path
124
+ // and reach another endpoint of the same origin.
125
+ if (!segments.every(isSafeSegment)) {
126
+ return new Response("Bad request", { status: 400 });
127
+ }
128
+ // The incoming segments already carry the full service path (e.g.
129
+ // `cms/v1/read/{slug}/media/foo.webp`) because they come from the stored media
130
+ // URL's pathname. So build the upstream from the service ORIGIN, not the full
131
+ // base URL — otherwise the `/cms/v1` prefix is duplicated and the fetch 404/401s.
132
+ const config = getParrelLedgerConfig();
133
+ const origin = resolveParrelApiOrigin(options.apiOrigin ?? config?.apiOrigin);
134
+ const upstreamUrl = `${origin}/${segments.join("/")}`;
135
+ // The copy of a file (rulebook LIM-13): fresh for ttlSeconds without any request, then checked against the hash
136
+ // of the file in the manifest, and downloaded again at the latest maxAgeSeconds after its download.
137
+ const maxBytes = config?.cache?.enabled === false ? 0 : (config?.cache?.mediaCacheMaxBytes ?? DEFAULT_MEDIA_CACHE_MAX_BYTES);
138
+ const target = maxBytes > 0 ? parseMediaSegments(segments) : null;
139
+ const times = copyTimes(config ?? {});
140
+ const cacheKey = target ? `${origin}|${target.slug}|${target.name}` : "";
141
+ const now = Date.now();
142
+ let cached = target ? mediaCache.get(cacheKey) : undefined;
143
+ if (cached && now - cached.downloadedAt >= times.maxAgeSeconds * 1000) {
144
+ cached = undefined;
145
+ }
146
+ let hash;
147
+ if (cached && now - cached.checkedAt < times.ttlSeconds * 1000) {
148
+ hash = cached.hash;
149
+ }
150
+ else if (target) {
151
+ const manifest = await readProxyManifest(origin, target.slug, times.manifestTtlSeconds, config?.siteOrigin);
152
+ hash = manifest ? mediaHash(manifest, target.name) : undefined;
153
+ if (cached && hash === cached.hash) {
154
+ cached.checkedAt = now;
155
+ }
156
+ else {
157
+ cached = undefined;
158
+ }
159
+ }
160
+ if (target && hash) {
161
+ const etag = `"${hash}"`;
162
+ const ifNoneMatch = options.ifNoneMatch ?? options.request?.headers.get("if-none-match");
163
+ if (matchesEtag(ifNoneMatch, etag)) {
164
+ return new Response(null, {
165
+ status: 304,
166
+ headers: { ETag: etag, "Cache-Control": "public, max-age=300, stale-while-revalidate=60" },
167
+ });
168
+ }
169
+ if (cached) {
170
+ return mediaResponse(cached.bytes, cached.contentType, etag);
171
+ }
172
+ }
173
+ let upstream;
174
+ try {
175
+ upstream = await fetch(upstreamUrl, { cache: "no-store", headers: parrelHandshakeHeader() });
176
+ }
177
+ catch (cause) {
178
+ return unreachableResponse(cause);
179
+ }
180
+ // An error answer of the service keeps its status, its Parrel error body and its content type, so the browser
181
+ // sees the real error code. Nothing else of the answer is copied, never a cookie. It is not cached.
182
+ if (!upstream.ok) {
183
+ return new Response(upstream.body, {
184
+ status: upstream.status,
185
+ headers: {
186
+ "Content-Type": upstream.headers.get("content-type") ?? "application/json",
187
+ "Cache-Control": "no-store",
188
+ },
189
+ });
190
+ }
191
+ const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
192
+ if (target && hash && maxBytes > 0) {
193
+ // The file is read whole to keep it. One that is larger than the cap is passed on and not kept.
194
+ const bytes = await upstream.arrayBuffer();
195
+ const downloadedAt = Date.now();
196
+ storeMedia(cacheKey, { hash, bytes, contentType, downloadedAt, checkedAt: downloadedAt }, maxBytes);
197
+ return mediaResponse(bytes, contentType, `"${hash}"`);
198
+ }
199
+ return mediaResponse(upstream.body, contentType, hash ? `"${hash}"` : undefined);
200
+ }
201
+ /** The `502` answer for a service that cannot be reached: a Parrel error body with the code `SD01000003`. */
202
+ function unreachableResponse(cause) {
203
+ const error = new ParrelError("SD01000003", "Ledger could not be reached to read media. Check your internet connection and the `apiOrigin` setting (or PARREL_API_ORIGIN), then try again.", { status: 502, codeName: "LEDGER_MEDIA_READ_UNREACHABLE", cause });
204
+ return new Response(JSON.stringify(error.toJSON()), {
205
+ status: 502,
206
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
207
+ });
208
+ }
209
+ function isSafeSegment(segment) {
210
+ let decoded;
211
+ try {
212
+ decoded = decodeURIComponent(segment);
213
+ }
214
+ catch {
215
+ return false;
216
+ }
217
+ return decoded !== "" && decoded !== "." && decoded !== ".." && !/[/\\]/.test(decoded);
218
+ }
219
+ //# sourceMappingURL=media-proxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media-proxy.js","sourceRoot":"","sources":["../../src/core/media-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,MAAM,UAAU,CAAC;AAC3E,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AAC,SAAS,CAAC,CAAC;AAClF,CAAC;AAED,6GAA6G;AAC7G,SAAS,mBAAmB,CAAC,KAAc;IAC1C,MAAM,KAAK,GAAG,IAAI,WAAW,CAC5B,YAAY,EACZ,+IAA+I,EAC/I,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,+BAA+B,EAAE,KAAK,EAAE,CACjE,CAAC;IACF,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;QACnD,MAAM,EAAE,GAAG;QACX,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,eAAe,EAAE,UAAU,EAAE;KAC5E,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,aAAa,CAAC,OAAe;IACrC,IAAI,OAAe,CAAC;IACpB,IAAI,CAAC;QACJ,OAAO,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;IACD,OAAO,OAAO,KAAK,EAAE,IAAI,OAAO,KAAK,GAAG,IAAI,OAAO,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACxF,CAAC"}
@@ -0,0 +1,34 @@
1
+ /** The name of this package, as it appears in the `X-Parrel-Package` header. */
2
+ export declare const PACKAGE_NAME: "@parrel/ledger";
3
+ /** The version of this package. A test checks that it equals the version in `package.json`. */
4
+ export declare const PACKAGE_VERSION = "5.0.0";
5
+ /**
6
+ * The handshake header of Parrel: it tells the service which package and version sent a call, so the service can
7
+ * count and log calls per package. The value is `@parrel/ledger@<version>`.
8
+ *
9
+ * Calls from a server, from the CLI and from a browser always send it, unless the option `sendHandshakeFromBrowser`
10
+ * is `false` in a browser.
11
+ *
12
+ * @returns The header as an object that can be spread into the headers of a request.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * await fetch(url, { headers: { Accept: "application/json", ...parrelHandshakeHeader() } });
17
+ * // X-Parrel-Package: @parrel/ledger@5.0.0
18
+ * ```
19
+ */
20
+ export declare function parrelHandshakeHeader(): {
21
+ "X-Parrel-Package": string;
22
+ };
23
+ /** True when the code runs in a browser page: there is a `window` with a `document`. */
24
+ /** True in a browser: a `window` with a `document`. */
25
+ export declare function runsInBrowser(): boolean;
26
+ /**
27
+ * The handshake headers for one call: always on a server or in the CLI, in a browser unless
28
+ * `sendHandshakeFromBrowser` is `false`.
29
+ *
30
+ * @param sendHandshakeFromBrowser The option of the same name from the `define` call.
31
+ * @returns The header to spread into the request headers, or an empty object.
32
+ */
33
+ export declare function handshakeHeaders(sendHandshakeFromBrowser?: boolean): Record<string, string>;
34
+ //# sourceMappingURL=package-info.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package-info.d.ts","sourceRoot":"","sources":["../../src/core/package-info.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,eAAO,MAAM,YAAY,EAAG,gBAAyB,CAAC;AAEtD,+FAA+F;AAC/F,eAAO,MAAM,eAAe,UAAU,CAAC;AAEvC;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,qBAAqB,IAAI;IAAE,kBAAkB,EAAE,MAAM,CAAA;CAAE,CAEtE;AAED,wFAAwF;AACxF,uDAAuD;AACvD,wBAAgB,aAAa,IAAI,OAAO,CAGvC;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,wBAAwB,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE3F"}
@@ -0,0 +1,39 @@
1
+ /** The name of this package, as it appears in the `X-Parrel-Package` header. */
2
+ export const PACKAGE_NAME = "@parrel/ledger";
3
+ /** The version of this package. A test checks that it equals the version in `package.json`. */
4
+ export const PACKAGE_VERSION = "5.0.0";
5
+ /**
6
+ * The handshake header of Parrel: it tells the service which package and version sent a call, so the service can
7
+ * count and log calls per package. The value is `@parrel/ledger@<version>`.
8
+ *
9
+ * Calls from a server, from the CLI and from a browser always send it, unless the option `sendHandshakeFromBrowser`
10
+ * is `false` in a browser.
11
+ *
12
+ * @returns The header as an object that can be spread into the headers of a request.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * await fetch(url, { headers: { Accept: "application/json", ...parrelHandshakeHeader() } });
17
+ * // X-Parrel-Package: @parrel/ledger@5.0.0
18
+ * ```
19
+ */
20
+ export function parrelHandshakeHeader() {
21
+ return { "X-Parrel-Package": `${PACKAGE_NAME}@${PACKAGE_VERSION}` };
22
+ }
23
+ /** True when the code runs in a browser page: there is a `window` with a `document`. */
24
+ /** True in a browser: a `window` with a `document`. */
25
+ export function runsInBrowser() {
26
+ const scope = globalThis;
27
+ return typeof scope.window !== "undefined" && typeof scope.window.document !== "undefined";
28
+ }
29
+ /**
30
+ * The handshake headers for one call: always on a server or in the CLI, in a browser unless
31
+ * `sendHandshakeFromBrowser` is `false`.
32
+ *
33
+ * @param sendHandshakeFromBrowser The option of the same name from the `define` call.
34
+ * @returns The header to spread into the request headers, or an empty object.
35
+ */
36
+ export function handshakeHeaders(sendHandshakeFromBrowser) {
37
+ return runsInBrowser() && sendHandshakeFromBrowser === false ? {} : parrelHandshakeHeader();
38
+ }
39
+ //# sourceMappingURL=package-info.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package-info.js","sourceRoot":"","sources":["../../src/core/package-info.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,MAAM,CAAC,MAAM,YAAY,GAAG,gBAAyB,CAAC;AAEtD,+FAA+F;AAC/F,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC;AAEvC;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,qBAAqB;IACpC,OAAO,EAAE,kBAAkB,EAAE,GAAG,YAAY,IAAI,eAAe,EAAE,EAAE,CAAC;AACrE,CAAC;AAED,wFAAwF;AACxF,uDAAuD;AACvD,MAAM,UAAU,aAAa;IAC5B,MAAM,KAAK,GAAG,UAAiD,CAAC;IAChE,OAAO,OAAO,KAAK,CAAC,MAAM,KAAK,WAAW,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,QAAQ,KAAK,WAAW,CAAC;AAC5F,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,wBAAkC;IAClE,OAAO,aAAa,EAAE,IAAI,wBAAwB,KAAK,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,qBAAqB,EAAE,CAAC;AAC7F,CAAC"}
@@ -0,0 +1,160 @@
1
+ import type { LedgerErrorCode } from "./error-codes.generated.js";
2
+ /** The page of every error code is at `${DOCS_BASE_URL}/<code>`. */
3
+ export declare const DOCS_BASE_URL = "https://docs.parrel.dev/errors";
4
+ /** One invalid field of a validation error, as the backend reports it. */
5
+ export interface ParrelFieldError {
6
+ /** The path of the field in the request body, for example `email` or `address.postalCode`. */
7
+ readonly field: string;
8
+ /** The code of this field, for example `LE09900002`. */
9
+ readonly code: string;
10
+ /** The name of the code in `UPPER_SNAKE_CASE`. */
11
+ readonly name?: string;
12
+ /** A readable English message. */
13
+ readonly message: string;
14
+ }
15
+ /** Options of the {@link ParrelError} constructor. */
16
+ export interface ParrelErrorOptions {
17
+ /** The HTTP status when the error came from a backend answer. Leave it out for an error raised in the package. */
18
+ status?: number;
19
+ /** The request id of the backend that produced the error. Give it to Parrel support. */
20
+ traceId?: string;
21
+ /** One entry for each invalid field of a validation error. */
22
+ fieldErrors?: readonly ParrelFieldError[];
23
+ /** The documentation page of the code. Default: the page of the code on docs.parrel.dev. */
24
+ docs?: string;
25
+ /** The name of the code in `UPPER_SNAKE_CASE`, when the backend sent it. */
26
+ codeName?: string;
27
+ /** The original error or answer. */
28
+ cause?: unknown;
29
+ }
30
+ /** What {@link ParrelError.toJSON} returns. Absent values are `null`, so the shape never changes. */
31
+ export interface ParrelErrorJson {
32
+ /** The Parrel error code. */
33
+ code: string;
34
+ /** The name of the code in `UPPER_SNAKE_CASE` when it is known, otherwise `ParrelError`. */
35
+ name: string;
36
+ /** The message of the error. */
37
+ message: string;
38
+ /** The HTTP status, or `null` for an error that was raised in the package. */
39
+ status: number | null;
40
+ /** The request id of the backend, or `null`. */
41
+ traceId: string | null;
42
+ /** The invalid fields of a validation error, or `null`. */
43
+ fieldErrors: readonly ParrelFieldError[] | null;
44
+ /** The documentation page of the code. */
45
+ docs: string;
46
+ }
47
+ /**
48
+ * The error that `@parrel/ledger` throws. It carries a stable Parrel error code: branch on `code`, never on
49
+ * the message.
50
+ *
51
+ * A code is two letters for the system, three digits for the area and five digits for the case, for example
52
+ * `SD00100007`. An error that a Parrel backend returned keeps the code, the status and the trace id of the
53
+ * backend. An error that the package found itself has an `SD` code and no status. `error.toJSON()` returns a plain
54
+ * object for logs and API answers.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { ParrelError, isParrelError } from "@parrel/ledger";
59
+ *
60
+ * try {
61
+ * await doSomething();
62
+ * } catch (error) {
63
+ * if (isParrelError(error) && error.status === 404) {
64
+ * showNotFound(error.traceId);
65
+ * } else {
66
+ * throw error;
67
+ * }
68
+ * }
69
+ * ```
70
+ */
71
+ export declare class ParrelError extends Error {
72
+ /** Ten-character Parrel error code such as `SD00100007`. */
73
+ readonly code: LedgerErrorCode;
74
+ /** HTTP status when the error came from a backend answer. Errors raised in the package have none. */
75
+ readonly status?: number;
76
+ /** Request id of the backend that produced the error. Quote it when you contact Parrel support. */
77
+ readonly traceId?: string;
78
+ /** One entry for each invalid field of a validation error. */
79
+ readonly fieldErrors?: readonly ParrelFieldError[];
80
+ /** The documentation page of the code: what it means and what to do. */
81
+ readonly docs: string;
82
+ /** The name of the code in `UPPER_SNAKE_CASE`, when the backend sent it. */
83
+ readonly codeName?: string;
84
+ constructor(code: LedgerErrorCode, message: string, options?: ParrelErrorOptions);
85
+ /**
86
+ * A plain object with `code`, `name`, `message`, `status`, `traceId`, `fieldErrors` and `docs`, for logs and
87
+ * API answers. `JSON.stringify(error)` uses it. `name` is the name of the code when it is known and
88
+ * `ParrelError` otherwise; use `getErrorInfo(code)` from the `/errors` entry to look up the name of any code.
89
+ *
90
+ * @example
91
+ * ```ts
92
+ * console.log(JSON.stringify(error));
93
+ * // {"code":"SD00100007","name":"ParrelError","message":"...","status":null,"traceId":null,"fieldErrors":null,"docs":"https://docs.parrel.dev/errors/SD00100007"}
94
+ * ```
95
+ */
96
+ toJSON(): ParrelErrorJson;
97
+ }
98
+ /**
99
+ * Whether `value` looks like a Parrel error: an object with a `code` in the Parrel format. It checks the shape and
100
+ * never uses `instanceof`, so it also recognises an error from another Parrel package, from another copy of this
101
+ * package or from another realm, where each package has its own `ParrelError` class.
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * import { isParrelError } from "@parrel/ledger";
106
+ *
107
+ * try {
108
+ * await doSomething();
109
+ * } catch (error) {
110
+ * if (isParrelError(error)) {
111
+ * console.error(error.code, error.traceId);
112
+ * }
113
+ * }
114
+ * ```
115
+ */
116
+ export declare function isParrelError(value: unknown): value is ParrelError;
117
+ /** The parts of a `Response` that {@link parseApiError} reads. A `fetch` response fits. */
118
+ export interface ParrelErrorResponse {
119
+ status: number;
120
+ headers: {
121
+ get(name: string): string | null;
122
+ };
123
+ text(): Promise<string>;
124
+ clone?(): ParrelErrorResponse;
125
+ }
126
+ /** An error answer that you already read: the HTTP status and the body. */
127
+ export interface ParrelErrorAnswer {
128
+ status: number;
129
+ /** The parsed JSON body, or its text. */
130
+ body: unknown;
131
+ /** The request id, when it comes from the `X-Request-Id` header. */
132
+ traceId?: string;
133
+ }
134
+ /**
135
+ * Turns an error answer of Ledger into a {@link ParrelError}. It never throws and never rejects, so it is safe to
136
+ * call inside a `catch` block.
137
+ *
138
+ * - A Parrel error body keeps its `code`, `status`, `traceId`, `fieldErrors` and `docs`.
139
+ * - Anything else (free text, an old format, an empty body, an HTML page from a proxy) becomes the code
140
+ * `SD01000012` with the HTTP status of the answer.
141
+ *
142
+ * Pass a `Response` to get a promise; the body is read from a clone, so you can still read the original. Pass the
143
+ * status and the body when you have read them already to get the error at once.
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * import { parseApiError } from "@parrel/ledger";
148
+ *
149
+ * const response = await fetch("https://api.parrel.dev/...");
150
+ * if (!response.ok) {
151
+ * const error = await parseApiError(response);
152
+ * console.error(error.code, error.status, error.traceId);
153
+ * }
154
+ *
155
+ * const sync = parseApiError({ status: 403, body: { code: "LE04000017", message: "Origin not allowed." } });
156
+ * ```
157
+ */
158
+ export declare function parseApiError(response: ParrelErrorResponse): Promise<ParrelError>;
159
+ export declare function parseApiError(answer: ParrelErrorAnswer): ParrelError;
160
+ //# sourceMappingURL=parrel-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parrel-error.d.ts","sourceRoot":"","sources":["../../src/core/parrel-error.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAElE,oEAAoE;AACpE,eAAO,MAAM,aAAa,mCAAmC,CAAC;AAc9D,0EAA0E;AAC1E,MAAM,WAAW,gBAAgB;IAChC,8FAA8F;IAC9F,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,wDAAwD;IACxD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,kDAAkD;IAClD,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,kCAAkC;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CACzB;AAED,sDAAsD;AACtD,MAAM,WAAW,kBAAkB;IAClC,kHAAkH;IAClH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wFAAwF;IACxF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,8DAA8D;IAC9D,WAAW,CAAC,EAAE,SAAS,gBAAgB,EAAE,CAAC;IAC1C,4FAA4F;IAC5F,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oCAAoC;IACpC,KAAK,CAAC,EAAE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