Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*//** Local mock and passthrough proxy for the Copilot policy endpoints. */importtype{ IncomingMessage, ServerResponse }from'node:http';importtype{ EndpointDef, EndpointResponseMode }from'./endpoints';const http =require('node:http')astypeofimport('node:http');const https =require('node:https')astypeofimport('node:https');const fs =require('node:fs'
os
path
fileURLToPath
stripTypeScriptTypes
endpoints EndpointDef
path__dirname
path
path
path
path__dirname
args processargv
argshost
argsschema processenv
argsupstream processenv
argshelp
process
path
path
path
path
path__dirname
status
body
mode EndpointResponseMode
active
state
endpoint
preset
status
body
mode EndpointResponseMode
active
at
method
path
outcome
status
requestLog LogEntry
server httpreq res
url requrl
pathname urlpathname
pathname pathname
req
res error
req res pathname
reqmethod pathname
pathname res
pathname
res
res
endpoint endpointsendpoint pathname endpointpath
endpoint urlsearchParams
res
reqmethod reqmethod
res
res
endpoint stateendpointidactive
entry stateendpointid
res
reqmethod
res
res
reqmethod
req res pathname entry
req res url
e
res error e
res ServerResponse
res
res
res
res
res
req IncomingMessage res ServerResponse pathname
pathname reqmethod
res
pathname pathname reqmethod
res
name
stateUpdate
single endpoint preset status body mode active
bulk endpoints endpoint active endpoint active
routes
method path purpose
method path purpose
method path purpose
method path purpose
method path purpose
method path purpose
method path purpose
method path purpose
method path purpose
pathname reqmethod
req err raw
err
res error err
payload
payload raw
e
res error
result payload
resultok
res error resulterror
res
pathname reqmethod
res
pathname reqmethod
result res result
e res error e
pathname reqmethod
res
e
res error e
pathname reqmethod
res entries requestLog
pathname reqmethod
requestLog
res entries requestLog
pathname reqmethod
res
e
res error e
pathname reqmethod
res
e
res error e
res error
payload ok ok error
payload
ok error
rawUpdates
Objectpayload
unknownKeys Objectpayloadkey key
unknownKeyslength
ok error
payloadendpoints payloadendpointslength
ok error
rawUpdates payloadendpoints
rawUpdates payload
updates EndpointUpdate
seen
index rawUpdate rawUpdates
prefix rawUpdateslength
rawUpdate
ok error
unknownKeys ObjectrawUpdatekey key
unknownKeyslength
ok error
rawUpdateendpoint
ok error
seenrawUpdateendpoint
ok error
seenrawUpdateendpoint
def endpointsendpoint endpointid rawUpdateendpoint
def
ok error
key ObjectrawUpdate key
ok error
ObjectrawUpdate
rawUpdatepreset
ok error
defpresetspreset presetid rawUpdatepreset
ok error
ObjectrawUpdate
rawUpdatestatus NumberrawUpdatestatus rawUpdatestatus rawUpdatestatus
ok error
ObjectrawUpdate rawUpdateactive
ok error
ObjectrawUpdate rawUpdatemode
ok error
update EndpointUpdate endpoint rawUpdateendpoint
rawUpdatepreset
updatepreset rawUpdatepreset
rawUpdatestatus
updatestatus rawUpdatestatus
ObjectrawUpdate
updatebody rawUpdatebody
rawUpdatemode
updatemode rawUpdatemode
rawUpdateactive
updateactive rawUpdateactive
updatesupdate
nextState
id entry state
nextStateid status entrystatus body entrybody mode entrymode active entryactive
update updates
def endpointsendpoint endpointid updateendpoint
entry nextStateupdateendpoint
updatepreset
preset defpresetscandidate candidateid updatepreset
entrystatus presetstatus
entrybody presetbody
entryactive
updatestatus
entrystatus updatestatus
Objectupdate
entrybody updatebody
updatemode
entrymode updatemode
updateactive
entryactive updateactive
id entry nextState
stateid entry
ok
state
endpoint endpoints
preset endpointpresets
stateendpointid
status presetstatus
body preset presetbody
mode
active endpointmockedByDefault
req IncomingMessage
origin reqheadersorigin
origin
origin reqheadershost
originorigin origin
req IncomingMessage res ServerResponse url
target urlpathname urlsearch
transport targetprotocol http https
headers reqheaders
headershost targethost
connectionHeaders headersconnection headersconnection headersconnection
hopByHopHeaders
connectionHeadersvalue valuevalue valueBoolean
header hopByHopHeaders
headersheader
headers
upstreamReq transporttarget method reqmethod headers upstreamRes
req urlpathname upstreamResstatusCode
upstreamRes error
req urlpathname
reserror
resupstreamResstatusCode upstreamResheaders
upstreamResres
upstreamReq e
req urlpathname
resheadersSent
res
res error
requpstreamReq
server error
Reflecterror
processexitCode
error
server
base
dirs
base rest
base
dirspathbase rest
processenv
processplatform
pathos
processplatform
processenv pathos
processenv pathos
dirs
cleared dir files missing
cleared dir files
missing
dir
entries
entries fsdir
error
Reflecterror
missingdir
error
fsdir recursive force
cleared dir files entrieslength
cleared missing
req IncomingMessage pathname outcome LogEntry status
requestLog at Date method reqmethod path pathname outcome status
requestLoglength
requestLoglength
endpoint EndpointDef
source resolved ok schema error
source
source
res source
resok
source resolved source ok error
source resolved source ok schema res
filePath source
source
pathprocess source
pathsource filePath
source resolved filePath ok error
fsfilePath
source resolved filePath ok error
schema fsfilePath
source resolved filePath ok schema
e
source resolved source ok error e emessage e
candidates
primaryCheckout
primaryCheckout
candidatespathpathprimaryCheckout
candidates
pathprocess
path
candidatescandidate fscandidate candidates
dotGit path
fsdotGit
match fsdotGit
match
gitDir path match
pathgitDir gitDir
pathgitDir
pathgitDir
gitDir pathgitDir
endpoints endpointse
id eid
label elabel
path epath
productKey eproductKey
description edescription
schema eschema
url e
presets epresets
status stateeidstatus
body stateeidbody
mode stateeidmode
active stateeidactive
wired
overridesPath
overridesSnippet
baseUrl
upstream
cacheDirs
product fs
baseAgent productdefaultChatAgent
defaultChatAgent baseAgent
Record
urls Record
endpoint endpoints
urlsendpointproductKey endpoint
urls
overrides
overrides fs
agent overridesdefaultChatAgent
agent
urls
Objecturlskey agentkey urlskey
product fs
baseAgent productdefaultChatAgent
fs
fs
overrides
overrides fs
overrides
existingAgent overridesdefaultChatAgent baseAgent
overridesdefaultChatAgent
baseAgent
existingAgent
fs overrides
fs
fs
fs force
overrides
overrides fs
overridesdefaultChatAgent
product fs
baseAgent productdefaultChatAgent
agent overridesdefaultChatAgent
endpoint endpoints
baseAgentendpointproductKey
agentendpointproductKey
agentendpointproductKey baseAgentendpointproductKey
agent baseAgent
overridesdefaultChatAgent
overridesdefaultChatAgent agent
Objectoverrideslength
fs force
fs overrides
filePath res ServerResponse
source Buffer
source fsfilePath
res error
filePath
source source
res filePath
ressource
filePath
pathfilePath
res ServerResponse status obj
resstatus
resobj
req IncomingMessage res ServerResponse pathname entry EndpointState
entrymode
req pathname entrystatus
res entrystatus entrybody
req pathname entrystatus
resentrystatus
res
req pathname
res
req pathname
timer res
timer
res timer
value value EndpointResponseMode
value value value value
req IncomingMessage err Error raw
raw
req chunk raw chunk rawlength req
req raw
req err err
value value Record
value value value
a Record b Record
ak Objecta
bk Objectb
aklength bklength
akk ak bk
value
value
e
e emessage e
value
value value value
host
schema
upstream
help
argv ServerArgs
out ServerArgs help
i i argvlength i
argument argvi
argument
outhelp
argument
key inline argument
key key key
next argvi
value inline next next next
value
outkey value
inline
i
out
message
process
`${prefix}.status must be an integer from 200 to 599.`
}
;
}
}
if
(
.
hasOwn
(
,
'active'
)
&&
typeof
.
!==
'boolean'
)
{
return
{
:
false
,
:
`${prefix}.active must be a boolean.`
}
;
}
if
(
.
hasOwn
(
,
'mode'
)
&&
!
isEndpointResponseMode
(
.
)
)
{
return
{
:
false
,
:
`${prefix}.mode must be one of: json, malformed-json, disconnect, timeout.`
}
;
}
const
:
=
{
:
.
}
;
if
(
typeof
.
===
'string'
)
{
.
=
.
;
}
if
(
typeof
.
===
'number'
)
{
.
=
.
;
}
if
(
.
hasOwn
(
,
'body'
)
)
{
.
=
.
;
}
if
(
isEndpointResponseMode
(
.
)
)
{
.
=
.
;
}
if
(
typeof
.
===
'boolean'
)
{
.
=
.
;
}
.
push
(
)
;
}
const
=
new
Map<string, EndpointState>
(
)
;
for
(
const
[
,
]
of
)
{
.
set
(
,
{
:
.
,
:
clone
(
.
)
,
:
.
,
:
.
}
)
;
}
for
(
const
of
)
{
const
=
.
find
(
=>
.
===
.
)
!
;
const
=
.
get
(
.
)
!
;
if
(
.
!==
undefined
)
{
const
=
.
.
find
(
=>
.
===
.
)
!
;
.
=
.
??
200
;
.
=
clone
(
.
)
;
.
=
true
;
}
if
(
.
!==
undefined
)
{
.
=
.
;
}
if
(
.
hasOwn
(
,
'body'
)
)
{
.
=
clone
(
.
)
;
}
if
(
.
!==
undefined
)
{
.
=
.
;
}
if
(
.
!==
undefined
)
{
.
=
.
;
}
}
for
(
const
[
,
]
of
)
{
.
set
(
,
)
;
}
return
{
:
true
}
;
}
function
resetEndpointState
(
)
:
void
{
.
clear
(
)
;
for
(
const
of
)
{
const
=
.
[
0
]
;
.
set
(
.
,
{
:
?.
??
200
,
:
?
clone
(
.
)
:
{
}
,
:
'json'
,
:
.
===
true
}
)
;
}
}
function
isAllowedControlOrigin
(
:
)
:
boolean
{
const
=
.
.
;
if
(
!
)
{
return
true
;
}
if
(
Array
.
isArray
(
)
||
!
.
.
)
{
return
false
;
}
try
{
return
new
URL
(
)
.
===
new
URL
(
`http://${req.headers.host}`
)
.
;
}
catch
{
return
false
;
}
}
/**
* Forward a request to the real upstream API and stream the response back, so
* anything this server is not deliberately faking still behaves normally.
*/
function
passthrough
(
:
,
:
,
:
URL
)
:
void
{
const
=
new
URL
(
.
+
.
,
UPSTREAM
)
;
const
=
.
===
'http:'
?
:
;
const
=
{
...
.
}
;
// Rewrite Host so upstream TLS/vhost routing works, and drop hop-by-hop
// headers that only described the connection to this server. The client's
// Authorization header is forwarded untouched so the response is real.
.
=
.
;
const
=
Array
.
isArray
(
.
)
?
.
:
[
.
??
''
]
;
const
=
[
'connection'
,
'keep-alive'
,
'proxy-authenticate'
,
'proxy-authorization'
,
'proxy-connection'
,
'te'
,
'trailer'
,
'transfer-encoding'
,
'upgrade'
,
...
.
flatMap
(
=>
.
split
(
','
)
)
.
map
(
=>
.
trim
(
)
.
toLowerCase
(
)
)
.
filter
(
)
,
]
;
for
(
const
of
)
{
delete
[
]
;
}
// Never negotiate compression on the client's behalf: identity keeps the
// streamed bytes readable in a proxy UI.
delete
[
'accept-encoding'
]
;
const
=
.
request
(
,
{
:
.
,
}
,
=>
{
record
(
,
.
,
'passthrough'
,
.
??
0
)
;
.
on
(
'error'
,
=>
{
record
(
,
.
,
'upstream-error'
,
502
)
;
.
destroy
(
)
;
}
)
;
.
writeHead
(
.
??
502
,
.
)
;
.
pipe
(
)
;
}
)
;
.
on
(
'error'
,
=>
{
record
(
,
.
,
'upstream-error'
,
502
)
;
if
(
.
)
{
.
end
(
)
;
}
else
{
sendJson
(
,
502
,
{
:
`Upstream request to ${target.host} failed: ${errorMessage(e)}`
}
)
;
}
}
)
;
.
pipe
(
)
;
}
.
on
(
'error'
,
=>
{
if
(
.
get
(
,
'code'
)
===
'EADDRINUSE'
)
{
console
.
error
(
`\n Error: server already running at http://${HOST}:${PORT}/\n`
)
;
.
=
1
;
return
;
}
throw
;
}
)
;
.
listen
(
PORT
,
HOST
,
(
)
=>
{
const
=
`http://${HOST}:${PORT}`
;
console
.
log
(
''
)
;
console
.
log
(
' Mock Copilot policy endpoints dev server'
)
;
console
.
log
(
' ----------------------------------------'
)
;
console
.
log
(
''
)
;
console
.
log
(
` Open the GUI: ${base}/`
)
;
console
.
log
(
' Configure endpoint mocking and client routing in the GUI.'
)
;
console
.
log
(
''
)
;
console
.
log
(
` Upstream ${UPSTREAM} (anything not mocked is proxied here)`
)
;
console
.
log
(
` Schema ${SCHEMA_SOURCE}`
)
;
console
.
log
(
''
)
;
}
)
;
function
printHelp
(
)
:
void
{
console
.
log
(
''
)
;
console
.
log
(
' Mock Copilot policy endpoints dev server.'
)
;
console
.
log
(
''
)
;
console
.
log
(
' Usage:'
)
;
console
.
log
(
' npm run mock-policy-server [-- <options>]'
)
;
console
.
log
(
''
)
;
console
.
log
(
' Options:'
)
;
console
.
log
(
' --host <addr> Address to bind (default 127.0.0.1)'
)
;
console
.
log
(
' --upstream <url> Real API that un-mocked requests are proxied to'
/**
* Directories the Copilot runtime may use for its managed-settings disk cache.
*
* Mirrors `path_helpers::copilot_cache_home` +
* `managed_settings_cache::CACHE_SUBDIR` in copilot-agent-runtime:
* `COPILOT_CACHE_HOME` wins outright, otherwise the platform cache base is
* `~/Library/Caches` (macOS), `%LOCALAPPDATA%` (Windows) or
* `${XDG_CACHE_HOME:-~/.cache}` (Linux), with `copilot/managed-settings`
* beneath it.
*
* This matters because a *fresh* entry (< 1 hour) makes the runtime skip the
* network entirely, so a policy change here is never even requested.
*/
function
managedSettingsCacheDirs
(
)
:
string
[
]
{
const
:
string
[
]
=
[
]
;
const
add
=
(
:
string
|
undefined
,
...
:
string
[
]
)
=>
{
if
(
)
{
.
push
(
.
join
(
,
...
)
)
;
}
}
;
// COPILOT_CACHE_HOME replaces the whole platform cache base, so
// `copilot` is not appended beneath it.
add
(
.
.
COPILOT_CACHE_HOME
,
'managed-settings'
)
;
if
(
.
===
'darwin'
)
{
add
(
.
join
(
.
homedir
(
)
,
'Library'
,
'Caches'
)
,
'copilot'
,
'managed-settings'
)
;
}
else
if
(
.
===
'win32'
)
{
add
(
.
.
LOCALAPPDATA
||
.
join
(
.
homedir
(
)
,
'.cache'
)
,
'copilot'
,
'managed-settings'
)
;
}
else
{
add
(
.
.
XDG_CACHE_HOME
||
.
join
(
.
homedir
(
)
,
'.cache'
)
,
'copilot'
,
'managed-settings'
)
;
}
return
[
...
new
Set
(
)
]
;
}
/**
* Delete every managed-settings cache entry, reporting how many files were
* removed per directory so the GUI can say something more useful than "done".
* A missing directory is the normal case, not an error.
*/
function
clearManagedSettingsCache
(
)
:
{
:
{
:
string
;
:
number
}
[
]
;
:
string
[
]
}
{
const
:
{
:
string
;
:
number
}
[
]
=
[
]
;
const
:
string
[
]
=
[
]
;
for
(
const
of
managedSettingsCacheDirs
(
)
)
{
let
:
string
[
]
;
try
{
=
.
readdirSync
(
)
;
}
catch
(
)
{
if
(
.
get
(
,
'code'
)
===
'ENOENT'
)
{
.
push
(
)
;
continue
;
}
throw
;
}
.
rmSync
(
,
{
:
true
,
:
true
}
)
;
.
push
(
{
,
:
.
}
)
;
}
return
{
,
}
;
}
/** Append to the rolling request log, newest first. */
function
record
(
:
,
:
string
,
:
[
'outcome'
]
,
:
number
)
:
void
{
.
unshift
(
{
:
.
now
(
)
,
:
.
??
'GET'
,
:
,
,
}
)
;
if
(
.
>
REQUEST_LOG_LIMIT
)
{
.
=
REQUEST_LOG_LIMIT
;
}
}
/** Local URL for an endpoint. */
function
endpointUrl
(
:
)
:
string
{
return
`http://${HOST}:${PORT}${endpoint.path}`
;
}
/**
* Resolve and load the managed-settings JSON schema from {@link SCHEMA_SOURCE}.
* Accepts a web URL (`http(s)://`), a `file://` URI, or a filesystem path
* (relative paths are resolved against the app's cwd). The GUI loads it once
* during initialization.
*/
async
function
loadSchema
(
)
:
Promise
<
{
:
string
;
:
string
;
:
boolean
;
?
:
unknown
;
?
:
string
}
>
{
const
=
SCHEMA_SOURCE
;
try
{
if
(
/^https?:\/\//i
.
test
(
)
)
{
const
=
await
fetch
(
)
;
if
(
!
.
)
{
return
{
,
:
,
:
false
,
:
`HTTP ${res.status}${res.statusText}`
}
;
}
return
{
,
:
,
:
true
,
:
await
.
json
(
)
}
;
}
const
=
.
startsWith
(
'file://'
)
?
fileURLToPath
(
)
:
.
resolve
(
.
cwd
(
)
,
)
;
// Guard against relative path traversal.
if
(
!
.
isAbsolute
(
)
&&
.
includes
(
'..'
)
)
{
return
{
,
:
,
:
false
,
:
'Relative paths must not contain ".."'
}
;
}
if
(
!
.
existsSync
(
)
)
{
return
{
,
:
,
:
false
,
:
`Schema file not found at ${filePath}`
}
;
}
const
=
JSON
.
parse
(
.
readFileSync
(
,
'utf8'
)
)
;
return
{
,
:
,
:
true
,
}
;
}
catch
(
)
{
return
{
,
:
,
:
false
,
:
instanceof
Error
?
.
:
String
(
)
}
;
}
}
/**
* Prefer the schema checkout beside the primary VS Code checkout. Git worktrees
* point their `.git` file back to that checkout, so this also finds repositories
* such as `/Users/name/git/copilot-agent-runtime` when VS Code is running from a
* nested worktree.
*/
function
resolveDefaultSchemaSource
(
)
:
string
{
const
:
string
[
]
=
[
]
;
const
=
primaryCheckoutRoot
(
)
;
if
(
)
{
.
push
(
.
join
(
.
dirname
(
)
,
DEFAULT_SCHEMA_RELATIVE_PATH
)
)
;
}
.
push
(
.
resolve
(
.
cwd
(
)
,
DEFAULT_SCHEMA_RELATIVE_PATH
)
,
.
resolve
(
ROOT
,
DEFAULT_SCHEMA_RELATIVE_PATH
)
)
;
return
.
find
(
=>
.
existsSync
(
)
)
??
[
0
]
;
}
function
primaryCheckoutRoot
(
)
:
string
|
undefined
{
const
=
.
join
(
ROOT
,
'.git'
)
;
try
{
if
(
.
statSync
(
)
.
isDirectory
(
)
)
{
return
ROOT
;
}
const
=
/^gitdir:\s*(.+)$/m
.
exec
(
.
readFileSync
(
,
'utf8'
)
)
;
if
(
!
)
{
return
undefined
;
}
let
=
.
resolve
(
ROOT
,
[
1
]
.
trim
(
)
)
;
while
(
.
dirname
(
)
!==
)
{
if
(
.
basename
(
)
===
'.git'
)
{
return
.
dirname
(
)
;
}
=
.
dirname
(
)
;
}
}
catch
{
return
undefined
;
}
return
undefined
;
}
/** Build the state object the GUI renders. */
function
getState
(
)
{
return
{
:
.
map
(
=>
(
{
:
.
,
:
.
,
:
.
,
:
.
,
:
.
,
:
.
===
true
,
:
endpointUrl
(
)
,
:
.
,
:
.
get
(
.
)
!
.
,
:
.
get
(
.
)
!
.
,
:
.
get
(
.
)
!
.
,
:
.
get
(
.
)
!
.
}
)
)
,
:
isWired
(
)
,
:
PRODUCT_OVERRIDES_JSON
,
:
buildOverridesSnippet
(
)
,
:
`http://${HOST}:${PORT}`
,
:
UPSTREAM
,
:
managedSettingsCacheDirs
(
)
}
;
}
/** Build the full overrides JSON a user would paste into product.overrides.json. */
function
buildOverridesSnippet
(
)
{
const
=
JSON
.
parse
(
.
readFileSync
(
PRODUCT_JSON
,
'utf8'
)
)
;
const
=
?.
??
{
}
;
return
JSON
.
stringify
(
{
:
{
...
,
...
overrideUrls
(
)
}
}
,
null
,
'\t'
)
;
}
/** The `defaultChatAgent` URL overrides this server provides. */
function
overrideUrls
(
)
:
<
string
,
string
>
{
const
:
<
string
,
string
>
=
{
}
;
for
(
const
of
)
{
[
.
]
=
endpointUrl
(
)
;
}
return
;
}
/** Whether `product.overrides.json` currently points every endpoint at this server. */
function
isWired
(
)
:
boolean
{
let
;
try
{
=
JSON
.
parse
(
.
readFileSync
(
PRODUCT_OVERRIDES_JSON
,
'utf8'
)
)
;
}
catch
{
return
false
;
}
const
=
?.
;
if
(
!
)
{
return
false
;
}
const
=
overrideUrls
(
)
;
return
.
keys
(
)
.
every
(
=>
[
]
===
[
]
)
;
}
/**
* Write `product.overrides.json` so Code OSS calls this server for every policy
* endpoint.
*
* `src/bootstrap-meta.ts` merges overrides via `Object.assign` (shallow,
* top-level), so overriding nested keys requires writing back the whole
* `defaultChatAgent` object. We seed it from `product.json` and flip only the
* endpoint URLs, preserving every other key. Any other top-level overrides
* already present are kept untouched.
*/
function
wireOverrides
(
)
:
void
{
const
=
JSON
.
parse
(
.
readFileSync
(
PRODUCT_JSON
,
'utf8'
)
)
;
const
=
?.
??
{
}
;
// Back up existing overrides before touching them.
if
(
.
existsSync
(
PRODUCT_OVERRIDES_JSON
)
)
{
.
copyFileSync
(
PRODUCT_OVERRIDES_JSON
,
PRODUCT_OVERRIDES_BACKUP
)
;
console
.
log
(
` Backed up ${PRODUCT_OVERRIDES_JSON} -> ${PRODUCT_OVERRIDES_BACKUP}`
/**
* Revert the endpoint overrides: restore each URL to its `product.json` value
* (or drop the key if absent). If `defaultChatAgent` ends up identical to
* `product.json`, drop it; if the overrides file ends up empty, remove it.
*/
function
unwireOverrides
(
)
:
void
{
// If we have a backup, restore it wholesale instead of surgically reverting.
if
(
.
existsSync
(
PRODUCT_OVERRIDES_BACKUP
)
)
{
.
copyFileSync
(
PRODUCT_OVERRIDES_BACKUP
,
PRODUCT_OVERRIDES_JSON
)
;
.
rmSync
(
PRODUCT_OVERRIDES_BACKUP
,
{
:
true
}
)
;
console
.
log
(
` Restored ${PRODUCT_OVERRIDES_JSON} from backup`
)
;
return
;
}
let
;
try
{
=
JSON
.
parse
(
.
readFileSync
(
PRODUCT_OVERRIDES_JSON
,
'utf8'
)
)
;
}
catch
{
return
;
// nothing to unwire
}
if
(
!
.
)
{
return
;
}
const
=
JSON
.
parse
(
.
readFileSync
(
PRODUCT_JSON
,
'utf8'
)
)
;
const
=
?.
??
{
}
;
const
=
{
...
.
}
;
for
(
const
of
)
{
if
(
[
.
]
===
undefined
)
{
delete
[
.
]
;
}
else
{
[
.
]
=
[
.
]
;
}
}
if
(
shallowEqual
(
,
)
)
{
delete
.
;
}
else
{
.
=
;
}
if
(
.
keys
(
)
.
===
0
)
{
.
rmSync
(
PRODUCT_OVERRIDES_JSON
,
{
:
true
}
)
;
console
.
log
(
` Removed ${PRODUCT_OVERRIDES_JSON} (no overrides left)`
)
;
}
else
{
.
writeFileSync
(
PRODUCT_OVERRIDES_JSON
,
JSON
.
stringify
(
,
null
,
'\t'
)
+
'\n'
)
;
console
.
log
(
` Unwired ${PRODUCT_OVERRIDES_JSON}`
)
;
}
}
/**
* Serve one allowlisted GUI asset. `.ts` sources are served as plain JavaScript
* via Node's built-in `module.stripTypeScriptTypes()`, which lets the browser
* GUI stay in TypeScript with no build step.
*
* `filePath` always comes from {@link GUI_ASSETS}, so there is no
* user-controlled path to traverse out of and no way for a static read to
* shadow an API path that should be proxied upstream.
*/
function
serveAsset
(
:
string
,
:
)
:
void
{
let
:
|
string
;
try
{
=
.
readFileSync
(
)
;
}
catch
{
return
sendJson
(
,
404
,
{
:
`Missing GUI asset ${path.basename(filePath)}`
}
)
;
}
if
(
.
endsWith
(
'.ts'
)
)
{
=
stripTypeScriptTypes
(
.
toString
(
'utf8'
)
)
;
}
.
writeHead
(
200
,
{
'Content-Type'
:
contentType
(
)
,
'Cache-Control'
:
'no-store'
}
)
;
.
end
(
)
;
}
function
contentType
(
:
string
)
:
string
{
switch
(
.
extname
(
)
)
{
case
'.html'
:
return
'text/html; charset=utf-8'
;
case
'.js'
:
return
'text/javascript; charset=utf-8'
;
// `.ts` assets are served type-stripped, so they are JavaScript by the
// time they reach the browser.
case
'.ts'
:
return
'text/javascript; charset=utf-8'
;
case
'.css'
:
return
'text/css; charset=utf-8'
;
case
'.json'
:
return
'application/json; charset=utf-8'
;
default
:
return
'application/octet-stream'
;
}
}
function
sendJson
(
:
,
:
number
,
:
unknown
)
:
void
{
.
writeHead
(
,
{
'Content-Type'
:
'application/json; charset=utf-8'
,
'Cache-Control'
:
'no-store'
}
)
;
.
end
(
JSON
.
stringify
(
,
null
,
2
)
)
;
}
function
sendMockedResponse
(
:
,
:
,
:
string
,
:
)
:
void
{
switch
(
.
)
{
case
'json'
:
record
(
,
,
'mocked'
,
.
)
;
sendJson
(
,
.
,
.
)
;
return
;
case
'malformed-json'
:
record
(
,
,
'mocked'
,
.
)
;
.
writeHead
(
.
,
{
'Content-Type'
:
'application/json; charset=utf-8'
,
'Cache-Control'
:
'no-store'
}
)
;
.
end
(
'{"unterminated":'
)
;
return
;
case
'disconnect'
:
record
(
,
,
'mocked'
,
0
)
;
.
destroy
(
)
;
return
;
case
'timeout'
:
{
record
(
,
,
'mocked'
,
0
)
;
const
=
setTimeout
(
(
)
=>
.
destroy
(
)
,
10_000
)
;
.
unref
(
)
;
.
on
(
'close'
,
(
)
=>
clearTimeout
(
)
)
;
return
;
}
}
}
function
isEndpointResponseMode
(
:
unknown
)
:
is
{
return
===
'json'
||
===
'malformed-json'
||
===
'disconnect'
||
===
'timeout'
;
}
function
readBody
(
:
,
cb
:
(
:
|
null
,
:
string
)
=>
void
)
:
void
{
let
=
''
;
.
on
(
'data'
,
=>
{
+=
;
if
(
.
>
1_000_000
)
{
.
destroy
(
)
;
}
}
)
;
.
on
(
'end'
,
(
)
=>
cb
(
null
,
)
)
;
.
on
(
'error'
,
=>
cb
(
,
''
)
)
;
}
function
isRecord
(
:
unknown
)
:
is
<
string
,
unknown
>
{
return
typeof
===
'object'
&&
!==
null
&&
!
Array
.
isArray
(
)
;
}
function
shallowEqual
(
:
<
string
,
unknown
>
,
:
<
string
,
unknown
>
)
:
boolean
{
const
=
.
keys
(
)
;
const
=
.
keys
(
)
;
if
(
.
!==
.
)
{
return
false
;
}
return
.
every
(
=>
JSON
.
stringify
(
[
]
)
===
JSON
.
stringify
(
[
]
)
)
;
}
function
clone
(
:
unknown
)
:
unknown
{
return
JSON
.
parse
(
JSON
.
stringify
(
)
)
;
}
function
errorMessage
(
:
unknown
)
:
string
{
return
instanceof
Error
?
.
:
String
(
)
;
}
function
stripTrailingSlash
(
:
string
)
:
string
{
return
.
endsWith
(
'/'
)
?
.
slice
(
0
,
-
1
)
:
;
}
interface
ServerArgs
{
?
:
string
;
?
:
string
;
?
:
string
;
:
boolean
;
}
function
parseArgs
(
:
string
[
]
)
:
{
const
:
=
{
:
false
}
;
for
(
let
=
0
;
<
.
;
++
)
{
const
=
[
]
;
if
(
===
'--help'
)
{
.
=
true
;
continue
;
}
if
(
!
.
startsWith
(
'--'
)
)
{
failArgument
(
`Unexpected argument "${argument}".`
)
;
}
const
[
,
]
=
.
slice
(
2
)
.
split
(
'='
,
2
)
;
if
(
!==
'host'
&&
!==
'schema'
&&
!==
'upstream'
)
{
failArgument
(
`Unknown option "--${key}".`
)
;
}
const
=
[
+
1
]
;
const
=
??
(
&&
!
.
startsWith
(
'--'
)
?
:
undefined
)
;
if
(
!
)
{
failArgument
(
`Option "--${key}" requires a value.`
)
;
}
[
]
=
;
if
(
===
undefined
)
{
++
;
}
}
return
;
}
function
failArgument
(
:
string
)
:
never
{
console
.
error
(
`\n Error: ${message} Run with --help for usage.\n`