@zortexhq/indra-v2.5 0.3.2 → 0.4.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 +93 -152
- package/dist/auto-update.js +1 -1
- package/dist/bundled-handbook.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/mcp.js +2 -2
- package/dist/onboard-cli.js +1 -0
- package/dist/onboard.js +1 -0
- package/dist/operation-telemetry.js +1 -1
- package/dist/public-tool.js +1 -1
- package/dist/recovery-resident-port.js +1 -0
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +3 -3
- package/dist/resident-runtime-identity.js +1 -1
- package/dist/resident-shutdown.js +1 -0
- package/dist/resident-startup-preference.js +1 -0
- package/dist/resident-telemetry.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/update-command.js +1 -0
- package/dist/update-handover.js +1 -0
- package/dist/update-recovery.js +1 -1
- package/dist/update-tool.js +1 -1
- package/dist/web.js +1 -1
- package/dist/zortex-cli.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-graph.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/service-sdk-matrix.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/portrait-producer.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/record-identity.js +6 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
- package/package.json +7 -7
- package/release-provenance.json +16 -16
- package/update-manifest.json +143 -95
package/README.md
CHANGED
|
@@ -1,180 +1,121 @@
|
|
|
1
1
|
# Zortex
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
Connect one source through its actual sign-in, QR or permission gateway, then use
|
|
6
|
-
its Actions or query stored data through MCP.
|
|
3
|
+
Connect the sources you choose and use their information through your local
|
|
4
|
+
installation. Your Vault holds records, settings and protected authorization.
|
|
7
5
|
|
|
8
|
-
|
|
9
|
-
version and `release-provenance.json`; editing this repository does not update an
|
|
10
|
-
already-published package. Install Node.js 24 or later for npm use. Platform
|
|
11
|
-
packaging support does not establish that every source has passed a real-account
|
|
12
|
-
trial on that machine.
|
|
6
|
+
## Get started
|
|
13
7
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
Install the verified version or archive supplied in the release handoff. To
|
|
17
|
-
inspect the public candidate and choose an exact published version:
|
|
18
|
-
|
|
19
|
-
```sh
|
|
20
|
-
npm view @zortexhq/indra-v2.5 dist-tags.next --registry https://registry.npmjs.org
|
|
21
|
-
npm install -g '@zortexhq/indra-v2.5@<exact-published-version>' --registry https://registry.npmjs.org
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
Replace placeholders before running commands. Set `ZORTEX_ROOT` to the desired
|
|
25
|
-
absolute Vault directory before installation. New installations default to
|
|
26
|
-
`%LOCALAPPDATA%\Zortex\Indra` on Windows and `~/.zortex/indra-v2` on Unix. Existing
|
|
27
|
-
catalog bindings, Vaults and source opt-outs are preserved.
|
|
28
|
-
|
|
29
|
-
If background full sync is not wanted, set `ZORTEX_AUTO_SYNC=0` in the installation
|
|
30
|
-
and launch shell; in PowerShell use `$env:ZORTEX_AUTO_SYNC = '0'`. Keep that setting
|
|
31
|
-
for later independent host, MCP and web launches. Explicit source sync is still
|
|
32
|
-
available. Stop an old host before starting a new version with the same Vault;
|
|
33
|
-
changing the shell environment does not alter a running process.
|
|
34
|
-
|
|
35
|
-
The package includes `indra` and `zortex`. `indra` uses an explicit `--root` for
|
|
36
|
-
Vault commands. `zortex` selects `--root`, then `ZORTEX_ROOT`, then its saved Codex
|
|
37
|
-
binding, then the platform default. If an older installation already owns the
|
|
38
|
-
bare `zortex` command, use a separate npm prefix or this package's executable;
|
|
39
|
-
do not force-overwrite the other installation.
|
|
40
|
-
|
|
41
|
-
## Connect and use a source
|
|
8
|
+
With Node.js 24 or later installed, run:
|
|
42
9
|
|
|
43
10
|
```sh
|
|
44
|
-
indra
|
|
45
|
-
indra
|
|
46
|
-
indra --root <absolute Vault directory> connect --source whatsapp --presentation return-url
|
|
47
|
-
indra --root <absolute Vault directory> status
|
|
48
|
-
indra --root <absolute Vault directory> actions --json '{"source":"gmail"}'
|
|
49
|
-
indra --root <absolute Vault directory> search --sql 'SELECT source,title,body FROM z_records LIMIT 20'
|
|
50
|
-
indra web --root <absolute Vault directory>
|
|
11
|
+
npm install -g @zortexhq/indra-v2.5@next
|
|
12
|
+
indra onboard
|
|
51
13
|
```
|
|
52
14
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
transaction. No embedded browser agent or isolated browser is started.
|
|
59
|
-
|
|
60
|
-
`help` prints commands. `web` explicitly opens management and prints a signed
|
|
61
|
-
loopback address; open that exact address. `mcp` exposes normal search, actions,
|
|
62
|
-
management and documentation tools without starting account connection. A
|
|
63
|
-
successful empty read, an unavailable source and incomplete sync are different
|
|
64
|
-
results; inspect the returned status.
|
|
15
|
+
The first command installs the package. `indra onboard` prepares the local
|
|
16
|
+
service, registers its Codex plugin when Codex is available, and opens setup.
|
|
17
|
+
Choose the sources you want and complete their sign-in or permission requests
|
|
18
|
+
in that page. The command returns after opening it; the background service keeps
|
|
19
|
+
setup alive. Repeating `indra onboard` reuses the current setup session.
|
|
65
20
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
21
|
+
The product chooses its private Vault automatically. Existing bindings and data
|
|
22
|
+
are preserved. New installations use `%LOCALAPPDATA%\Zortex\Indra` on Windows or
|
|
23
|
+
`~/.zortex/indra-v2` on Unix. Login startup is configured on Windows and macOS
|
|
24
|
+
unless you previously disabled it. Registration and an open setup page do not
|
|
25
|
+
establish that a source is connected or that a read succeeded.
|
|
70
26
|
|
|
71
|
-
|
|
27
|
+
When onboarding reports that Codex was installed or refreshed, open a new Codex
|
|
28
|
+
session to load it. The ordinary agent tool is `zortex`; its six intents are
|
|
29
|
+
`ensure_ready`, `find`, `act`, `status`, `guide` and `update`. The installed tool
|
|
30
|
+
schema describes the available arguments. Source sign-in and consent remain in
|
|
31
|
+
the provider's actual flow.
|
|
72
32
|
|
|
73
|
-
|
|
74
|
-
start MCP or access account data. Set `ZORTEX_CODEX_SETUP=0` before installing to
|
|
75
|
-
skip preparation. An explicit new catalog can be created and registered with:
|
|
33
|
+
## Update
|
|
76
34
|
|
|
77
35
|
```sh
|
|
78
|
-
indra
|
|
79
|
-
codex plugin marketplace add <absolute catalog directory>
|
|
80
|
-
codex plugin add zortex@zortex-local
|
|
36
|
+
indra update
|
|
81
37
|
```
|
|
82
38
|
|
|
83
|
-
|
|
84
|
-
the
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
##
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
indra --
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
the
|
|
116
|
-
|
|
39
|
+
This command chooses the current release, verifies and stages its files, and
|
|
40
|
+
restarts the same idle background service after applying them. It preserves the
|
|
41
|
+
Vault, saved sync policy and startup preference. If work is active or paused,
|
|
42
|
+
the update is deferred and the result explains why. Failure keeps or restores
|
|
43
|
+
the previous installation. Repeat the command to repair an interrupted handover.
|
|
44
|
+
|
|
45
|
+
An agent can request the same update with `zortex({"intent":"update"})`.
|
|
46
|
+
There is no routine version/token selection or manual host restart. A Codex
|
|
47
|
+
session may need to reconnect after its plugin is refreshed. Remote/scoped
|
|
48
|
+
endpoints do not expose host updates.
|
|
49
|
+
|
|
50
|
+
## If setup needs attention
|
|
51
|
+
|
|
52
|
+
Use only the recovery that matches the returned result:
|
|
53
|
+
|
|
54
|
+
| Situation | Next step |
|
|
55
|
+
| --- | --- |
|
|
56
|
+
| No browser opens | `indra onboard --no-open` prints the local setup URL. |
|
|
57
|
+
| A source needs sign-in, QR pairing or permission | Continue the request shown in the setup page. Other sources remain usable. |
|
|
58
|
+
| Codex is unavailable on a fresh install | Continue in the local app; repeat `indra onboard` when Codex is available. |
|
|
59
|
+
| An existing agent binding cannot be verified | Restore Codex access and retry. To use only the local app, use `indra onboard --no-codex --root <existing Vault>`. |
|
|
60
|
+
| A custom catalog is needed | Create it with `indra setup codex --out <new directory> --root <existing Vault>`, then run `indra onboard --catalog <directory>`. Use absolute paths. |
|
|
61
|
+
| An old running version cannot safely hand over | Finish its current work and use that installation's CLI to stop its owner before retrying. |
|
|
62
|
+
|
|
63
|
+
Disabled Codex integration and disabled login startup remain disabled. To opt
|
|
64
|
+
out of Codex preparation, set `ZORTEX_CODEX_SETUP=0`. To choose a new Vault,
|
|
65
|
+
set `ZORTEX_ROOT` before the first installation. Existing conflicting bindings
|
|
66
|
+
are never silently replaced.
|
|
67
|
+
|
|
68
|
+
`indra update check` is a read-only diagnostic. The advanced
|
|
69
|
+
`update apply --version <version> --confirmation-token <token>` form remains
|
|
70
|
+
available for compatibility. Source workspaces, store-managed installs and old
|
|
71
|
+
versions without the updater use their package manager. The published channel
|
|
72
|
+
is `next`; release identity is recorded in `release-provenance.json` and the
|
|
73
|
+
package's `zortexRelease` metadata.
|
|
74
|
+
|
|
75
|
+
## Optional controls
|
|
76
|
+
|
|
77
|
+
`indra help` lists explicit source, host and diagnostic commands. Most advanced
|
|
78
|
+
Vault commands require `indra --root <absolute Vault directory>`; the `zortex`
|
|
79
|
+
alias also resolves the configured root. `indra web --root <Vault>` opens the
|
|
80
|
+
management application separately.
|
|
81
|
+
|
|
82
|
+
`host start` runs the service now; `host stop` ends it. `host enable` and
|
|
83
|
+
`host disable` control login startup. None deletes data. Authorized sources may
|
|
84
|
+
sync while the host runs. Set `ZORTEX_AUTO_SYNC=0` before installation and launch
|
|
85
|
+
to opt out of background sync; source switches and revocations remain effective.
|
|
86
|
+
`ZORTEX_UPDATES=0` disables background update checks.
|
|
87
|
+
|
|
88
|
+
Optional `host local-cloud` commands control authenticated remote access to this
|
|
89
|
+
computer. They require an awake, online host and actual relay provisioning.
|
|
90
|
+
They do not upload a cloud copy of the Vault.
|
|
117
91
|
|
|
118
92
|
## Privacy and feedback
|
|
119
93
|
|
|
120
|
-
The Vault and protected credentials stay outside the package. SQL
|
|
121
|
-
private credential and authorization tables.
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
Provider and OS consent remains in the actual connection flow. Credential custody
|
|
129
|
-
uses Windows DPAPI or macOS Keychain-backed protection; unavailable protection
|
|
130
|
-
fails explicitly. Real source and native-platform acceptance remains separate
|
|
131
|
-
from synthetic verification.
|
|
132
|
-
|
|
133
|
-
Enabled telemetry contains operational metadata, not record content, questions,
|
|
134
|
-
SQL or credentials. Set `ZORTEX_TELEMETRY=0` or `DO_NOT_TRACK=1` to disable it.
|
|
135
|
-
`indra --root <Vault> feedback` offers fixed ratings for recent operations;
|
|
136
|
-
`feedback --list` inspects receipts. No response means unrated, and feedback does
|
|
137
|
-
not force an upload or start account setup.
|
|
138
|
-
|
|
139
|
-
## Updates and release identity
|
|
140
|
-
|
|
141
|
-
`indra update` or `zortex update` checks the current offer. Apply the returned
|
|
142
|
-
version and opaque release token with:
|
|
143
|
-
|
|
144
|
-
```sh
|
|
145
|
-
indra update apply --version <version> --confirmation-token <token>
|
|
146
|
-
```
|
|
94
|
+
The Vault and protected credentials stay outside the installed package. SQL
|
|
95
|
+
excludes private credential and authorization tables. Full sync stores records;
|
|
96
|
+
ordinary bounded source Actions and reads have their own retention rules.
|
|
97
|
+
Provider and OS consent is required by the selected source. Native credential
|
|
98
|
+
protection uses Windows DPAPI or macOS Keychain; unavailable protection fails
|
|
99
|
+
explicitly. A successful empty read, an unavailable source and a failed read
|
|
100
|
+
are different results.
|
|
147
101
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
dependency changes are staged through npm. Failure keeps or restores the previous
|
|
153
|
-
installation; the Vault is not replaced. Restart the host and MCP sessions after
|
|
154
|
-
success. Set `ZORTEX_UPDATES=0` to disable update checks. Older releases without the
|
|
155
|
-
updater, source workspaces and store-managed installs use their package manager.
|
|
156
|
-
|
|
157
|
-
Before replacing a running installation, use its CLI to disable and stop its host.
|
|
158
|
-
If IPC versions differ, use the previous verified artifact to stop the old owner;
|
|
159
|
-
a failed status reply is not proof it exited.
|
|
160
|
-
|
|
161
|
-
Daily candidates use the public npm `next` channel. Their source commit, dependency
|
|
162
|
-
lock and package digests are recorded in `release-provenance.json`; daily source
|
|
163
|
-
identity is also recorded under `zortexRelease` in `package.json`. An upload or a
|
|
164
|
-
scheduled workflow does not by itself prove public registry availability. Use the
|
|
165
|
-
published version and integrity from the release handoff; this guide does not
|
|
166
|
-
claim a new publication or real-user acceptance.
|
|
102
|
+
Enabled telemetry records operational metadata rather than record content,
|
|
103
|
+
prompts, SQL or credentials. Set `ZORTEX_TELEMETRY=0` or `DO_NOT_TRACK=1` to
|
|
104
|
+
disable it. `indra --root <Vault> feedback` offers optional ratings for recent
|
|
105
|
+
operations; no response means unrated.
|
|
167
106
|
|
|
168
107
|
## Remove
|
|
169
108
|
|
|
170
|
-
Stop and disable the
|
|
109
|
+
Stop and disable the service before removing its runtime:
|
|
171
110
|
|
|
172
111
|
```sh
|
|
173
|
-
indra --root <
|
|
174
|
-
indra --root <
|
|
112
|
+
indra --root <Vault> host disable
|
|
113
|
+
indra --root <Vault> host stop
|
|
175
114
|
codex plugin remove zortex@zortex-local
|
|
176
115
|
npm uninstall -g @zortexhq/indra-v2.5
|
|
177
116
|
```
|
|
178
117
|
|
|
179
|
-
Uninstalling
|
|
180
|
-
|
|
118
|
+
Uninstalling leaves the Vault and its records in place. Delete that directory
|
|
119
|
+
separately only when its data is no longer wanted. If an older package owns the
|
|
120
|
+
global `zortex` command, use this installation's executable or a separate npm
|
|
121
|
+
prefix; do not force-overwrite another installation.
|
package/dist/auto-update.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,randomUUID}from"node:crypto";import{readFile,writeFile,mkdir,lstat,realpath,rename,copyFile,cp,rm,chmod}from"node:fs/promises";import{resolve,join,dirname,relative,isAbsolute,sep}from"node:path";import{homedir}from"node:os";import{fileURLToPath}from"node:url";import{execFile}from"node:child_process";import{promisify}from"node:util";import{prepareDependencyUpdate}from"./update-dependencies.js";import{createUpdateTelemetry}from"./update-telemetry.js";import{createUpdateRecovery,safePath,safeFile,optionalBytes,dependencyPath,atomicWrite,JOURNAL,RECOVERY_FILE}from"./update-recovery.js";const execute=promisify(execFile);const NAME="@zortexhq/indra-v2.5";const MANIFEST="update-manifest.json";const MAX_BYTES=12e7;const hash=bytes=>createHash("sha256").update(bytes).digest("hex");const jsonBytes=value=>Buffer.from(JSON.stringify(value,null,2)+"\n");function metadataDigest(pkg){const update=pkg.zortexUpdate;if(update?.schemaVersion!==1||update.manifest!==MANIFEST||!/^[a-f0-9]{64}$/.test(update.sha256??""))return void 0;return update.sha256}function validateManifest(bytes,digest,version){if(hash(bytes)!==digest)throw Error("Update manifest integrity check failed.");const value=JSON.parse(bytes.toString("utf8"));if(value.schemaVersion!==1||value.package?.name!==NAME||value.package.version!==version||value.package.zortexUpdate||!Array.isArray(value.files)||value.files.length>8e3)throw Error("Invalid update manifest.");let total=0;const paths=new Set;for(const file of value.files){safePath(file.path);const key=file.path.toLowerCase();if(paths.has(key)||[MANIFEST,"package.json","release-provenance.json"].includes(key)||!/^[a-f0-9]{64}$/.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0||file.mode!==void 0&&![420,493,420,493].includes(file.mode))throw Error("Invalid update file entry.");paths.add(key);total+=file.size}if(total>MAX_BYTES)throw Error("Update exceeds the installed product size limit.");return value}function dependencyShape(pkg){const bundled=new Set(pkg.bundledDependencies??[]);return JSON.stringify(["dependencies","optionalDependencies","peerDependencies","peerDependenciesMeta"].map(field=>[field,Object.entries(pkg[field]??{}).filter(([name])=>!bundled.has(name)).sort(([a],[b])=>a.localeCompare(b))]))}function binShape(pkg){const bins=typeof pkg.bin==="string"?{[pkg.name.split("/").at(-1)]:pkg.bin}:pkg.bin??{};return JSON.stringify(Object.entries(bins).map(([name,path])=>[name,typeof path==="string"?path.replace(/^\.\//,""):path]).sort(([a],[b])=>String(a).localeCompare(String(b))))}function versionParts(version){const match=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);if(!match)throw Error("Invalid registry version.");return[Number(match[1]),Number(match[2]),Number(match[3]),match[4]]}function newer(current,target,times={}){if(current===target)return false;const a=versionParts(current),b=versionParts(target);for(const i of[0,1,2])if(a[i]!==b[i])return b[i]>a[i];if(!a[3])return false;if(!b[3])return true;const oldTime=Date.parse(times[current]??""),newTime=Date.parse(times[target]??"");if(Number.isFinite(oldTime)&&Number.isFinite(newTime))return newTime>oldTime;const left=a[3].split("."),right=b[3].split(".");for(let i=0;i<Math.max(left.length,right.length);i++){if(left[i]===right[i])continue;if(left[i]===void 0)return true;if(right[i]===void 0)return false;return/^\d+$/.test(left[i])&&/^\d+$/.test(right[i])?Number(right[i])>Number(left[i]):right[i]>left[i]}return false}function manual(version,installationPath){return`Use the package manager that installed ${installationPath} to upgrade ${NAME} to exactly ${version} at that installation path.`}export function createUpdater(options={}){let packageRoot=resolve(options.packageRoot??fileURLToPath(new URL("..",import.meta.url)));const requestedRoot=packageRoot;const{recover,recoverLocked,withRecoveryLock,publishLock,rollback}=createUpdateRecovery(requestedRoot);let rootIsLinked=false,rootReady;const canonicalizeRoot=()=>rootReady??=(async()=>{rootIsLinked=(await lstat(requestedRoot)).isSymbolicLink();packageRoot=await realpath(requestedRoot)})();const cacheRoot=resolve(options.cacheRoot??join(homedir(),".zortex","updates",hash(packageRoot).slice(0,24)));const registry=(options.registryUrl??"https://registry.npmjs.org").replace(/\/$/,"");const content=(options.contentBaseUrl??"https://cdn.jsdelivr.net/npm").replace(/\/$/,"");const fetcher=options.fetch??globalThis.fetch,now=options.now??Date.now;const env=options.env??process.env;const outcomes=createUpdateTelemetry({cacheRoot,env,now});const disabled=()=>/^(0|false|off)$/i.test(env.ZORTEX_UPDATES??"");const offerPath=join(cacheRoot,"offer.json"),statusPath=join(cacheRoot,"status.json");const pkg=async()=>{await canonicalizeRoot();return JSON.parse(await readFile(join(packageRoot,"package.json"),"utf8"))};async function get(url,limit,timeout=5e3){const response=await fetcher(url,{signal:AbortSignal.timeout(timeout),redirect:"error"});if(!response.ok||!response.body)throw Error(`Update download unavailable (${response.status}).`);if(Number(response.headers.get("content-length")??0)>limit)throw Error("Update response exceeds its size limit.");const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.length;if(size>limit)throw Error("Update response exceeds its size limit.");chunks.push(chunk)}return Buffer.concat(chunks)}const fileUrl=(version,path)=>`${content}/${NAME}@${encodeURIComponent(version)}/${path.split("/").map(encodeURIComponent).join("/")}`;async function savedOffer(){await canonicalizeRoot();const bytes=await optionalBytes(offerPath);const parsed=bytes?JSON.parse(bytes.toString("utf8")):void 0;const offered=parsed?(({confirmationRequired:_legacy,...offer})=>offer)(parsed):void 0;return offered?.installationPath===packageRoot?offered:void 0}async function savedStatus(version){try{const bytes=await optionalBytes(statusPath);const cached=bytes?JSON.parse(bytes.toString("utf8")):void 0;if(cached?.status?.currentVersion===version&&cached.expiresAt>now())return cached.status}catch{}return void 0}async function remember(status2,ttl){await rm(offerPath,{force:true});await mkdir(cacheRoot,{recursive:true});await atomicWrite(statusPath,jsonBytes({status:status2,checkedAt:now(),expiresAt:now()+ttl}));return status2}async function writableInstallation(){await canonicalizeRoot();if(rootIsLinked||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(packageRoot)||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(requestedRoot)||await optionalBytes(join(packageRoot,"tsconfig.json")))throw Error("This installation is managed by a workspace or another package manager. Use its original upgrade command.");if((await pkg()).name!==NAME)throw Error("The running installation is not the Zortex package.")}async function check({force=false}={}){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(!force&&cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached;if(!force){const cachedStatus=await savedStatus(installed.version);if(cachedStatus)return cachedStatus}const packument=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}`,16e6)).toString("utf8"));const channel="next";const target=packument["dist-tags"]?.[channel];if(typeof target!=="string")throw Error("The update channel is unavailable.");if(!newer(installed.version,target,packument.time))return await remember({state:"current",currentVersion:installed.version},6*60*6e4);const targetPackage=packument.versions?.[target];if(targetPackage?.name!==NAME||targetPackage.version!==target)throw Error("Invalid registry package identity.");const digest=metadataDigest(targetPackage);if(!digest)return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release does not publish verified incremental updates. No package was downloaded.",manualCommand:manual(target,packageRoot)},6*60*6e4);if(binShape(installed)!==binShape(targetPackage))return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release changes installed command links and requires its original package manager.",manualCommand:manual(target,packageRoot)},6*60*6e4);await writableInstallation();let expectedDownloadBytes,expectedChangedFiles;try{const manifestBytes=await get(fileUrl(target,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,digest,target);const oldDigest=metadataDigest(installed),oldBytes=oldDigest?await optionalBytes(join(packageRoot,MANIFEST)):void 0;if(oldDigest&&oldBytes){const old=validateManifest(oldBytes,oldDigest,installed.version);const oldByPath=new Map(old.files.map(file=>[file.path,file.sha256]));const generated=await reconstruct(manifest,manifestBytes,digest);for(const[path,bytes]of generated){if(oldByPath.get(path)===hash(bytes))continue;expectedDownloadBytes=(expectedDownloadBytes??0)+bytes.length;expectedChangedFiles=(expectedChangedFiles??0)+1}for(const file of manifest.files){if(oldByPath.get(file.path)===file.sha256)continue;expectedDownloadBytes=(expectedDownloadBytes??0)+file.size;expectedChangedFiles=(expectedChangedFiles??0)+1}}}catch{}const offer={state:"available",currentVersion:installed.version,targetVersion:target,installationPath:packageRoot,confirmationToken:randomUUID(),manifestSha256:digest,checkedAt:now(),expiresAt:now()+15*6e4,channel,...expectedDownloadBytes!==void 0&&expectedChangedFiles!==void 0?{expectedDownloadBytes,expectedChangedFiles}:{}};await mkdir(cacheRoot,{recursive:true});await atomicWrite(offerPath,jsonBytes(offer));await rm(statusPath,{force:true});return offer}catch(error){const unavailable={state:"unavailable",currentVersion:installed.version,message:error instanceof Error?error.message:"Update check failed."};try{await remember(unavailable,15*6e4)}catch{}return unavailable}}async function status(){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached}catch{}return await savedStatus(installed.version)??{state:"unavailable",currentVersion:installed.version,message:"No current update result is cached. Use update check to check the registry."}}async function reconstruct(manifest,bytes,digest){const packageBytes=jsonBytes({...manifest.package,zortexUpdate:{schemaVersion:1,manifest:MANIFEST,sha256:digest}});const generated=new Map([["package.json",packageBytes],[MANIFEST,bytes]]);if(manifest.provenance){const provenance=structuredClone(manifest.provenance);const own=manifest.files.filter(file=>!file.path.startsWith("node_modules/")).map(file=>({path:file.path,sha256:file.sha256}));own.push({path:"package.json",sha256:hash(packageBytes)},{path:MANIFEST,sha256:hash(bytes)});const root=provenance.packages?.find(row=>row.target==="");if(!root||root.filesSha256!==null)throw Error("Invalid update provenance template.");root.filesSha256=hash(own.map(file=>file.path+"\0"+file.sha256).sort().join("\n"));generated.set("release-provenance.json",jsonBytes(provenance))}return generated}async function smoke(version){if(options.smokeTest)return options.smokeTest(packageRoot,version);const cli=join(packageRoot,"dist","cli.js");const verificationEnv={...env,ZORTEX_UPDATES:"0",ZORTEX_UPDATE_VERIFY:"1",ZORTEX_AUTO_SYNC:"0",ZORTEX_CODEX_SETUP:"0",ZORTEX_TELEMETRY:"0",ZORTEX_FEEDBACK_TRAFFIC_CLASS:"internal_test"};const result=await execute(process.execPath,[cli,"--version"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024});if(JSON.parse(result.stdout).version!==version)throw Error("The updated command still runs a different version.");await execute(process.execPath,[cli,"--help"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024})}async function apply({version,confirmationToken}){if(disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");const offered=await savedOffer();if(!confirmationToken||!offered||offered.confirmationToken!==confirmationToken||offered.targetVersion!==version||offered.expiresAt<=now())throw Error("The release offer is missing, expired or mismatched. Run check again and retry with its version and token.");const confirmedAt=performance.now();const attempt=await outcomes.confirmed(offered.currentVersion,version).catch(()=>void 0);try{const result=await applyConfirmed(offered,version);const durationMs=Math.round(performance.now()-confirmedAt);await outcomes.installed(attempt,durationMs).catch(()=>{});return{...result,durationMs}}catch(error){await outcomes.failed(attempt,performance.now()-confirmedAt).catch(()=>{});throw error}}async function applyConfirmed(offered,version){await writableInstallation();await recover();const installed=await pkg();if(installed.version!==offered.currentVersion)throw Error("The installed version changed. Check again before updating.");await mkdir(cacheRoot,{recursive:true});let unlock;try{unlock=await withRecoveryLock(async()=>{await recoverLocked();return publishLock(join(packageRoot,".zortex-update.lock"))})}catch(error){if(error.code==="EEXIST")throw Error("Another update holds the installation lock.");throw error}const started=performance.now();const stageName=".zortex-update-"+randomUUID(),stage=join(packageRoot,stageName);let journal,retainRecovery=false;try{const target=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}/${encodeURIComponent(version)}`,2e6)).toString("utf8"));if(target.name!==NAME||target.version!==version||metadataDigest(target)!==offered.manifestSha256)throw Error("The release changed. Run check again and retry with the current version and token.");const manifestBytes=await get(fileUrl(version,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,offered.manifestSha256,version);if(!manifest.files.some(file=>file.path===RECOVERY_FILE))throw Error("This release removes the standalone update recovery module. "+manual(version,packageRoot));if(binShape(installed)!==binShape(manifest.package))throw Error("This release changes installed command links. "+manual(version,packageRoot));const dependencyChange=dependencyShape(installed)!==dependencyShape(manifest.package);const oldDigest=metadataDigest(installed),oldBytes=await optionalBytes(join(packageRoot,MANIFEST));if(!oldDigest||!oldBytes)throw Error(`This installation predates the incremental updater. One package-manager upgrade is required to install the baseline. ${manual(version,packageRoot)}`);const old=validateManifest(oldBytes,oldDigest,installed.version);const oldSpelling=new Map(old.files.map(file=>[file.path.toLowerCase(),file.path]));if(manifest.files.some(file=>oldSpelling.has(file.path.toLowerCase())&&oldSpelling.get(file.path.toLowerCase())!==file.path))throw Error("This release renames files only by letter case. "+manual(version,packageRoot));const generated=await reconstruct(manifest,manifestBytes,offered.manifestSha256);const nextPaths=new Set(manifest.files.map(file=>file.path));const removed=old.files.filter(file=>!nextPaths.has(file.path)).map(file=>file.path);let dependencies;if(dependencyChange){const dependencyStage=join(stage,"dependencies");dependencies=await(options.prepareDependencies??prepareDependencyUpdate)({packageRoot,stageRoot:dependencyStage,installedPackage:installed,targetPackage:manifest.package,env,registryUrl:registry});if(dependencies.replacements.length+dependencies.removals.length>2e3)throw Error("Too many dependency changes.");const seen=new Set,owned=[...old.files,...manifest.files].map(file=>file.path.toLowerCase());for(const path of[...dependencies.removals,...dependencies.replacements.map(row=>row.path)]){dependencyPath(path);const key=path.toLowerCase();if(seen.has(key)||owned.some(file=>file===key||file.startsWith(key+"/")))throw Error("Dependency update overlaps bundled product files.");seen.add(key);const existing=await lstat(await safeFile(packageRoot,path)).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(existing&&!existing.isDirectory())throw Error("Dependency update destination is not a directory.")}for(const replacement of dependencies.replacements){const source=await realpath(replacement.source),rel=relative(dependencyStage,source);if(!rel||isAbsolute(rel)||rel===".."||rel.startsWith(".."+sep)||!(await lstat(source)).isDirectory()||(await lstat(replacement.source)).isSymbolicLink())throw Error("Dependency update source is outside the staging directory.");replacement.source=source}const hiddenLock="node_modules/.package-lock.json";if(await optionalBytes(await safeFile(packageRoot,hiddenLock)))removed.push(hiddenLock)}const changes=[];const binPaths=new Set((typeof manifest.package.bin==="string"?[manifest.package.bin]:Object.values(manifest.package.bin??{})).map(path=>path.replace(/^\.\//,"")));let downloadedBytes=manifestBytes.length,reusedBytes=0;let cursor=0;await Promise.all(Array.from({length:8},async()=>{while(cursor<manifest.files.length){const file=manifest.files[cursor++];const destination=await safeFile(packageRoot,file.path);const existing=await optionalBytes(destination);const existingMode=existing===null?void 0:(await lstat(destination)).mode&511;const mode=file.mode??(binPaths.has(file.path)?493:existingMode);if(existing?.length===file.size&&hash(existing)===file.sha256){reusedBytes+=file.size;if(process.platform!=="win32"&&mode!==void 0&&mode!==existingMode)changes.push({path:file.path,bytes:existing,mode});continue}const bytes=await get(fileUrl(version,file.path),file.size,3e4);if(bytes.length!==file.size||hash(bytes)!==file.sha256)throw Error("Updated file integrity check failed: "+file.path);downloadedBytes+=bytes.length;changes.push({path:file.path,bytes,...mode===void 0?{}:{mode}})}}));for(const[path,bytes]of generated)changes.push({path,bytes});changes.sort((a,b)=>a.path===RECOVERY_FILE?-1:b.path===RECOVERY_FILE?1:a.path==="package.json"?1:b.path==="package.json"?-1:a.path.localeCompare(b.path));await mkdir(join(stage,"backup"),{recursive:true});const files=[];for(const path of[...dependencies?.removals??[],...dependencies?.replacements.map(row=>row.path)??[]]){const destination=await safeFile(packageRoot,path),existing=await lstat(destination).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});files.push({path,existed:!!existing,kind:"directory"});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await cp(destination,backup,{recursive:true,verbatimSymlinks:true})}}for(const path of[...removed,...changes.map(file=>file.path)]){const destination=await safeFile(packageRoot,path),existing=await optionalBytes(destination);files.push({path,existed:existing!==null});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await copyFile(destination,backup)}}for(const file of changes){const staged=join(stage,"new",file.path);await mkdir(dirname(staged),{recursive:true});await writeFile(staged,file.bytes);if(file.mode!==void 0)await chmod(staged,file.mode)}journal={schemaVersion:1,pid:process.pid,stage:stageName,phase:"applying",files};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(journal));for(const path of removed)await rm(await safeFile(packageRoot,path),{force:true});for(const path of dependencies?.removals??[])await rm(await safeFile(packageRoot,path),{recursive:true,force:true});for(const replacement of dependencies?.replacements??[]){const destination=await safeFile(packageRoot,replacement.path);await rm(destination,{recursive:true,force:true});await mkdir(dirname(destination),{recursive:true});await rename(replacement.source,destination)}for(const file of changes){const destination=await safeFile(packageRoot,file.path);await mkdir(dirname(destination),{recursive:true});await rename(join(stage,"new",file.path),destination)}await smoke(version);const committed={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(committed));journal=committed;await rm(offerPath,{force:true}).catch(()=>{});await rm(statusPath,{force:true}).catch(()=>{});return{state:"updated",currentVersion:installed.version,targetVersion:version,installationPath:packageRoot,downloadedBytes,reusedBytes,byteScope:"product-files",...dependencies?{dependencyUpdate:{reusedPackages:dependencies.reusedPackages,changedPackages:dependencies.changedPackages,durationMs:dependencies.durationMs}}:{},changedFiles:changes.length,removedFiles:removed.length,durationMs:Math.round(performance.now()-started),restartRequired:true}}catch(error){if(journal?.phase==="applying"){try{await rollback(journal);const restored={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(restored));journal=restored}catch(recoveryError){retainRecovery=true;throw recoveryError}}throw error}finally{try{if(!retainRecovery){try{await rm(stage,{recursive:true,force:true});await rm(join(packageRoot,JOURNAL),{force:true})}catch(cleanupError){if(journal?.phase!=="committed")throw cleanupError}}}finally{await unlock()}}}return{check,status,apply,recover,observe:outcomes.observe}}export const productUpdater=createUpdater();
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";import{readFile,writeFile,mkdir,lstat,realpath,rename,copyFile,cp,rm,chmod}from"node:fs/promises";import{resolve,join,dirname,relative,isAbsolute,sep}from"node:path";import{homedir}from"node:os";import{fileURLToPath}from"node:url";import{execFile}from"node:child_process";import{promisify}from"node:util";import{prepareDependencyUpdate}from"./update-dependencies.js";import{createUpdateTelemetry}from"./update-telemetry.js";import{createUpdateRecovery,safePath,safeFile,optionalBytes,dependencyPath,atomicWrite,JOURNAL,RECOVERY_FILE}from"./update-recovery.js";const execute=promisify(execFile);const NAME="@zortexhq/indra-v2.5";const MANIFEST="update-manifest.json";const MAX_BYTES=12e7;const hash=bytes=>createHash("sha256").update(bytes).digest("hex");const jsonBytes=value=>Buffer.from(JSON.stringify(value,null,2)+"\n");function metadataDigest(pkg){const update=pkg.zortexUpdate;if(update?.schemaVersion!==1||update.manifest!==MANIFEST||!/^[a-f0-9]{64}$/.test(update.sha256??""))return void 0;return update.sha256}function validateManifest(bytes,digest,version){if(hash(bytes)!==digest)throw Error("Update manifest integrity check failed.");const value=JSON.parse(bytes.toString("utf8"));if(value.schemaVersion!==1||value.package?.name!==NAME||value.package.version!==version||value.package.zortexUpdate||!Array.isArray(value.files)||value.files.length>8e3)throw Error("Invalid update manifest.");let total=0;const paths=new Set;for(const file of value.files){safePath(file.path);const key=file.path.toLowerCase();if(paths.has(key)||[MANIFEST,"package.json","release-provenance.json"].includes(key)||!/^[a-f0-9]{64}$/.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0||file.mode!==void 0&&![420,493,420,493].includes(file.mode))throw Error("Invalid update file entry.");paths.add(key);total+=file.size}if(total>MAX_BYTES)throw Error("Update exceeds the installed product size limit.");return value}function dependencyShape(pkg){const bundled=new Set(pkg.bundledDependencies??[]);return JSON.stringify(["dependencies","optionalDependencies","peerDependencies","peerDependenciesMeta"].map(field=>[field,Object.entries(pkg[field]??{}).filter(([name])=>!bundled.has(name)).sort(([a],[b])=>a.localeCompare(b))]))}function binShape(pkg){const bins=typeof pkg.bin==="string"?{[pkg.name.split("/").at(-1)]:pkg.bin}:pkg.bin??{};return JSON.stringify(Object.entries(bins).map(([name,path])=>[name,typeof path==="string"?path.replace(/^\.\//,""):path]).sort(([a],[b])=>String(a).localeCompare(String(b))))}function versionParts(version){const match=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);if(!match)throw Error("Invalid registry version.");return[Number(match[1]),Number(match[2]),Number(match[3]),match[4]]}function newer(current,target,times={}){if(current===target)return false;const a=versionParts(current),b=versionParts(target);for(const i of[0,1,2])if(a[i]!==b[i])return b[i]>a[i];if(!a[3])return false;if(!b[3])return true;const oldTime=Date.parse(times[current]??""),newTime=Date.parse(times[target]??"");if(Number.isFinite(oldTime)&&Number.isFinite(newTime))return newTime>oldTime;const left=a[3].split("."),right=b[3].split(".");for(let i=0;i<Math.max(left.length,right.length);i++){if(left[i]===right[i])continue;if(left[i]===void 0)return true;if(right[i]===void 0)return false;return/^\d+$/.test(left[i])&&/^\d+$/.test(right[i])?Number(right[i])>Number(left[i]):right[i]>left[i]}return false}function manual(version,installationPath){return`Use the package manager that installed ${installationPath} to upgrade ${NAME} to exactly ${version} at that installation path.`}export function createUpdater(options={}){let packageRoot=resolve(options.packageRoot??fileURLToPath(new URL("..",import.meta.url)));const requestedRoot=packageRoot;const{recover,recoverLocked,withRecoveryLock,publishLock,rollback}=createUpdateRecovery(requestedRoot);let rootIsLinked=false,rootReady;const canonicalizeRoot=()=>rootReady??=(async()=>{rootIsLinked=(await lstat(requestedRoot)).isSymbolicLink();packageRoot=await realpath(requestedRoot)})();const cacheRoot=resolve(options.cacheRoot??join(homedir(),".zortex","updates",hash(packageRoot).slice(0,24)));const registry=(options.registryUrl??"https://registry.npmjs.org").replace(/\/$/,"");const content=(options.contentBaseUrl??"https://cdn.jsdelivr.net/npm").replace(/\/$/,"");const fetcher=options.fetch??globalThis.fetch,now=options.now??Date.now;const env=options.env??process.env;const outcomes=createUpdateTelemetry({cacheRoot,env,now});const disabled=()=>/^(0|false|off)$/i.test(env.ZORTEX_UPDATES??"");const offerPath=join(cacheRoot,"offer.json"),statusPath=join(cacheRoot,"status.json");const pkg=async()=>{await canonicalizeRoot();return JSON.parse(await readFile(join(packageRoot,"package.json"),"utf8"))};async function get(url,limit,timeout=5e3){const response=await fetcher(url,{signal:AbortSignal.timeout(timeout),redirect:"error"});if(!response.ok||!response.body)throw Error(`Update download unavailable (${response.status}).`);if(Number(response.headers.get("content-length")??0)>limit)throw Error("Update response exceeds its size limit.");const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.length;if(size>limit)throw Error("Update response exceeds its size limit.");chunks.push(chunk)}return Buffer.concat(chunks)}const fileUrl=(version,path)=>`${content}/${NAME}@${encodeURIComponent(version)}/${path.split("/").map(encodeURIComponent).join("/")}`;async function savedOffer(){await canonicalizeRoot();const bytes=await optionalBytes(offerPath);const parsed=bytes?JSON.parse(bytes.toString("utf8")):void 0;const offered=parsed?(({confirmationRequired:_legacy,...offer})=>offer)(parsed):void 0;return offered?.installationPath===packageRoot?offered:void 0}async function savedStatus(version){try{const bytes=await optionalBytes(statusPath);const cached=bytes?JSON.parse(bytes.toString("utf8")):void 0;if(cached?.status?.currentVersion===version&&cached.expiresAt>now())return cached.status}catch{}return void 0}async function remember(status2,ttl){await rm(offerPath,{force:true});await mkdir(cacheRoot,{recursive:true});await atomicWrite(statusPath,jsonBytes({status:status2,checkedAt:now(),expiresAt:now()+ttl}));return status2}async function writableInstallation(){await canonicalizeRoot();if(rootIsLinked||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(packageRoot)||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(requestedRoot)||await optionalBytes(join(packageRoot,"tsconfig.json")))throw Error("This installation is managed by a workspace or another package manager. Use its original upgrade command.");if((await pkg()).name!==NAME)throw Error("The running installation is not the Zortex package.")}async function check({force=false}={}){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(!force&&cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached;if(!force){const cachedStatus=await savedStatus(installed.version);if(cachedStatus)return cachedStatus}const packument=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}`,16e6)).toString("utf8"));const channel="next";const target=packument["dist-tags"]?.[channel];if(typeof target!=="string")throw Error("The update channel is unavailable.");if(!newer(installed.version,target,packument.time))return await remember({state:"current",currentVersion:installed.version},6*60*6e4);const targetPackage=packument.versions?.[target];if(targetPackage?.name!==NAME||targetPackage.version!==target)throw Error("Invalid registry package identity.");const digest=metadataDigest(targetPackage);if(!digest)return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release does not publish verified incremental updates. No package was downloaded.",manualCommand:manual(target,packageRoot)},6*60*6e4);if(binShape(installed)!==binShape(targetPackage))return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release changes installed command links and requires its original package manager.",manualCommand:manual(target,packageRoot)},6*60*6e4);await writableInstallation();let expectedDownloadBytes,expectedChangedFiles;try{const manifestBytes=await get(fileUrl(target,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,digest,target);const oldDigest=metadataDigest(installed),oldBytes=oldDigest?await optionalBytes(join(packageRoot,MANIFEST)):void 0;if(oldDigest&&oldBytes){const old=validateManifest(oldBytes,oldDigest,installed.version);const oldByPath=new Map(old.files.map(file=>[file.path,file.sha256]));const generated=await reconstruct(manifest,manifestBytes,digest);for(const[path,bytes]of generated){if(oldByPath.get(path)===hash(bytes))continue;expectedDownloadBytes=(expectedDownloadBytes??0)+bytes.length;expectedChangedFiles=(expectedChangedFiles??0)+1}for(const file of manifest.files){if(oldByPath.get(file.path)===file.sha256)continue;expectedDownloadBytes=(expectedDownloadBytes??0)+file.size;expectedChangedFiles=(expectedChangedFiles??0)+1}}}catch{}const offer={state:"available",currentVersion:installed.version,targetVersion:target,installationPath:packageRoot,confirmationToken:randomUUID(),manifestSha256:digest,checkedAt:now(),expiresAt:now()+15*6e4,channel,...expectedDownloadBytes!==void 0&&expectedChangedFiles!==void 0?{expectedDownloadBytes,expectedChangedFiles}:{}};await mkdir(cacheRoot,{recursive:true});await atomicWrite(offerPath,jsonBytes(offer));await rm(statusPath,{force:true});return offer}catch(error){const unavailable={state:"unavailable",currentVersion:installed.version,message:error instanceof Error?error.message:"Update check failed."};try{await remember(unavailable,15*6e4)}catch{}return unavailable}}async function status(){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached}catch{}return await savedStatus(installed.version)??{state:"unavailable",currentVersion:installed.version,message:"No current update result is cached. Use update check to check the registry."}}async function reconstruct(manifest,bytes,digest){const packageBytes=jsonBytes({...manifest.package,zortexUpdate:{schemaVersion:1,manifest:MANIFEST,sha256:digest}});const generated=new Map([["package.json",packageBytes],[MANIFEST,bytes]]);if(manifest.provenance){const provenance=structuredClone(manifest.provenance);const own=manifest.files.filter(file=>!file.path.startsWith("node_modules/")).map(file=>({path:file.path,sha256:file.sha256}));own.push({path:"package.json",sha256:hash(packageBytes)},{path:MANIFEST,sha256:hash(bytes)});const root=provenance.packages?.find(row=>row.target==="");if(!root||root.filesSha256!==null)throw Error("Invalid update provenance template.");root.filesSha256=hash(own.map(file=>file.path+"\0"+file.sha256).sort().join("\n"));generated.set("release-provenance.json",jsonBytes(provenance))}return generated}async function smoke(version){if(options.smokeTest)return options.smokeTest(packageRoot,version);const cli=join(packageRoot,"dist","cli.js");const verificationEnv={...env,ZORTEX_UPDATES:"0",ZORTEX_UPDATE_VERIFY:"1",ZORTEX_AUTO_SYNC:"0",ZORTEX_CODEX_SETUP:"0",ZORTEX_TELEMETRY:"0",ZORTEX_FEEDBACK_TRAFFIC_CLASS:"internal_test"};const result=await execute(process.execPath,[cli,"--version"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024});if(JSON.parse(result.stdout).version!==version)throw Error("The updated command still runs a different version.");await execute(process.execPath,[cli,"--help"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024})}async function withInstallationLock(action){if(disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");await writableInstallation();await recover();let unlock;try{unlock=await withRecoveryLock(async()=>{await recoverLocked();return publishLock(join(packageRoot,".zortex-update.lock"))})}catch(error){if(error.code==="EEXIST")throw Error("Another update holds the installation lock.");throw error}try{return await action({installationPath:packageRoot,environment:{ZORTEX_UPDATE_HANDOVER:unlock.token}})}finally{await unlock()}}async function apply({version,confirmationToken},lifecycle){if(disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");const offered=await savedOffer();if(!confirmationToken||!offered||offered.confirmationToken!==confirmationToken||offered.targetVersion!==version||offered.expiresAt<=now())throw Error("The release offer is missing, expired or mismatched. Run check again and retry with its version and token.");const confirmedAt=performance.now();const attempt=await outcomes.confirmed(offered.currentVersion,version).catch(()=>void 0);try{const result=await applyConfirmed(offered,version,lifecycle);const durationMs=Math.round(performance.now()-confirmedAt);await outcomes.installed(attempt,durationMs).catch(()=>{});return{...result,durationMs}}catch(error){await outcomes.failed(attempt,performance.now()-confirmedAt).catch(()=>{});throw error}}async function applyConfirmed(offered,version,lifecycle){return withInstallationLock(async lease=>{const installed=await pkg();if(installed.version!==offered.currentVersion)throw Error("The installed version changed. Check again before updating.");await mkdir(cacheRoot,{recursive:true});const started=performance.now();const stageName=".zortex-update-"+randomUUID(),stage=join(packageRoot,stageName);let journal,retainRecovery=false,updated=false;try{const target=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}/${encodeURIComponent(version)}`,2e6)).toString("utf8"));if(target.name!==NAME||target.version!==version||metadataDigest(target)!==offered.manifestSha256)throw Error("The release changed. Run check again and retry with the current version and token.");const manifestBytes=await get(fileUrl(version,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,offered.manifestSha256,version);if(!manifest.files.some(file=>file.path===RECOVERY_FILE))throw Error("This release removes the standalone update recovery module. "+manual(version,packageRoot));if(binShape(installed)!==binShape(manifest.package))throw Error("This release changes installed command links. "+manual(version,packageRoot));const dependencyChange=dependencyShape(installed)!==dependencyShape(manifest.package);const oldDigest=metadataDigest(installed),oldBytes=await optionalBytes(join(packageRoot,MANIFEST));if(!oldDigest||!oldBytes)throw Error(`This installation predates the incremental updater. One package-manager upgrade is required to install the baseline. ${manual(version,packageRoot)}`);const old=validateManifest(oldBytes,oldDigest,installed.version);const oldSpelling=new Map(old.files.map(file=>[file.path.toLowerCase(),file.path]));if(manifest.files.some(file=>oldSpelling.has(file.path.toLowerCase())&&oldSpelling.get(file.path.toLowerCase())!==file.path))throw Error("This release renames files only by letter case. "+manual(version,packageRoot));const generated=await reconstruct(manifest,manifestBytes,offered.manifestSha256);const nextPaths=new Set(manifest.files.map(file=>file.path));const removed=old.files.filter(file=>!nextPaths.has(file.path)).map(file=>file.path);let dependencies;if(dependencyChange){const dependencyStage=join(stage,"dependencies");dependencies=await(options.prepareDependencies??prepareDependencyUpdate)({packageRoot,stageRoot:dependencyStage,installedPackage:installed,targetPackage:manifest.package,env,registryUrl:registry});if(dependencies.replacements.length+dependencies.removals.length>2e3)throw Error("Too many dependency changes.");const seen=new Set,owned=[...old.files,...manifest.files].map(file=>file.path.toLowerCase());for(const path of[...dependencies.removals,...dependencies.replacements.map(row=>row.path)]){dependencyPath(path);const key=path.toLowerCase();if(seen.has(key)||owned.some(file=>file===key||file.startsWith(key+"/")))throw Error("Dependency update overlaps bundled product files.");seen.add(key);const existing=await lstat(await safeFile(packageRoot,path)).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(existing&&!existing.isDirectory())throw Error("Dependency update destination is not a directory.")}for(const replacement of dependencies.replacements){const source=await realpath(replacement.source),rel=relative(dependencyStage,source);if(!rel||isAbsolute(rel)||rel===".."||rel.startsWith(".."+sep)||!(await lstat(source)).isDirectory()||(await lstat(replacement.source)).isSymbolicLink())throw Error("Dependency update source is outside the staging directory.");replacement.source=source}const hiddenLock="node_modules/.package-lock.json";if(await optionalBytes(await safeFile(packageRoot,hiddenLock)))removed.push(hiddenLock)}const changes=[];const binPaths=new Set((typeof manifest.package.bin==="string"?[manifest.package.bin]:Object.values(manifest.package.bin??{})).map(path=>path.replace(/^\.\//,"")));let downloadedBytes=manifestBytes.length,reusedBytes=0;let cursor=0,downloadFailed=false;const downloads=await Promise.allSettled(Array.from({length:8},async()=>{try{while(!downloadFailed&&cursor<manifest.files.length){const file=manifest.files[cursor++];const destination=await safeFile(packageRoot,file.path);const existing=await optionalBytes(destination);const existingMode=existing===null?void 0:(await lstat(destination)).mode&511;const mode=file.mode??(binPaths.has(file.path)?493:existingMode);if(existing?.length===file.size&&hash(existing)===file.sha256){reusedBytes+=file.size;if(process.platform!=="win32"&&mode!==void 0&&mode!==existingMode)changes.push({path:file.path,bytes:existing,mode});continue}const bytes=await get(fileUrl(version,file.path),file.size,3e4);if(bytes.length!==file.size||hash(bytes)!==file.sha256)throw Error("Updated file integrity check failed: "+file.path);downloadedBytes+=bytes.length;changes.push({path:file.path,bytes,...mode===void 0?{}:{mode}})}}catch(error){downloadFailed=true;throw error}}));const failed=downloads.find(result=>result.status==="rejected");if(failed)throw failed.reason;for(const[path,bytes]of generated)changes.push({path,bytes});changes.sort((a,b)=>a.path===RECOVERY_FILE?-1:b.path===RECOVERY_FILE?1:a.path==="package.json"?1:b.path==="package.json"?-1:a.path.localeCompare(b.path));await mkdir(join(stage,"backup"),{recursive:true});const files=[];for(const path of[...dependencies?.removals??[],...dependencies?.replacements.map(row=>row.path)??[]]){const destination=await safeFile(packageRoot,path),existing=await lstat(destination).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});files.push({path,existed:!!existing,kind:"directory"});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await cp(destination,backup,{recursive:true,verbatimSymlinks:true})}}for(const path of[...removed,...changes.map(file=>file.path)]){const destination=await safeFile(packageRoot,path),existing=await optionalBytes(destination);files.push({path,existed:existing!==null});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await copyFile(destination,backup)}}for(const file of changes){const staged=join(stage,"new",file.path);await mkdir(dirname(staged),{recursive:true});await writeFile(staged,file.bytes);if(file.mode!==void 0)await chmod(staged,file.mode)}await lifecycle?.before(lease);journal={schemaVersion:1,pid:process.pid,stage:stageName,phase:"applying",files};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(journal));for(const path of removed)await rm(await safeFile(packageRoot,path),{force:true});for(const path of dependencies?.removals??[])await rm(await safeFile(packageRoot,path),{recursive:true,force:true});for(const replacement of dependencies?.replacements??[]){const destination=await safeFile(packageRoot,replacement.path);await rm(destination,{recursive:true,force:true});await mkdir(dirname(destination),{recursive:true});await rename(replacement.source,destination)}for(const file of changes){const destination=await safeFile(packageRoot,file.path);await mkdir(dirname(destination),{recursive:true});await rename(join(stage,"new",file.path),destination)}await smoke(version);const committed={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(committed));journal=committed;updated=true;await rm(offerPath,{force:true}).catch(()=>{});await rm(statusPath,{force:true}).catch(()=>{});return{state:"updated",currentVersion:installed.version,targetVersion:version,installationPath:packageRoot,downloadedBytes,reusedBytes,byteScope:"product-files",...dependencies?{dependencyUpdate:{reusedPackages:dependencies.reusedPackages,changedPackages:dependencies.changedPackages,durationMs:dependencies.durationMs}}:{},changedFiles:changes.length,removedFiles:removed.length,durationMs:Math.round(performance.now()-started),restartRequired:true}}catch(error){if(journal?.phase==="applying"){try{await rollback(journal);const restored={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(restored));journal=restored}catch(recoveryError){retainRecovery=true;throw recoveryError}}throw error}finally{try{await lifecycle?.after(lease,retainRecovery?"recovery-required":updated?"updated":"unchanged")}finally{if(!retainRecovery){try{await rm(stage,{recursive:true,force:true});await rm(join(packageRoot,JOURNAL),{force:true})}catch(cleanupError){if(journal?.phase!=="committed")throw cleanupError}}}}})}return{check,status,apply,recover,withInstallationLock,get installationPath(){return packageRoot},get updatesEnabled(){return!disabled()},observe:outcomes.observe}}export const productUpdater=createUpdater();
|