appduct 0.10.0 → 0.11.1
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 +122 -52
- package/dist/artifact-inspect.d.ts +0 -1
- package/dist/bin.d.ts +0 -1
- package/dist/bin.js +1250 -2
- package/dist/cli/command-options.d.ts +8 -1
- package/dist/cli/create-cli.d.ts +0 -1
- package/dist/cli/dispatch.d.ts +10 -1
- package/dist/cli/envelope.d.ts +19 -0
- package/dist/cli/global-flags.d.ts +30 -0
- package/dist/cli/open-target.d.ts +25 -8
- package/dist/cli/result-types.d.ts +31 -5
- package/dist/cli/router.d.ts +78 -0
- package/dist/cli/routes/daemon/index.d.ts +9 -0
- package/dist/cli/routes/daemon/index.js +848 -0
- package/dist/cli/routes/daemon/run.d.ts +3 -0
- package/dist/cli/routes/daemon/run.js +3246 -0
- package/dist/cli/routes/daemon/start.d.ts +3 -0
- package/dist/cli/routes/daemon/start.js +1677 -0
- package/dist/cli/routes/daemon/status.d.ts +4 -0
- package/dist/cli/routes/daemon/status.js +1685 -0
- package/dist/cli/routes/daemon/stop.d.ts +4 -0
- package/dist/cli/routes/daemon/stop.js +1655 -0
- package/dist/cli/routes/doctor.d.ts +3 -0
- package/dist/cli/routes/doctor.js +1075 -0
- package/dist/cli/routes/events.d.ts +3 -0
- package/dist/cli/routes/events.js +1915 -0
- package/dist/cli/routes/init.d.ts +3 -0
- package/dist/cli/routes/init.js +1486 -0
- package/dist/cli/routes/invoke.d.ts +3 -0
- package/dist/cli/routes/invoke.js +1893 -0
- package/dist/cli/routes/keygen.d.ts +3 -0
- package/dist/cli/routes/keygen.js +928 -0
- package/dist/cli/routes/link.d.ts +3 -0
- package/dist/cli/routes/link.js +2714 -0
- package/dist/cli/routes/ls.d.ts +3 -0
- package/dist/cli/routes/ls.js +1668 -0
- package/dist/cli/routes/mcp.d.ts +5 -0
- package/dist/cli/routes/mcp.js +3929 -0
- package/dist/cli/routes/revoke.d.ts +3 -0
- package/dist/cli/routes/revoke.js +1684 -0
- package/dist/cli/routes/tools.d.ts +3 -0
- package/dist/cli/routes/tools.js +1860 -0
- package/dist/cli/runner.d.ts +3 -11
- package/dist/cli/types.d.ts +9 -6
- package/dist/cli/version-guard.d.ts +20 -0
- package/dist/cli.d.ts +0 -1
- package/dist/client/app-client.d.ts +4 -4
- package/dist/client/bootstrap.d.ts +4 -4
- package/dist/client/connect.d.ts +0 -1
- package/dist/client/errors.d.ts +0 -1
- package/dist/client/index.d.ts +1 -2
- package/dist/client/index.js +2389 -16
- package/dist/commands/daemon/context.d.ts +14 -0
- package/dist/commands/daemon/run.d.ts +11 -0
- package/dist/commands/daemon/start.d.ts +5 -0
- package/dist/commands/daemon/status.d.ts +5 -0
- package/dist/commands/daemon/stop.d.ts +5 -0
- package/dist/commands/doctor.d.ts +0 -1
- package/dist/commands/events.d.ts +0 -1
- package/dist/commands/init.d.ts +17 -4
- package/dist/commands/invoke.d.ts +0 -1
- package/dist/commands/keygen.d.ts +0 -1
- package/dist/commands/link.d.ts +1 -2
- package/dist/commands/ls.d.ts +0 -1
- package/dist/commands/mcp.d.ts +2 -4
- package/dist/commands/revoke.d.ts +0 -1
- package/dist/commands/tools.d.ts +19 -3
- package/dist/daemon/address.d.ts +0 -1
- package/dist/daemon/audit.d.ts +6 -11
- package/dist/daemon/calls.d.ts +0 -1
- package/dist/daemon/config.d.ts +13 -16
- package/dist/daemon/daemon.d.ts +0 -1
- package/dist/daemon/event-bus.d.ts +0 -1
- package/dist/daemon/links.d.ts +0 -1
- package/dist/daemon/listener.d.ts +0 -1
- package/dist/daemon/log-rotation.d.ts +0 -1
- package/dist/daemon/pidfile.d.ts +14 -8
- package/dist/daemon/policy.d.ts +0 -1
- package/dist/daemon/registry.d.ts +0 -1
- package/dist/daemon/rpc-errors.d.ts +16 -0
- package/dist/daemon/rpc-server.d.ts +0 -11
- package/dist/daemon/sessions.d.ts +0 -1
- package/dist/daemon/socket-probe.d.ts +0 -1
- package/dist/daemon/state-dir.d.ts +0 -1
- package/dist/daemon/timers.d.ts +0 -1
- package/dist/daemon/tls.d.ts +0 -1
- package/dist/errors.d.ts +0 -1
- package/dist/host-certificate.d.ts +0 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.js +1307 -3
- package/dist/key-material.d.ts +0 -1
- package/dist/link.d.ts +8 -7
- package/dist/mcp/app-tools.d.ts +153 -0
- package/dist/mcp/connect-tool.d.ts +14 -8
- package/dist/mcp/daemon-tools.d.ts +2 -11
- package/dist/mcp/events-tool.d.ts +0 -1
- package/dist/mcp/server.d.ts +33 -14
- package/dist/native-scheme.d.ts +0 -1
- package/dist/output.d.ts +8 -11
- package/dist/package-root.d.ts +11 -0
- package/dist/package-version.d.ts +0 -1
- package/dist/qr-terminal.d.ts +0 -1
- package/dist/rpc/client.d.ts +3 -3
- package/dist/scheme.d.ts +60 -2
- package/dist/spki-pin.d.ts +0 -1
- package/package.json +6 -3
- package/dist/artifact-inspect.d.ts.map +0 -1
- package/dist/artifact-inspect.js +0 -334
- package/dist/bin.d.ts.map +0 -1
- package/dist/cli/command-options.d.ts.map +0 -1
- package/dist/cli/command-options.js +0 -95
- package/dist/cli/create-cli.d.ts.map +0 -1
- package/dist/cli/create-cli.js +0 -56
- package/dist/cli/dispatch.d.ts.map +0 -1
- package/dist/cli/dispatch.js +0 -275
- package/dist/cli/open-target.d.ts.map +0 -1
- package/dist/cli/open-target.js +0 -438
- package/dist/cli/result-types.d.ts.map +0 -1
- package/dist/cli/result-types.js +0 -6
- package/dist/cli/runner.d.ts.map +0 -1
- package/dist/cli/runner.js +0 -111
- package/dist/cli/types.d.ts.map +0 -1
- package/dist/cli/types.js +0 -10
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js +0 -2
- package/dist/client/app-client.d.ts.map +0 -1
- package/dist/client/app-client.js +0 -223
- package/dist/client/bootstrap.d.ts.map +0 -1
- package/dist/client/bootstrap.js +0 -108
- package/dist/client/connect.d.ts.map +0 -1
- package/dist/client/connect.js +0 -38
- package/dist/client/errors.d.ts.map +0 -1
- package/dist/client/errors.js +0 -40
- package/dist/client/index.d.ts.map +0 -1
- package/dist/commands/daemon.d.ts +0 -22
- package/dist/commands/daemon.d.ts.map +0 -1
- package/dist/commands/daemon.js +0 -128
- package/dist/commands/doctor.d.ts.map +0 -1
- package/dist/commands/doctor.js +0 -42
- package/dist/commands/events.d.ts.map +0 -1
- package/dist/commands/events.js +0 -76
- package/dist/commands/init.d.ts.map +0 -1
- package/dist/commands/init.js +0 -231
- package/dist/commands/invoke.d.ts.map +0 -1
- package/dist/commands/invoke.js +0 -54
- package/dist/commands/keygen.d.ts.map +0 -1
- package/dist/commands/keygen.js +0 -46
- package/dist/commands/link.d.ts.map +0 -1
- package/dist/commands/link.js +0 -43
- package/dist/commands/ls.d.ts.map +0 -1
- package/dist/commands/ls.js +0 -7
- package/dist/commands/mcp.d.ts.map +0 -1
- package/dist/commands/mcp.js +0 -98
- package/dist/commands/revoke.d.ts.map +0 -1
- package/dist/commands/revoke.js +0 -7
- package/dist/commands/tools.d.ts.map +0 -1
- package/dist/commands/tools.js +0 -52
- package/dist/daemon/address.d.ts.map +0 -1
- package/dist/daemon/address.js +0 -71
- package/dist/daemon/audit.d.ts.map +0 -1
- package/dist/daemon/audit.js +0 -237
- package/dist/daemon/calls.d.ts.map +0 -1
- package/dist/daemon/calls.js +0 -158
- package/dist/daemon/config.d.ts.map +0 -1
- package/dist/daemon/config.js +0 -170
- package/dist/daemon/daemon.d.ts.map +0 -1
- package/dist/daemon/daemon.js +0 -560
- package/dist/daemon/event-bus.d.ts.map +0 -1
- package/dist/daemon/event-bus.js +0 -111
- package/dist/daemon/links.d.ts.map +0 -1
- package/dist/daemon/links.js +0 -118
- package/dist/daemon/listener.d.ts.map +0 -1
- package/dist/daemon/listener.js +0 -132
- package/dist/daemon/log-rotation.d.ts.map +0 -1
- package/dist/daemon/log-rotation.js +0 -136
- package/dist/daemon/pidfile.d.ts.map +0 -1
- package/dist/daemon/pidfile.js +0 -90
- package/dist/daemon/policy.d.ts.map +0 -1
- package/dist/daemon/policy.js +0 -24
- package/dist/daemon/registry.d.ts.map +0 -1
- package/dist/daemon/registry.js +0 -31
- package/dist/daemon/rpc-server.d.ts.map +0 -1
- package/dist/daemon/rpc-server.js +0 -203
- package/dist/daemon/sessions.d.ts.map +0 -1
- package/dist/daemon/sessions.js +0 -429
- package/dist/daemon/socket-probe.d.ts.map +0 -1
- package/dist/daemon/socket-probe.js +0 -28
- package/dist/daemon/state-dir.d.ts.map +0 -1
- package/dist/daemon/state-dir.js +0 -43
- package/dist/daemon/timers.d.ts.map +0 -1
- package/dist/daemon/timers.js +0 -12
- package/dist/daemon/tls.d.ts.map +0 -1
- package/dist/daemon/tls.js +0 -79
- package/dist/errors.d.ts.map +0 -1
- package/dist/errors.js +0 -162
- package/dist/host-certificate.d.ts.map +0 -1
- package/dist/host-certificate.js +0 -111
- package/dist/index.d.ts.map +0 -1
- package/dist/key-material.d.ts.map +0 -1
- package/dist/key-material.js +0 -42
- package/dist/link.d.ts.map +0 -1
- package/dist/link.js +0 -117
- package/dist/mcp/connect-tool.d.ts.map +0 -1
- package/dist/mcp/connect-tool.js +0 -396
- package/dist/mcp/daemon-tools.d.ts.map +0 -1
- package/dist/mcp/daemon-tools.js +0 -29
- package/dist/mcp/events-tool.d.ts.map +0 -1
- package/dist/mcp/events-tool.js +0 -322
- package/dist/mcp/server.d.ts.map +0 -1
- package/dist/mcp/server.js +0 -538
- package/dist/mcp/tool-mapping.d.ts +0 -58
- package/dist/mcp/tool-mapping.d.ts.map +0 -1
- package/dist/mcp/tool-mapping.js +0 -143
- package/dist/mcp/tool-namespace.d.ts +0 -40
- package/dist/mcp/tool-namespace.d.ts.map +0 -1
- package/dist/mcp/tool-namespace.js +0 -65
- package/dist/native-scheme.d.ts.map +0 -1
- package/dist/native-scheme.js +0 -465
- package/dist/output.d.ts.map +0 -1
- package/dist/output.js +0 -342
- package/dist/package-version.d.ts.map +0 -1
- package/dist/package-version.js +0 -47
- package/dist/qr-terminal.d.ts.map +0 -1
- package/dist/qr-terminal.js +0 -45
- package/dist/rpc/client.d.ts.map +0 -1
- package/dist/rpc/client.js +0 -819
- package/dist/scheme.d.ts.map +0 -1
- package/dist/scheme.js +0 -321
- package/dist/spki-pin.d.ts.map +0 -1
- package/dist/spki-pin.js +0 -14
|
@@ -0,0 +1,2714 @@
|
|
|
1
|
+
// src/cli/open-target.ts
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { mkdtemp, readFile as readFile4, rm as rm3 } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
// src/rpc/client.ts
|
|
8
|
+
import { connect as connect2 } from "node:net";
|
|
9
|
+
import { spawn as spawnChildProcess } from "node:child_process";
|
|
10
|
+
import { open as open2, readFile as readFile3, rm as rm2, stat as stat2 } from "node:fs/promises";
|
|
11
|
+
import { join as join3 } from "node:path";
|
|
12
|
+
import { RPC_METHODS } from "@appduct/shared";
|
|
13
|
+
|
|
14
|
+
// src/daemon/log-rotation.ts
|
|
15
|
+
import { chmod as chmod2, rename, stat } from "node:fs/promises";
|
|
16
|
+
|
|
17
|
+
// src/daemon/config.ts
|
|
18
|
+
import { readFile } from "node:fs/promises";
|
|
19
|
+
var KNOWN_TOP_LEVEL_KEYS = /* @__PURE__ */ new Set([
|
|
20
|
+
"wssPort",
|
|
21
|
+
"keyPath",
|
|
22
|
+
"graceSeconds",
|
|
23
|
+
"linkTtlSeconds",
|
|
24
|
+
"keepaliveIntervalSeconds",
|
|
25
|
+
"eventBufferSize",
|
|
26
|
+
"auditRetentionDays",
|
|
27
|
+
"daemonLogMaxBytes",
|
|
28
|
+
"policy",
|
|
29
|
+
"advertisedIp",
|
|
30
|
+
"scheme",
|
|
31
|
+
"restartDaemonOnVersionMismatch"
|
|
32
|
+
]);
|
|
33
|
+
var KNOWN_POLICY_KEYS = /* @__PURE__ */ new Set(["default", "destructive", "tools"]);
|
|
34
|
+
var POLICY_DECISIONS = /* @__PURE__ */ new Set(["allow", "deny", "prompt"]);
|
|
35
|
+
var DEFAULT_AUDIT_RETENTION_DAYS = 30;
|
|
36
|
+
var DEFAULT_DAEMON_LOG_MAX_BYTES = 10 * 1024 * 1024;
|
|
37
|
+
var AppductConfigError = class extends Error {
|
|
38
|
+
constructor(key, message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.key = key;
|
|
41
|
+
this.name = "AppductConfigError";
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var configError = (key, message) => {
|
|
45
|
+
return new AppductConfigError(key, `Invalid Appduct config value for "${key}": ${message}`);
|
|
46
|
+
};
|
|
47
|
+
var requireWssPort = (value, key) => {
|
|
48
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 65535) {
|
|
49
|
+
throw configError(key, "must be a port number between 0 and 65535 (0 binds an OS-assigned port).");
|
|
50
|
+
}
|
|
51
|
+
return value;
|
|
52
|
+
};
|
|
53
|
+
var requirePositiveInteger = (value, key) => {
|
|
54
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
|
|
55
|
+
throw configError(key, "must be a positive integer.");
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
};
|
|
59
|
+
var requireNonEmptyString = (value, key) => {
|
|
60
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
61
|
+
throw configError(key, "must be a non-empty string.");
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
};
|
|
65
|
+
var requireBoolean = (value, key) => {
|
|
66
|
+
if (typeof value !== "boolean") {
|
|
67
|
+
throw configError(key, "must be a boolean.");
|
|
68
|
+
}
|
|
69
|
+
return value;
|
|
70
|
+
};
|
|
71
|
+
var requirePolicyDecision = (value, key) => {
|
|
72
|
+
if (typeof value !== "string" || !POLICY_DECISIONS.has(value)) {
|
|
73
|
+
throw configError(key, 'must be "allow", "deny", or "prompt".');
|
|
74
|
+
}
|
|
75
|
+
return value;
|
|
76
|
+
};
|
|
77
|
+
var defaultConfig = (paths) => {
|
|
78
|
+
return {
|
|
79
|
+
wssPort: 8443,
|
|
80
|
+
keyPath: paths.keyPath,
|
|
81
|
+
graceSeconds: 600,
|
|
82
|
+
linkTtlSeconds: 300,
|
|
83
|
+
keepaliveIntervalSeconds: 15,
|
|
84
|
+
eventBufferSize: 256,
|
|
85
|
+
auditRetentionDays: DEFAULT_AUDIT_RETENTION_DAYS,
|
|
86
|
+
daemonLogMaxBytes: DEFAULT_DAEMON_LOG_MAX_BYTES,
|
|
87
|
+
restartDaemonOnVersionMismatch: false,
|
|
88
|
+
policy: {
|
|
89
|
+
default: "allow",
|
|
90
|
+
destructive: "allow"
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
var loadConfig = async (paths, options = {}) => {
|
|
95
|
+
const warn = options.warn ?? (() => {
|
|
96
|
+
});
|
|
97
|
+
const config = defaultConfig(paths);
|
|
98
|
+
let raw;
|
|
99
|
+
try {
|
|
100
|
+
raw = JSON.parse(await readFile(paths.configPath, "utf8"));
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error.code === "ENOENT") {
|
|
103
|
+
return config;
|
|
104
|
+
}
|
|
105
|
+
throw configError("config.json", `could not be read/parsed (${error.message}).`);
|
|
106
|
+
}
|
|
107
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
108
|
+
throw configError("config.json", "must be a JSON object.");
|
|
109
|
+
}
|
|
110
|
+
const parsed = raw;
|
|
111
|
+
for (const key of Object.keys(parsed)) {
|
|
112
|
+
if (!KNOWN_TOP_LEVEL_KEYS.has(key)) {
|
|
113
|
+
warn(`Unknown Appduct config key "${key}" is ignored.`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (parsed.wssPort !== void 0) {
|
|
117
|
+
config.wssPort = requireWssPort(parsed.wssPort, "wssPort");
|
|
118
|
+
}
|
|
119
|
+
if (parsed.keyPath !== void 0) {
|
|
120
|
+
config.keyPath = requireNonEmptyString(parsed.keyPath, "keyPath");
|
|
121
|
+
}
|
|
122
|
+
if (parsed.advertisedIp !== void 0) {
|
|
123
|
+
config.advertisedIp = requireNonEmptyString(parsed.advertisedIp, "advertisedIp");
|
|
124
|
+
}
|
|
125
|
+
if (parsed.scheme !== void 0) {
|
|
126
|
+
config.scheme = requireNonEmptyString(parsed.scheme, "scheme");
|
|
127
|
+
}
|
|
128
|
+
if (parsed.graceSeconds !== void 0) {
|
|
129
|
+
config.graceSeconds = requirePositiveInteger(parsed.graceSeconds, "graceSeconds");
|
|
130
|
+
}
|
|
131
|
+
if (parsed.linkTtlSeconds !== void 0) {
|
|
132
|
+
config.linkTtlSeconds = requirePositiveInteger(parsed.linkTtlSeconds, "linkTtlSeconds");
|
|
133
|
+
}
|
|
134
|
+
if (parsed.keepaliveIntervalSeconds !== void 0) {
|
|
135
|
+
config.keepaliveIntervalSeconds = requirePositiveInteger(
|
|
136
|
+
parsed.keepaliveIntervalSeconds,
|
|
137
|
+
"keepaliveIntervalSeconds"
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
if (parsed.eventBufferSize !== void 0) {
|
|
141
|
+
config.eventBufferSize = requirePositiveInteger(parsed.eventBufferSize, "eventBufferSize");
|
|
142
|
+
}
|
|
143
|
+
if (parsed.auditRetentionDays !== void 0) {
|
|
144
|
+
config.auditRetentionDays = requirePositiveInteger(parsed.auditRetentionDays, "auditRetentionDays");
|
|
145
|
+
}
|
|
146
|
+
if (parsed.daemonLogMaxBytes !== void 0) {
|
|
147
|
+
config.daemonLogMaxBytes = requirePositiveInteger(parsed.daemonLogMaxBytes, "daemonLogMaxBytes");
|
|
148
|
+
}
|
|
149
|
+
if (parsed.restartDaemonOnVersionMismatch !== void 0) {
|
|
150
|
+
config.restartDaemonOnVersionMismatch = requireBoolean(
|
|
151
|
+
parsed.restartDaemonOnVersionMismatch,
|
|
152
|
+
"restartDaemonOnVersionMismatch"
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
if (parsed.policy !== void 0) {
|
|
156
|
+
if (typeof parsed.policy !== "object" || parsed.policy === null || Array.isArray(parsed.policy)) {
|
|
157
|
+
throw configError("policy", "must be an object.");
|
|
158
|
+
}
|
|
159
|
+
const policy = parsed.policy;
|
|
160
|
+
for (const key of Object.keys(policy)) {
|
|
161
|
+
if (!KNOWN_POLICY_KEYS.has(key)) {
|
|
162
|
+
warn(`Unknown Appduct config key "policy.${key}" is ignored.`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (policy.default !== void 0) {
|
|
166
|
+
config.policy.default = requirePolicyDecision(policy.default, "policy.default");
|
|
167
|
+
}
|
|
168
|
+
if (policy.destructive !== void 0) {
|
|
169
|
+
config.policy.destructive = requirePolicyDecision(policy.destructive, "policy.destructive");
|
|
170
|
+
}
|
|
171
|
+
if (policy.tools !== void 0) {
|
|
172
|
+
if (typeof policy.tools !== "object" || policy.tools === null || Array.isArray(policy.tools)) {
|
|
173
|
+
throw configError("policy.tools", "must be an object.");
|
|
174
|
+
}
|
|
175
|
+
const tools = {};
|
|
176
|
+
for (const [toolKey, toolValue] of Object.entries(policy.tools)) {
|
|
177
|
+
tools[toolKey] = requirePolicyDecision(toolValue, `policy.tools["${toolKey}"]`);
|
|
178
|
+
}
|
|
179
|
+
config.policy.tools = tools;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return config;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// src/daemon/pidfile.ts
|
|
186
|
+
import { readFileSync } from "node:fs";
|
|
187
|
+
import { open, readFile as readFile2, rm } from "node:fs/promises";
|
|
188
|
+
var readProcStatus = (pid) => {
|
|
189
|
+
try {
|
|
190
|
+
return readFileSync(`/proc/${pid}/status`, "utf8");
|
|
191
|
+
} catch {
|
|
192
|
+
return void 0;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
var isZombie = (pid, readStatus) => {
|
|
196
|
+
const status = readStatus(pid);
|
|
197
|
+
if (status === void 0) {
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
return /^State:\s*Z\b/mu.test(status);
|
|
201
|
+
};
|
|
202
|
+
var isProcessAlive = (pid, readStatus = readProcStatus) => {
|
|
203
|
+
try {
|
|
204
|
+
process.kill(pid, 0);
|
|
205
|
+
} catch (error) {
|
|
206
|
+
return error.code === "EPERM";
|
|
207
|
+
}
|
|
208
|
+
return !isZombie(pid, readStatus);
|
|
209
|
+
};
|
|
210
|
+
var readPidFromFile = async (pidFilePath) => {
|
|
211
|
+
let contents;
|
|
212
|
+
try {
|
|
213
|
+
contents = await readFile2(pidFilePath, "utf8");
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (error.code === "ENOENT") {
|
|
216
|
+
return void 0;
|
|
217
|
+
}
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
const pid = Number.parseInt(contents.trim(), 10);
|
|
221
|
+
return Number.isInteger(pid) && pid > 0 ? pid : void 0;
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
// src/daemon/socket-probe.ts
|
|
225
|
+
import { connect } from "node:net";
|
|
226
|
+
var isSocketConnectable = (socketPath) => {
|
|
227
|
+
return new Promise((resolve2) => {
|
|
228
|
+
const socket = connect(socketPath);
|
|
229
|
+
socket.once("connect", () => {
|
|
230
|
+
socket.destroy();
|
|
231
|
+
resolve2(true);
|
|
232
|
+
});
|
|
233
|
+
socket.once("error", () => {
|
|
234
|
+
socket.destroy();
|
|
235
|
+
resolve2(false);
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// src/daemon/state-dir.ts
|
|
241
|
+
import { join } from "node:path";
|
|
242
|
+
import { mkdir, chmod } from "node:fs/promises";
|
|
243
|
+
var getStateDirPaths = (stateDir) => {
|
|
244
|
+
return {
|
|
245
|
+
root: stateDir,
|
|
246
|
+
socketPath: join(stateDir, "daemon.sock"),
|
|
247
|
+
pidFilePath: join(stateDir, "daemon.pid"),
|
|
248
|
+
logFilePath: join(stateDir, "daemon.log"),
|
|
249
|
+
keyPath: join(stateDir, "key.pem"),
|
|
250
|
+
configPath: join(stateDir, "config.json"),
|
|
251
|
+
auditDir: join(stateDir, "audit"),
|
|
252
|
+
spawnLockPath: join(stateDir, "daemon.spawn.lock")
|
|
253
|
+
};
|
|
254
|
+
};
|
|
255
|
+
var ensureStateDir = async (stateDir) => {
|
|
256
|
+
const paths = getStateDirPaths(stateDir);
|
|
257
|
+
await mkdir(paths.auditDir, { recursive: true });
|
|
258
|
+
await chmod(paths.root, 448);
|
|
259
|
+
await chmod(paths.auditDir, 448);
|
|
260
|
+
return paths;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
// src/daemon/log-rotation.ts
|
|
264
|
+
var STATE_FILE_MODE = 384;
|
|
265
|
+
var daemonLogBackupPath = (logFilePath) => `${logFilePath}.1`;
|
|
266
|
+
var isDaemonHoldingLog = async (pidFilePath) => {
|
|
267
|
+
try {
|
|
268
|
+
const pid = await readPidFromFile(pidFilePath);
|
|
269
|
+
return pid !== void 0 && isProcessAlive(pid);
|
|
270
|
+
} catch {
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
var rotateDaemonLogIfNeeded = async (options) => {
|
|
275
|
+
const warn = options.warn ?? ((message) => {
|
|
276
|
+
process.stderr.write(`${message}
|
|
277
|
+
`);
|
|
278
|
+
});
|
|
279
|
+
try {
|
|
280
|
+
const stats = await stat(options.logFilePath);
|
|
281
|
+
if (!stats.isFile() || stats.size <= options.maxBytes) {
|
|
282
|
+
return { rotated: false };
|
|
283
|
+
}
|
|
284
|
+
const held = options.pidFilePath !== void 0 && await isDaemonHoldingLog(options.pidFilePath) || options.socketPath !== void 0 && await isSocketConnectable(options.socketPath);
|
|
285
|
+
if (held) {
|
|
286
|
+
warn(
|
|
287
|
+
`appduct: "${options.logFilePath}" is over its size cap but a daemon still holds it; leaving it in place.`
|
|
288
|
+
);
|
|
289
|
+
return { rotated: false, skipped: "daemon_running" };
|
|
290
|
+
}
|
|
291
|
+
const backupPath = daemonLogBackupPath(options.logFilePath);
|
|
292
|
+
await rename(options.logFilePath, backupPath);
|
|
293
|
+
try {
|
|
294
|
+
await chmod2(backupPath, STATE_FILE_MODE);
|
|
295
|
+
} catch (error) {
|
|
296
|
+
warn(`appduct: rotated "${options.logFilePath}" but could not set 0600 on "${backupPath}": ${error.message}`);
|
|
297
|
+
}
|
|
298
|
+
return { rotated: true, rotatedBytes: stats.size };
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error.code === "ENOENT") {
|
|
301
|
+
return { rotated: false };
|
|
302
|
+
}
|
|
303
|
+
warn(`appduct: failed to rotate "${options.logFilePath}": ${error.message}`);
|
|
304
|
+
return { rotated: false };
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
var ensureDaemonLogMode = async (logFilePath, warn = (message) => process.stderr.write(`${message}
|
|
308
|
+
`)) => {
|
|
309
|
+
try {
|
|
310
|
+
await chmod2(logFilePath, STATE_FILE_MODE);
|
|
311
|
+
return true;
|
|
312
|
+
} catch (error) {
|
|
313
|
+
warn(`appduct: could not set 0600 on "${logFilePath}": ${error.message}`);
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
var resolveDaemonLogMaxBytes = async (stateDir) => {
|
|
318
|
+
try {
|
|
319
|
+
return (await loadConfig(getStateDirPaths(stateDir))).daemonLogMaxBytes;
|
|
320
|
+
} catch {
|
|
321
|
+
return DEFAULT_DAEMON_LOG_MAX_BYTES;
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
// src/package-root.ts
|
|
326
|
+
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
327
|
+
import { dirname, join as join2 } from "node:path";
|
|
328
|
+
import { fileURLToPath } from "node:url";
|
|
329
|
+
var PACKAGE_NAME = "appduct";
|
|
330
|
+
var cached;
|
|
331
|
+
var getPackageRoot = () => {
|
|
332
|
+
if (cached !== void 0) {
|
|
333
|
+
return cached;
|
|
334
|
+
}
|
|
335
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
336
|
+
for (; ; ) {
|
|
337
|
+
const candidate = join2(dir, "package.json");
|
|
338
|
+
if (existsSync(candidate)) {
|
|
339
|
+
let name;
|
|
340
|
+
try {
|
|
341
|
+
name = JSON.parse(readFileSync2(candidate, "utf8")).name;
|
|
342
|
+
} catch {
|
|
343
|
+
}
|
|
344
|
+
if (name === PACKAGE_NAME) {
|
|
345
|
+
cached = dir;
|
|
346
|
+
return dir;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const parent = dirname(dir);
|
|
350
|
+
if (parent === dir) {
|
|
351
|
+
throw new Error(`Could not locate the "${PACKAGE_NAME}" package root above ${import.meta.url}.`);
|
|
352
|
+
}
|
|
353
|
+
dir = parent;
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
// src/package-version.ts
|
|
358
|
+
var DAEMON_VERSION_OVERRIDE_ENV = "APPDUCT_DAEMON_VERSION_OVERRIDE";
|
|
359
|
+
|
|
360
|
+
// src/rpc/client.ts
|
|
361
|
+
var defaultBinPath = join3(getPackageRoot(), "bin.js");
|
|
362
|
+
var DaemonRpcError = class extends Error {
|
|
363
|
+
constructor(code, message, data) {
|
|
364
|
+
super(message);
|
|
365
|
+
this.code = code;
|
|
366
|
+
this.data = data;
|
|
367
|
+
this.name = "DaemonRpcError";
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
var DaemonUnavailableError = class extends Error {
|
|
371
|
+
constructor(message, reason = "unreachable") {
|
|
372
|
+
super(message);
|
|
373
|
+
this.reason = reason;
|
|
374
|
+
this.name = "DaemonUnavailableError";
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
var isRequestTimeoutError = (error) => {
|
|
378
|
+
return error instanceof DaemonUnavailableError && error.reason === "timeout";
|
|
379
|
+
};
|
|
380
|
+
var describeLiveState = (state) => {
|
|
381
|
+
const parts = [];
|
|
382
|
+
if (state.sessions > 0) {
|
|
383
|
+
parts.push(`${state.sessions} connected session(s)`);
|
|
384
|
+
}
|
|
385
|
+
if (state.pendingLinks > 0) {
|
|
386
|
+
parts.push(`${state.pendingLinks} unclaimed link(s)`);
|
|
387
|
+
}
|
|
388
|
+
return parts.join(" and ");
|
|
389
|
+
};
|
|
390
|
+
var DaemonVersionMismatchError = class extends Error {
|
|
391
|
+
constructor(daemonVersion, clientVersion, live, message) {
|
|
392
|
+
super(
|
|
393
|
+
message ?? `The running Appduct daemon is version ${daemonVersion}, but this client is version ${clientVersion}. It was not restarted automatically because ${describeLiveState(live)} would be lost. Run "appduct daemon stop" once that state is expendable, or force it with "--daemon-restart".`
|
|
394
|
+
);
|
|
395
|
+
this.daemonVersion = daemonVersion;
|
|
396
|
+
this.clientVersion = clientVersion;
|
|
397
|
+
this.name = "DaemonVersionMismatchError";
|
|
398
|
+
this.sessionCount = live.sessions;
|
|
399
|
+
this.pendingLinkCount = live.pendingLinks;
|
|
400
|
+
}
|
|
401
|
+
sessionCount;
|
|
402
|
+
pendingLinkCount;
|
|
403
|
+
};
|
|
404
|
+
var DaemonVersionRestartIneffectiveError = class extends DaemonVersionMismatchError {
|
|
405
|
+
constructor(daemonVersion, clientVersion, live) {
|
|
406
|
+
super(
|
|
407
|
+
daemonVersion,
|
|
408
|
+
clientVersion,
|
|
409
|
+
live,
|
|
410
|
+
`The Appduct daemon was restarted to match this client (version ${clientVersion}), but the daemon now answering still reports version ${daemonVersion}. Either the old daemon never exited (compare "daemon.pid" with what "appduct daemon status" reports), or another process spawned an older daemon in the meantime. Run "appduct daemon stop", then retry.`
|
|
411
|
+
);
|
|
412
|
+
this.name = "DaemonVersionRestartIneffectiveError";
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
var parseVersion = (value) => {
|
|
416
|
+
const match = /^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u.exec(value.trim());
|
|
417
|
+
if (!match) {
|
|
418
|
+
return void 0;
|
|
419
|
+
}
|
|
420
|
+
return {
|
|
421
|
+
numbers: match[1].split(".").map(Number),
|
|
422
|
+
// Build metadata (`+…`) is dropped, per semver: it never affects precedence, so two versions
|
|
423
|
+
// differing only there are the same version and neither restarts nor warns about the other.
|
|
424
|
+
prerelease: match[2]?.split(".")
|
|
425
|
+
};
|
|
426
|
+
};
|
|
427
|
+
var isNumericIdentifier = (identifier) => /^\d+$/u.test(identifier);
|
|
428
|
+
var comparePrerelease = (left, right) => {
|
|
429
|
+
const length = Math.max(left.length, right.length);
|
|
430
|
+
for (let index = 0; index < length; index += 1) {
|
|
431
|
+
const a = left[index];
|
|
432
|
+
const b = right[index];
|
|
433
|
+
if (a === void 0) {
|
|
434
|
+
return -1;
|
|
435
|
+
}
|
|
436
|
+
if (b === void 0) {
|
|
437
|
+
return 1;
|
|
438
|
+
}
|
|
439
|
+
if (a === b) {
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
const aNumeric = isNumericIdentifier(a);
|
|
443
|
+
const bNumeric = isNumericIdentifier(b);
|
|
444
|
+
if (aNumeric && bNumeric) {
|
|
445
|
+
return Number(a) < Number(b) ? -1 : 1;
|
|
446
|
+
}
|
|
447
|
+
if (aNumeric !== bNumeric) {
|
|
448
|
+
return aNumeric ? -1 : 1;
|
|
449
|
+
}
|
|
450
|
+
return a < b ? -1 : 1;
|
|
451
|
+
}
|
|
452
|
+
return 0;
|
|
453
|
+
};
|
|
454
|
+
var compareVersions = (a, b) => {
|
|
455
|
+
const left = parseVersion(a);
|
|
456
|
+
const right = parseVersion(b);
|
|
457
|
+
if (!left || !right) {
|
|
458
|
+
return void 0;
|
|
459
|
+
}
|
|
460
|
+
const length = Math.max(left.numbers.length, right.numbers.length);
|
|
461
|
+
for (let index = 0; index < length; index += 1) {
|
|
462
|
+
const difference = (left.numbers[index] ?? 0) - (right.numbers[index] ?? 0);
|
|
463
|
+
if (difference !== 0) {
|
|
464
|
+
return difference < 0 ? -1 : 1;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
if (left.prerelease === void 0 && right.prerelease === void 0) {
|
|
468
|
+
return 0;
|
|
469
|
+
}
|
|
470
|
+
if (left.prerelease === void 0) {
|
|
471
|
+
return 1;
|
|
472
|
+
}
|
|
473
|
+
if (right.prerelease === void 0) {
|
|
474
|
+
return -1;
|
|
475
|
+
}
|
|
476
|
+
return comparePrerelease(left.prerelease, right.prerelease);
|
|
477
|
+
};
|
|
478
|
+
var isSameVersion = (a, b) => {
|
|
479
|
+
return a === b || compareVersions(a, b) === 0;
|
|
480
|
+
};
|
|
481
|
+
var isConnectionMissingError = (error) => {
|
|
482
|
+
const code = error.code;
|
|
483
|
+
return code === "ENOENT" || code === "ECONNREFUSED";
|
|
484
|
+
};
|
|
485
|
+
var isDaemonUnreachableError = (error) => {
|
|
486
|
+
return error instanceof DaemonUnavailableError || isConnectionMissingError(error);
|
|
487
|
+
};
|
|
488
|
+
var nextRequestId = 1;
|
|
489
|
+
var sendRequest = (socketPath, method, params, timeoutMs) => {
|
|
490
|
+
return new Promise((resolve2, reject) => {
|
|
491
|
+
const id = nextRequestId;
|
|
492
|
+
nextRequestId += 1;
|
|
493
|
+
let socket;
|
|
494
|
+
let settled = false;
|
|
495
|
+
let buffer = "";
|
|
496
|
+
const finish = (fn) => {
|
|
497
|
+
if (settled) {
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
settled = true;
|
|
501
|
+
clearTimeout(timeout);
|
|
502
|
+
socket.destroy();
|
|
503
|
+
fn();
|
|
504
|
+
};
|
|
505
|
+
const timeout = setTimeout(() => {
|
|
506
|
+
finish(
|
|
507
|
+
() => reject(new DaemonUnavailableError(`Timed out waiting for a response to "${method}".`, "timeout"))
|
|
508
|
+
);
|
|
509
|
+
}, timeoutMs);
|
|
510
|
+
socket = connect2(socketPath);
|
|
511
|
+
socket.on("error", (error) => {
|
|
512
|
+
finish(() => reject(error));
|
|
513
|
+
});
|
|
514
|
+
socket.on("connect", () => {
|
|
515
|
+
socket.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
|
|
516
|
+
`);
|
|
517
|
+
});
|
|
518
|
+
socket.on("data", (chunk) => {
|
|
519
|
+
buffer += chunk.toString("utf8");
|
|
520
|
+
let newlineIndex = buffer.indexOf("\n");
|
|
521
|
+
while (newlineIndex !== -1) {
|
|
522
|
+
const line = buffer.slice(0, newlineIndex);
|
|
523
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
524
|
+
newlineIndex = buffer.indexOf("\n");
|
|
525
|
+
if (line.length === 0) {
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
let message;
|
|
529
|
+
try {
|
|
530
|
+
message = JSON.parse(line);
|
|
531
|
+
} catch {
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
if (message.id !== id) {
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
if (message.error) {
|
|
538
|
+
finish(
|
|
539
|
+
() => reject(new DaemonRpcError(message.error.code, message.error.message, message.error.data))
|
|
540
|
+
);
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
finish(() => resolve2(message.result));
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
socket.on("close", () => {
|
|
548
|
+
finish(
|
|
549
|
+
() => reject(new DaemonUnavailableError("Connection to the Appduct daemon closed.", "closed"))
|
|
550
|
+
);
|
|
551
|
+
});
|
|
552
|
+
});
|
|
553
|
+
};
|
|
554
|
+
var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
555
|
+
var pollForSocket = async (socketPath, timeoutMs, pollIntervalMs) => {
|
|
556
|
+
const deadline = Date.now() + timeoutMs;
|
|
557
|
+
while (Date.now() < deadline) {
|
|
558
|
+
if (await isSocketConnectable(socketPath)) {
|
|
559
|
+
return true;
|
|
560
|
+
}
|
|
561
|
+
await sleep(pollIntervalMs);
|
|
562
|
+
}
|
|
563
|
+
return isSocketConnectable(socketPath);
|
|
564
|
+
};
|
|
565
|
+
var unlinkStaleSocketIfDaemonDead = async (paths) => {
|
|
566
|
+
let pid;
|
|
567
|
+
try {
|
|
568
|
+
pid = Number.parseInt((await readFile3(paths.pidFilePath, "utf8")).trim(), 10);
|
|
569
|
+
} catch {
|
|
570
|
+
pid = void 0;
|
|
571
|
+
}
|
|
572
|
+
if (pid === void 0 || Number.isNaN(pid) || !isProcessAlive(pid)) {
|
|
573
|
+
await rm2(paths.socketPath, { force: true });
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
var defaultSpawn = async (args, context) => {
|
|
577
|
+
const paths = getStateDirPaths(context.stateDir);
|
|
578
|
+
await rotateDaemonLogIfNeeded({
|
|
579
|
+
logFilePath: context.logFilePath,
|
|
580
|
+
maxBytes: await resolveDaemonLogMaxBytes(context.stateDir),
|
|
581
|
+
pidFilePath: paths.pidFilePath,
|
|
582
|
+
socketPath: paths.socketPath
|
|
583
|
+
});
|
|
584
|
+
const logFd = await open2(context.logFilePath, "a", 384);
|
|
585
|
+
try {
|
|
586
|
+
await ensureDaemonLogMode(context.logFilePath);
|
|
587
|
+
const childEnv = { ...process.env, APPDUCT_STATE_DIR: context.stateDir };
|
|
588
|
+
delete childEnv[DAEMON_VERSION_OVERRIDE_ENV];
|
|
589
|
+
const child = spawnChildProcess(process.execPath, [defaultBinPath, ...args], {
|
|
590
|
+
detached: true,
|
|
591
|
+
stdio: ["ignore", logFd.fd, logFd.fd],
|
|
592
|
+
env: childEnv
|
|
593
|
+
});
|
|
594
|
+
child.unref();
|
|
595
|
+
} finally {
|
|
596
|
+
await logFd.close();
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
var SPAWN_LOCK_STALE_MS = 3e4;
|
|
600
|
+
var pollUntilLockReleased = async (lockPath, timeoutMs, pollIntervalMs) => {
|
|
601
|
+
const deadline = Date.now() + timeoutMs;
|
|
602
|
+
while (Date.now() < deadline) {
|
|
603
|
+
if (!await pathExists(lockPath)) {
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
await sleep(pollIntervalMs);
|
|
607
|
+
}
|
|
608
|
+
return !await pathExists(lockPath);
|
|
609
|
+
};
|
|
610
|
+
var readPidfilePid = async (paths) => {
|
|
611
|
+
try {
|
|
612
|
+
const pid = Number.parseInt((await readFile3(paths.pidFilePath, "utf8")).trim(), 10);
|
|
613
|
+
return Number.isNaN(pid) ? void 0 : pid;
|
|
614
|
+
} catch {
|
|
615
|
+
return void 0;
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
var pathExists = async (target) => {
|
|
619
|
+
try {
|
|
620
|
+
await stat2(target);
|
|
621
|
+
return true;
|
|
622
|
+
} catch {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
var acquireSpawnLock = async (lockPath) => {
|
|
627
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
628
|
+
try {
|
|
629
|
+
const lockHandle = await open2(lockPath, "wx", 384);
|
|
630
|
+
await lockHandle.close();
|
|
631
|
+
return true;
|
|
632
|
+
} catch (error) {
|
|
633
|
+
if (error.code !== "EEXIST") {
|
|
634
|
+
throw error;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
let heldForMs;
|
|
638
|
+
try {
|
|
639
|
+
heldForMs = Date.now() - (await stat2(lockPath)).mtimeMs;
|
|
640
|
+
} catch {
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
if (heldForMs < SPAWN_LOCK_STALE_MS) {
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
await rm2(lockPath, { force: true });
|
|
647
|
+
}
|
|
648
|
+
return false;
|
|
649
|
+
};
|
|
650
|
+
var spawnDaemonAndWait = async (paths, spawn, waitTimeoutMs, pollIntervalMs, options = {}) => {
|
|
651
|
+
await ensureStateDir(paths.root);
|
|
652
|
+
const acquiredLock = await acquireSpawnLock(paths.spawnLockPath);
|
|
653
|
+
let lockWaitTimedOut = false;
|
|
654
|
+
if (acquiredLock) {
|
|
655
|
+
try {
|
|
656
|
+
const shouldSpawn = options.beforeSpawn ? await options.beforeSpawn() : true;
|
|
657
|
+
if (shouldSpawn) {
|
|
658
|
+
await unlinkStaleSocketIfDaemonDead(paths);
|
|
659
|
+
await spawn(["daemon", "run"], { stateDir: paths.root, logFilePath: paths.logFilePath });
|
|
660
|
+
}
|
|
661
|
+
} finally {
|
|
662
|
+
await rm2(paths.spawnLockPath, { force: true });
|
|
663
|
+
}
|
|
664
|
+
} else if (options.awaitLockRelease) {
|
|
665
|
+
lockWaitTimedOut = !await pollUntilLockReleased(paths.spawnLockPath, waitTimeoutMs, pollIntervalMs);
|
|
666
|
+
}
|
|
667
|
+
const ready = await pollForSocket(paths.socketPath, waitTimeoutMs, pollIntervalMs);
|
|
668
|
+
if (!ready) {
|
|
669
|
+
const lockHint = await pathExists(paths.spawnLockPath) ? ` Another process holds the spawn-lock at "${paths.spawnLockPath}"; if no "appduct daemon" is starting, delete it and retry.` : "";
|
|
670
|
+
throw new DaemonUnavailableError(
|
|
671
|
+
`Timed out waiting for the Appduct daemon socket at "${paths.socketPath}".${lockHint}`
|
|
672
|
+
);
|
|
673
|
+
}
|
|
674
|
+
return { ownedLock: acquiredLock, lockWaitTimedOut };
|
|
675
|
+
};
|
|
676
|
+
var versionChecks = /* @__PURE__ */ new Map();
|
|
677
|
+
var RESTART_REQUEST_TIMEOUT_MS = 3e3;
|
|
678
|
+
var readStatusSpawningIfNeeded = async (context) => {
|
|
679
|
+
try {
|
|
680
|
+
return await sendRequest(
|
|
681
|
+
context.paths.socketPath,
|
|
682
|
+
RPC_METHODS.daemonStatus,
|
|
683
|
+
{},
|
|
684
|
+
context.requestTimeoutMs
|
|
685
|
+
);
|
|
686
|
+
} catch (error) {
|
|
687
|
+
if (!isConnectionMissingError(error)) {
|
|
688
|
+
throw error;
|
|
689
|
+
}
|
|
690
|
+
if (!context.autoSpawn) {
|
|
691
|
+
return void 0;
|
|
692
|
+
}
|
|
693
|
+
await spawnDaemonAndWait(context.paths, context.spawn, context.waitTimeoutMs, context.pollIntervalMs);
|
|
694
|
+
return sendRequest(
|
|
695
|
+
context.paths.socketPath,
|
|
696
|
+
RPC_METHODS.daemonStatus,
|
|
697
|
+
{},
|
|
698
|
+
context.requestTimeoutMs
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
var readStatusIfReachable = async (context) => {
|
|
703
|
+
try {
|
|
704
|
+
return await sendRequest(
|
|
705
|
+
context.paths.socketPath,
|
|
706
|
+
RPC_METHODS.daemonStatus,
|
|
707
|
+
{},
|
|
708
|
+
RESTART_REQUEST_TIMEOUT_MS
|
|
709
|
+
);
|
|
710
|
+
} catch (error) {
|
|
711
|
+
if (isConnectionMissingError(error)) {
|
|
712
|
+
return void 0;
|
|
713
|
+
}
|
|
714
|
+
if (isRequestTimeoutError(error)) {
|
|
715
|
+
throw new DaemonUnavailableError(
|
|
716
|
+
`The Appduct daemon at "${context.paths.socketPath}" did not answer "daemon.status" within ${RESTART_REQUEST_TIMEOUT_MS}ms, so it was not replaced. It is running but unresponsive \u2014 run "appduct daemon stop" and retry.`,
|
|
717
|
+
"timeout"
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
throw error;
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
var isDaemonGone = async (paths) => {
|
|
724
|
+
if (await isSocketConnectable(paths.socketPath)) {
|
|
725
|
+
return false;
|
|
726
|
+
}
|
|
727
|
+
let pid;
|
|
728
|
+
try {
|
|
729
|
+
pid = Number.parseInt((await readFile3(paths.pidFilePath, "utf8")).trim(), 10);
|
|
730
|
+
} catch {
|
|
731
|
+
return true;
|
|
732
|
+
}
|
|
733
|
+
return pid === void 0 || Number.isNaN(pid) || !isProcessAlive(pid);
|
|
734
|
+
};
|
|
735
|
+
var readLiveState = (status) => {
|
|
736
|
+
return {
|
|
737
|
+
sessions: Array.isArray(status.sessions) ? status.sessions.length : 0,
|
|
738
|
+
pendingLinks: typeof status.pendingLinks === "number" ? status.pendingLinks : 0
|
|
739
|
+
};
|
|
740
|
+
};
|
|
741
|
+
var isSafeToRestart = (live) => {
|
|
742
|
+
return live.sessions === 0 && live.pendingLinks === 0;
|
|
743
|
+
};
|
|
744
|
+
var pollUntilDaemonGone = async (paths, timeoutMs, pollIntervalMs) => {
|
|
745
|
+
const deadline = Date.now() + timeoutMs;
|
|
746
|
+
while (Date.now() < deadline) {
|
|
747
|
+
if (await isDaemonGone(paths)) {
|
|
748
|
+
return true;
|
|
749
|
+
}
|
|
750
|
+
await sleep(pollIntervalMs);
|
|
751
|
+
}
|
|
752
|
+
return isDaemonGone(paths);
|
|
753
|
+
};
|
|
754
|
+
var restartDaemon = async (context) => {
|
|
755
|
+
const pidBefore = await readPidfilePid(context.paths);
|
|
756
|
+
const outcome = await spawnDaemonAndWait(
|
|
757
|
+
context.paths,
|
|
758
|
+
context.spawn,
|
|
759
|
+
context.waitTimeoutMs,
|
|
760
|
+
context.pollIntervalMs,
|
|
761
|
+
{
|
|
762
|
+
awaitLockRelease: true,
|
|
763
|
+
beforeSpawn: async () => {
|
|
764
|
+
const status = await readStatusIfReachable(context);
|
|
765
|
+
if (status === void 0) {
|
|
766
|
+
return true;
|
|
767
|
+
}
|
|
768
|
+
if (isSameVersion(status.version, context.check.clientVersion)) {
|
|
769
|
+
return false;
|
|
770
|
+
}
|
|
771
|
+
const live = readLiveState(status);
|
|
772
|
+
if (!isSafeToRestart(live) && !context.check.forceRestart) {
|
|
773
|
+
throw new DaemonVersionMismatchError(status.version, context.check.clientVersion, live);
|
|
774
|
+
}
|
|
775
|
+
try {
|
|
776
|
+
await sendRequest(
|
|
777
|
+
context.paths.socketPath,
|
|
778
|
+
RPC_METHODS.daemonShutdown,
|
|
779
|
+
{},
|
|
780
|
+
RESTART_REQUEST_TIMEOUT_MS
|
|
781
|
+
);
|
|
782
|
+
} catch (error) {
|
|
783
|
+
if (isRequestTimeoutError(error)) {
|
|
784
|
+
throw new DaemonUnavailableError(
|
|
785
|
+
`The Appduct daemon at "${context.paths.socketPath}" did not acknowledge "daemon.shutdown" within ${RESTART_REQUEST_TIMEOUT_MS}ms, so it was left running. Run "appduct daemon stop" and retry.`,
|
|
786
|
+
"timeout"
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
if (!isDaemonUnreachableError(error)) {
|
|
790
|
+
throw error;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
if (!await pollUntilDaemonGone(context.paths, context.waitTimeoutMs, context.pollIntervalMs)) {
|
|
794
|
+
throw new DaemonUnavailableError(
|
|
795
|
+
`The Appduct daemon at "${context.paths.socketPath}" did not shut down in time; run "appduct daemon stop" and retry.`
|
|
796
|
+
);
|
|
797
|
+
}
|
|
798
|
+
return true;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
);
|
|
802
|
+
if (!outcome.ownedLock && outcome.lockWaitTimedOut && await readPidfilePid(context.paths) === pidBefore) {
|
|
803
|
+
throw new DaemonUnavailableError(
|
|
804
|
+
`The Appduct daemon at "${context.paths.socketPath}" did not shut down in time: another process has held the spawn-lock at "${context.paths.spawnLockPath}" for longer than this command waited. Retry, or run "appduct daemon stop" if nothing is starting a daemon.`
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
var warnOlderClient = (context, daemonVersion) => {
|
|
809
|
+
const message = `appduct: the running daemon is version ${daemonVersion}, newer than this client (${context.check.clientVersion}). Continuing without restarting it \u2014 a newer daemon serves an older client, and replacing it would downgrade whatever started it. Run "appduct daemon stop" if you want this client's daemon instead.
|
|
810
|
+
`;
|
|
811
|
+
const warn = context.check.onWarning ?? ((text) => void process.stderr.write(text));
|
|
812
|
+
warn(message);
|
|
813
|
+
};
|
|
814
|
+
var runVersionCheck = async (context) => {
|
|
815
|
+
const status = await readStatusSpawningIfNeeded(context);
|
|
816
|
+
if (status === void 0) {
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
if (isSameVersion(status.version, context.check.clientVersion)) {
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
if ((compareVersions(context.check.clientVersion, status.version) ?? -1) <= 0) {
|
|
823
|
+
warnOlderClient(context, status.version);
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
const live = readLiveState(status);
|
|
827
|
+
if (!isSafeToRestart(live) && !context.check.forceRestart) {
|
|
828
|
+
throw new DaemonVersionMismatchError(status.version, context.check.clientVersion, live);
|
|
829
|
+
}
|
|
830
|
+
await restartDaemon(context);
|
|
831
|
+
const replacement = await readStatusIfReachable(context);
|
|
832
|
+
if (replacement === void 0) {
|
|
833
|
+
throw new DaemonUnavailableError(
|
|
834
|
+
`The Appduct daemon was restarted but nothing is listening at "${context.paths.socketPath}"; check "${context.paths.logFilePath}".`
|
|
835
|
+
);
|
|
836
|
+
}
|
|
837
|
+
if (isSameVersion(replacement.version, context.check.clientVersion)) {
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
if ((compareVersions(context.check.clientVersion, replacement.version) ?? -1) <= 0) {
|
|
841
|
+
warnOlderClient(context, replacement.version);
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
throw new DaemonVersionRestartIneffectiveError(
|
|
845
|
+
replacement.version,
|
|
846
|
+
context.check.clientVersion,
|
|
847
|
+
readLiveState(replacement)
|
|
848
|
+
);
|
|
849
|
+
};
|
|
850
|
+
var ensureDaemonVersion = async (paths, options, spawn) => {
|
|
851
|
+
const check = options.checkVersion;
|
|
852
|
+
if (!check) {
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
const cached2 = versionChecks.get(paths.socketPath);
|
|
856
|
+
if (cached2) {
|
|
857
|
+
return cached2;
|
|
858
|
+
}
|
|
859
|
+
const pending = runVersionCheck({
|
|
860
|
+
paths,
|
|
861
|
+
spawn,
|
|
862
|
+
autoSpawn: options.autoSpawn ?? true,
|
|
863
|
+
requestTimeoutMs: options.requestTimeoutMs ?? 1e4,
|
|
864
|
+
waitTimeoutMs: options.spawnWaitTimeoutMs ?? 5e3,
|
|
865
|
+
pollIntervalMs: options.spawnPollIntervalMs ?? 100,
|
|
866
|
+
check
|
|
867
|
+
}).catch((error) => {
|
|
868
|
+
if (!(error instanceof DaemonVersionMismatchError)) {
|
|
869
|
+
versionChecks.delete(paths.socketPath);
|
|
870
|
+
}
|
|
871
|
+
throw error;
|
|
872
|
+
});
|
|
873
|
+
versionChecks.set(paths.socketPath, pending);
|
|
874
|
+
return pending;
|
|
875
|
+
};
|
|
876
|
+
var ensureDaemonVersionMatches = async (options) => {
|
|
877
|
+
const paths = getStateDirPaths(options.stateDir);
|
|
878
|
+
await ensureDaemonVersion(
|
|
879
|
+
paths,
|
|
880
|
+
{ ...options, autoSpawn: options.autoSpawn ?? false },
|
|
881
|
+
options.spawn ?? defaultSpawn
|
|
882
|
+
);
|
|
883
|
+
};
|
|
884
|
+
var callDaemon = async (method, params, options) => {
|
|
885
|
+
const paths = getStateDirPaths(options.stateDir);
|
|
886
|
+
const autoSpawn = options.autoSpawn ?? true;
|
|
887
|
+
const spawn = options.spawn ?? defaultSpawn;
|
|
888
|
+
const requestTimeoutMs = options.requestTimeoutMs ?? 1e4;
|
|
889
|
+
await ensureDaemonVersion(paths, options, spawn);
|
|
890
|
+
try {
|
|
891
|
+
return await sendRequest(paths.socketPath, method, params, requestTimeoutMs);
|
|
892
|
+
} catch (error) {
|
|
893
|
+
if (!autoSpawn || !isConnectionMissingError(error)) {
|
|
894
|
+
throw error;
|
|
895
|
+
}
|
|
896
|
+
await spawnDaemonAndWait(
|
|
897
|
+
paths,
|
|
898
|
+
spawn,
|
|
899
|
+
options.spawnWaitTimeoutMs ?? 5e3,
|
|
900
|
+
options.spawnPollIntervalMs ?? 100
|
|
901
|
+
);
|
|
902
|
+
return sendRequest(paths.socketPath, method, params, requestTimeoutMs);
|
|
903
|
+
}
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
// src/errors.ts
|
|
907
|
+
var EXIT_CODE_BY_ERROR_TYPE = {
|
|
908
|
+
usage_error: 64,
|
|
909
|
+
validation_error: 65,
|
|
910
|
+
// EX_NOINPUT (66): "an input file did not exist or was not readable" — `doctor` throws this for a
|
|
911
|
+
// missing external tool or an unreadable/corrupt artifact, deliberately distinct from every other
|
|
912
|
+
// code here so a release pipeline can't mistake "we couldn't tell" for either a clean pass or an
|
|
913
|
+
// assertion failure (docs/tasks/08-appduct-doctor.md).
|
|
914
|
+
inspection_error: 66,
|
|
915
|
+
connection_error: 70,
|
|
916
|
+
session_error: 71,
|
|
917
|
+
tool_error: 72,
|
|
918
|
+
permission_error: 77,
|
|
919
|
+
internal_error: 1,
|
|
920
|
+
// `doctor --assert-present`/`--assert-absent`: the artifact was inspected successfully and the
|
|
921
|
+
// assertion did not hold. Distinct from `inspection_error` (66) — this means the answer is known
|
|
922
|
+
// and it's "no", not "couldn't tell" — and distinct from `internal_error` (1) so a caller can't
|
|
923
|
+
// conflate a normal assertion failure with an unexpected crash.
|
|
924
|
+
assertion_error: 3
|
|
925
|
+
};
|
|
926
|
+
var RPC_ERROR_EXIT_CLASS = {
|
|
927
|
+
no_session: "session_error",
|
|
928
|
+
ambiguous_session: "session_error",
|
|
929
|
+
unknown_session: "session_error",
|
|
930
|
+
session_not_active: "session_error",
|
|
931
|
+
session_suspended: "session_error",
|
|
932
|
+
tool_not_found: "tool_error",
|
|
933
|
+
tool_input_validation_error: "tool_error",
|
|
934
|
+
tool_output_validation_error: "tool_error",
|
|
935
|
+
tool_execution_error: "tool_error",
|
|
936
|
+
tool_serialization_error: "tool_error",
|
|
937
|
+
tool_timeout: "tool_error",
|
|
938
|
+
tool_cancelled: "tool_error",
|
|
939
|
+
policy_denied: "permission_error",
|
|
940
|
+
invalid_request: "validation_error"
|
|
941
|
+
};
|
|
942
|
+
var AppductCliError = class extends Error {
|
|
943
|
+
type;
|
|
944
|
+
details;
|
|
945
|
+
constructor(type, message, details) {
|
|
946
|
+
super(message);
|
|
947
|
+
this.name = "AppductCliError";
|
|
948
|
+
this.type = type;
|
|
949
|
+
this.details = details;
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
var usageError = (message, details) => {
|
|
953
|
+
return new AppductCliError("usage_error", message, details);
|
|
954
|
+
};
|
|
955
|
+
var connectionError = (message, details) => {
|
|
956
|
+
return new AppductCliError("connection_error", message, details);
|
|
957
|
+
};
|
|
958
|
+
var isAppductCliError = (value) => {
|
|
959
|
+
return value instanceof AppductCliError;
|
|
960
|
+
};
|
|
961
|
+
var rpcErrorClass = (error) => {
|
|
962
|
+
const type = error.data?.type;
|
|
963
|
+
return type ? RPC_ERROR_EXIT_CLASS[type] : void 0;
|
|
964
|
+
};
|
|
965
|
+
var toCliError = (error) => {
|
|
966
|
+
if (isAppductCliError(error)) {
|
|
967
|
+
return {
|
|
968
|
+
type: error.type,
|
|
969
|
+
message: error.message,
|
|
970
|
+
details: error.details
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
if (error instanceof DaemonVersionMismatchError) {
|
|
974
|
+
return {
|
|
975
|
+
type: "connection_error",
|
|
976
|
+
message: error.message,
|
|
977
|
+
details: {
|
|
978
|
+
daemon_version: error.daemonVersion,
|
|
979
|
+
client_version: error.clientVersion,
|
|
980
|
+
session_count: error.sessionCount,
|
|
981
|
+
pending_link_count: error.pendingLinkCount
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
if (error instanceof DaemonRpcError && error.data?.type) {
|
|
986
|
+
return {
|
|
987
|
+
type: error.data.type,
|
|
988
|
+
message: error.message,
|
|
989
|
+
details: error.data.details
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
if (isDaemonUnreachableError(error)) {
|
|
993
|
+
return {
|
|
994
|
+
type: "connection_error",
|
|
995
|
+
message: error instanceof Error ? error.message : "The Appduct daemon is unreachable."
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
if (error instanceof Error) {
|
|
999
|
+
return {
|
|
1000
|
+
type: "internal_error",
|
|
1001
|
+
message: error.message
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
return {
|
|
1005
|
+
type: "internal_error",
|
|
1006
|
+
message: "An unexpected error occurred.",
|
|
1007
|
+
details: error
|
|
1008
|
+
};
|
|
1009
|
+
};
|
|
1010
|
+
var getExitCodeForError = (error) => {
|
|
1011
|
+
if (isAppductCliError(error)) {
|
|
1012
|
+
return EXIT_CODE_BY_ERROR_TYPE[error.type];
|
|
1013
|
+
}
|
|
1014
|
+
if (error instanceof DaemonVersionMismatchError) {
|
|
1015
|
+
return EXIT_CODE_BY_ERROR_TYPE.connection_error;
|
|
1016
|
+
}
|
|
1017
|
+
if (error instanceof DaemonRpcError) {
|
|
1018
|
+
const cliErrorClass = rpcErrorClass(error);
|
|
1019
|
+
return EXIT_CODE_BY_ERROR_TYPE[cliErrorClass ?? "internal_error"];
|
|
1020
|
+
}
|
|
1021
|
+
if (isDaemonUnreachableError(error)) {
|
|
1022
|
+
return EXIT_CODE_BY_ERROR_TYPE.connection_error;
|
|
1023
|
+
}
|
|
1024
|
+
return EXIT_CODE_BY_ERROR_TYPE.internal_error;
|
|
1025
|
+
};
|
|
1026
|
+
|
|
1027
|
+
// src/cli/open-target.ts
|
|
1028
|
+
var isOpenTarget = (value) => {
|
|
1029
|
+
return value === "android" || value === "ios-sim" || value === "ios-device";
|
|
1030
|
+
};
|
|
1031
|
+
var OPEN_TARGETS = ["android", "ios-sim", "ios-device"];
|
|
1032
|
+
var usesLoopbackAddress = (target) => {
|
|
1033
|
+
return target === "android" || target === "ios-sim";
|
|
1034
|
+
};
|
|
1035
|
+
var platformOf = (target) => {
|
|
1036
|
+
if (target === "android") {
|
|
1037
|
+
return "android";
|
|
1038
|
+
}
|
|
1039
|
+
if (target === "ios-device") {
|
|
1040
|
+
return "ios";
|
|
1041
|
+
}
|
|
1042
|
+
return void 0;
|
|
1043
|
+
};
|
|
1044
|
+
var isLoopbackAddress = (address) => {
|
|
1045
|
+
const normalized = address.trim().toLowerCase().replace(/^\[|\]$/gu, "");
|
|
1046
|
+
return normalized === "localhost" || normalized === "::1" || normalized === "0.0.0.0" || normalized === "::" || /^127\./u.test(normalized);
|
|
1047
|
+
};
|
|
1048
|
+
var loopbackAddressMessage = (address) => `The daemon advertised "${address}", which a physical device cannot reach \u2014 it would point the phone at itself and the session would never be claimed. No routable LAN address was detected; set "advertisedIp" in config.json to this machine's address on the network the device is on, and retry.`;
|
|
1049
|
+
var defaultExec = (command, args) => {
|
|
1050
|
+
return new Promise((resolve2, reject) => {
|
|
1051
|
+
execFile(command, args, { encoding: "utf8" }, (error, stdout, stderr) => {
|
|
1052
|
+
if (error) {
|
|
1053
|
+
reject(Object.assign(error, { stdout, stderr }));
|
|
1054
|
+
return;
|
|
1055
|
+
}
|
|
1056
|
+
resolve2({ stdout, stderr });
|
|
1057
|
+
});
|
|
1058
|
+
});
|
|
1059
|
+
};
|
|
1060
|
+
var TOOL_INSTALL_HINT = {
|
|
1061
|
+
adb: "the Android platform-tools (adb)",
|
|
1062
|
+
xcrun: "the Xcode command line tools (xcrun)"
|
|
1063
|
+
};
|
|
1064
|
+
var run = async (exec, command, args) => {
|
|
1065
|
+
try {
|
|
1066
|
+
return await exec(command, args);
|
|
1067
|
+
} catch (error) {
|
|
1068
|
+
const err = error;
|
|
1069
|
+
if (err.code === "ENOENT") {
|
|
1070
|
+
throw connectionError(
|
|
1071
|
+
`"${command}" was not found on PATH. Install ${TOOL_INSTALL_HINT[command] ?? command} and retry.`
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
const stderr = (err.stderr ?? "").trim();
|
|
1075
|
+
throw connectionError(
|
|
1076
|
+
`"${command} ${args.join(" ")}" failed${stderr ? `: ${stderr}` : `: ${err.message}`}`
|
|
1077
|
+
);
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
var parseBootedSimulators = (stdout) => {
|
|
1081
|
+
let parsed;
|
|
1082
|
+
try {
|
|
1083
|
+
parsed = JSON.parse(stdout);
|
|
1084
|
+
} catch {
|
|
1085
|
+
return [];
|
|
1086
|
+
}
|
|
1087
|
+
return Object.values(parsed.devices ?? {}).flat().filter(
|
|
1088
|
+
(entry) => entry.state === "Booted" && typeof entry.udid === "string" && entry.udid.length > 0
|
|
1089
|
+
).map((entry) => ({ udid: entry.udid, name: entry.name ?? entry.udid }));
|
|
1090
|
+
};
|
|
1091
|
+
var listBootedSimulators = async (exec) => {
|
|
1092
|
+
const preflight = await run(exec, "xcrun", ["simctl", "list", "devices", "booted", "--json"]);
|
|
1093
|
+
return parseBootedSimulators(preflight.stdout);
|
|
1094
|
+
};
|
|
1095
|
+
var describeSimulator = (simulator) => `${simulator.name} (${simulator.udid})`;
|
|
1096
|
+
var deliverIosSim = async (exec, deepLink, device) => {
|
|
1097
|
+
if (device) {
|
|
1098
|
+
await run(exec, "xcrun", ["simctl", "openurl", device, deepLink]);
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
const booted = await listBootedSimulators(exec);
|
|
1102
|
+
if (booted.length === 0) {
|
|
1103
|
+
throw usageError("No booted iOS simulator found. Boot a simulator (e.g. via Xcode) and retry.");
|
|
1104
|
+
}
|
|
1105
|
+
if (booted.length > 1) {
|
|
1106
|
+
throw usageError(
|
|
1107
|
+
`Multiple iOS simulators are booted (${booted.map(describeSimulator).join(", ")}); specify --device <udid>.`
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
await run(exec, "xcrun", ["simctl", "openurl", booted[0].udid, deepLink]);
|
|
1111
|
+
};
|
|
1112
|
+
var runDevicectlJson = async (exec, buildArgs) => {
|
|
1113
|
+
let dir;
|
|
1114
|
+
try {
|
|
1115
|
+
dir = await mkdtemp(path.join(tmpdir(), "appduct-devicectl-"));
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
throw connectionError(
|
|
1118
|
+
`A temporary directory for devicectl's --json-output could not be created in "${tmpdir()}" (${error.message}). Set TMPDIR to a writable directory and retry.`
|
|
1119
|
+
);
|
|
1120
|
+
}
|
|
1121
|
+
const file = path.join(dir, "devicectl.json");
|
|
1122
|
+
try {
|
|
1123
|
+
await run(exec, "xcrun", buildArgs(file));
|
|
1124
|
+
try {
|
|
1125
|
+
return JSON.parse(await readFile4(file, "utf8"));
|
|
1126
|
+
} catch {
|
|
1127
|
+
return void 0;
|
|
1128
|
+
}
|
|
1129
|
+
} finally {
|
|
1130
|
+
await rm3(dir, { force: true, recursive: true }).catch(() => {
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
var DELIVERABLE_PLATFORM = "ios";
|
|
1135
|
+
var UNREACHABLE_TUNNEL_STATE = "unavailable";
|
|
1136
|
+
var USABLE_PAIRING_STATE = "paired";
|
|
1137
|
+
var parsePairedIosDevices = (payload) => {
|
|
1138
|
+
const devices = payload?.result?.devices;
|
|
1139
|
+
if (!Array.isArray(devices)) {
|
|
1140
|
+
return [];
|
|
1141
|
+
}
|
|
1142
|
+
return devices.map((entry) => {
|
|
1143
|
+
const platform = entry?.hardwareProperties?.platform;
|
|
1144
|
+
if (typeof platform === "string" && platform.toLowerCase() !== DELIVERABLE_PLATFORM) {
|
|
1145
|
+
return void 0;
|
|
1146
|
+
}
|
|
1147
|
+
const tunnelState = entry?.connectionProperties?.tunnelState;
|
|
1148
|
+
if (typeof tunnelState === "string" && tunnelState.toLowerCase() === UNREACHABLE_TUNNEL_STATE) {
|
|
1149
|
+
return void 0;
|
|
1150
|
+
}
|
|
1151
|
+
const pairingState = entry?.connectionProperties?.pairingState;
|
|
1152
|
+
if (typeof pairingState === "string" && pairingState.toLowerCase() !== USABLE_PAIRING_STATE) {
|
|
1153
|
+
return void 0;
|
|
1154
|
+
}
|
|
1155
|
+
const hardwareUdid = entry?.hardwareProperties?.udid;
|
|
1156
|
+
const udid = typeof hardwareUdid === "string" && hardwareUdid.length > 0 ? hardwareUdid : entry?.identifier;
|
|
1157
|
+
return typeof udid === "string" && udid.length > 0 ? { udid, name: entry?.deviceProperties?.name ?? udid } : void 0;
|
|
1158
|
+
}).filter((device) => device !== void 0);
|
|
1159
|
+
};
|
|
1160
|
+
var listPairedIosDevices = async (exec) => {
|
|
1161
|
+
const payload = await runDevicectlJson(exec, (file) => [
|
|
1162
|
+
"devicectl",
|
|
1163
|
+
"list",
|
|
1164
|
+
"devices",
|
|
1165
|
+
"--timeout",
|
|
1166
|
+
"5",
|
|
1167
|
+
"--json-output",
|
|
1168
|
+
file
|
|
1169
|
+
]);
|
|
1170
|
+
return parsePairedIosDevices(payload);
|
|
1171
|
+
};
|
|
1172
|
+
var describeIosDevice = (device) => `${device.name} (${device.udid})`;
|
|
1173
|
+
var MISSING_APP_ID_MESSAGE = 'Delivering to a device needs the installed app\'s id (the Android package name, or the iOS bundle id): pass "--app-id <id>" (or "appId" over MCP), or record it as "appId.<platform>" in .appduct/config.json \u2014 run `appduct init --android-app-id <id> --ios-app-id <id>` to write it.';
|
|
1174
|
+
var APP_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
|
|
1175
|
+
var isValidAppId = (value) => APP_ID_PATTERN.test(value);
|
|
1176
|
+
var invalidAppIdMessage = (value) => `"${value}" is not a valid app id (letters, digits, ".", "_" and "-", starting with a letter or digit).`;
|
|
1177
|
+
var resolveSingleIosDevice = async (exec) => {
|
|
1178
|
+
const paired = await listPairedIosDevices(exec);
|
|
1179
|
+
if (paired.length === 0) {
|
|
1180
|
+
throw usageError(
|
|
1181
|
+
'No connected iOS device was found ("xcrun devicectl list devices" listed none, ignoring disconnected devices and non-iOS ones such as a paired Watch or Vision Pro). Connect the device, trust this Mac, and enable Developer Mode on it, then retry.'
|
|
1182
|
+
);
|
|
1183
|
+
}
|
|
1184
|
+
if (paired.length > 1) {
|
|
1185
|
+
throw usageError(
|
|
1186
|
+
`Multiple connected iOS devices were found (${paired.map(describeIosDevice).join(", ")}); specify --device <udid>.`
|
|
1187
|
+
);
|
|
1188
|
+
}
|
|
1189
|
+
return paired[0].udid;
|
|
1190
|
+
};
|
|
1191
|
+
var deliverIosDevice = async (exec, deepLink, device, appId, relaunch) => {
|
|
1192
|
+
if (!appId) {
|
|
1193
|
+
throw usageError(MISSING_APP_ID_MESSAGE);
|
|
1194
|
+
}
|
|
1195
|
+
if (!isValidAppId(appId)) {
|
|
1196
|
+
throw usageError(invalidAppIdMessage(appId));
|
|
1197
|
+
}
|
|
1198
|
+
const udid = device ?? await resolveSingleIosDevice(exec);
|
|
1199
|
+
await run(exec, "xcrun", [
|
|
1200
|
+
"devicectl",
|
|
1201
|
+
"device",
|
|
1202
|
+
"process",
|
|
1203
|
+
"launch",
|
|
1204
|
+
"--device",
|
|
1205
|
+
udid,
|
|
1206
|
+
// Opt-in only (`--relaunch` / `relaunch: true`). A plain `process launch` is what the vendored
|
|
1207
|
+
// Expo CLI does, so it is the better-attested default; what it does when the app is *already
|
|
1208
|
+
// running* is the one thing nobody here can verify without hardware. If that turns out to fail
|
|
1209
|
+
// rather than deliver the URL, `--terminate-existing` is the escape hatch — it kills the
|
|
1210
|
+
// running instance first, which Appduct copes with because a delivered link supersedes a
|
|
1211
|
+
// held session.
|
|
1212
|
+
...relaunch ? ["--terminate-existing"] : [],
|
|
1213
|
+
"--payload-url",
|
|
1214
|
+
deepLink,
|
|
1215
|
+
appId
|
|
1216
|
+
]);
|
|
1217
|
+
};
|
|
1218
|
+
var parseAdbDevices = (stdout) => {
|
|
1219
|
+
return stdout.split("\n").slice(1).map((line) => line.trim()).filter((line) => line.length > 0).map((line) => {
|
|
1220
|
+
const [serial = "", state = ""] = line.split(/\s+/u);
|
|
1221
|
+
return { serial, state };
|
|
1222
|
+
}).filter((entry) => entry.serial.length > 0);
|
|
1223
|
+
};
|
|
1224
|
+
var listAttachedAndroidDevices = async (exec) => {
|
|
1225
|
+
const listing = await run(exec, "adb", ["devices"]);
|
|
1226
|
+
return parseAdbDevices(listing.stdout).filter((entry) => entry.state === "device").map((entry) => entry.serial);
|
|
1227
|
+
};
|
|
1228
|
+
var resolveAndroidSerial = async (exec, device, env) => {
|
|
1229
|
+
if (device) {
|
|
1230
|
+
return device;
|
|
1231
|
+
}
|
|
1232
|
+
if (env.ANDROID_SERIAL) {
|
|
1233
|
+
return void 0;
|
|
1234
|
+
}
|
|
1235
|
+
const attached = await listAttachedAndroidDevices(exec);
|
|
1236
|
+
if (attached.length === 0) {
|
|
1237
|
+
throw usageError('No Android device or emulator is attached ("adb devices" listed none).');
|
|
1238
|
+
}
|
|
1239
|
+
if (attached.length > 1) {
|
|
1240
|
+
throw usageError(
|
|
1241
|
+
`Multiple Android devices are attached (${attached.join(
|
|
1242
|
+
", "
|
|
1243
|
+
)}); specify --device <serial> or set ANDROID_SERIAL.`
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
return void 0;
|
|
1247
|
+
};
|
|
1248
|
+
var withSerial = (args, serial) => {
|
|
1249
|
+
return serial ? ["-s", serial, ...args] : args;
|
|
1250
|
+
};
|
|
1251
|
+
var AM_START_ERROR_PATTERN = /^(?:Error:|Exception occurred while executing|Security exception:)/mu;
|
|
1252
|
+
var deliverAndroid = async (exec, deepLink, wssPort, device, env, appId) => {
|
|
1253
|
+
if (!isValidAppId(appId)) {
|
|
1254
|
+
throw usageError(invalidAppIdMessage(appId));
|
|
1255
|
+
}
|
|
1256
|
+
const serial = await resolveAndroidSerial(exec, device, env);
|
|
1257
|
+
await run(exec, "adb", withSerial(["reverse", `tcp:${wssPort}`, `tcp:${wssPort}`], serial));
|
|
1258
|
+
const { stdout, stderr } = await run(
|
|
1259
|
+
exec,
|
|
1260
|
+
"adb",
|
|
1261
|
+
withSerial(
|
|
1262
|
+
[
|
|
1263
|
+
"shell",
|
|
1264
|
+
"am",
|
|
1265
|
+
"start",
|
|
1266
|
+
"-a",
|
|
1267
|
+
"android.intent.action.VIEW",
|
|
1268
|
+
"-d",
|
|
1269
|
+
// `adb shell` reconstructs everything after "shell" into one string and re-parses it on the
|
|
1270
|
+
// device's own shell; single-quoting the URL here (not just for local execFile, which never
|
|
1271
|
+
// re-tokenizes argv) protects against that second, remote parse (ARCHITECTURE.md §8).
|
|
1272
|
+
`'${deepLink}'`,
|
|
1273
|
+
// Names the app explicitly: without this, more than one installed app declaring the same
|
|
1274
|
+
// scheme makes Android show an "Open with" chooser, which `am start` still reports as a
|
|
1275
|
+
// successful launch — see `AM_START_ERROR_PATTERN` below for the other half of the fix.
|
|
1276
|
+
"-p",
|
|
1277
|
+
appId
|
|
1278
|
+
],
|
|
1279
|
+
serial
|
|
1280
|
+
)
|
|
1281
|
+
);
|
|
1282
|
+
if (AM_START_ERROR_PATTERN.test(stdout) || AM_START_ERROR_PATTERN.test(stderr)) {
|
|
1283
|
+
throw usageError(
|
|
1284
|
+
`"adb shell am start" could not launch "${appId}": ${(stdout + stderr).trim() || "(no output)"} \u2014 the app is likely not installed on this device, or its installed build does not declare a matching deep-link scheme.`
|
|
1285
|
+
);
|
|
1286
|
+
}
|
|
1287
|
+
};
|
|
1288
|
+
var deliverToOpenTarget = async (options) => {
|
|
1289
|
+
const exec = options.exec ?? defaultExec;
|
|
1290
|
+
if (options.target === "ios-sim") {
|
|
1291
|
+
await deliverIosSim(exec, options.deepLink, options.device);
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
if (options.target === "ios-device") {
|
|
1295
|
+
await deliverIosDevice(
|
|
1296
|
+
exec,
|
|
1297
|
+
options.deepLink,
|
|
1298
|
+
options.device,
|
|
1299
|
+
options.appId,
|
|
1300
|
+
options.relaunch ?? false
|
|
1301
|
+
);
|
|
1302
|
+
return;
|
|
1303
|
+
}
|
|
1304
|
+
if (!options.appId) {
|
|
1305
|
+
throw usageError(MISSING_APP_ID_MESSAGE);
|
|
1306
|
+
}
|
|
1307
|
+
await deliverAndroid(
|
|
1308
|
+
exec,
|
|
1309
|
+
options.deepLink,
|
|
1310
|
+
options.wssPort,
|
|
1311
|
+
options.device,
|
|
1312
|
+
options.env ?? process.env,
|
|
1313
|
+
options.appId
|
|
1314
|
+
);
|
|
1315
|
+
};
|
|
1316
|
+
|
|
1317
|
+
// src/link.ts
|
|
1318
|
+
import { RPC_METHODS as RPC_METHODS2 } from "@appduct/shared";
|
|
1319
|
+
|
|
1320
|
+
// src/scheme.ts
|
|
1321
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
1322
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
1323
|
+
import { homedir } from "node:os";
|
|
1324
|
+
import { dirname as dirname2, join as join5, resolve } from "node:path";
|
|
1325
|
+
|
|
1326
|
+
// src/native-scheme.ts
|
|
1327
|
+
import { readdir, readFile as readFile5, stat as stat3 } from "node:fs/promises";
|
|
1328
|
+
import { join as join4 } from "node:path";
|
|
1329
|
+
var MAX_PROBE_FILE_BYTES = 2 * 1024 * 1024;
|
|
1330
|
+
var MAX_PLIST_WALK_DEPTH = 2;
|
|
1331
|
+
var MAX_WALK_ENTRIES = 5e3;
|
|
1332
|
+
var EXCLUDED_WALK_DIRS = /* @__PURE__ */ new Set(["Pods", "build", "node_modules", "DerivedData"]);
|
|
1333
|
+
var readCappedText = async (path2) => {
|
|
1334
|
+
const buffer = await readCappedBuffer(path2);
|
|
1335
|
+
if (!buffer.ok) {
|
|
1336
|
+
return buffer;
|
|
1337
|
+
}
|
|
1338
|
+
return { ok: true, text: buffer.data.toString("utf8") };
|
|
1339
|
+
};
|
|
1340
|
+
var readCappedBuffer = async (path2) => {
|
|
1341
|
+
let size;
|
|
1342
|
+
try {
|
|
1343
|
+
const stats = await stat3(path2);
|
|
1344
|
+
if (!stats.isFile()) {
|
|
1345
|
+
return { ok: false, reason: "not-found" };
|
|
1346
|
+
}
|
|
1347
|
+
size = stats.size;
|
|
1348
|
+
} catch {
|
|
1349
|
+
return { ok: false, reason: "not-found" };
|
|
1350
|
+
}
|
|
1351
|
+
if (size > MAX_PROBE_FILE_BYTES) {
|
|
1352
|
+
return { ok: false, reason: "too-large" };
|
|
1353
|
+
}
|
|
1354
|
+
try {
|
|
1355
|
+
return { ok: true, data: await readFile5(path2) };
|
|
1356
|
+
} catch {
|
|
1357
|
+
return { ok: false, reason: "unreadable" };
|
|
1358
|
+
}
|
|
1359
|
+
};
|
|
1360
|
+
var requireValidNativeScheme = (value, origin) => {
|
|
1361
|
+
if (!isValidScheme(value)) {
|
|
1362
|
+
throw usageError(
|
|
1363
|
+
`Invalid deep-link scheme ${JSON.stringify(value)} from ${origin}: a scheme must start with a letter and contain only letters, digits, "+", "-" or "." (for example "myapp") \u2014 do not include "://".`
|
|
1364
|
+
);
|
|
1365
|
+
}
|
|
1366
|
+
return value;
|
|
1367
|
+
};
|
|
1368
|
+
var GRADLE_PLACEHOLDER_PATTERN = /manifestPlaceholders\s*(?:\[\s*["']appductScheme["']\s*\]|\.\s*appductScheme)\s*=\s*["']([^"']*)["']/u;
|
|
1369
|
+
var extractGradleScheme = (text) => {
|
|
1370
|
+
const match = GRADLE_PLACEHOLDER_PATTERN.exec(text);
|
|
1371
|
+
const value = match?.[1];
|
|
1372
|
+
return value !== void 0 && value.length > 0 ? value : void 0;
|
|
1373
|
+
};
|
|
1374
|
+
var probeAndroidGradle = async (root) => {
|
|
1375
|
+
const candidates = [join4(root, "app", "build.gradle.kts"), join4(root, "app", "build.gradle")];
|
|
1376
|
+
const notes = [];
|
|
1377
|
+
for (const candidate of candidates) {
|
|
1378
|
+
const read = await readCappedText(candidate);
|
|
1379
|
+
if (!read.ok) {
|
|
1380
|
+
if (read.reason === "too-large") {
|
|
1381
|
+
notes.push(`${candidate} (too large, skipped)`);
|
|
1382
|
+
}
|
|
1383
|
+
continue;
|
|
1384
|
+
}
|
|
1385
|
+
const scheme = extractGradleScheme(read.text);
|
|
1386
|
+
if (scheme !== void 0) {
|
|
1387
|
+
requireValidNativeScheme(scheme, `"appductScheme" in ${candidate}`);
|
|
1388
|
+
return {
|
|
1389
|
+
result: {
|
|
1390
|
+
source: "android-gradle",
|
|
1391
|
+
scheme,
|
|
1392
|
+
origin: `"appductScheme" in ${candidate}`
|
|
1393
|
+
},
|
|
1394
|
+
tried: [describeAndroidGradleTried(candidates, notes)]
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
return { tried: [describeAndroidGradleTried(candidates, notes)] };
|
|
1399
|
+
};
|
|
1400
|
+
var describeAndroidGradleTried = (candidates, notes) => {
|
|
1401
|
+
const base = `${candidates.join(", ")} ("appductScheme" manifest placeholder)`;
|
|
1402
|
+
return notes.length === 0 ? base : `${base} \u2014 ${notes.join(", ")}`;
|
|
1403
|
+
};
|
|
1404
|
+
var INTENT_FILTER_PATTERN = /<intent-filter\b[^>]*>([\s\S]*?)<\/intent-filter>/giu;
|
|
1405
|
+
var VIEW_ACTION_PATTERN = /<action\b[^>]*\bandroid:name\s*=\s*["']android\.intent\.action\.VIEW["']/iu;
|
|
1406
|
+
var DATA_SCHEME_PATTERN = /<data\b[^>]*\bandroid:scheme\s*=\s*["']([^"']*)["']/iu;
|
|
1407
|
+
var extractManifestScheme = (xml) => {
|
|
1408
|
+
for (const match of xml.matchAll(INTENT_FILTER_PATTERN)) {
|
|
1409
|
+
const block = match[1] ?? "";
|
|
1410
|
+
if (!VIEW_ACTION_PATTERN.test(block)) {
|
|
1411
|
+
continue;
|
|
1412
|
+
}
|
|
1413
|
+
const dataMatch = DATA_SCHEME_PATTERN.exec(block);
|
|
1414
|
+
const scheme = dataMatch?.[1];
|
|
1415
|
+
if (scheme !== void 0 && scheme.length > 0) {
|
|
1416
|
+
return scheme;
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
return void 0;
|
|
1420
|
+
};
|
|
1421
|
+
var probeAndroidManifest = async (root) => {
|
|
1422
|
+
const manifestPath = join4(root, "app", "src", "main", "AndroidManifest.xml");
|
|
1423
|
+
const read = await readCappedText(manifestPath);
|
|
1424
|
+
const description = `${manifestPath} (first <data android:scheme> in a VIEW intent-filter)`;
|
|
1425
|
+
if (!read.ok) {
|
|
1426
|
+
return {
|
|
1427
|
+
tried: [read.reason === "too-large" ? `${description} \u2014 too large, skipped` : description]
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
const scheme = extractManifestScheme(read.text);
|
|
1431
|
+
if (scheme === void 0) {
|
|
1432
|
+
return { tried: [description] };
|
|
1433
|
+
}
|
|
1434
|
+
requireValidNativeScheme(scheme, `"android:scheme" in ${manifestPath}`);
|
|
1435
|
+
return {
|
|
1436
|
+
result: {
|
|
1437
|
+
source: "android-manifest",
|
|
1438
|
+
scheme,
|
|
1439
|
+
origin: `"android:scheme" in ${manifestPath}`
|
|
1440
|
+
},
|
|
1441
|
+
tried: [description]
|
|
1442
|
+
};
|
|
1443
|
+
};
|
|
1444
|
+
var XML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
1445
|
+
var decodeXmlEntities = (text) => {
|
|
1446
|
+
return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/gu, (whole, entity) => {
|
|
1447
|
+
if (entity.startsWith("#x")) {
|
|
1448
|
+
const code = Number.parseInt(entity.slice(2), 16);
|
|
1449
|
+
return Number.isNaN(code) ? whole : String.fromCodePoint(code);
|
|
1450
|
+
}
|
|
1451
|
+
if (entity.startsWith("#")) {
|
|
1452
|
+
const code = Number.parseInt(entity.slice(1), 10);
|
|
1453
|
+
return Number.isNaN(code) ? whole : String.fromCodePoint(code);
|
|
1454
|
+
}
|
|
1455
|
+
return XML_ENTITIES[entity] ?? whole;
|
|
1456
|
+
});
|
|
1457
|
+
};
|
|
1458
|
+
var tokenizePlistXml = (xml) => {
|
|
1459
|
+
const cleaned = xml.replace(/<\?[\s\S]*?\?>/gu, "").replace(/<!DOCTYPE[\s\S]*?>/giu, "").replace(/<!--[\s\S]*?-->/gu, "");
|
|
1460
|
+
const root = { tag: "#root", children: [], text: "" };
|
|
1461
|
+
const stack = [root];
|
|
1462
|
+
const tagOrTextPattern = /<(\/?)([a-zA-Z][\w.:-]*)\b[^>]*?(\/?)>|([^<]+)/gu;
|
|
1463
|
+
for (const match of cleaned.matchAll(tagOrTextPattern)) {
|
|
1464
|
+
const [, closing, name, selfClosing, text] = match;
|
|
1465
|
+
const top = stack[stack.length - 1];
|
|
1466
|
+
if (text !== void 0) {
|
|
1467
|
+
top.text += decodeXmlEntities(text);
|
|
1468
|
+
continue;
|
|
1469
|
+
}
|
|
1470
|
+
if (closing) {
|
|
1471
|
+
if (stack.length > 1) {
|
|
1472
|
+
stack.pop();
|
|
1473
|
+
}
|
|
1474
|
+
continue;
|
|
1475
|
+
}
|
|
1476
|
+
const node = { tag: name ?? "", children: [], text: "" };
|
|
1477
|
+
top.children.push(node);
|
|
1478
|
+
if (!selfClosing) {
|
|
1479
|
+
stack.push(node);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
return root;
|
|
1483
|
+
};
|
|
1484
|
+
var plistNodeToValue = (node) => {
|
|
1485
|
+
switch (node.tag) {
|
|
1486
|
+
case "true":
|
|
1487
|
+
return true;
|
|
1488
|
+
case "false":
|
|
1489
|
+
return false;
|
|
1490
|
+
case "integer": {
|
|
1491
|
+
const value = Number.parseInt(node.text.trim(), 10);
|
|
1492
|
+
return Number.isNaN(value) ? node.text.trim() : value;
|
|
1493
|
+
}
|
|
1494
|
+
case "real": {
|
|
1495
|
+
const value = Number.parseFloat(node.text.trim());
|
|
1496
|
+
return Number.isNaN(value) ? node.text.trim() : value;
|
|
1497
|
+
}
|
|
1498
|
+
case "array":
|
|
1499
|
+
return node.children.map(plistNodeToValue);
|
|
1500
|
+
case "dict": {
|
|
1501
|
+
const result = {};
|
|
1502
|
+
for (let index = 0; index < node.children.length; index += 2) {
|
|
1503
|
+
const keyNode = node.children[index];
|
|
1504
|
+
const valueNode = node.children[index + 1];
|
|
1505
|
+
if (keyNode?.tag === "key" && valueNode !== void 0) {
|
|
1506
|
+
result[keyNode.text.trim()] = plistNodeToValue(valueNode);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
return result;
|
|
1510
|
+
}
|
|
1511
|
+
default:
|
|
1512
|
+
return node.text.trim();
|
|
1513
|
+
}
|
|
1514
|
+
};
|
|
1515
|
+
var parsePlistXml = (xml) => {
|
|
1516
|
+
const root = tokenizePlistXml(xml);
|
|
1517
|
+
const plistNode = root.children.find((child) => child.tag === "plist");
|
|
1518
|
+
const valueNode = plistNode?.children[0];
|
|
1519
|
+
return valueNode ? plistNodeToValue(valueNode) : void 0;
|
|
1520
|
+
};
|
|
1521
|
+
var isBinaryPlist = (buffer) => {
|
|
1522
|
+
return buffer.length >= 6 && buffer.subarray(0, 6).toString("latin1") === "bplist";
|
|
1523
|
+
};
|
|
1524
|
+
var firstPlistUrlScheme = (cfBundleURLTypes) => {
|
|
1525
|
+
if (!Array.isArray(cfBundleURLTypes)) {
|
|
1526
|
+
return void 0;
|
|
1527
|
+
}
|
|
1528
|
+
for (const entry of cfBundleURLTypes) {
|
|
1529
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
|
|
1530
|
+
continue;
|
|
1531
|
+
}
|
|
1532
|
+
const scheme = firstConfiguredScheme(entry.CFBundleURLSchemes);
|
|
1533
|
+
if (scheme !== void 0) {
|
|
1534
|
+
return scheme;
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
return void 0;
|
|
1538
|
+
};
|
|
1539
|
+
var walkForFilename = async (root, filename, maxDepth) => {
|
|
1540
|
+
const hits = [];
|
|
1541
|
+
let visited = 0;
|
|
1542
|
+
const walk = async (dir, depth) => {
|
|
1543
|
+
let entries;
|
|
1544
|
+
try {
|
|
1545
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
1546
|
+
} catch {
|
|
1547
|
+
return;
|
|
1548
|
+
}
|
|
1549
|
+
for (const entry of entries) {
|
|
1550
|
+
if (visited >= MAX_WALK_ENTRIES) {
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
visited += 1;
|
|
1554
|
+
if (entry.isSymbolicLink()) {
|
|
1555
|
+
continue;
|
|
1556
|
+
}
|
|
1557
|
+
if (entry.isDirectory()) {
|
|
1558
|
+
if (EXCLUDED_WALK_DIRS.has(entry.name)) {
|
|
1559
|
+
continue;
|
|
1560
|
+
}
|
|
1561
|
+
if (depth < maxDepth) {
|
|
1562
|
+
await walk(join4(dir, entry.name), depth + 1);
|
|
1563
|
+
}
|
|
1564
|
+
continue;
|
|
1565
|
+
}
|
|
1566
|
+
if (entry.isFile() && entry.name === filename) {
|
|
1567
|
+
hits.push({ path: join4(dir, entry.name), depth });
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
await walk(root, 0);
|
|
1572
|
+
hits.sort((a, b) => a.depth - b.depth || a.path.localeCompare(b.path));
|
|
1573
|
+
return hits;
|
|
1574
|
+
};
|
|
1575
|
+
var probeIosInfoPlist = async (root) => {
|
|
1576
|
+
const files = await walkForFilename(root, "Info.plist", MAX_PLIST_WALK_DEPTH);
|
|
1577
|
+
const describeSearch = (notes2) => {
|
|
1578
|
+
const base = files.length === 0 ? `Info.plist up to ${MAX_PLIST_WALK_DEPTH} levels below ${root} (excluding Pods/build/node_modules/DerivedData) \u2014 none found` : `${files.map((file) => file.path).join(", ")} (first "CFBundleURLSchemes" entry)`;
|
|
1579
|
+
return notes2.length === 0 ? base : `${base} \u2014 ${notes2.join(", ")}`;
|
|
1580
|
+
};
|
|
1581
|
+
const notes = [];
|
|
1582
|
+
for (const file of files) {
|
|
1583
|
+
const read = await readCappedBuffer(file.path);
|
|
1584
|
+
if (!read.ok) {
|
|
1585
|
+
notes.push(
|
|
1586
|
+
`${file.path} (${read.reason === "too-large" ? "too large, skipped" : "unreadable"})`
|
|
1587
|
+
);
|
|
1588
|
+
continue;
|
|
1589
|
+
}
|
|
1590
|
+
if (isBinaryPlist(read.data)) {
|
|
1591
|
+
notes.push(`${file.path} (binary plist \u2014 unreadable, use --scheme)`);
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
const value = parsePlistXml(read.data.toString("utf8"));
|
|
1595
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1596
|
+
continue;
|
|
1597
|
+
}
|
|
1598
|
+
const scheme = firstPlistUrlScheme(value.CFBundleURLTypes);
|
|
1599
|
+
if (scheme === void 0) {
|
|
1600
|
+
continue;
|
|
1601
|
+
}
|
|
1602
|
+
requireValidNativeScheme(scheme, `"CFBundleURLSchemes" in ${file.path}`);
|
|
1603
|
+
return {
|
|
1604
|
+
result: {
|
|
1605
|
+
source: "ios-info-plist",
|
|
1606
|
+
scheme,
|
|
1607
|
+
origin: `"CFBundleURLSchemes" in ${file.path}`
|
|
1608
|
+
},
|
|
1609
|
+
tried: [describeSearch(notes)]
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
return { tried: [describeSearch(notes)] };
|
|
1613
|
+
};
|
|
1614
|
+
var PROJECT_YML_SCHEME_PATTERN = /CFBundleURLSchemes\s*:\s*(?:\[\s*["']?([^"'\],\r\n]*)["']?|\r?\n[ \t]*-[ \t]*["']?([^"'\r\n]*)["']?)/u;
|
|
1615
|
+
var extractProjectYmlScheme = (text) => {
|
|
1616
|
+
const match = PROJECT_YML_SCHEME_PATTERN.exec(text);
|
|
1617
|
+
const raw = (match?.[1] ?? match?.[2])?.trim();
|
|
1618
|
+
return raw !== void 0 && raw.length > 0 ? raw : void 0;
|
|
1619
|
+
};
|
|
1620
|
+
var probeIosProjectYml = async (root) => {
|
|
1621
|
+
const path2 = join4(root, "project.yml");
|
|
1622
|
+
const description = `${path2} ("info.properties.CFBundleURLTypes" > "CFBundleURLSchemes")`;
|
|
1623
|
+
const read = await readCappedText(path2);
|
|
1624
|
+
if (!read.ok) {
|
|
1625
|
+
return {
|
|
1626
|
+
tried: [read.reason === "too-large" ? `${description} \u2014 too large, skipped` : description]
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
const scheme = extractProjectYmlScheme(read.text);
|
|
1630
|
+
if (scheme === void 0) {
|
|
1631
|
+
return { tried: [description] };
|
|
1632
|
+
}
|
|
1633
|
+
requireValidNativeScheme(scheme, `"CFBundleURLSchemes" in ${path2}`);
|
|
1634
|
+
return {
|
|
1635
|
+
result: { source: "ios-project-yml", scheme, origin: `"CFBundleURLSchemes" in ${path2}` },
|
|
1636
|
+
tried: [description]
|
|
1637
|
+
};
|
|
1638
|
+
};
|
|
1639
|
+
var PROBES = [
|
|
1640
|
+
probeAndroidGradle,
|
|
1641
|
+
probeAndroidManifest,
|
|
1642
|
+
probeIosInfoPlist,
|
|
1643
|
+
probeIosProjectYml
|
|
1644
|
+
];
|
|
1645
|
+
var discoverNativeScheme = async (root) => {
|
|
1646
|
+
const tried = [];
|
|
1647
|
+
const results = [];
|
|
1648
|
+
for (const probe of PROBES) {
|
|
1649
|
+
const outcome = await probe(root);
|
|
1650
|
+
tried.push(...outcome.tried);
|
|
1651
|
+
if (outcome.result !== void 0) {
|
|
1652
|
+
results.push(outcome.result);
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
if (results.length === 0) {
|
|
1656
|
+
return { tried };
|
|
1657
|
+
}
|
|
1658
|
+
const distinctSchemes = new Set(results.map((entry) => entry.scheme));
|
|
1659
|
+
if (distinctSchemes.size > 1) {
|
|
1660
|
+
throw usageError(
|
|
1661
|
+
"Conflicting deep-link schemes found in this project: " + results.map((entry) => `${entry.origin} says ${JSON.stringify(entry.scheme)}`).join(", but ") + ". Appduct will not guess which one is right \u2014 pass --scheme <scheme> to pick one."
|
|
1662
|
+
);
|
|
1663
|
+
}
|
|
1664
|
+
return { result: results[0], tried };
|
|
1665
|
+
};
|
|
1666
|
+
|
|
1667
|
+
// src/scheme.ts
|
|
1668
|
+
var PROJECT_CONFIG_DIR = ".appduct";
|
|
1669
|
+
var PROJECT_CONFIG_FILENAME = "config.json";
|
|
1670
|
+
var PROJECT_CONFIG_RELATIVE_PATH = join5(PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILENAME);
|
|
1671
|
+
var APP_JSON_FILENAME = "app.json";
|
|
1672
|
+
var SCHEME_ENV_VAR = "APPDUCT_SCHEME";
|
|
1673
|
+
var SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*$/u;
|
|
1674
|
+
var isValidScheme = (value) => SCHEME_PATTERN.test(value);
|
|
1675
|
+
var requireValidScheme = (value, origin) => {
|
|
1676
|
+
if (!isValidScheme(value)) {
|
|
1677
|
+
throw usageError(
|
|
1678
|
+
`Invalid deep-link scheme ${JSON.stringify(value)} from ${origin}: a scheme must start with a letter and contain only letters, digits, "+", "-" or "." (for example "myapp") \u2014 do not include "://".`
|
|
1679
|
+
);
|
|
1680
|
+
}
|
|
1681
|
+
return value;
|
|
1682
|
+
};
|
|
1683
|
+
var isPlainObject = (value) => {
|
|
1684
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1685
|
+
};
|
|
1686
|
+
var readJsonFile = async (path2) => {
|
|
1687
|
+
let text;
|
|
1688
|
+
try {
|
|
1689
|
+
text = await readFile6(path2, "utf8");
|
|
1690
|
+
} catch (error) {
|
|
1691
|
+
const code = error.code;
|
|
1692
|
+
if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR") {
|
|
1693
|
+
return void 0;
|
|
1694
|
+
}
|
|
1695
|
+
throw error;
|
|
1696
|
+
}
|
|
1697
|
+
try {
|
|
1698
|
+
return { raw: JSON.parse(text) };
|
|
1699
|
+
} catch (error) {
|
|
1700
|
+
throw usageError(`Could not parse ${path2}: ${error.message}`);
|
|
1701
|
+
}
|
|
1702
|
+
};
|
|
1703
|
+
var firstConfiguredScheme = (value) => {
|
|
1704
|
+
if (Array.isArray(value)) {
|
|
1705
|
+
return value.find((entry) => typeof entry === "string" && entry.length > 0);
|
|
1706
|
+
}
|
|
1707
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1708
|
+
};
|
|
1709
|
+
var discoverExpoScheme = async (dir) => {
|
|
1710
|
+
const path2 = join5(resolve(dir), APP_JSON_FILENAME);
|
|
1711
|
+
const file = await readJsonFile(path2);
|
|
1712
|
+
if (!file || !isPlainObject(file.raw)) {
|
|
1713
|
+
return void 0;
|
|
1714
|
+
}
|
|
1715
|
+
const expo = file.raw.expo;
|
|
1716
|
+
if (!isPlainObject(expo)) {
|
|
1717
|
+
return void 0;
|
|
1718
|
+
}
|
|
1719
|
+
const scheme = firstConfiguredScheme(expo.scheme);
|
|
1720
|
+
return scheme === void 0 ? void 0 : requireValidScheme(scheme, `"expo.scheme" in ${path2}`);
|
|
1721
|
+
};
|
|
1722
|
+
var discoverStaticProjectScheme = async (cwd) => {
|
|
1723
|
+
const appJsonPath = join5(resolve(cwd), APP_JSON_FILENAME);
|
|
1724
|
+
const tried = [`${appJsonPath} ("expo.scheme")`];
|
|
1725
|
+
const appJsonScheme = await discoverExpoScheme(cwd);
|
|
1726
|
+
if (appJsonScheme !== void 0) {
|
|
1727
|
+
return { scheme: appJsonScheme, source: "app-json", origin: appJsonPath, tried };
|
|
1728
|
+
}
|
|
1729
|
+
const native = await discoverNativeScheme(resolve(cwd));
|
|
1730
|
+
tried.push(...native.tried);
|
|
1731
|
+
if (native.result !== void 0) {
|
|
1732
|
+
return {
|
|
1733
|
+
scheme: native.result.scheme,
|
|
1734
|
+
source: native.result.source,
|
|
1735
|
+
origin: native.result.origin,
|
|
1736
|
+
tried
|
|
1737
|
+
};
|
|
1738
|
+
}
|
|
1739
|
+
return { tried };
|
|
1740
|
+
};
|
|
1741
|
+
var globalConfigDirs = (options = {}) => {
|
|
1742
|
+
const excluded = /* @__PURE__ */ new Set([join5(resolve(options.homeDir ?? homedir()), PROJECT_CONFIG_DIR)]);
|
|
1743
|
+
if (options.stateDirRoot !== void 0) {
|
|
1744
|
+
excluded.add(resolve(options.stateDirRoot));
|
|
1745
|
+
}
|
|
1746
|
+
return excluded;
|
|
1747
|
+
};
|
|
1748
|
+
var findProjectConfigs = (startDir, options = {}) => {
|
|
1749
|
+
const excluded = globalConfigDirs(options);
|
|
1750
|
+
const found = [];
|
|
1751
|
+
let dir = resolve(startDir);
|
|
1752
|
+
for (; ; ) {
|
|
1753
|
+
const projectDir = join5(dir, PROJECT_CONFIG_DIR);
|
|
1754
|
+
if (!excluded.has(projectDir)) {
|
|
1755
|
+
const candidate = join5(projectDir, PROJECT_CONFIG_FILENAME);
|
|
1756
|
+
if (existsSync2(candidate)) {
|
|
1757
|
+
found.push(candidate);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
const parent = dirname2(dir);
|
|
1761
|
+
if (parent === dir) {
|
|
1762
|
+
return found;
|
|
1763
|
+
}
|
|
1764
|
+
dir = parent;
|
|
1765
|
+
}
|
|
1766
|
+
};
|
|
1767
|
+
var readProjectConfigScheme = async (path2) => {
|
|
1768
|
+
const file = await readJsonFile(path2);
|
|
1769
|
+
if (!file) {
|
|
1770
|
+
return void 0;
|
|
1771
|
+
}
|
|
1772
|
+
if (!isPlainObject(file.raw)) {
|
|
1773
|
+
throw usageError(`Invalid Appduct project config at ${path2}: must be a JSON object.`);
|
|
1774
|
+
}
|
|
1775
|
+
const scheme = file.raw.scheme;
|
|
1776
|
+
if (scheme === void 0) {
|
|
1777
|
+
return void 0;
|
|
1778
|
+
}
|
|
1779
|
+
if (typeof scheme !== "string" || scheme.length === 0) {
|
|
1780
|
+
throw usageError(
|
|
1781
|
+
`Invalid Appduct project config at ${path2}: "scheme" must be a non-empty string.`
|
|
1782
|
+
);
|
|
1783
|
+
}
|
|
1784
|
+
return requireValidScheme(scheme, `"scheme" in ${path2}`);
|
|
1785
|
+
};
|
|
1786
|
+
var APP_ID_PLATFORMS = /* @__PURE__ */ new Set(["ios", "android"]);
|
|
1787
|
+
var readProjectConfigAppId = async (path2, platform) => {
|
|
1788
|
+
const file = await readJsonFile(path2);
|
|
1789
|
+
if (!file) {
|
|
1790
|
+
return void 0;
|
|
1791
|
+
}
|
|
1792
|
+
if (!isPlainObject(file.raw)) {
|
|
1793
|
+
throw usageError(`Invalid Appduct project config at ${path2}: must be a JSON object.`);
|
|
1794
|
+
}
|
|
1795
|
+
const appId = file.raw.appId;
|
|
1796
|
+
if (appId === void 0) {
|
|
1797
|
+
return void 0;
|
|
1798
|
+
}
|
|
1799
|
+
if (!isPlainObject(appId)) {
|
|
1800
|
+
throw usageError(
|
|
1801
|
+
`Invalid Appduct project config at ${path2}: "appId" must be an object with "ios" and/or "android" keys.`
|
|
1802
|
+
);
|
|
1803
|
+
}
|
|
1804
|
+
for (const key of Object.keys(appId)) {
|
|
1805
|
+
if (!APP_ID_PLATFORMS.has(key)) {
|
|
1806
|
+
throw usageError(
|
|
1807
|
+
`Invalid Appduct project config at ${path2}: unknown key "appId.${key}" (expected "ios" and/or "android").`
|
|
1808
|
+
);
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
const value = appId[platform];
|
|
1812
|
+
if (value === void 0) {
|
|
1813
|
+
return void 0;
|
|
1814
|
+
}
|
|
1815
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
1816
|
+
throw usageError(
|
|
1817
|
+
`Invalid Appduct project config at ${path2}: "appId.${platform}" must be a non-empty string.`
|
|
1818
|
+
);
|
|
1819
|
+
}
|
|
1820
|
+
return value;
|
|
1821
|
+
};
|
|
1822
|
+
var resolveScheme = async (options = {}) => {
|
|
1823
|
+
const env = options.env ?? process.env;
|
|
1824
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
1825
|
+
const tried = [];
|
|
1826
|
+
tried.push("the --scheme flag");
|
|
1827
|
+
if (options.flagScheme !== void 0 && options.flagScheme.length > 0) {
|
|
1828
|
+
return {
|
|
1829
|
+
scheme: requireValidScheme(options.flagScheme, "the --scheme flag"),
|
|
1830
|
+
source: "flag",
|
|
1831
|
+
tried
|
|
1832
|
+
};
|
|
1833
|
+
}
|
|
1834
|
+
tried.push(`the ${SCHEME_ENV_VAR} environment variable`);
|
|
1835
|
+
const envScheme = env[SCHEME_ENV_VAR];
|
|
1836
|
+
if (typeof envScheme === "string" && envScheme.length > 0) {
|
|
1837
|
+
return {
|
|
1838
|
+
scheme: requireValidScheme(envScheme, `the ${SCHEME_ENV_VAR} environment variable`),
|
|
1839
|
+
source: "env",
|
|
1840
|
+
tried
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
const projectConfigPaths = findProjectConfigs(cwd, {
|
|
1844
|
+
stateDirRoot: options.stateDirRoot,
|
|
1845
|
+
homeDir: options.homeDir
|
|
1846
|
+
});
|
|
1847
|
+
tried.push(
|
|
1848
|
+
projectConfigPaths.length === 0 ? `${PROJECT_CONFIG_RELATIVE_PATH} (searched upwards from ${cwd})` : projectConfigPaths.join(", ")
|
|
1849
|
+
);
|
|
1850
|
+
for (const projectConfigPath of projectConfigPaths) {
|
|
1851
|
+
const projectScheme = await readProjectConfigScheme(projectConfigPath);
|
|
1852
|
+
if (projectScheme !== void 0) {
|
|
1853
|
+
return { scheme: projectScheme, source: "project-config", tried };
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
tried.push(
|
|
1857
|
+
options.stateConfigPath === void 0 ? `the state directory's config.json ("scheme")` : `${options.stateConfigPath} ("scheme")`
|
|
1858
|
+
);
|
|
1859
|
+
if (options.configScheme !== void 0 && options.configScheme.length > 0) {
|
|
1860
|
+
return {
|
|
1861
|
+
scheme: requireValidScheme(
|
|
1862
|
+
options.configScheme,
|
|
1863
|
+
options.stateConfigPath === void 0 ? `the state directory's config.json "scheme"` : `"scheme" in ${options.stateConfigPath}`
|
|
1864
|
+
),
|
|
1865
|
+
source: "state-config",
|
|
1866
|
+
tried
|
|
1867
|
+
};
|
|
1868
|
+
}
|
|
1869
|
+
const discovered = await discoverStaticProjectScheme(cwd);
|
|
1870
|
+
tried.push(...discovered.tried);
|
|
1871
|
+
if (discovered.scheme !== void 0) {
|
|
1872
|
+
return { scheme: discovered.scheme, source: discovered.source, tried };
|
|
1873
|
+
}
|
|
1874
|
+
return { tried };
|
|
1875
|
+
};
|
|
1876
|
+
var describeMissingScheme = (tried) => {
|
|
1877
|
+
const locations = tried.length === 0 ? "" : `Looked in, in order:
|
|
1878
|
+
${tried.map((location, index) => ` ${index + 1}. ${location}`).join("\n")}
|
|
1879
|
+
`;
|
|
1880
|
+
return "A deep-link scheme is required to compose the link, and none was found. " + locations + `Set one with --scheme <scheme>, ${SCHEME_ENV_VAR}=<scheme>, "expo.scheme" in ${APP_JSON_FILENAME}, or run \`appduct init\` in your app root to write ${PROJECT_CONFIG_RELATIVE_PATH}.`;
|
|
1881
|
+
};
|
|
1882
|
+
var resolveSchemeOrThrow = async (options = {}) => {
|
|
1883
|
+
const resolved = await resolveScheme(options);
|
|
1884
|
+
if (resolved.scheme === void 0) {
|
|
1885
|
+
throw usageError(describeMissingScheme(resolved.tried));
|
|
1886
|
+
}
|
|
1887
|
+
return resolved.scheme;
|
|
1888
|
+
};
|
|
1889
|
+
var resolveAppId = async (options) => {
|
|
1890
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
1891
|
+
const tried = [];
|
|
1892
|
+
tried.push("the --app-id flag");
|
|
1893
|
+
if (options.flagAppId !== void 0 && options.flagAppId.length > 0) {
|
|
1894
|
+
return { appId: options.flagAppId, source: "flag", tried };
|
|
1895
|
+
}
|
|
1896
|
+
const projectConfigPaths = findProjectConfigs(cwd, {
|
|
1897
|
+
stateDirRoot: options.stateDirRoot,
|
|
1898
|
+
homeDir: options.homeDir
|
|
1899
|
+
});
|
|
1900
|
+
tried.push(
|
|
1901
|
+
projectConfigPaths.length === 0 ? `${PROJECT_CONFIG_RELATIVE_PATH} (searched upwards from ${cwd})` : projectConfigPaths.join(", ")
|
|
1902
|
+
);
|
|
1903
|
+
for (const projectConfigPath of projectConfigPaths) {
|
|
1904
|
+
const projectAppId = await readProjectConfigAppId(projectConfigPath, options.platform);
|
|
1905
|
+
if (projectAppId !== void 0) {
|
|
1906
|
+
return { appId: projectAppId, source: "project-config", tried };
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
return { tried };
|
|
1910
|
+
};
|
|
1911
|
+
var describeMissingAppId = (platform, tried) => {
|
|
1912
|
+
const locations = tried.length === 0 ? "" : `Looked in, in order:
|
|
1913
|
+
${tried.map((location, index) => ` ${index + 1}. ${location}`).join("\n")}
|
|
1914
|
+
`;
|
|
1915
|
+
const platformLabel = platform === "android" ? "Android" : "a physical iPhone/iPad";
|
|
1916
|
+
const initFlag = platform === "android" ? "--android-app-id" : "--ios-app-id";
|
|
1917
|
+
return `Delivering to ${platformLabel} needs the installed app's id, and none was found. ${locations}Set one with \`appduct init ${initFlag} <id>\`, --app-id <id>, or "appId.${platform}" in ${PROJECT_CONFIG_RELATIVE_PATH}.`;
|
|
1918
|
+
};
|
|
1919
|
+
|
|
1920
|
+
// src/link.ts
|
|
1921
|
+
var OPEN_TARGET_ADDRESS_OVERRIDE = "127.0.0.1";
|
|
1922
|
+
var composeDeepLink = (scheme, result) => `${scheme}:///?appduct=${result.deepLinkPayload}&pin=${encodeURIComponent(result.pin)}`;
|
|
1923
|
+
var mintLink = async (options) => {
|
|
1924
|
+
if (options.target !== void 0 && !isOpenTarget(options.target)) {
|
|
1925
|
+
throw usageError(
|
|
1926
|
+
`"target" must be one of ${OPEN_TARGETS.map((target) => `"${target}"`).join(", ")} (got "${options.target}").`
|
|
1927
|
+
);
|
|
1928
|
+
}
|
|
1929
|
+
if (options.device !== void 0 && options.target === void 0) {
|
|
1930
|
+
throw usageError('"device" only applies alongside a target.');
|
|
1931
|
+
}
|
|
1932
|
+
if (options.appId !== void 0 && options.target !== "android" && options.target !== "ios-device") {
|
|
1933
|
+
throw usageError('"appId" only applies alongside target "android" or target "ios-device".');
|
|
1934
|
+
}
|
|
1935
|
+
if (options.relaunch !== void 0 && options.target !== "ios-device") {
|
|
1936
|
+
throw usageError('"relaunch" only applies alongside target "ios-device".');
|
|
1937
|
+
}
|
|
1938
|
+
const paths = getStateDirPaths(options.stateDir);
|
|
1939
|
+
const config = await loadConfig(paths);
|
|
1940
|
+
const scheme = await resolveSchemeOrThrow({
|
|
1941
|
+
flagScheme: options.scheme,
|
|
1942
|
+
env: options.schemeEnv,
|
|
1943
|
+
cwd: options.cwd,
|
|
1944
|
+
configScheme: config.scheme,
|
|
1945
|
+
stateConfigPath: paths.configPath,
|
|
1946
|
+
stateDirRoot: paths.root
|
|
1947
|
+
});
|
|
1948
|
+
const platform = options.target === void 0 ? void 0 : platformOf(options.target);
|
|
1949
|
+
let appId;
|
|
1950
|
+
if (platform !== void 0) {
|
|
1951
|
+
const resolved = await resolveAppId({
|
|
1952
|
+
platform,
|
|
1953
|
+
flagAppId: options.appId,
|
|
1954
|
+
cwd: options.cwd,
|
|
1955
|
+
stateDirRoot: paths.root
|
|
1956
|
+
});
|
|
1957
|
+
if (resolved.appId === void 0) {
|
|
1958
|
+
throw usageError(describeMissingAppId(platform, resolved.tried));
|
|
1959
|
+
}
|
|
1960
|
+
appId = resolved.appId;
|
|
1961
|
+
}
|
|
1962
|
+
if (appId !== void 0 && !isValidAppId(appId)) {
|
|
1963
|
+
throw usageError(invalidAppIdMessage(appId));
|
|
1964
|
+
}
|
|
1965
|
+
const result = await callDaemon(
|
|
1966
|
+
RPC_METHODS2.linkCreate,
|
|
1967
|
+
{
|
|
1968
|
+
ttlSeconds: options.ttlSeconds,
|
|
1969
|
+
addressOverride: options.target && usesLoopbackAddress(options.target) ? OPEN_TARGET_ADDRESS_OVERRIDE : void 0
|
|
1970
|
+
},
|
|
1971
|
+
{ stateDir: options.stateDir, spawn: options.spawn, autoSpawn: options.autoSpawn }
|
|
1972
|
+
);
|
|
1973
|
+
if (options.target === "ios-device" && isLoopbackAddress(result.endpoint.address)) {
|
|
1974
|
+
throw usageError(loopbackAddressMessage(result.endpoint.address));
|
|
1975
|
+
}
|
|
1976
|
+
const deepLink = composeDeepLink(scheme, result);
|
|
1977
|
+
if (options.target) {
|
|
1978
|
+
await deliverToOpenTarget({
|
|
1979
|
+
target: options.target,
|
|
1980
|
+
deepLink,
|
|
1981
|
+
wssPort: result.endpoint.port,
|
|
1982
|
+
device: options.device,
|
|
1983
|
+
appId,
|
|
1984
|
+
relaunch: options.relaunch,
|
|
1985
|
+
exec: options.exec,
|
|
1986
|
+
env: options.env
|
|
1987
|
+
});
|
|
1988
|
+
return {
|
|
1989
|
+
sessionId: result.sessionId,
|
|
1990
|
+
deepLink,
|
|
1991
|
+
endpoint: result.endpoint,
|
|
1992
|
+
expiresAt: result.expiresAt,
|
|
1993
|
+
pin: result.pin,
|
|
1994
|
+
delivered: true,
|
|
1995
|
+
target: options.target
|
|
1996
|
+
};
|
|
1997
|
+
}
|
|
1998
|
+
return {
|
|
1999
|
+
sessionId: result.sessionId,
|
|
2000
|
+
deepLink,
|
|
2001
|
+
endpoint: result.endpoint,
|
|
2002
|
+
expiresAt: result.expiresAt,
|
|
2003
|
+
pin: result.pin
|
|
2004
|
+
};
|
|
2005
|
+
};
|
|
2006
|
+
|
|
2007
|
+
// src/commands/link.ts
|
|
2008
|
+
var handleLinkCommand = async (options, context) => {
|
|
2009
|
+
let openTarget;
|
|
2010
|
+
if (options.open !== void 0) {
|
|
2011
|
+
if (!isOpenTarget(options.open)) {
|
|
2012
|
+
throw usageError(
|
|
2013
|
+
`"--open" must be one of ${OPEN_TARGETS.map((target) => `"${target}"`).join(", ")} (got "${options.open}").`
|
|
2014
|
+
);
|
|
2015
|
+
}
|
|
2016
|
+
openTarget = options.open;
|
|
2017
|
+
}
|
|
2018
|
+
if (options.device !== void 0 && openTarget === void 0) {
|
|
2019
|
+
throw usageError('"--device" only applies with "--open".');
|
|
2020
|
+
}
|
|
2021
|
+
if (options.appId !== void 0 && openTarget !== "android" && openTarget !== "ios-device") {
|
|
2022
|
+
throw usageError('"--app-id" only applies with "--open android" or "--open ios-device".');
|
|
2023
|
+
}
|
|
2024
|
+
if (options.relaunch !== void 0 && openTarget !== "ios-device") {
|
|
2025
|
+
throw usageError('"--relaunch" only applies with "--open ios-device".');
|
|
2026
|
+
}
|
|
2027
|
+
const result = await mintLink({
|
|
2028
|
+
stateDir: context.stateDir,
|
|
2029
|
+
spawn: context.spawn,
|
|
2030
|
+
ttlSeconds: options.ttlSeconds,
|
|
2031
|
+
scheme: options.scheme,
|
|
2032
|
+
cwd: context.cwd,
|
|
2033
|
+
target: openTarget,
|
|
2034
|
+
device: options.device,
|
|
2035
|
+
appId: options.appId,
|
|
2036
|
+
relaunch: options.relaunch,
|
|
2037
|
+
exec: context.exec,
|
|
2038
|
+
env: context.env,
|
|
2039
|
+
schemeEnv: context.schemeEnv
|
|
2040
|
+
});
|
|
2041
|
+
return { ok: true, data: result };
|
|
2042
|
+
};
|
|
2043
|
+
|
|
2044
|
+
// src/cli/command-options.ts
|
|
2045
|
+
var parsePositiveIntegerOption = (value, flagName) => {
|
|
2046
|
+
if (value === void 0) {
|
|
2047
|
+
return void 0;
|
|
2048
|
+
}
|
|
2049
|
+
const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
|
|
2050
|
+
if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed <= 0) {
|
|
2051
|
+
throw usageError(`"${flagName}" must be a positive integer.`);
|
|
2052
|
+
}
|
|
2053
|
+
return parsed;
|
|
2054
|
+
};
|
|
2055
|
+
|
|
2056
|
+
// src/cli/global-flags.ts
|
|
2057
|
+
var formatJson = (value, flags) => {
|
|
2058
|
+
return flags.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);
|
|
2059
|
+
};
|
|
2060
|
+
|
|
2061
|
+
// src/output.ts
|
|
2062
|
+
import pc from "picocolors";
|
|
2063
|
+
import {
|
|
2064
|
+
formatAgentWebSocketUrl,
|
|
2065
|
+
renderToolSignature,
|
|
2066
|
+
summarizeToolDescription
|
|
2067
|
+
} from "@appduct/shared";
|
|
2068
|
+
|
|
2069
|
+
// src/qr-terminal.ts
|
|
2070
|
+
import { toQR } from "toqr";
|
|
2071
|
+
var HALF_UPPER = "\u2580";
|
|
2072
|
+
var HALF_LOWER = "\u2584";
|
|
2073
|
+
var FULL = "\u2588";
|
|
2074
|
+
var renderQrToTerminal = (content, options) => {
|
|
2075
|
+
const margin = options?.margin ?? 0;
|
|
2076
|
+
const ecLevel = options?.ecLevel ?? 1;
|
|
2077
|
+
const modules = toQR(content, ecLevel);
|
|
2078
|
+
const side = Math.sqrt(modules.length);
|
|
2079
|
+
if (!Number.isInteger(side)) {
|
|
2080
|
+
throw new Error("Invalid QR matrix size");
|
|
2081
|
+
}
|
|
2082
|
+
const dim = side + 2 * margin;
|
|
2083
|
+
const isDark = (row, col) => {
|
|
2084
|
+
if (row < margin || col < margin || row >= margin + side || col >= margin + side) {
|
|
2085
|
+
return false;
|
|
2086
|
+
}
|
|
2087
|
+
const mr = row - margin;
|
|
2088
|
+
const mc = col - margin;
|
|
2089
|
+
return modules[mr * side + mc] === 1;
|
|
2090
|
+
};
|
|
2091
|
+
const lines = [];
|
|
2092
|
+
for (let row = 0; row < dim; row += 2) {
|
|
2093
|
+
let line = "";
|
|
2094
|
+
for (let col = 0; col < dim; col++) {
|
|
2095
|
+
const top = isDark(row, col);
|
|
2096
|
+
const bottom = row + 1 < dim ? isDark(row + 1, col) : false;
|
|
2097
|
+
line += top ? bottom ? FULL : HALF_UPPER : bottom ? HALF_LOWER : " ";
|
|
2098
|
+
}
|
|
2099
|
+
lines.push(line);
|
|
2100
|
+
}
|
|
2101
|
+
return lines.join("\n");
|
|
2102
|
+
};
|
|
2103
|
+
|
|
2104
|
+
// src/output.ts
|
|
2105
|
+
var renderMetaLines = (meta) => {
|
|
2106
|
+
if (!meta) {
|
|
2107
|
+
return [];
|
|
2108
|
+
}
|
|
2109
|
+
return [
|
|
2110
|
+
"Meta",
|
|
2111
|
+
` Command: ${meta.command}`,
|
|
2112
|
+
` Timestamp: ${meta.timestamp}`,
|
|
2113
|
+
...typeof meta.duration_ms === "number" ? [` Duration: ${meta.duration_ms} ms`] : []
|
|
2114
|
+
];
|
|
2115
|
+
};
|
|
2116
|
+
var formatScalar = (value, flags) => {
|
|
2117
|
+
if (typeof value === "string") {
|
|
2118
|
+
return value;
|
|
2119
|
+
}
|
|
2120
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
2121
|
+
return String(value);
|
|
2122
|
+
}
|
|
2123
|
+
if (value === null || value === void 0) {
|
|
2124
|
+
return "null";
|
|
2125
|
+
}
|
|
2126
|
+
return formatJson(value, flags);
|
|
2127
|
+
};
|
|
2128
|
+
var renderFields = (title, fields, flags) => {
|
|
2129
|
+
const visibleFields = fields.filter(([, value]) => value !== void 0);
|
|
2130
|
+
if (visibleFields.length === 0) {
|
|
2131
|
+
return [];
|
|
2132
|
+
}
|
|
2133
|
+
const width = Math.max(...visibleFields.map(([label]) => label.length));
|
|
2134
|
+
return [
|
|
2135
|
+
title,
|
|
2136
|
+
...visibleFields.map(([label, value]) => ` ${label.padEnd(width)} ${formatScalar(value, flags)}`)
|
|
2137
|
+
];
|
|
2138
|
+
};
|
|
2139
|
+
var formatAge = (fromIso, toIso) => {
|
|
2140
|
+
const elapsedMs = Math.max(0, new Date(toIso).getTime() - new Date(fromIso).getTime());
|
|
2141
|
+
const elapsedSeconds = Math.floor(elapsedMs / 1e3);
|
|
2142
|
+
if (elapsedSeconds < 60) {
|
|
2143
|
+
return `${elapsedSeconds}s`;
|
|
2144
|
+
}
|
|
2145
|
+
const elapsedMinutes = Math.floor(elapsedSeconds / 60);
|
|
2146
|
+
if (elapsedMinutes < 60) {
|
|
2147
|
+
return `${elapsedMinutes}m`;
|
|
2148
|
+
}
|
|
2149
|
+
const elapsedHours = Math.floor(elapsedMinutes / 60);
|
|
2150
|
+
if (elapsedHours < 24) {
|
|
2151
|
+
return `${elapsedHours}h`;
|
|
2152
|
+
}
|
|
2153
|
+
return `${Math.floor(elapsedHours / 24)}d`;
|
|
2154
|
+
};
|
|
2155
|
+
var formatDevice = (device) => {
|
|
2156
|
+
const parts = [device.manufacturer, device.model].filter((part) => Boolean(part));
|
|
2157
|
+
const label = parts.length > 0 ? parts.join(" ") : "unknown device";
|
|
2158
|
+
return device.os ? `${label} (${device.os})` : label;
|
|
2159
|
+
};
|
|
2160
|
+
var renderLsData = (colors, data, now) => {
|
|
2161
|
+
if (data.length === 0) {
|
|
2162
|
+
return [colors.dim("Sessions"), " No Appduct sessions are registered."];
|
|
2163
|
+
}
|
|
2164
|
+
const nowIso = now.toISOString();
|
|
2165
|
+
const headers = ["Alias", "State", "Device", "Tools", "Age"];
|
|
2166
|
+
const rows = data.map((session) => [
|
|
2167
|
+
session.alias,
|
|
2168
|
+
session.state,
|
|
2169
|
+
formatDevice(session.device),
|
|
2170
|
+
String(session.toolCount),
|
|
2171
|
+
formatAge(session.claimedAt ?? session.createdAt, nowIso)
|
|
2172
|
+
]);
|
|
2173
|
+
const widths = headers.map(
|
|
2174
|
+
(header, index) => Math.max(header.length, ...rows.map((row) => row[index].length))
|
|
2175
|
+
);
|
|
2176
|
+
return [
|
|
2177
|
+
colors.green("Sessions"),
|
|
2178
|
+
` ${headers.map((header, index) => header.padEnd(widths[index])).join(" ")}`,
|
|
2179
|
+
...rows.map((row) => ` ${row.map((cell, index) => cell.padEnd(widths[index])).join(" ")}`)
|
|
2180
|
+
];
|
|
2181
|
+
};
|
|
2182
|
+
var isToolsListing = (data) => {
|
|
2183
|
+
return typeof data === "object" && data !== null && Array.isArray(data.tools);
|
|
2184
|
+
};
|
|
2185
|
+
var isToolGroupsListing = (data) => {
|
|
2186
|
+
return typeof data === "object" && data !== null && Array.isArray(data.groups) && !Array.isArray(data.tools);
|
|
2187
|
+
};
|
|
2188
|
+
var UNGROUPED_LABEL = "(ungrouped)";
|
|
2189
|
+
var MAX_FOOTER_GROUPS = 10;
|
|
2190
|
+
var hasAnyGroup = (groups) => {
|
|
2191
|
+
return (groups ?? []).some((entry) => entry.group !== null);
|
|
2192
|
+
};
|
|
2193
|
+
var topLevelGroups = (groups) => {
|
|
2194
|
+
return (groups ?? []).filter((entry) => entry.group !== null && !entry.group.includes("/"));
|
|
2195
|
+
};
|
|
2196
|
+
var renderEmptyToolsLine = (data) => {
|
|
2197
|
+
if (data.total > 0) {
|
|
2198
|
+
return ` No tools at offset ${data.offset ?? 0}; ${data.total} matching tool${data.total === 1 ? "" : "s"} in total.`;
|
|
2199
|
+
}
|
|
2200
|
+
if (data.group !== void 0) {
|
|
2201
|
+
const match = data.filter === void 0 ? "" : ` match ${JSON.stringify(data.filter)}`;
|
|
2202
|
+
return ` No tools in group ${JSON.stringify(data.group)}${match}. Run \`appduct tools --groups\` to see the session's groups.`;
|
|
2203
|
+
}
|
|
2204
|
+
return data.filter === void 0 ? " No tools registered." : ` No tools match ${JSON.stringify(data.filter)}.`;
|
|
2205
|
+
};
|
|
2206
|
+
var renderGroupHint = (data) => {
|
|
2207
|
+
if (data.group !== void 0 || !hasAnyGroup(data.groups)) {
|
|
2208
|
+
return void 0;
|
|
2209
|
+
}
|
|
2210
|
+
const top = topLevelGroups(data.groups);
|
|
2211
|
+
const named = top.slice(0, MAX_FOOTER_GROUPS).map((entry) => `${entry.group} ${entry.total}`);
|
|
2212
|
+
const more = top.length > MAX_FOOTER_GROUPS ? `, ... ${top.length - MAX_FOOTER_GROUPS} more; see --groups` : "";
|
|
2213
|
+
return `--group <name> (groups: ${named.join(", ")}${more})`;
|
|
2214
|
+
};
|
|
2215
|
+
var renderTruncationLine = (data) => {
|
|
2216
|
+
if (data.tools.length >= data.total) {
|
|
2217
|
+
return [];
|
|
2218
|
+
}
|
|
2219
|
+
const groupHint = renderGroupHint(data);
|
|
2220
|
+
const narrow = groupHint === void 0 ? "--filter <text> or" : `${groupHint} or --filter <text>, or`;
|
|
2221
|
+
return [
|
|
2222
|
+
"",
|
|
2223
|
+
`Showing ${data.tools.length} of ${data.total} tools (offset ${data.offset ?? 0}). Narrow with ${narrow} page with --offset <n>.`
|
|
2224
|
+
];
|
|
2225
|
+
};
|
|
2226
|
+
var renderToolSummaryLines = (tool, indent) => {
|
|
2227
|
+
const tag = tool.policy === "allow" ? "" : ` [${tool.policy}]`;
|
|
2228
|
+
return [`${indent}${renderToolSignature(tool)}${tag}`, `${indent} ${summarizeToolDescription(tool.description)}`];
|
|
2229
|
+
};
|
|
2230
|
+
var renderGroupedToolLines = (colors, tools) => {
|
|
2231
|
+
const byGroup = /* @__PURE__ */ new Map();
|
|
2232
|
+
for (const tool of tools) {
|
|
2233
|
+
const key = tool.group ?? null;
|
|
2234
|
+
const bucket = byGroup.get(key);
|
|
2235
|
+
if (bucket) {
|
|
2236
|
+
bucket.push(tool);
|
|
2237
|
+
} else {
|
|
2238
|
+
byGroup.set(key, [tool]);
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
const tops = /* @__PURE__ */ new Map();
|
|
2242
|
+
for (const key of byGroup.keys()) {
|
|
2243
|
+
if (key === null) {
|
|
2244
|
+
continue;
|
|
2245
|
+
}
|
|
2246
|
+
const slash = key.indexOf("/");
|
|
2247
|
+
const top = slash === -1 ? key : key.slice(0, slash);
|
|
2248
|
+
const subs = tops.get(top) ?? [];
|
|
2249
|
+
if (slash !== -1) {
|
|
2250
|
+
subs.push(key);
|
|
2251
|
+
}
|
|
2252
|
+
tops.set(top, subs);
|
|
2253
|
+
}
|
|
2254
|
+
const byCodePoint = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
2255
|
+
const lines = [];
|
|
2256
|
+
for (const top of [...tops.keys()].sort(byCodePoint)) {
|
|
2257
|
+
lines.push(` ${colors.cyan(top)}`);
|
|
2258
|
+
lines.push(...(byGroup.get(top) ?? []).flatMap((tool) => renderToolSummaryLines(tool, " ")));
|
|
2259
|
+
for (const sub of tops.get(top).sort(byCodePoint)) {
|
|
2260
|
+
lines.push(` ${colors.cyan(sub)}`);
|
|
2261
|
+
lines.push(...byGroup.get(sub).flatMap((tool) => renderToolSummaryLines(tool, " ")));
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
const ungrouped = byGroup.get(null);
|
|
2265
|
+
if (ungrouped) {
|
|
2266
|
+
lines.push(` ${colors.cyan(UNGROUPED_LABEL)}`);
|
|
2267
|
+
lines.push(...ungrouped.flatMap((tool) => renderToolSummaryLines(tool, " ")));
|
|
2268
|
+
}
|
|
2269
|
+
return lines;
|
|
2270
|
+
};
|
|
2271
|
+
var renderToolsTitle = (colors, data) => {
|
|
2272
|
+
return colors.green(data.group === void 0 ? "Tools" : `Tools in group ${data.group}`);
|
|
2273
|
+
};
|
|
2274
|
+
var renderToolSummaryTable = (colors, data) => {
|
|
2275
|
+
if (data.tools.length === 0) {
|
|
2276
|
+
return [renderToolsTitle(colors, data), renderEmptyToolsLine(data)];
|
|
2277
|
+
}
|
|
2278
|
+
const grouped = data.group === void 0 && hasAnyGroup(data.groups);
|
|
2279
|
+
return [
|
|
2280
|
+
renderToolsTitle(colors, data),
|
|
2281
|
+
...grouped ? renderGroupedToolLines(colors, data.tools) : data.tools.flatMap((tool) => renderToolSummaryLines(tool, " ")),
|
|
2282
|
+
...renderTruncationLine(data),
|
|
2283
|
+
"",
|
|
2284
|
+
"Run `appduct tools <name>` for a tool's full schema."
|
|
2285
|
+
];
|
|
2286
|
+
};
|
|
2287
|
+
var renderToolDetail = (colors, tool, flags) => {
|
|
2288
|
+
return renderFields(
|
|
2289
|
+
colors.green(`Tool: ${tool.name}`),
|
|
2290
|
+
[
|
|
2291
|
+
["Signature", renderToolSignature(tool)],
|
|
2292
|
+
["Description", tool.description],
|
|
2293
|
+
["Input schema", tool.input_schema],
|
|
2294
|
+
["Output schema", tool.output_schema],
|
|
2295
|
+
// `?? undefined` keeps an ungrouped tool's row hidden rather than printing a bare "null":
|
|
2296
|
+
// `renderFields` drops undefined rows, and the machine form's `null` is for consumers, not
|
|
2297
|
+
// for a human scanning one tool's schema.
|
|
2298
|
+
["Group", tool.group ?? void 0],
|
|
2299
|
+
["Annotations", tool.annotations],
|
|
2300
|
+
// Only rendered for a tool that declares one; `renderFields` drops undefined rows, so a
|
|
2301
|
+
// tool on the daemon's default deadline shows no line at all rather than a misleading
|
|
2302
|
+
// "10000".
|
|
2303
|
+
["Timeout (ms)", tool.timeout_ms]
|
|
2304
|
+
],
|
|
2305
|
+
flags
|
|
2306
|
+
);
|
|
2307
|
+
};
|
|
2308
|
+
var renderToolsFullListing = (colors, data, flags) => {
|
|
2309
|
+
if (data.tools.length === 0) {
|
|
2310
|
+
return [renderToolsTitle(colors, data), renderEmptyToolsLine(data)];
|
|
2311
|
+
}
|
|
2312
|
+
return [
|
|
2313
|
+
...data.tools.flatMap((tool, index) => [
|
|
2314
|
+
...index > 0 ? [""] : [],
|
|
2315
|
+
...renderToolDetail(colors, tool, flags)
|
|
2316
|
+
]),
|
|
2317
|
+
...renderTruncationLine(data)
|
|
2318
|
+
];
|
|
2319
|
+
};
|
|
2320
|
+
var renderToolGroups = (colors, data) => {
|
|
2321
|
+
if (data.groups.length === 0) {
|
|
2322
|
+
return [colors.green("Groups"), " No tools registered."];
|
|
2323
|
+
}
|
|
2324
|
+
const label = (entry) => {
|
|
2325
|
+
if (entry.group === null) {
|
|
2326
|
+
return UNGROUPED_LABEL;
|
|
2327
|
+
}
|
|
2328
|
+
return entry.group.includes("/") ? ` ${entry.group}` : entry.group;
|
|
2329
|
+
};
|
|
2330
|
+
const width = Math.max(...data.groups.map((entry) => label(entry).length));
|
|
2331
|
+
const countWidth = Math.max(...data.groups.map((entry) => String(entry.total).length));
|
|
2332
|
+
return [
|
|
2333
|
+
colors.green("Groups"),
|
|
2334
|
+
...data.groups.map((entry) => ` ${label(entry).padEnd(width)} ${String(entry.total).padStart(countWidth)}`),
|
|
2335
|
+
"",
|
|
2336
|
+
`${data.total} tool${data.total === 1 ? "" : "s"} in total. ` + (hasAnyGroup(data.groups) ? "Run `appduct tools --group <name>` to list one group's tools." : "No tool declares a group.")
|
|
2337
|
+
];
|
|
2338
|
+
};
|
|
2339
|
+
var renderToolsData = (colors, data, flags, full) => {
|
|
2340
|
+
if (isToolGroupsListing(data)) {
|
|
2341
|
+
return renderToolGroups(colors, data);
|
|
2342
|
+
}
|
|
2343
|
+
if (!isToolsListing(data)) {
|
|
2344
|
+
return renderToolDetail(colors, data, flags);
|
|
2345
|
+
}
|
|
2346
|
+
return full ? renderToolsFullListing(colors, data, flags) : renderToolSummaryTable(colors, data);
|
|
2347
|
+
};
|
|
2348
|
+
var renderInvokeData = (colors, data, flags) => {
|
|
2349
|
+
return [colors.green("Result"), formatScalar(data, flags)];
|
|
2350
|
+
};
|
|
2351
|
+
var renderLinkData = (colors, data, flags, qr) => {
|
|
2352
|
+
const lines = [
|
|
2353
|
+
colors.green("Link Created"),
|
|
2354
|
+
...renderFields(
|
|
2355
|
+
"Link",
|
|
2356
|
+
[
|
|
2357
|
+
["Session", data.sessionId],
|
|
2358
|
+
["Deep link", data.deepLink],
|
|
2359
|
+
["Endpoint", formatAgentWebSocketUrl(data.endpoint)],
|
|
2360
|
+
["Pin", data.pin],
|
|
2361
|
+
["Expires", new Date(data.expiresAt * 1e3).toISOString()],
|
|
2362
|
+
["Delivered", data.delivered ? `yes (${data.target})` : void 0]
|
|
2363
|
+
],
|
|
2364
|
+
flags
|
|
2365
|
+
)
|
|
2366
|
+
];
|
|
2367
|
+
if (qr) {
|
|
2368
|
+
lines.push("", "QR", renderQrToTerminal(data.deepLink));
|
|
2369
|
+
}
|
|
2370
|
+
return lines;
|
|
2371
|
+
};
|
|
2372
|
+
var renderRevokeData = (colors, _data) => {
|
|
2373
|
+
return [colors.green("Session Revoked")];
|
|
2374
|
+
};
|
|
2375
|
+
var renderKeygenData = (colors, data, flags) => {
|
|
2376
|
+
return [
|
|
2377
|
+
colors.green("Key Ready"),
|
|
2378
|
+
...renderFields(
|
|
2379
|
+
"Key",
|
|
2380
|
+
[
|
|
2381
|
+
["Path", data.path],
|
|
2382
|
+
["Fingerprint", data.pin]
|
|
2383
|
+
],
|
|
2384
|
+
flags
|
|
2385
|
+
)
|
|
2386
|
+
];
|
|
2387
|
+
};
|
|
2388
|
+
var renderInitData = (colors, data, flags) => {
|
|
2389
|
+
const snippet = JSON.stringify(
|
|
2390
|
+
{ mcpServers: { appduct: data.mcpServerEntry } },
|
|
2391
|
+
null,
|
|
2392
|
+
2
|
|
2393
|
+
);
|
|
2394
|
+
return [
|
|
2395
|
+
colors.green(data.changed ? "Project Initialized" : "Project Already Initialized"),
|
|
2396
|
+
...renderFields(
|
|
2397
|
+
"Config",
|
|
2398
|
+
[
|
|
2399
|
+
["Path", data.path],
|
|
2400
|
+
["Scheme", data.scheme],
|
|
2401
|
+
["Source", data.source],
|
|
2402
|
+
// Only present for a scheme discovery read off a static project file (app.json, or one of
|
|
2403
|
+
// the native Android/iOS probes) — names the exact file/key, not just which platform.
|
|
2404
|
+
["Read from", data.origin],
|
|
2405
|
+
["Written", data.changed ? data.created ? "created" : "updated" : "unchanged"]
|
|
2406
|
+
],
|
|
2407
|
+
flags
|
|
2408
|
+
),
|
|
2409
|
+
...data.note === void 0 ? [] : ["", colors.yellow(`Note: ${data.note}`)],
|
|
2410
|
+
"",
|
|
2411
|
+
"MCP server entry",
|
|
2412
|
+
...snippet.split("\n").map((line) => ` ${line}`),
|
|
2413
|
+
"",
|
|
2414
|
+
"Next",
|
|
2415
|
+
...data.nextSteps.map((step, index) => ` ${index + 1}. ${step}`)
|
|
2416
|
+
];
|
|
2417
|
+
};
|
|
2418
|
+
var renderDaemonRunData = (colors, data, flags) => {
|
|
2419
|
+
return [
|
|
2420
|
+
colors.green("Daemon Running"),
|
|
2421
|
+
...renderFields(
|
|
2422
|
+
"Daemon",
|
|
2423
|
+
[
|
|
2424
|
+
["PID", data.daemon.pid],
|
|
2425
|
+
["State dir", data.daemon.state_dir],
|
|
2426
|
+
["Socket", data.daemon.socket_path]
|
|
2427
|
+
],
|
|
2428
|
+
flags
|
|
2429
|
+
)
|
|
2430
|
+
];
|
|
2431
|
+
};
|
|
2432
|
+
var renderDaemonStartData = (colors, data, flags) => {
|
|
2433
|
+
return [
|
|
2434
|
+
colors.green("Daemon Started"),
|
|
2435
|
+
...renderFields(
|
|
2436
|
+
"Daemon",
|
|
2437
|
+
[
|
|
2438
|
+
["PID", data.daemon.pid],
|
|
2439
|
+
["WSS port", data.daemon.wss_port],
|
|
2440
|
+
["Started at", data.daemon.started_at]
|
|
2441
|
+
],
|
|
2442
|
+
flags
|
|
2443
|
+
)
|
|
2444
|
+
];
|
|
2445
|
+
};
|
|
2446
|
+
var renderDaemonStopData = (colors, data, flags) => {
|
|
2447
|
+
return [
|
|
2448
|
+
colors.green("Daemon Stopped"),
|
|
2449
|
+
...renderFields("Daemon", [["Method", data.daemon.method]], flags)
|
|
2450
|
+
];
|
|
2451
|
+
};
|
|
2452
|
+
var formatByteSize = (bytes) => {
|
|
2453
|
+
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
|
|
2454
|
+
let value = bytes;
|
|
2455
|
+
let unit = 0;
|
|
2456
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
2457
|
+
value /= 1024;
|
|
2458
|
+
unit += 1;
|
|
2459
|
+
}
|
|
2460
|
+
return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`;
|
|
2461
|
+
};
|
|
2462
|
+
var renderDaemonStatusData = (colors, data, flags) => {
|
|
2463
|
+
return [
|
|
2464
|
+
colors.green("Daemon Status"),
|
|
2465
|
+
...renderFields(
|
|
2466
|
+
"Daemon",
|
|
2467
|
+
[
|
|
2468
|
+
["Version", data.daemon.version],
|
|
2469
|
+
["PID", data.daemon.pid],
|
|
2470
|
+
["Started at", data.daemon.started_at],
|
|
2471
|
+
["WSS port", data.daemon.wss_port],
|
|
2472
|
+
["Pinned keys", data.daemon.pinned_keys.length],
|
|
2473
|
+
["Sessions", data.daemon.session_count]
|
|
2474
|
+
],
|
|
2475
|
+
flags
|
|
2476
|
+
),
|
|
2477
|
+
"",
|
|
2478
|
+
...renderFields(
|
|
2479
|
+
"Policy",
|
|
2480
|
+
[
|
|
2481
|
+
["Default", data.policy.default],
|
|
2482
|
+
["Destructive", data.policy.destructive],
|
|
2483
|
+
["Overrides", data.policy.tools ? Object.keys(data.policy.tools).length : 0]
|
|
2484
|
+
],
|
|
2485
|
+
flags
|
|
2486
|
+
),
|
|
2487
|
+
"",
|
|
2488
|
+
// The retention rows drop out entirely against a daemon that predates them (`renderFields`
|
|
2489
|
+
// skips `undefined`), rather than printing "undefined" or an invented zero.
|
|
2490
|
+
...renderFields(
|
|
2491
|
+
"Audit",
|
|
2492
|
+
[
|
|
2493
|
+
["Path", data.audit.path],
|
|
2494
|
+
["Retention", data.audit.retention_days === void 0 ? void 0 : `${data.audit.retention_days} days`],
|
|
2495
|
+
["Files", data.audit.files],
|
|
2496
|
+
["Size", data.audit.bytes === void 0 ? void 0 : formatByteSize(data.audit.bytes)],
|
|
2497
|
+
["Failed writes", data.audit.failed_writes],
|
|
2498
|
+
["Failed prunes", data.audit.failed_prunes]
|
|
2499
|
+
],
|
|
2500
|
+
flags
|
|
2501
|
+
),
|
|
2502
|
+
// Version drift (issue #30) is the one thing here an operator has to act on, so it goes last
|
|
2503
|
+
// — the line still on screen after the block scrolls — and in yellow, not a quiet field row.
|
|
2504
|
+
...data.warning ? ["", colors.yellow(`Warning: ${data.warning}`)] : []
|
|
2505
|
+
];
|
|
2506
|
+
};
|
|
2507
|
+
var renderDoctorData = (colors, data, flags) => {
|
|
2508
|
+
return [
|
|
2509
|
+
data.present ? colors.green("Appduct Present") : colors.yellow("Appduct Absent"),
|
|
2510
|
+
...renderFields(
|
|
2511
|
+
"Artifact",
|
|
2512
|
+
[
|
|
2513
|
+
["Path", data.artifact],
|
|
2514
|
+
["Platform", data.platform],
|
|
2515
|
+
["Format", data.format],
|
|
2516
|
+
["Present", data.present],
|
|
2517
|
+
["Signals", data.signals.length > 0 ? data.signals.join(", ") : "none"],
|
|
2518
|
+
["Assertion", data.assertion ? `${data.assertion.expected} (holds)` : void 0]
|
|
2519
|
+
],
|
|
2520
|
+
flags
|
|
2521
|
+
)
|
|
2522
|
+
];
|
|
2523
|
+
};
|
|
2524
|
+
var renderSuccessData = (colors, command, data, options) => {
|
|
2525
|
+
const flags = options.flags;
|
|
2526
|
+
switch (command) {
|
|
2527
|
+
case "init":
|
|
2528
|
+
return renderInitData(colors, data, flags);
|
|
2529
|
+
case "keygen":
|
|
2530
|
+
return renderKeygenData(colors, data, flags);
|
|
2531
|
+
case "link":
|
|
2532
|
+
return renderLinkData(colors, data, flags, options.qr);
|
|
2533
|
+
case "ls":
|
|
2534
|
+
return renderLsData(colors, data, options.now ?? /* @__PURE__ */ new Date());
|
|
2535
|
+
case "tools":
|
|
2536
|
+
return renderToolsData(colors, data, flags, options.full);
|
|
2537
|
+
case "invoke":
|
|
2538
|
+
return renderInvokeData(colors, data, flags);
|
|
2539
|
+
case "revoke":
|
|
2540
|
+
return renderRevokeData(colors, data);
|
|
2541
|
+
case "daemon run":
|
|
2542
|
+
return renderDaemonRunData(colors, data, flags);
|
|
2543
|
+
case "daemon start":
|
|
2544
|
+
return renderDaemonStartData(colors, data, flags);
|
|
2545
|
+
case "daemon stop":
|
|
2546
|
+
return renderDaemonStopData(colors, data, flags);
|
|
2547
|
+
case "daemon status":
|
|
2548
|
+
return renderDaemonStatusData(colors, data, flags);
|
|
2549
|
+
case "doctor":
|
|
2550
|
+
return renderDoctorData(colors, data, flags);
|
|
2551
|
+
default:
|
|
2552
|
+
return [colors.green("Command Complete"), formatJson(data, flags)];
|
|
2553
|
+
}
|
|
2554
|
+
};
|
|
2555
|
+
var renderHumanError = (colors, error, flags, meta) => {
|
|
2556
|
+
return [
|
|
2557
|
+
colors.red("Command Failed"),
|
|
2558
|
+
...renderFields(
|
|
2559
|
+
"Error",
|
|
2560
|
+
[
|
|
2561
|
+
["Type", error.type],
|
|
2562
|
+
["Message", error.message],
|
|
2563
|
+
["Details", error.details]
|
|
2564
|
+
],
|
|
2565
|
+
flags
|
|
2566
|
+
),
|
|
2567
|
+
...meta ? ["", ...renderMetaLines(meta)] : []
|
|
2568
|
+
].join("\n");
|
|
2569
|
+
};
|
|
2570
|
+
var renderResult = (result, options) => {
|
|
2571
|
+
if (options.flags.json) {
|
|
2572
|
+
return {
|
|
2573
|
+
stdout: `${formatJson(result, options.flags)}
|
|
2574
|
+
`
|
|
2575
|
+
};
|
|
2576
|
+
}
|
|
2577
|
+
const colors = pc.createColors(options.flags.color);
|
|
2578
|
+
if (!result.ok) {
|
|
2579
|
+
return {
|
|
2580
|
+
stderr: `${renderHumanError(colors, result.error, options.flags, result.meta)}
|
|
2581
|
+
`
|
|
2582
|
+
};
|
|
2583
|
+
}
|
|
2584
|
+
const lines = [
|
|
2585
|
+
...renderSuccessData(colors, options.command, result.data, options),
|
|
2586
|
+
"",
|
|
2587
|
+
...renderMetaLines(result.meta)
|
|
2588
|
+
].filter((line, index, collection) => {
|
|
2589
|
+
if (line !== "") {
|
|
2590
|
+
return true;
|
|
2591
|
+
}
|
|
2592
|
+
return index > 0 && collection[index - 1] !== "" && index < collection.length - 1;
|
|
2593
|
+
});
|
|
2594
|
+
return {
|
|
2595
|
+
stdout: `${lines.join("\n")}
|
|
2596
|
+
`
|
|
2597
|
+
};
|
|
2598
|
+
};
|
|
2599
|
+
|
|
2600
|
+
// src/cli/envelope.ts
|
|
2601
|
+
var createCommandMeta = (command, startedAt, finishedAt) => {
|
|
2602
|
+
return {
|
|
2603
|
+
command,
|
|
2604
|
+
timestamp: finishedAt.toISOString(),
|
|
2605
|
+
duration_ms: finishedAt.getTime() - startedAt.getTime()
|
|
2606
|
+
};
|
|
2607
|
+
};
|
|
2608
|
+
var finalizeResult = (result, timing, flags) => {
|
|
2609
|
+
if (!flags.verbose) {
|
|
2610
|
+
return result;
|
|
2611
|
+
}
|
|
2612
|
+
return {
|
|
2613
|
+
...result,
|
|
2614
|
+
meta: createCommandMeta(timing.command, timing.startedAt, timing.finishedAt)
|
|
2615
|
+
};
|
|
2616
|
+
};
|
|
2617
|
+
|
|
2618
|
+
// src/cli/runner.ts
|
|
2619
|
+
var writeRenderedOutput = (rendered, writers) => {
|
|
2620
|
+
if (rendered.stdout) {
|
|
2621
|
+
writers.stdout.write(rendered.stdout);
|
|
2622
|
+
}
|
|
2623
|
+
if (rendered.stderr) {
|
|
2624
|
+
writers.stderr.write(rendered.stderr);
|
|
2625
|
+
}
|
|
2626
|
+
};
|
|
2627
|
+
var executeCommand = async (command, handler, env, render = {}) => {
|
|
2628
|
+
const startedAt = env.clock.now();
|
|
2629
|
+
try {
|
|
2630
|
+
const result = await handler();
|
|
2631
|
+
const finishedAt = env.clock.now();
|
|
2632
|
+
const finalized = finalizeResult(result, { command, startedAt, finishedAt }, env.flags);
|
|
2633
|
+
const renderOptions = {
|
|
2634
|
+
command,
|
|
2635
|
+
flags: env.flags,
|
|
2636
|
+
now: finishedAt,
|
|
2637
|
+
qr: render.qr,
|
|
2638
|
+
full: render.full
|
|
2639
|
+
};
|
|
2640
|
+
writeRenderedOutput(renderResult(finalized, renderOptions), env);
|
|
2641
|
+
return 0;
|
|
2642
|
+
} catch (error) {
|
|
2643
|
+
const finishedAt = env.clock.now();
|
|
2644
|
+
const cliError = toCliError(error);
|
|
2645
|
+
const result = { ok: false, error: cliError };
|
|
2646
|
+
const finalized = finalizeResult(result, { command, startedAt, finishedAt }, env.flags);
|
|
2647
|
+
const renderOptions = {
|
|
2648
|
+
command,
|
|
2649
|
+
flags: env.flags,
|
|
2650
|
+
now: finishedAt,
|
|
2651
|
+
qr: render.qr,
|
|
2652
|
+
full: render.full
|
|
2653
|
+
};
|
|
2654
|
+
writeRenderedOutput(renderResult(finalized, renderOptions), env);
|
|
2655
|
+
return getExitCodeForError(error);
|
|
2656
|
+
}
|
|
2657
|
+
};
|
|
2658
|
+
|
|
2659
|
+
// src/cli/router.ts
|
|
2660
|
+
var commandName = (context) => {
|
|
2661
|
+
return context.path.join(" ");
|
|
2662
|
+
};
|
|
2663
|
+
|
|
2664
|
+
// src/cli/version-guard.ts
|
|
2665
|
+
var versionCheckOptions = async (context, onWarning = context.versionCheck.warn) => {
|
|
2666
|
+
return {
|
|
2667
|
+
clientVersion: context.versionCheck.clientVersion,
|
|
2668
|
+
forceRestart: await context.versionCheck.forceRestart(),
|
|
2669
|
+
onWarning
|
|
2670
|
+
};
|
|
2671
|
+
};
|
|
2672
|
+
var guarded = (context) => {
|
|
2673
|
+
return (handler) => {
|
|
2674
|
+
return async () => {
|
|
2675
|
+
await ensureDaemonVersionMatches({
|
|
2676
|
+
stateDir: context.stateDir,
|
|
2677
|
+
autoSpawn: false,
|
|
2678
|
+
checkVersion: await versionCheckOptions(context)
|
|
2679
|
+
});
|
|
2680
|
+
return handler();
|
|
2681
|
+
};
|
|
2682
|
+
};
|
|
2683
|
+
};
|
|
2684
|
+
|
|
2685
|
+
// src/cli/routes/link.ts
|
|
2686
|
+
var route = async (context) => {
|
|
2687
|
+
const { options, stateDir } = context;
|
|
2688
|
+
return executeCommand(
|
|
2689
|
+
commandName(context),
|
|
2690
|
+
guarded(context)(
|
|
2691
|
+
() => handleLinkCommand(
|
|
2692
|
+
{
|
|
2693
|
+
ttlSeconds: parsePositiveIntegerOption(options.ttl, "--ttl"),
|
|
2694
|
+
scheme: typeof options.scheme === "string" ? options.scheme : void 0,
|
|
2695
|
+
open: typeof options.open === "string" ? options.open : void 0,
|
|
2696
|
+
device: typeof options.device === "string" ? options.device : void 0,
|
|
2697
|
+
// cac camelCases `--app-id`; the dashed spelling is kept as a fallback so a
|
|
2698
|
+
// parser change can't silently drop the flag.
|
|
2699
|
+
appId: typeof options.appId === "string" ? options.appId : typeof options["app-id"] === "string" ? options["app-id"] : void 0,
|
|
2700
|
+
// Left `undefined` when absent rather than coerced to `false`, so that
|
|
2701
|
+
// "--relaunch only applies with --open ios-device" fires on the flag actually being
|
|
2702
|
+
// passed and not on every `link` invocation.
|
|
2703
|
+
relaunch: options.relaunch === true ? true : void 0
|
|
2704
|
+
},
|
|
2705
|
+
{ stateDir }
|
|
2706
|
+
)
|
|
2707
|
+
),
|
|
2708
|
+
context.env,
|
|
2709
|
+
{ qr: Boolean(options.qr) }
|
|
2710
|
+
);
|
|
2711
|
+
};
|
|
2712
|
+
export {
|
|
2713
|
+
route
|
|
2714
|
+
};
|