@adea-ai/app-framework 0.26.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +183 -17
- package/dist/app/create-application.d.ts +2 -0
- package/dist/app/create-application.js +6 -0
- package/dist/app/service-registry.js +4 -0
- package/dist/appearance/custom-theme-import.js +43 -7
- package/dist/appearance/custom-theme-library.d.ts +2 -0
- package/dist/appearance/custom-theme-library.js +5 -1
- package/dist/appearance/theme-record-adapter.js +4 -2
- package/dist/appearance/theme-registry.js +7 -1
- package/dist/cli/cef-helper-cli.js +0 -0
- package/dist/cli/create-application-cli.js +4 -2
- package/dist/cli/electrobun-shortcut-patch-cli.js +0 -0
- package/dist/cli/framework-update-cli.js +0 -0
- package/dist/cli/macos-signing-cli.js +0 -0
- package/dist/cli/release-assets-plan-cli.js +0 -0
- package/dist/cli/release-cut-cli.js +0 -0
- package/dist/cli/release-descriptor-staging-cli.js +0 -0
- package/dist/cli/release-finalize-cli.js +0 -0
- package/dist/cli/release-promote-cli.js +0 -0
- package/dist/cli/release-publish-cli.js +0 -0
- package/dist/cli/release-sign-cli.js +0 -0
- package/dist/cli/release-step-cli.js +6 -1
- package/dist/cli/toolchain-identity-cli.js +0 -0
- package/dist/cli/update-helper-cli.js +28 -6
- package/dist/cli/windows-runtime-patch-cli.js +0 -0
- package/dist/desktop/client-asset-manifest.d.ts +47 -0
- package/dist/desktop/client-asset-manifest.js +114 -0
- package/dist/desktop/client-asset-stream.d.ts +10 -0
- package/dist/desktop/client-asset-stream.js +138 -33
- package/dist/desktop/client-assets.d.ts +20 -0
- package/dist/desktop/client-assets.js +132 -22
- package/dist/desktop/client-response-lifecycle.d.ts +22 -0
- package/dist/desktop/client-response-lifecycle.js +233 -0
- package/dist/desktop/desktop-host.d.ts +40 -2
- package/dist/desktop/desktop-host.js +159 -9
- package/dist/framework-source.json +1 -1
- package/dist/installer/command-artifact.d.ts +4 -2
- package/dist/installer/command-artifact.js +119 -19
- package/dist/installer/installer-identity.d.ts +4 -1
- package/dist/installer/installer-identity.js +6 -3
- package/dist/installer/installer-layout.d.ts +2 -0
- package/dist/installer/installer-layout.js +5 -1
- package/dist/installer/linux-process-group.d.ts +13 -0
- package/dist/installer/linux-process-group.js +58 -0
- package/dist/native/darwin-sync.d.ts +7 -0
- package/dist/native/darwin-sync.js +43 -0
- package/dist/native/desktop-build-hook.js +7 -0
- package/dist/native/directory-exchange.d.ts +10 -0
- package/dist/native/directory-exchange.js +90 -0
- package/dist/native/electrobun-source-patch.d.ts +5 -0
- package/dist/native/electrobun-source-patch.js +19 -1
- package/dist/native/posix-launcher-build.d.ts +24 -0
- package/dist/native/posix-launcher-build.js +232 -0
- package/dist/native/posix-tree-removal.d.ts +36 -0
- package/dist/native/posix-tree-removal.js +425 -0
- package/dist/release/release-steps.d.ts +5 -0
- package/dist/release/release-steps.js +2 -1
- package/dist/update-helper.bundle.js +1483 -105
- package/dist/updates/channel-update-manager.d.ts +5 -0
- package/dist/updates/channel-update-manager.js +13 -1
- package/dist/updates/desktop-updater.d.ts +78 -2
- package/dist/updates/desktop-updater.js +320 -37
- package/dist/updates/launch-environment.d.ts +2 -0
- package/dist/updates/launch-environment.js +4 -0
- package/dist/updates/native-file-lock.d.ts +15 -0
- package/dist/updates/native-file-lock.js +189 -0
- package/dist/updates/packaged-launch-admission.d.ts +13 -0
- package/dist/updates/packaged-launch-admission.js +45 -0
- package/dist/updates/packaged-release-config.d.ts +18 -0
- package/dist/updates/packaged-release-config.js +60 -0
- package/dist/updates/packaged-update-startup.d.ts +44 -0
- package/dist/updates/packaged-update-startup.js +81 -0
- package/dist/updates/update-arm.d.ts +9 -8
- package/dist/updates/update-arm.js +227 -62
- package/dist/updates/update-cleanup-error.d.ts +23 -0
- package/dist/updates/update-cleanup-error.js +65 -0
- package/dist/updates/update-download-cleanup.d.ts +11 -0
- package/dist/updates/update-download-cleanup.js +112 -2
- package/dist/updates/update-download-lock.d.ts +20 -0
- package/dist/updates/update-download-lock.js +73 -0
- package/dist/updates/update-download.d.ts +2 -0
- package/dist/updates/update-download.js +7 -3
- package/dist/updates/update-generation-lease.d.ts +6 -0
- package/dist/updates/update-generation-lease.js +14 -0
- package/dist/updates/update-helper.d.ts +11 -2
- package/dist/updates/update-helper.js +322 -13
- package/dist/updates/update-inherited-launch-lease.d.ts +22 -0
- package/dist/updates/update-inherited-launch-lease.js +58 -0
- package/dist/updates/update-instance-lease.d.ts +15 -0
- package/dist/updates/update-instance-lease.js +25 -0
- package/dist/updates/update-launch-gate.d.ts +137 -0
- package/dist/updates/update-launch-gate.js +617 -0
- package/dist/updates/update-launch.js +3 -1
- package/dist/updates/update-lock.d.ts +12 -0
- package/dist/updates/update-lock.js +18 -0
- package/dist/updates/update-manager.d.ts +2 -0
- package/dist/updates/update-manager.js +9 -2
- package/dist/updates/update-marker.d.ts +7 -0
- package/dist/updates/update-marker.js +62 -0
- package/dist/updates/update-preflight-error.d.ts +7 -0
- package/dist/updates/update-preflight-error.js +11 -0
- package/dist/updates/update-process-fence.d.ts +4 -0
- package/dist/updates/update-process-fence.js +85 -73
- package/dist/updates/update-process-liveness.d.ts +2 -0
- package/dist/updates/update-process-liveness.js +11 -0
- package/dist/updates/update-resume.d.ts +37 -3
- package/dist/updates/update-resume.js +839 -23
- package/dist/updates/update-retention-marker.d.ts +67 -0
- package/dist/updates/update-retention-marker.js +165 -0
- package/dist/updates/update-retention-plan.d.ts +25 -0
- package/dist/updates/update-retention-plan.js +54 -0
- package/dist/updates/update-retention-sync.d.ts +34 -0
- package/dist/updates/update-retention-sync.js +83 -0
- package/dist/updates/update-retirement.d.ts +205 -0
- package/dist/updates/update-retirement.js +1485 -0
- package/dist/updates/update-shutdown.d.ts +16 -4
- package/dist/updates/update-shutdown.js +133 -8
- package/dist/updates/update-state-store.d.ts +58 -0
- package/dist/updates/update-state-store.js +139 -0
- package/dist/updates/update-swap-stage.d.ts +1 -1
- package/dist/updates/update-swap-stage.js +85 -14
- package/dist/updates/update-swap.d.ts +45 -2
- package/dist/updates/update-swap.js +207 -17
- package/package.json +31 -1
- package/src/appearance/custom-theme-import.ts +96 -14
- package/src/appearance/custom-theme-library.ts +5 -0
- package/src/appearance/theme-record-adapter.ts +15 -6
- package/src/appearance/theme-registry.ts +8 -1
- package/src/desktop/client-asset-manifest.ts +207 -0
- package/src/desktop/client-asset-stream.ts +193 -32
- package/src/desktop/client-assets.ts +210 -19
- package/src/desktop/client-response-lifecycle.ts +305 -0
- package/src/native/electrobun-posix-launch-lease.patch +398 -0
- package/templates/application/README.md +50 -0
- package/templates/application/electrobun.config.ts +5 -1
- package/templates/application/scripts/build-desktop.ts +4 -0
- package/templates/application/src/bun/index.ts +173 -16
- package/templates/application/vite.config.ts +112 -6
|
@@ -1,6 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import type { Stats } from 'node:fs'
|
|
3
|
+
import { open, readFile, realpath, stat } from 'node:fs/promises'
|
|
2
4
|
import { extname, join, posix, relative, resolve, sep } from 'node:path'
|
|
3
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
createClientAssetStream,
|
|
7
|
+
type ClientAssetVerificationCache,
|
|
8
|
+
verifyClientAssetCached,
|
|
9
|
+
verifyClientAssetDigest,
|
|
10
|
+
} from './client-asset-stream'
|
|
11
|
+
import { parseClientAssetManifest, snapshotClientAssetAllowlist } from './client-asset-manifest'
|
|
12
|
+
export {
|
|
13
|
+
createClientAssetVerificationCache,
|
|
14
|
+
type ClientAssetVerificationCache,
|
|
15
|
+
} from './client-asset-stream'
|
|
16
|
+
export {
|
|
17
|
+
CLIENT_ASSET_ASSET_PATTERN,
|
|
18
|
+
CLIENT_ASSET_CHUNK_PATTERN,
|
|
19
|
+
CLIENT_ASSET_MANIFEST_FILE,
|
|
20
|
+
clientAssetAssetEvidenceKey,
|
|
21
|
+
clientAssetChunkEvidenceKey,
|
|
22
|
+
createClientAssetManifest,
|
|
23
|
+
parseClientAssetManifest,
|
|
24
|
+
snapshotClientAssetAllowlist,
|
|
25
|
+
type ClientAssetManifest,
|
|
26
|
+
} from './client-asset-manifest'
|
|
4
27
|
|
|
5
28
|
const MIME: Record<string, string> = {
|
|
6
29
|
'.html': 'text/html',
|
|
@@ -10,6 +33,12 @@ const MIME: Record<string, string> = {
|
|
|
10
33
|
'.svg': 'image/svg+xml',
|
|
11
34
|
'.json': 'application/json',
|
|
12
35
|
'.png': 'image/png',
|
|
36
|
+
'.jpg': 'image/jpeg',
|
|
37
|
+
'.jpeg': 'image/jpeg',
|
|
38
|
+
'.gif': 'image/gif',
|
|
39
|
+
'.webp': 'image/webp',
|
|
40
|
+
'.avif': 'image/avif',
|
|
41
|
+
'.webmanifest': 'application/manifest+json',
|
|
13
42
|
'.ico': 'image/x-icon',
|
|
14
43
|
'.woff2': 'font/woff2',
|
|
15
44
|
'.wasm': 'application/wasm',
|
|
@@ -21,13 +50,152 @@ export type ClientOptions = {
|
|
|
21
50
|
transformHtml?: (html: string, request: Request) => string
|
|
22
51
|
/** Stream GET bodies instead of buffered snapshots. Use only for immutable asset roots. */
|
|
23
52
|
streamAssets?: boolean
|
|
53
|
+
/** Explicit URL path to SHA-256 allowlist from a generated client asset manifest. */
|
|
54
|
+
immutableAssets?: ReadonlyMap<string, string>
|
|
55
|
+
/** Bounded, host-lifetime cache of successful checks for unchanged immutable files. */
|
|
56
|
+
verificationCache?: ClientAssetVerificationCache
|
|
24
57
|
}
|
|
25
58
|
|
|
26
59
|
const unavailable = (status = 404) =>
|
|
27
60
|
new Response(null, { status, headers: { 'cache-control': 'no-store' } })
|
|
28
61
|
|
|
62
|
+
const IMMUTABLE_CACHE_CONTROL = 'public, max-age=31536000, immutable'
|
|
63
|
+
|
|
64
|
+
/** A caller-owned, immutable client root kept available for the resolver's lifetime. */
|
|
65
|
+
export type RetainedClientAssetRoot = Readonly<{
|
|
66
|
+
root: string
|
|
67
|
+
immutableAssets: ReadonlyMap<string, string>
|
|
68
|
+
}>
|
|
69
|
+
|
|
70
|
+
function clientPath(request: Request): string | undefined {
|
|
71
|
+
try {
|
|
72
|
+
const path = posix.normalize(
|
|
73
|
+
'/' + decodeURIComponent(new URL(request.url).pathname).replaceAll('\\', '/')
|
|
74
|
+
)
|
|
75
|
+
return path.includes('\0') ? undefined : path
|
|
76
|
+
} catch {
|
|
77
|
+
return undefined
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Resolve current assets first, then explicitly retained, content-verified assets.
|
|
83
|
+
* The caller owns every retained root and must keep it immutable and available
|
|
84
|
+
* until the host and every response body using it have stopped.
|
|
85
|
+
*/
|
|
86
|
+
export function createClientAssetResolver(
|
|
87
|
+
options: ClientOptions,
|
|
88
|
+
retained: readonly RetainedClientAssetRoot[] = []
|
|
89
|
+
): (request: Request) => Promise<Response> {
|
|
90
|
+
if (!Array.isArray(retained) || retained.length > 32)
|
|
91
|
+
throw new Error('Invalid retained client asset roots')
|
|
92
|
+
const primaryAssets = new Map(snapshotClientAssetAllowlist(options.immutableAssets))
|
|
93
|
+
const candidates = new Map<string, { root: string; assets: ReadonlyMap<string, string> }[]>()
|
|
94
|
+
for (const item of retained) {
|
|
95
|
+
if (!item || typeof item.root !== 'string' || !item.root)
|
|
96
|
+
throw new Error('Invalid retained client asset root')
|
|
97
|
+
const assets = snapshotClientAssetAllowlist(item.immutableAssets)
|
|
98
|
+
const candidate = { root: item.root, assets }
|
|
99
|
+
for (const [path, digest] of assets) {
|
|
100
|
+
const existing = primaryAssets.get(path)
|
|
101
|
+
if (existing !== undefined && existing !== digest)
|
|
102
|
+
throw new Error('Conflicting retained client asset digest')
|
|
103
|
+
primaryAssets.set(path, digest)
|
|
104
|
+
const roots = candidates.get(path) ?? []
|
|
105
|
+
roots.push(candidate)
|
|
106
|
+
candidates.set(path, roots)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const primary: ClientOptions = {
|
|
110
|
+
...options,
|
|
111
|
+
immutableAssets: primaryAssets,
|
|
112
|
+
...(options.deniedPaths ? { deniedPaths: [...options.deniedPaths] } : {}),
|
|
113
|
+
}
|
|
114
|
+
if (!candidates.size) return (request) => serveClient(request, primary)
|
|
115
|
+
return async (request) => {
|
|
116
|
+
const path = clientPath(request)
|
|
117
|
+
const roots =
|
|
118
|
+
path && (request.method === 'GET' || request.method === 'HEAD')
|
|
119
|
+
? candidates.get(path)
|
|
120
|
+
: undefined
|
|
121
|
+
if (!roots) return serveClient(request, primary)
|
|
122
|
+
const resolveRetained = async () => {
|
|
123
|
+
for (const candidate of roots) {
|
|
124
|
+
let previous: Response
|
|
125
|
+
try {
|
|
126
|
+
previous = await serveClient(request, {
|
|
127
|
+
...primary,
|
|
128
|
+
root: candidate.root,
|
|
129
|
+
immutableAssets: candidate.assets,
|
|
130
|
+
})
|
|
131
|
+
} catch {
|
|
132
|
+
continue
|
|
133
|
+
}
|
|
134
|
+
if (
|
|
135
|
+
previous.status === 200 &&
|
|
136
|
+
previous.headers.get('cache-control') === IMMUTABLE_CACHE_CONTROL
|
|
137
|
+
)
|
|
138
|
+
return previous
|
|
139
|
+
await previous.body?.cancel()
|
|
140
|
+
}
|
|
141
|
+
return unavailable()
|
|
142
|
+
}
|
|
143
|
+
let activeRootMissing = false
|
|
144
|
+
const response = await serveClientInternal(request, primary, async () => {
|
|
145
|
+
activeRootMissing = true
|
|
146
|
+
return resolveRetained()
|
|
147
|
+
})
|
|
148
|
+
if (activeRootMissing) return response
|
|
149
|
+
if (response.status !== 404) {
|
|
150
|
+
// A reused URL must not expose different bytes for the old renderer.
|
|
151
|
+
if (
|
|
152
|
+
response.status !== 200 ||
|
|
153
|
+
response.headers.get('cache-control') === IMMUTABLE_CACHE_CONTROL
|
|
154
|
+
)
|
|
155
|
+
return response
|
|
156
|
+
await response.body?.cancel()
|
|
157
|
+
return unavailable()
|
|
158
|
+
}
|
|
159
|
+
return resolveRetained()
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function matchesManifestDigest(
|
|
164
|
+
path: string,
|
|
165
|
+
metadata: Stats,
|
|
166
|
+
sha256: string,
|
|
167
|
+
verificationCache?: ClientAssetVerificationCache
|
|
168
|
+
): Promise<boolean> {
|
|
169
|
+
try {
|
|
170
|
+
const verify = () => verifyClientAssetDigest(path, metadata, sha256)
|
|
171
|
+
return verificationCache
|
|
172
|
+
? await verifyClientAssetCached(verificationCache, path, metadata, sha256, verify)
|
|
173
|
+
: await verify()
|
|
174
|
+
} catch {
|
|
175
|
+
// Cache eligibility is optional; a transient verification failure must not fail the asset.
|
|
176
|
+
return false
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Missing or invalid manifests disable immutable caching without disrupting the app. */
|
|
181
|
+
export async function loadClientAssetManifest(path: string): Promise<ReadonlyMap<string, string>> {
|
|
182
|
+
try {
|
|
183
|
+
return parseClientAssetManifest(await readFile(path, 'utf8'))
|
|
184
|
+
} catch {
|
|
185
|
+
return new Map()
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
29
189
|
/** Serve a bundled SPA without resolving links outside its root. */
|
|
30
190
|
export async function serveClient(request: Request, options: ClientOptions): Promise<Response> {
|
|
191
|
+
return serveClientInternal(request, options)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function serveClientInternal(
|
|
195
|
+
request: Request,
|
|
196
|
+
options: ClientOptions,
|
|
197
|
+
onMissingRoot?: () => Promise<Response>
|
|
198
|
+
): Promise<Response> {
|
|
31
199
|
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
32
200
|
return new Response(null, {
|
|
33
201
|
status: 405,
|
|
@@ -35,15 +203,8 @@ export async function serveClient(request: Request, options: ClientOptions): Pro
|
|
|
35
203
|
})
|
|
36
204
|
}
|
|
37
205
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
logical = posix.normalize(
|
|
41
|
-
'/' + decodeURIComponent(new URL(request.url).pathname).replaceAll('\\', '/')
|
|
42
|
-
)
|
|
43
|
-
} catch {
|
|
44
|
-
return unavailable()
|
|
45
|
-
}
|
|
46
|
-
if (logical.includes('\0')) return unavailable()
|
|
206
|
+
const logical = clientPath(request)
|
|
207
|
+
if (logical === undefined) return unavailable()
|
|
47
208
|
const denied = (path: string) =>
|
|
48
209
|
(options.deniedPaths ?? []).some((item) => {
|
|
49
210
|
const prefix =
|
|
@@ -55,7 +216,13 @@ export async function serveClient(request: Request, options: ClientOptions): Pro
|
|
|
55
216
|
return prefix === '/' || folded === prefix || folded.startsWith(prefix + '/')
|
|
56
217
|
})
|
|
57
218
|
if (denied(logical)) return unavailable()
|
|
58
|
-
|
|
219
|
+
let root: string
|
|
220
|
+
try {
|
|
221
|
+
root = await realpath(options.root)
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (onMissingRoot && (error as NodeJS.ErrnoException).code === 'ENOENT') return onMissingRoot()
|
|
224
|
+
throw error
|
|
225
|
+
}
|
|
59
226
|
let filePath = resolve(root, '.' + logical)
|
|
60
227
|
const inside = (path: string) => path === root || path.startsWith(root + sep)
|
|
61
228
|
if (!inside(filePath)) return unavailable(403)
|
|
@@ -77,22 +244,37 @@ export async function serveClient(request: Request, options: ClientOptions): Pro
|
|
|
77
244
|
if (denied('/' + relative(root, physical).replaceAll('\\', '/'))) return unavailable()
|
|
78
245
|
const extension = extname(physical).toLowerCase()
|
|
79
246
|
const contentType = MIME[extension] ?? 'application/octet-stream'
|
|
247
|
+
const configuredSha256 = options.immutableAssets?.get(logical)
|
|
248
|
+
const immutableSha256 =
|
|
249
|
+
extension !== '.html' &&
|
|
250
|
+
extension !== '.map' &&
|
|
251
|
+
typeof configuredSha256 === 'string' &&
|
|
252
|
+
/^[a-f0-9]{64}$/.test(configuredSha256)
|
|
253
|
+
? configuredSha256
|
|
254
|
+
: undefined
|
|
80
255
|
if (request.method === 'HEAD' && !(extension === '.html' && options.transformHtml)) {
|
|
81
256
|
// Open the file to check readability and derive the representation length.
|
|
82
257
|
const file = await open(physical, 'r')
|
|
83
|
-
let
|
|
258
|
+
let fileMetadata: Stats
|
|
84
259
|
try {
|
|
85
|
-
|
|
260
|
+
fileMetadata = await file.stat()
|
|
86
261
|
if (!fileMetadata.isFile()) return unavailable()
|
|
87
|
-
size = fileMetadata.size
|
|
88
262
|
} finally {
|
|
89
263
|
await file.close()
|
|
90
264
|
}
|
|
265
|
+
const cacheVerified =
|
|
266
|
+
immutableSha256 !== undefined &&
|
|
267
|
+
(await matchesManifestDigest(
|
|
268
|
+
physical,
|
|
269
|
+
fileMetadata,
|
|
270
|
+
immutableSha256,
|
|
271
|
+
options.verificationCache
|
|
272
|
+
))
|
|
91
273
|
return new Response(null, {
|
|
92
274
|
headers: {
|
|
93
275
|
'content-type': contentType,
|
|
94
|
-
'content-length': String(size),
|
|
95
|
-
'cache-control': 'no-store',
|
|
276
|
+
'content-length': String(fileMetadata.size),
|
|
277
|
+
'cache-control': cacheVerified ? IMMUTABLE_CACHE_CONTROL : 'no-store',
|
|
96
278
|
},
|
|
97
279
|
})
|
|
98
280
|
}
|
|
@@ -102,10 +284,13 @@ export async function serveClient(request: Request, options: ClientOptions): Pro
|
|
|
102
284
|
!(extension === '.html' && options.transformHtml)
|
|
103
285
|
) {
|
|
104
286
|
// The stream rechecks this snapshot against its opened file before reading.
|
|
287
|
+
const cacheVerified =
|
|
288
|
+
immutableSha256 !== undefined &&
|
|
289
|
+
(await matchesManifestDigest(physical, metadata, immutableSha256, options.verificationCache))
|
|
105
290
|
return new Response(createClientAssetStream(physical, metadata), {
|
|
106
291
|
headers: {
|
|
107
292
|
'content-type': contentType,
|
|
108
|
-
'cache-control': 'no-store',
|
|
293
|
+
'cache-control': cacheVerified ? IMMUTABLE_CACHE_CONTROL : 'no-store',
|
|
109
294
|
'content-length': String(metadata.size),
|
|
110
295
|
},
|
|
111
296
|
})
|
|
@@ -115,10 +300,16 @@ export async function serveClient(request: Request, options: ClientOptions): Pro
|
|
|
115
300
|
if (extension === '.html' && options.transformHtml) {
|
|
116
301
|
body = new TextEncoder().encode(options.transformHtml(new TextDecoder().decode(body), request))
|
|
117
302
|
}
|
|
303
|
+
const cacheVerified =
|
|
304
|
+
immutableSha256 !== undefined &&
|
|
305
|
+
createHash('sha256').update(body).digest('hex') === immutableSha256
|
|
118
306
|
return new Response(request.method === 'HEAD' ? null : body, {
|
|
119
307
|
headers: {
|
|
120
308
|
'content-type': contentType,
|
|
121
|
-
'cache-control': 'no-store',
|
|
309
|
+
'cache-control': cacheVerified ? IMMUTABLE_CACHE_CONTROL : 'no-store',
|
|
310
|
+
...(cacheVerified && request.method === 'GET'
|
|
311
|
+
? { 'content-length': String(body.byteLength) }
|
|
312
|
+
: {}),
|
|
122
313
|
...(request.method === 'HEAD' ? { 'content-length': String(body.byteLength) } : {}),
|
|
123
314
|
},
|
|
124
315
|
})
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/** A request was admitted after the response lifecycle had started draining. */
|
|
2
|
+
export class ClientResponseLifecycleClosedError extends Error {
|
|
3
|
+
constructor() {
|
|
4
|
+
super('Client response lifecycle is closed')
|
|
5
|
+
this.name = 'ClientResponseLifecycleClosedError'
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type ClientResponseLifecycleTracker = Readonly<{
|
|
10
|
+
/** Run an asset handler while registering it synchronously for shutdown drain. */
|
|
11
|
+
handle(factory: () => Response | PromiseLike<Response>): Promise<Response>
|
|
12
|
+
/** Pause admission and wait for current handlers and response bodies to finish naturally. */
|
|
13
|
+
quiesce(): Promise<void>
|
|
14
|
+
/** Resume admission after an aborted shutdown that has not started stopping the host. */
|
|
15
|
+
resume(): void
|
|
16
|
+
/** Stop admission, cancel outstanding response bodies, and await all cleanup. */
|
|
17
|
+
stopAndDrain(reason?: unknown): Promise<void>
|
|
18
|
+
readonly accepting: boolean
|
|
19
|
+
}>
|
|
20
|
+
|
|
21
|
+
type TrackedBody = Readonly<{
|
|
22
|
+
cancel(reason: unknown): Promise<void>
|
|
23
|
+
settled: Promise<void>
|
|
24
|
+
}>
|
|
25
|
+
|
|
26
|
+
type TrackedResponseBody = TrackedBody & Readonly<{ stream: ReadableStream<Uint8Array> }>
|
|
27
|
+
|
|
28
|
+
async function cancelClientResponse(response: Response, reason: unknown) {
|
|
29
|
+
const body = response.body
|
|
30
|
+
if (!body) return
|
|
31
|
+
if (body.locked || response.bodyUsed) {
|
|
32
|
+
throw new Error('Cannot safely cancel an untracked client response body')
|
|
33
|
+
}
|
|
34
|
+
await body.cancel(reason)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Tracks async asset handlers and the response bodies they create. The response
|
|
39
|
+
* body returned from `handle` remains owned by its caller for normal reads; this
|
|
40
|
+
* tracker keeps a reader so shutdown can cancel it even while the body is locked
|
|
41
|
+
* by the host's response writer.
|
|
42
|
+
*/
|
|
43
|
+
export function createClientResponseLifecycleTracker(): ClientResponseLifecycleTracker {
|
|
44
|
+
let accepting = true
|
|
45
|
+
let drain: Promise<void> | undefined
|
|
46
|
+
const handlers = new Set<Promise<void>>()
|
|
47
|
+
const bodies = new Set<TrackedBody>()
|
|
48
|
+
const cleanupFailures: unknown[] = []
|
|
49
|
+
let stopped = false
|
|
50
|
+
|
|
51
|
+
const rememberFailure = (error: unknown) => {
|
|
52
|
+
cleanupFailures.push(error)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const trackBody = (source: ReadableStream<Uint8Array>): TrackedResponseBody => {
|
|
56
|
+
const reader = source.getReader()
|
|
57
|
+
const pendingReads = new Set<ReturnType<typeof reader.read>>()
|
|
58
|
+
const pendingPulls = new Set<Promise<void>>()
|
|
59
|
+
let controller: ReadableStreamDefaultController<Uint8Array> | undefined
|
|
60
|
+
let terminal = false
|
|
61
|
+
let sourceClosed = false
|
|
62
|
+
let sourceFailureRecorded = false
|
|
63
|
+
let cancelRequested = false
|
|
64
|
+
let cancelTask: Promise<void> | undefined
|
|
65
|
+
let cancelSettled = false
|
|
66
|
+
let settleBody!: () => void
|
|
67
|
+
const settled = new Promise<void>((resolve) => {
|
|
68
|
+
settleBody = resolve
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const settleIfReady = () => {
|
|
72
|
+
if (
|
|
73
|
+
terminal &&
|
|
74
|
+
pendingReads.size === 0 &&
|
|
75
|
+
pendingPulls.size === 0 &&
|
|
76
|
+
(!cancelRequested || cancelSettled)
|
|
77
|
+
) {
|
|
78
|
+
bodies.delete(body)
|
|
79
|
+
settleBody()
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const closeAfterPendingPulls = () => {
|
|
84
|
+
if (sourceClosed && pendingReads.size === 0 && pendingPulls.size === 0) closeOutput()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const closeOutput = () => {
|
|
88
|
+
if (terminal) return
|
|
89
|
+
terminal = true
|
|
90
|
+
try {
|
|
91
|
+
controller?.close()
|
|
92
|
+
} catch {
|
|
93
|
+
// A concurrent source error or consumer cancellation already closed it.
|
|
94
|
+
}
|
|
95
|
+
settleIfReady()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const errorOutput = (error: unknown) => {
|
|
99
|
+
if (terminal) return
|
|
100
|
+
if (!sourceFailureRecorded) {
|
|
101
|
+
sourceFailureRecorded = true
|
|
102
|
+
rememberFailure(error)
|
|
103
|
+
}
|
|
104
|
+
terminal = true
|
|
105
|
+
try {
|
|
106
|
+
controller?.error(error)
|
|
107
|
+
} catch {
|
|
108
|
+
// The response writer already canceled or closed the output stream.
|
|
109
|
+
}
|
|
110
|
+
settleIfReady()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const cancel = (reason: unknown): Promise<void> => {
|
|
114
|
+
if (cancelTask) return cancelTask
|
|
115
|
+
if (terminal) return settled
|
|
116
|
+
|
|
117
|
+
cancelRequested = true
|
|
118
|
+
try {
|
|
119
|
+
controller?.close()
|
|
120
|
+
} catch {
|
|
121
|
+
// The output stream may already be closed or errored.
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
let operation: Promise<void>
|
|
125
|
+
try {
|
|
126
|
+
operation = reader.cancel(reason)
|
|
127
|
+
} catch (error) {
|
|
128
|
+
operation = Promise.reject(error)
|
|
129
|
+
}
|
|
130
|
+
cancelTask = operation
|
|
131
|
+
.then(
|
|
132
|
+
() => {},
|
|
133
|
+
(error: unknown) => {
|
|
134
|
+
rememberFailure(error)
|
|
135
|
+
throw error
|
|
136
|
+
}
|
|
137
|
+
)
|
|
138
|
+
.finally(() => {
|
|
139
|
+
cancelSettled = true
|
|
140
|
+
terminal = true
|
|
141
|
+
settleIfReady()
|
|
142
|
+
})
|
|
143
|
+
return cancelTask
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const body: TrackedBody = { cancel, settled }
|
|
147
|
+
bodies.add(body)
|
|
148
|
+
|
|
149
|
+
const output = new ReadableStream<Uint8Array>(
|
|
150
|
+
{
|
|
151
|
+
start(value) {
|
|
152
|
+
controller = value
|
|
153
|
+
},
|
|
154
|
+
pull(value) {
|
|
155
|
+
if (terminal || cancelRequested) return
|
|
156
|
+
let operation!: Promise<void>
|
|
157
|
+
operation = Promise.resolve().then(async () => {
|
|
158
|
+
let read: ReturnType<typeof reader.read> | undefined
|
|
159
|
+
try {
|
|
160
|
+
read = reader.read()
|
|
161
|
+
pendingReads.add(read)
|
|
162
|
+
const result = await read
|
|
163
|
+
if (cancelRequested || terminal) return
|
|
164
|
+
if (result.done) {
|
|
165
|
+
sourceClosed = true
|
|
166
|
+
closeOutput()
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
value.enqueue(result.value)
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (!cancelRequested) errorOutput(error)
|
|
172
|
+
} finally {
|
|
173
|
+
if (read) pendingReads.delete(read)
|
|
174
|
+
pendingPulls.delete(operation)
|
|
175
|
+
closeAfterPendingPulls()
|
|
176
|
+
settleIfReady()
|
|
177
|
+
}
|
|
178
|
+
})
|
|
179
|
+
pendingPulls.add(operation)
|
|
180
|
+
return operation
|
|
181
|
+
},
|
|
182
|
+
cancel(reason) {
|
|
183
|
+
return cancel(reason)
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
// A zero-sized queue prevents the wrapper from reading ahead of its consumer.
|
|
187
|
+
{ highWaterMark: 0 }
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
// `closed` observes source errors and empty completion even before the host
|
|
191
|
+
// asks to read the wrapped response body.
|
|
192
|
+
void reader.closed.then(
|
|
193
|
+
() => {
|
|
194
|
+
if (!cancelRequested) {
|
|
195
|
+
sourceClosed = true
|
|
196
|
+
closeAfterPendingPulls()
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
(error: unknown) => {
|
|
200
|
+
if (!cancelRequested) errorOutput(error)
|
|
201
|
+
}
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
return { ...body, stream: output }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const handle = (factory: () => Response | PromiseLike<Response>): Promise<Response> => {
|
|
208
|
+
if (!accepting) return Promise.reject(new ClientResponseLifecycleClosedError())
|
|
209
|
+
|
|
210
|
+
let releaseHandler!: () => void
|
|
211
|
+
const handler = new Promise<void>((resolve) => {
|
|
212
|
+
releaseHandler = resolve
|
|
213
|
+
})
|
|
214
|
+
handlers.add(handler)
|
|
215
|
+
|
|
216
|
+
return (async () => {
|
|
217
|
+
try {
|
|
218
|
+
const response = await factory()
|
|
219
|
+
if (!(response instanceof Response))
|
|
220
|
+
throw new TypeError('Asset handler did not return a Response')
|
|
221
|
+
|
|
222
|
+
if (!accepting) {
|
|
223
|
+
try {
|
|
224
|
+
await cancelClientResponse(response, new ClientResponseLifecycleClosedError())
|
|
225
|
+
} catch (error) {
|
|
226
|
+
rememberFailure(error)
|
|
227
|
+
throw error
|
|
228
|
+
}
|
|
229
|
+
throw new ClientResponseLifecycleClosedError()
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (!response.body) return response
|
|
233
|
+
if (response.body.locked || response.bodyUsed) {
|
|
234
|
+
const error = new Error('Cannot track a locked or consumed client response body')
|
|
235
|
+
rememberFailure(error)
|
|
236
|
+
throw error
|
|
237
|
+
}
|
|
238
|
+
const tracked = trackBody(response.body)
|
|
239
|
+
try {
|
|
240
|
+
return new Response(tracked.stream, {
|
|
241
|
+
status: response.status,
|
|
242
|
+
statusText: response.statusText,
|
|
243
|
+
headers: response.headers,
|
|
244
|
+
})
|
|
245
|
+
} catch (error) {
|
|
246
|
+
// The tracked source remains registered so drain can still cancel it.
|
|
247
|
+
rememberFailure(error)
|
|
248
|
+
throw error
|
|
249
|
+
}
|
|
250
|
+
} finally {
|
|
251
|
+
handlers.delete(handler)
|
|
252
|
+
releaseHandler()
|
|
253
|
+
}
|
|
254
|
+
})()
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const quiesce = () => {
|
|
258
|
+
if (stopped) return Promise.reject(new ClientResponseLifecycleClosedError())
|
|
259
|
+
accepting = false
|
|
260
|
+
// With admission paused, active handlers can only settle or cancel their
|
|
261
|
+
// late response. No handler can add a new tracked body after this snapshot.
|
|
262
|
+
return Promise.all([...handlers, ...[...bodies].map((body) => body.settled)]).then(() => {})
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const resume = () => {
|
|
266
|
+
if (stopped) throw new ClientResponseLifecycleClosedError()
|
|
267
|
+
accepting = true
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const stopAndDrain = (reason: unknown = new ClientResponseLifecycleClosedError()) => {
|
|
271
|
+
accepting = false
|
|
272
|
+
if (drain) return drain
|
|
273
|
+
stopped = true
|
|
274
|
+
|
|
275
|
+
const pendingHandlers = [...handlers]
|
|
276
|
+
const pendingBodies = [...bodies]
|
|
277
|
+
const cancellations = pendingBodies.map((body) => body.cancel(reason))
|
|
278
|
+
drain = (async () => {
|
|
279
|
+
const results = await Promise.allSettled([
|
|
280
|
+
...pendingHandlers,
|
|
281
|
+
...pendingBodies.map((body) => body.settled),
|
|
282
|
+
...cancellations,
|
|
283
|
+
])
|
|
284
|
+
const failures = results.flatMap((result) =>
|
|
285
|
+
result.status === 'rejected' ? [result.reason] : []
|
|
286
|
+
)
|
|
287
|
+
failures.push(...cleanupFailures)
|
|
288
|
+
const uniqueFailures = [...new Set(failures)]
|
|
289
|
+
if (uniqueFailures.length > 0) {
|
|
290
|
+
throw new AggregateError(uniqueFailures, 'Client response cleanup failed')
|
|
291
|
+
}
|
|
292
|
+
})()
|
|
293
|
+
return drain
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
handle,
|
|
298
|
+
quiesce,
|
|
299
|
+
resume,
|
|
300
|
+
stopAndDrain,
|
|
301
|
+
get accepting() {
|
|
302
|
+
return accepting
|
|
303
|
+
},
|
|
304
|
+
}
|
|
305
|
+
}
|