-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost.ps1
More file actions
373 lines (309 loc) · 10.2 KB
/
host.ps1
File metadata and controls
373 lines (309 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
param(
[int]$Port = 8008,
[switch]$Pages
)
$ErrorActionPreference = "Stop"
$projectRoot = $PSScriptRoot
$sourceRoot = Join-Path -Path $projectRoot -ChildPath "src"
$buildRoot = Join-Path -Path $projectRoot -ChildPath "dist"
$hostStateRoot = Join-Path -Path $projectRoot -ChildPath ".host"
$fingerprintPath = Join-Path -Path $hostStateRoot -ChildPath "source-fingerprint.txt"
$nodeModulesPath = Join-Path -Path $projectRoot -ChildPath "node_modules"
$staticServerPath = Join-Path -Path $hostStateRoot -ChildPath "static_server.py"
$devVarsPath = Join-Path -Path $projectRoot -ChildPath ".dev.vars"
function Get-LocalIPv4Addresses {
$addresses = New-Object System.Collections.Generic.List[string]
try {
$interfaces = [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()
foreach ($interface in $interfaces) {
if ($interface.OperationalStatus -ne [System.Net.NetworkInformation.OperationalStatus]::Up) {
continue
}
$properties = $interface.GetIPProperties()
foreach ($unicastAddress in $properties.UnicastAddresses) {
if ($unicastAddress.Address.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) {
continue
}
$ipAddress = $unicastAddress.Address.ToString()
if ($ipAddress -eq "127.0.0.1" -or $ipAddress -like "169.254.*") {
continue
}
$addresses.Add($ipAddress)
}
}
return @($addresses | Select-Object -Unique | Sort-Object)
} catch {
return @()
}
}
function Stop-StaleHttpServerProcesses {
param(
[int]$Port,
[string]$StaticServerPath
)
$escapedStaticServerPath = [Regex]::Escape($StaticServerPath)
$processes = @(Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
Where-Object {
$_.Name -like "python*.exe" -and
(
$_.CommandLine -match "(^| )-m http\.server $Port( |$)" -or
$_.CommandLine -match "$escapedStaticServerPath.*--port $Port( |$)" -or
$_.CommandLine -match "--port $Port.*$escapedStaticServerPath"
)
})
foreach ($process in $processes) {
try {
if ($process.ProcessId -eq $PID) {
continue
}
Stop-Process -Id $process.ProcessId -Force -ErrorAction Stop
Write-Host "Stopped stale Python web server process $($process.ProcessId) on port $Port."
} catch {
Write-Warning "Could not stop stale Python web server process $($process.ProcessId) on port $Port."
}
}
}
function Get-SourceFingerprint {
param(
[string]$Root
)
$hash = [System.Security.Cryptography.SHA256]::Create()
try {
$builder = New-Object System.Text.StringBuilder
$paths = @(
(Join-Path -Path $Root -ChildPath "package.json"),
(Join-Path -Path $Root -ChildPath "package-lock.json"),
(Join-Path -Path $Root -ChildPath "astro.config.mjs"),
(Join-Path -Path $Root -ChildPath "tsconfig.json"),
(Join-Path -Path $Root -ChildPath "src\public\_worker.js"),
(Join-Path -Path $Root -ChildPath "wrangler.toml")
)
if (Test-Path -LiteralPath (Join-Path -Path $Root -ChildPath "src")) {
$paths += Get-ChildItem -LiteralPath (Join-Path -Path $Root -ChildPath "src") -Recurse -File | ForEach-Object {
$_.FullName
}
}
foreach ($path in ($paths | Sort-Object -Unique)) {
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
continue
}
$item = Get-Item -LiteralPath $path
[void]$builder.AppendLine($path)
[void]$builder.AppendLine($item.LastWriteTimeUtc.Ticks.ToString())
[void]$builder.AppendLine($item.Length.ToString())
}
$bytes = [System.Text.Encoding]::UTF8.GetBytes($builder.ToString())
$digest = $hash.ComputeHash($bytes)
return [System.Convert]::ToHexString($digest)
} finally {
$hash.Dispose()
}
}
function Write-HostStateFile {
param(
[string]$Path,
[string]$Content
)
$parentDirectory = Split-Path -Path $Path -Parent
if (-not (Test-Path -LiteralPath $parentDirectory -PathType Container)) {
New-Item -ItemType Directory -Path $parentDirectory -Force | Out-Null
}
[System.IO.File]::WriteAllText($Path, $Content, [System.Text.UTF8Encoding]::new($false))
}
function Convert-BuildOutputLine {
param(
[object]$Line
)
$text = [string]$Line
if ([string]::IsNullOrEmpty($text)) {
return $text
}
$text = [System.Text.RegularExpressions.Regex]::Replace($text, "\x1B\[[0-9;]*[A-Za-z]", "")
$text = $text.Replace("✓", "[ok]")
$text = $text.Replace("✔", "[ok]")
$text = $text.Replace("Ô£ô", "[ok]")
$text = $text.Replace("Ôö£ÔöÇ", "->")
return $text
}
function Test-BuildOutputContainsSpawnEperm {
param(
[object[]]$Lines
)
foreach ($line in $Lines) {
if ([string]$line -match 'spawn EPERM') {
return $true
}
}
return $false
}
function Invoke-AstroBuild {
param(
[string]$ProjectRoot
)
$startInfo = [System.Diagnostics.ProcessStartInfo]::new()
$startInfo.FileName = "node"
$startInfo.WorkingDirectory = $ProjectRoot
$startInfo.UseShellExecute = $false
$startInfo.RedirectStandardOutput = $true
$startInfo.RedirectStandardError = $true
$startInfo.CreateNoWindow = $true
[void]$startInfo.ArgumentList.Add(".\node_modules\astro\bin\astro.mjs")
[void]$startInfo.ArgumentList.Add("build")
$process = [System.Diagnostics.Process]::new()
$process.StartInfo = $startInfo
[void]$process.Start()
$lines = New-Object System.Collections.Generic.List[string]
while (-not $process.HasExited) {
while (-not $process.StandardOutput.EndOfStream) {
$line = $process.StandardOutput.ReadLine()
if ($null -ne $line) {
$lines.Add($line)
Write-Host (Convert-BuildOutputLine $line)
}
}
while (-not $process.StandardError.EndOfStream) {
$line = $process.StandardError.ReadLine()
if ($null -ne $line) {
$lines.Add($line)
Write-Host (Convert-BuildOutputLine $line)
}
}
Start-Sleep -Milliseconds 50
}
while (-not $process.StandardOutput.EndOfStream) {
$line = $process.StandardOutput.ReadLine()
if ($null -ne $line) {
$lines.Add($line)
Write-Host (Convert-BuildOutputLine $line)
}
}
while (-not $process.StandardError.EndOfStream) {
$line = $process.StandardError.ReadLine()
if ($null -ne $line) {
$lines.Add($line)
Write-Host (Convert-BuildOutputLine $line)
}
}
$process.WaitForExit()
return [PSCustomObject]@{
ExitCode = $process.ExitCode
Output = $lines.ToArray()
}
}
function Get-PagesDevArgumentList {
param(
[string]$ProjectRoot,
[string]$BuildRoot,
[string]$DevVarsPath,
[int]$Port
)
$arguments = @(
"wrangler",
"pages",
"dev",
$BuildRoot,
"--cwd",
$ProjectRoot,
"--port",
$Port.ToString(),
"--ip",
"0.0.0.0"
)
if (Test-Path -LiteralPath $DevVarsPath -PathType Leaf) {
$arguments += @("--env-file", $DevVarsPath)
}
foreach ($bindingName in @("GITHUB_TOKEN", "LIKES_HMAC_SECRET", "TURNSTILE_SECRET_KEY")) {
$bindingValue = [Environment]::GetEnvironmentVariable($bindingName)
if (-not [string]::IsNullOrWhiteSpace($bindingValue)) {
$arguments += @("--binding", ("{0}={1}" -f $bindingName, $bindingValue))
}
}
return $arguments
}
if (-not (Test-Path -LiteralPath $sourceRoot -PathType Container)) {
Write-Error "Could not find '$sourceRoot'."
exit 1
}
$currentFingerprint = Get-SourceFingerprint -Root $projectRoot
$cachedFingerprint = if (Test-Path -LiteralPath $fingerprintPath -PathType Leaf) {
(Get-Content -LiteralPath $fingerprintPath -Raw).Trim()
} else {
""
}
$needsBuild = $true
if ($cachedFingerprint -eq $currentFingerprint -and (Test-Path -LiteralPath $buildRoot -PathType Container)) {
$needsBuild = $false
}
if ($needsBuild) {
if (-not (Test-Path -LiteralPath $nodeModulesPath -PathType Container)) {
Write-Host "Installing project dependencies..."
Push-Location $projectRoot
try {
& npm install --ignore-scripts
} finally {
Pop-Location
}
if ($LASTEXITCODE -ne 0) {
Write-Error "Could not install project dependencies."
exit $LASTEXITCODE
}
}
Write-Host "Compiling Astro..."
$buildResult = Invoke-AstroBuild -ProjectRoot $projectRoot
$buildOutput = $buildResult.Output
$buildExitCode = $buildResult.ExitCode
if ($buildExitCode -ne 0) {
if (Test-BuildOutputContainsSpawnEperm -Lines $buildOutput) {
Write-Error "Astro build hit 'spawn EPERM'. In this shell, use the direct Node Astro path rather than wrapper commands."
exit $buildExitCode
}
Write-Error "Astro build failed with exit code $buildExitCode."
exit $buildExitCode
}
Write-HostStateFile -Path $fingerprintPath -Content $currentFingerprint
} else {
Write-Host "Reusing cached Astro build from '$buildRoot'."
}
if (-not (Test-Path -LiteralPath $buildRoot -PathType Container)) {
Write-Error "Astro did not produce a build directory at '$buildRoot'."
exit 1
}
if ($Pages -or -not [string]::IsNullOrWhiteSpace($env:GITHUB_TOKEN) -or (Test-Path -LiteralPath $devVarsPath -PathType Leaf)) {
Write-Host "Serving compiled Astro site through Cloudflare Pages dev at:"
Write-Host " http://127.0.0.1:$Port/"
$localAddresses = Get-LocalIPv4Addresses
foreach ($address in $localAddresses) {
Write-Host (" http://{0}:{1}/" -f $address, $Port)
}
Write-Host "Press Ctrl+C to stop."
$pagesDevArguments = Get-PagesDevArgumentList `
-ProjectRoot $projectRoot `
-BuildRoot $buildRoot `
-DevVarsPath $devVarsPath `
-Port $Port
Push-Location $projectRoot
try {
& npx @pagesDevArguments
} finally {
Pop-Location
}
exit $LASTEXITCODE
}
if (-not (Test-Path -LiteralPath $staticServerPath -PathType Leaf)) {
Write-Error "Could not find static server helper at '$staticServerPath'."
exit 1
}
Write-Host "Serving compiled Astro site at:"
Write-Host " http://127.0.0.1:$Port/"
$localAddresses = Get-LocalIPv4Addresses
foreach ($address in $localAddresses) {
Write-Host (" http://{0}:{1}/" -f $address, $Port)
}
Write-Host "Press Ctrl+C to stop."
Stop-StaleHttpServerProcesses -Port $Port -StaticServerPath $staticServerPath
Push-Location $buildRoot
try {
& python $staticServerPath --port $Port --directory $buildRoot
} finally {
Pop-Location
}