@octane-xplat/build 0.0.0-nightly.g1b95ef7

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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -0
  3. package/dist/add-worker.js +66 -0
  4. package/dist/build-worker.js +287 -0
  5. package/dist/compatibility-check.js +155 -0
  6. package/dist/compatibility-data/compatibility.js +109 -0
  7. package/dist/compatibility-data/compatibility.json +298 -0
  8. package/dist/compatibility.js +240 -0
  9. package/dist/css-platform.js +236 -0
  10. package/dist/css-platform.types.d.ts +11 -0
  11. package/dist/dev-inspector.web.js +125 -0
  12. package/dist/dev-log-client.web.js +79 -0
  13. package/dist/dev-log-server.js +13 -0
  14. package/dist/devtools-worker.js +94 -0
  15. package/dist/doctor-checks.js +414 -0
  16. package/dist/doctor-tool.js +27 -0
  17. package/dist/env.js +3 -0
  18. package/dist/fmt-plan.js +149 -0
  19. package/dist/fonts-worker.js +31 -0
  20. package/dist/fonts.js +614 -0
  21. package/dist/inline-stylesheets.js +44 -0
  22. package/dist/linux/config.js +43 -0
  23. package/dist/linux/gtk-runtime.js +86 -0
  24. package/dist/linux/package.js +189 -0
  25. package/dist/linux-gtk/bindings.mjs +675 -0
  26. package/dist/linux-gtk/native-gi-projection.js +36 -0
  27. package/dist/linux-gtk/vite.d.ts +39 -0
  28. package/dist/linux-gtk/vite.js +281 -0
  29. package/dist/macos/config.js +136 -0
  30. package/dist/macos/core-ui.js +59 -0
  31. package/dist/macos/core-vite.js +122 -0
  32. package/dist/macos/doctor-checks.js +58 -0
  33. package/dist/macos/executables.js +39 -0
  34. package/dist/macos/jsc-host/runtime.js +134 -0
  35. package/dist/macos/native.js +286 -0
  36. package/dist/macos/runtime-package.js +30 -0
  37. package/dist/macos/tab-item.js +62 -0
  38. package/dist/macos/vite.d.ts +13 -0
  39. package/dist/macos/vite.js +22 -0
  40. package/dist/markdown.js +11 -0
  41. package/dist/mason-engine.js +20 -0
  42. package/dist/mcp/contracts/actions.js +133 -0
  43. package/dist/mcp/dev-bridge.js +363 -0
  44. package/dist/mcp/dev-socket.js +203 -0
  45. package/dist/mcp/dev-stack.js +134 -0
  46. package/dist/mcp/inspection/dom.web.js +46 -0
  47. package/dist/native-regex.js +123 -0
  48. package/dist/package-manager.js +106 -0
  49. package/dist/package-root.js +48 -0
  50. package/dist/patches.js +356 -0
  51. package/dist/route-config.js +53 -0
  52. package/dist/route-data.js +42 -0
  53. package/dist/route-generator.js +514 -0
  54. package/dist/route-path.js +29 -0
  55. package/dist/route-source.js +67 -0
  56. package/dist/targets.js +37 -0
  57. package/dist/tsconfig-envs.js +400 -0
  58. package/dist/tsconfig-pin.js +31 -0
  59. package/dist/tsrx-leaf.js +57 -0
  60. package/dist/typecheck-globals/macos.d.ts +21 -0
  61. package/dist/typecheck-globals/native.d.ts +42 -0
  62. package/dist/ui/src/markdown/markdown-ast.js +33 -0
  63. package/dist/ui/src/markdown/markdown-character-references.js +79 -0
  64. package/dist/ui/src/markdown/markdown-parse.js +1930 -0
  65. package/dist/ui/src/markdown/markdown-plugins.js +564 -0
  66. package/dist/ui/src/markdown/markdown-url.js +17 -0
  67. package/dist/updates-worker.js +34 -0
  68. package/dist/upgrade-worker.js +63 -0
  69. package/dist/vite-target.js +57 -0
  70. package/dist/vite.d.ts +125 -0
  71. package/dist/vite.js +797 -0
  72. package/dist/workshop-worker.js +181 -0
  73. package/package.json +74 -0
@@ -0,0 +1,20 @@
1
+ // ../cli/src/mason-engine.ts
2
+ /** The only supported Mason engine on mobile; the old packages ship overlapping native classes. */
3
+ var masonCorePackage = "@octane-xplat/nativescript-mason-core";
4
+ var masonFullPackage = "@octane-xplat/nativescript-masonkit";
5
+ var masonLegacyPackage = "@triniwiz/nativescript-masonkit";
6
+ /**
7
+ * The engine the app must build with: core on iOS/Android, full MasonKit in
8
+ * the Windows preview (core ships no Windows artifacts). Rejects engine pins
9
+ * the core cutover replaced.
10
+ */
11
+ function masonEngine(declared, windows = false) {
12
+ if (windows) {
13
+ if (declared["@octane-xplat/nativescript-mason-core"]) throw new Error(`${masonCorePackage} supports iOS and Android only; Windows is unqualified.`);
14
+ return masonFullPackage;
15
+ }
16
+ const replaced = [masonFullPackage, masonLegacyPackage].filter((name) => declared[name]);
17
+ if (replaced.length) throw new Error(`${replaced.join(" and ")} was replaced by ${masonCorePackage}; their native classes and libraries overlap. Remove the replaced engine and run xplat upgrade.`);
18
+ return masonCorePackage;
19
+ }
20
+ export { masonCorePackage, masonEngine, masonFullPackage, masonLegacyPackage };
@@ -0,0 +1,133 @@
1
+ // ../cli/src/mcp/contracts/actions.ts
2
+ var DEV_ACTIONS_DEFAULT_TIMEOUT_MS = 3e4;
3
+ var DEV_ACTIONS_MAX_TIMEOUT_MS = 3e5;
4
+ var FIELD_TYPES = /* @__PURE__ */ new Set([
5
+ "string",
6
+ "number",
7
+ "integer",
8
+ "boolean",
9
+ "object",
10
+ "array"
11
+ ]);
12
+ var ACTION_ID = /^[a-z0-9][a-z0-9._-]{1,127}$/i;
13
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ function validateField(field, path, problems) {
15
+ if (!isRecord(field) || !FIELD_TYPES.has(field.type)) {
16
+ problems.push(`${path}: missing or unknown field type`);
17
+ return;
18
+ }
19
+ for (const key of [
20
+ "minLength",
21
+ "maxLength",
22
+ "minimum",
23
+ "maximum",
24
+ "minItems",
25
+ "maxItems"
26
+ ]) if (field[key] !== void 0 && typeof field[key] !== "number") problems.push(`${path}.${key}: must be a number`);
27
+ if (field.pattern !== void 0) try {
28
+ new RegExp(field.pattern);
29
+ } catch {
30
+ problems.push(`${path}.pattern: does not compile`);
31
+ }
32
+ if (field.fields !== void 0) {
33
+ if (!isRecord(field.fields)) problems.push(`${path}.fields: must be a named field map`);
34
+ else for (const [name, nested] of Object.entries(field.fields)) validateField(nested, `${path}.fields.${name}`, problems);
35
+ }
36
+ if (field.items !== void 0) validateField(field.items, `${path}.items`, problems);
37
+ }
38
+ var validateFields = (contract, path, problems) => {
39
+ if (contract === void 0) return;
40
+ if (!isRecord(contract) || contract.fields !== void 0 && !isRecord(contract.fields)) {
41
+ problems.push(`${path}: must be a { fields } contract`);
42
+ return;
43
+ }
44
+ for (const [name, field] of Object.entries(contract.fields ?? {})) validateField(field, `${path}.fields.${name}`, problems);
45
+ };
46
+ function validateActionDeclaration(action) {
47
+ const problems = [];
48
+ if (!isRecord(action)) return ["action declaration must be an object"];
49
+ if (typeof action.id !== "string" || !ACTION_ID.test(action.id)) problems.push("id: required, 2-128 chars of [a-z0-9._-] starting alphanumeric");
50
+ if (typeof action.title !== "string" || !action.title.trim()) problems.push("title: required");
51
+ if (typeof action.description !== "string" || !action.description.trim()) problems.push("description: required");
52
+ if (!isRecord(action.effects) || typeof action.effects.summary !== "string") problems.push("effects.summary: required");
53
+ validateFields(action.input, "input", problems);
54
+ validateFields(action.result, "result", problems);
55
+ if (action.availability?.platforms !== void 0) {
56
+ if (!Array.isArray(action.availability.platforms)) problems.push("availability.platforms: must be an array");
57
+ }
58
+ if (action.execution?.concurrency !== void 0 && !["serialized", "overlap"].includes(action.execution.concurrency)) problems.push("execution.concurrency: must be \"serialized\" or \"overlap\"");
59
+ if (action.execution?.timeoutMs !== void 0 && (typeof action.execution.timeoutMs !== "number" || action.execution.timeoutMs <= 0)) problems.push("execution.timeoutMs: must be a positive number");
60
+ return problems;
61
+ }
62
+ var checkValue = (field, value, path, errors) => {
63
+ const typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v === "number" && Number.isInteger(v) ? "integer" : typeof v;
64
+ const type = typeOf(value);
65
+ if (!(field.type === "number" ? type === "number" || type === "integer" : field.type === "integer" ? type === "integer" : field.type === "object" ? type === "object" : field.type === "array" ? type === "array" : type === field.type)) {
66
+ errors.push(`${path}: expected ${field.type}, got ${type}`);
67
+ return;
68
+ }
69
+ if (field.enum && !field.enum.some((candidate) => candidate === value)) errors.push(`${path}: not one of the declared values`);
70
+ if (field.type === "string") {
71
+ if (field.minLength !== void 0 && value.length < field.minLength) errors.push(`${path}: shorter than minLength ${field.minLength}`);
72
+ if (field.maxLength !== void 0 && value.length > field.maxLength) errors.push(`${path}: longer than maxLength ${field.maxLength}`);
73
+ if (field.pattern !== void 0 && !new RegExp(field.pattern).test(value)) errors.push(`${path}: does not match pattern`);
74
+ }
75
+ if (field.type === "number" || field.type === "integer") {
76
+ if (field.minimum !== void 0 && value < field.minimum) errors.push(`${path}: below minimum ${field.minimum}`);
77
+ if (field.maximum !== void 0 && value > field.maximum) errors.push(`${path}: above maximum ${field.maximum}`);
78
+ }
79
+ if (field.type === "array") {
80
+ if (field.minItems !== void 0 && value.length < field.minItems) errors.push(`${path}: fewer than minItems ${field.minItems}`);
81
+ if (field.maxItems !== void 0 && value.length > field.maxItems) errors.push(`${path}: more than maxItems ${field.maxItems}`);
82
+ if (field.items) value.forEach((item, index) => checkValue(field.items, item, `${path}[${index}]`, errors));
83
+ }
84
+ if (field.type === "object" && field.fields) checkFields(field.fields, value, path, errors);
85
+ };
86
+ function checkFields(fields, value, path, errors, out = null) {
87
+ for (const [name, field] of Object.entries(fields)) {
88
+ if (!(Object.prototype.hasOwnProperty.call(value, name) && value[name] !== void 0)) {
89
+ if (field.default === void 0) errors.push(`${path}.${name}: required`);
90
+ else if (out) out[name] = field.default;
91
+ continue;
92
+ }
93
+ if (out) out[name] = value[name];
94
+ checkValue(field, value[name], `${path}.${name}`, errors);
95
+ }
96
+ for (const key of Object.keys(value)) if (!Object.prototype.hasOwnProperty.call(fields, key)) errors.push(`${path}.${key}: not a declared field`);
97
+ }
98
+ function validateAgainst(contract, value, basePath) {
99
+ if (!isRecord(value)) return {
100
+ ok: false,
101
+ errors: [`${basePath}: expected an object of named fields`]
102
+ };
103
+ const fields = contract?.fields ?? {};
104
+ const out = {};
105
+ const errors = [];
106
+ checkFields(fields, value, basePath, errors, out);
107
+ return errors.length ? {
108
+ ok: false,
109
+ errors
110
+ } : {
111
+ ok: true,
112
+ value: out
113
+ };
114
+ }
115
+ function validateActionInput(contract, input) {
116
+ return validateAgainst(contract, input ?? {}, "input");
117
+ }
118
+ function validateActionOutput(contract, output) {
119
+ return validateAgainst(contract, output ?? {}, "result");
120
+ }
121
+ function actionAvailability(action, platform) {
122
+ const availability = action.availability;
123
+ if (availability?.platforms && !availability.platforms.includes(platform)) return {
124
+ ready: false,
125
+ reason: `not applicable on ${platform}`
126
+ };
127
+ if (availability?.ready === false) return {
128
+ ready: false,
129
+ reason: availability.reason ?? "reported unavailable by the app"
130
+ };
131
+ return { ready: true };
132
+ }
133
+ export { DEV_ACTIONS_DEFAULT_TIMEOUT_MS, DEV_ACTIONS_MAX_TIMEOUT_MS, actionAvailability, validateActionDeclaration, validateActionInput, validateActionOutput };
@@ -0,0 +1,363 @@
1
+ import { nativeDevSocketPlugin } from "./dev-socket.js";
2
+ import { createDevStackResolver } from "./dev-stack.js";
3
+ import { browserLogScript } from "../dev-log-client.web.js";
4
+ import { formatBrowserLogBatch } from "../dev-log-server.js";
5
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { randomBytes, randomUUID } from "node:crypto";
8
+ // ../cli/src/mcp/dev-bridge.ts
9
+ var PREFIX = "/__xplat_dev__";
10
+ var MAX_BODY = 1048576;
11
+ var INSTANCE_TTL_MS = 15e3;
12
+ var OUTCOME_TTL_MS = 6e5;
13
+ var MAX_WAIT_MS = 3e4;
14
+ var json = (res, status, body) => {
15
+ res.statusCode = status;
16
+ res.setHeader("content-type", "application/json");
17
+ res.end(JSON.stringify(body));
18
+ };
19
+ var readBody = (req) => new Promise((resolve, reject) => {
20
+ const chunks = [];
21
+ let size = 0;
22
+ req.on("data", (chunk) => {
23
+ size += chunk.length;
24
+ if (size > MAX_BODY) {
25
+ reject(/* @__PURE__ */ new Error("body too large"));
26
+ req.destroy();
27
+ return;
28
+ }
29
+ chunks.push(chunk);
30
+ });
31
+ req.on("end", () => {
32
+ try {
33
+ resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {});
34
+ } catch {
35
+ reject(/* @__PURE__ */ new Error("invalid JSON body"));
36
+ }
37
+ });
38
+ req.on("error", reject);
39
+ });
40
+ /**
41
+ * Vite plugin. `options.appRoot` defaults to the vite root — the session file
42
+ * always lands under <app>/node_modules/.cache/xplat/dev-bridge/ where the
43
+ * MCP server scans the bound app.
44
+ */
45
+ function devBridge(options = {}) {
46
+ const native = nativeDevSocketPlugin();
47
+ if (native) return native;
48
+ const token = randomBytes(24).toString("hex");
49
+ const serverId = `srv_${randomUUID()}`;
50
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
51
+ const instances = /* @__PURE__ */ new Map();
52
+ const requests = /* @__PURE__ */ new Map();
53
+ let viteServer;
54
+ const resolveStack = createDevStackResolver(() => viteServer);
55
+ const resolveOutcomeFailures = async (outcome) => {
56
+ const failures = outcome?.error?.failures;
57
+ if (!viteServer || !Array.isArray(failures)) return;
58
+ for (const failure of failures.slice(0, 20)) {
59
+ if (typeof failure?.stack !== "string") continue;
60
+ try {
61
+ const sourceStack = await resolveStack(failure.stack);
62
+ if (sourceStack) failure.sourceStack = sourceStack;
63
+ } catch {}
64
+ }
65
+ };
66
+ const prune = () => {
67
+ const now = Date.now();
68
+ for (const [id, entry] of instances) if (now - entry.at >= INSTANCE_TTL_MS) expireInstance(id, entry);
69
+ for (const [id, entry] of requests) if (entry.outcome && now - entry.completedAt > OUTCOME_TTL_MS) requests.delete(id);
70
+ };
71
+ const authorized = (req) => req.headers["x-xplat-dev-token"] === token;
72
+ const unauthorized = (res) => json(res, 401, { error: {
73
+ code: "unauthorized",
74
+ message: "missing or invalid dev-bridge token"
75
+ } });
76
+ const freshInstances = () => {
77
+ prune();
78
+ return [...instances.entries()].map(([id, entry]) => ({
79
+ ...entry.announcement,
80
+ appInstanceId: id
81
+ }));
82
+ };
83
+ const outcomeWaiters = /* @__PURE__ */ new Map();
84
+ const settleOutcome = (requestId) => {
85
+ for (const resolve of outcomeWaiters.get(requestId) ?? []) resolve();
86
+ outcomeWaiters.delete(requestId);
87
+ };
88
+ const awaitOutcome = (requestId, ms) => new Promise((resolve) => {
89
+ const timer = setTimeout(resolve, Math.min(ms, MAX_WAIT_MS));
90
+ const done = () => {
91
+ clearTimeout(timer);
92
+ resolve();
93
+ };
94
+ outcomeWaiters.set(requestId, [...outcomeWaiters.get(requestId) ?? [], done]);
95
+ });
96
+ const pollWaiters = /* @__PURE__ */ new Map();
97
+ const wakePollers = (instanceId) => {
98
+ for (const resolve of pollWaiters.get(instanceId) ?? []) resolve();
99
+ pollWaiters.delete(instanceId);
100
+ };
101
+ const expireInstance = (instanceId, instance) => {
102
+ if (instances.get(instanceId) !== instance) return;
103
+ clearTimeout(instance.timer);
104
+ instances.delete(instanceId);
105
+ for (const [requestId, entry] of requests) {
106
+ if (entry.request.appInstanceId !== instanceId || entry.outcome) continue;
107
+ const delivered = entry.state === "delivered";
108
+ entry.state = "completed";
109
+ entry.completedAt = Date.now();
110
+ entry.outcome = {
111
+ requestId,
112
+ status: "unknown",
113
+ error: {
114
+ code: "disconnected_runtime",
115
+ message: "The app stopped announcing its registry."
116
+ },
117
+ partialEffects: delivered ? ["The action was delivered; whether it completed is unknown."] : [],
118
+ completedAt: new Date(entry.completedAt).toISOString()
119
+ };
120
+ settleOutcome(requestId);
121
+ }
122
+ wakePollers(instanceId);
123
+ };
124
+ const awaitWork = (instanceId, ms) => new Promise((resolve) => {
125
+ const timer = setTimeout(resolve, Math.min(ms, MAX_WAIT_MS));
126
+ const done = () => {
127
+ clearTimeout(timer);
128
+ resolve();
129
+ };
130
+ pollWaiters.set(instanceId, [...pollWaiters.get(instanceId) ?? [], done]);
131
+ });
132
+ const workFor = (instanceId) => {
133
+ const invocations = [];
134
+ const cancel = [];
135
+ for (const [requestId, entry] of requests) {
136
+ if (entry.request.appInstanceId !== instanceId || entry.outcome) continue;
137
+ if (entry.state === "pending") {
138
+ entry.state = "delivered";
139
+ invocations.push({
140
+ requestId,
141
+ ...entry.request
142
+ });
143
+ }
144
+ if (entry.cancelRequested && !entry.outcome) cancel.push(requestId);
145
+ }
146
+ return {
147
+ invocations,
148
+ cancel
149
+ };
150
+ };
151
+ const routes = {
152
+ "POST /registry": async (req, res) => {
153
+ const body = await readBody(req);
154
+ if (body?.protocol !== "xplat-dev-actions" || typeof body.appInstanceId !== "string" || typeof body.revision !== "number" || !Array.isArray(body.actions)) return json(res, 400, { error: {
155
+ code: "invalid_selection",
156
+ message: "malformed registry announcement"
157
+ } });
158
+ clearTimeout(instances.get(body.appInstanceId)?.timer);
159
+ const instance = {
160
+ announcement: body,
161
+ at: Date.now()
162
+ };
163
+ instances.set(body.appInstanceId, instance);
164
+ instance.timer = setTimeout(() => expireInstance(body.appInstanceId, instance), INSTANCE_TTL_MS);
165
+ instance.timer.unref?.();
166
+ prune();
167
+ return json(res, 200, {
168
+ accepted: true,
169
+ serverId
170
+ });
171
+ },
172
+ "GET /registry": async (_req, res) => json(res, 200, {
173
+ serverId,
174
+ startedAt,
175
+ instances: freshInstances()
176
+ }),
177
+ "POST /invoke": async (req, res) => {
178
+ const body = await readBody(req);
179
+ const { requestId, appInstanceId, actionId, registryRevision } = body ?? {};
180
+ if (typeof requestId !== "string" || typeof appInstanceId !== "string" || typeof actionId !== "string") return json(res, 400, { error: {
181
+ code: "invalid_selection",
182
+ message: "malformed invocation request"
183
+ } });
184
+ if (requests.get(requestId)) return json(res, 200, {
185
+ accepted: true,
186
+ deduplicated: true,
187
+ requestId
188
+ });
189
+ if (!instances.has(appInstanceId)) return json(res, 404, { error: {
190
+ code: "not_found",
191
+ message: `app instance "${appInstanceId}" has not announced a registry`
192
+ } });
193
+ requests.set(requestId, {
194
+ request: {
195
+ requestId,
196
+ appInstanceId,
197
+ actionId,
198
+ registryRevision,
199
+ input: body.input ?? {}
200
+ },
201
+ state: "pending",
202
+ cancelRequested: false,
203
+ outcome: null,
204
+ createdAt: Date.now()
205
+ });
206
+ wakePollers(appInstanceId);
207
+ return json(res, 200, {
208
+ accepted: true,
209
+ requestId
210
+ });
211
+ },
212
+ "GET /poll": async (req, res, url) => {
213
+ const instanceId = url.searchParams.get("instance");
214
+ if (!instanceId || !instances.has(instanceId)) return json(res, 404, { error: {
215
+ code: "not_found",
216
+ message: "unknown app instance"
217
+ } });
218
+ const wait = Number(url.searchParams.get("wait") ?? 0);
219
+ let work = workFor(instanceId);
220
+ if (!work.invocations.length && !work.cancel.length && wait > 0) {
221
+ await awaitWork(instanceId, wait);
222
+ prune();
223
+ if (!instances.has(instanceId)) return json(res, 404, { error: {
224
+ code: "not_found",
225
+ message: "app instance expired"
226
+ } });
227
+ work = workFor(instanceId);
228
+ }
229
+ return json(res, 200, work);
230
+ },
231
+ "POST /result": async (req, res) => {
232
+ const body = await readBody(req);
233
+ if (typeof body?.requestId !== "string" || typeof body?.outcome?.status !== "string") return json(res, 400, { error: {
234
+ code: "invalid_selection",
235
+ message: "malformed invocation result"
236
+ } });
237
+ const entry = requests.get(body.requestId);
238
+ if (!entry) return json(res, 404, { error: {
239
+ code: "not_found",
240
+ message: `unknown request "${body.requestId}"`
241
+ } });
242
+ if (!entry.outcome) {
243
+ await resolveOutcomeFailures(body.outcome);
244
+ if (!entry.outcome) {
245
+ entry.outcome = body.outcome;
246
+ entry.completedAt = Date.now();
247
+ settleOutcome(body.requestId);
248
+ }
249
+ }
250
+ return json(res, 200, { accepted: true });
251
+ },
252
+ "POST /invoke/cancel": async (req, res) => {
253
+ const body = await readBody(req);
254
+ const entry = requests.get(body?.requestId);
255
+ if (!entry) return json(res, 404, { error: {
256
+ code: "not_found",
257
+ message: `unknown request "${body?.requestId}"`
258
+ } });
259
+ entry.cancelRequested = true;
260
+ wakePollers(entry.request.appInstanceId);
261
+ return json(res, 200, { accepted: true });
262
+ }
263
+ };
264
+ const middleware = async (req, res, next) => {
265
+ const url = new URL(req.url ?? "/", "http://localhost");
266
+ if (!url.pathname.startsWith(PREFIX)) return next();
267
+ if (!authorized(req)) return unauthorized(res);
268
+ try {
269
+ prune();
270
+ if (req.method === "POST" && url.pathname === `${PREFIX}/logs`) {
271
+ const body = await readBody(req);
272
+ const batch = formatBrowserLogBatch(body);
273
+ process.stderr.write(batch.text);
274
+ return json(res, 200, { accepted: batch.accepted });
275
+ }
276
+ const outcomeMatch = /^\/invoke\/([^/]+)$/.exec(url.pathname.slice(14));
277
+ if (req.method === "GET" && outcomeMatch) {
278
+ const requestId = outcomeMatch[1];
279
+ const entry = requests.get(requestId);
280
+ if (!entry) return json(res, 404, { error: {
281
+ code: "not_found",
282
+ message: `unknown request "${requestId}"`
283
+ } });
284
+ if (!entry.outcome) {
285
+ const wait = Number(url.searchParams.get("wait") ?? 0);
286
+ if (wait > 0) await awaitOutcome(requestId, wait);
287
+ }
288
+ return json(res, 200, {
289
+ requestId,
290
+ state: entry.outcome ? "completed" : entry.state,
291
+ outcome: entry.outcome ?? void 0
292
+ });
293
+ }
294
+ const handler = routes[`${req.method} ${url.pathname.slice(14)}`];
295
+ if (!handler) return json(res, 404, { error: {
296
+ code: "not_found",
297
+ message: "unknown bridge route"
298
+ } });
299
+ return await handler(req, res, url);
300
+ } catch (error) {
301
+ return json(res, 400, { error: {
302
+ code: "invalid_selection",
303
+ message: String(error?.message ?? error)
304
+ } });
305
+ }
306
+ };
307
+ return {
308
+ name: "xplat-dev-bridge",
309
+ apply: "serve",
310
+ transformIndexHtml() {
311
+ return [{
312
+ tag: "script",
313
+ attrs: { type: "module" },
314
+ children: browserLogScript(token, `${PREFIX}/logs`),
315
+ injectTo: "head-prepend"
316
+ }];
317
+ },
318
+ config() {
319
+ return { define: { __XPLAT_DEV_BRIDGE__: JSON.stringify({ token }) } };
320
+ },
321
+ configureServer(server) {
322
+ viteServer = server;
323
+ server.middlewares.use(middleware);
324
+ const writeSessionFile = () => {
325
+ const address = server.httpServer?.address();
326
+ if (!address || typeof address === "string") return;
327
+ const protocol = server.config.server.https ? "https" : "http";
328
+ const host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.address.includes(":") ? `[${address.address}]` : address.address;
329
+ const url = (server.resolvedUrls?.local?.[0] ?? `${protocol}://${host}:${address.port}`).replace(/\/$/, "");
330
+ const appRoot = options.appRoot ?? server.config.root;
331
+ const dir = join(appRoot, "node_modules", ".cache", "xplat", "dev-bridge");
332
+ try {
333
+ mkdirSync(dir, { recursive: true });
334
+ writeFileSync(join(dir, `${serverId}.json`), JSON.stringify({
335
+ serverId,
336
+ url,
337
+ token,
338
+ appRoot,
339
+ pid: process.pid,
340
+ startedAt
341
+ }));
342
+ } catch (error) {
343
+ console.warn(`[xplat] dev-bridge session file could not be written: ${error.message}`);
344
+ }
345
+ };
346
+ const removeSessionFile = () => {
347
+ const appRoot = options.appRoot ?? server.config.root;
348
+ try {
349
+ rmSync(join(appRoot, "node_modules", ".cache", "xplat", "dev-bridge", `${serverId}.json`), { force: true });
350
+ } catch {}
351
+ };
352
+ if (server.httpServer) {
353
+ if (server.httpServer.listening) writeSessionFile();
354
+ else server.httpServer.once("listening", writeSessionFile);
355
+ server.httpServer.on("close", removeSessionFile);
356
+ server.httpServer.on("close", () => {
357
+ for (const instance of instances.values()) clearTimeout(instance.timer);
358
+ });
359
+ }
360
+ }
361
+ };
362
+ }
363
+ export { devBridge };