@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
package/dist/vite.js ADDED
@@ -0,0 +1,797 @@
1
+ import { installedPackageDir, installedPackageRoot } from "./package-root.js";
2
+ import { css, cssWrapperQuery } from "./css-platform.js";
3
+ import { devBridge } from "./mcp/dev-bridge.js";
4
+ import { nativeDevSocketPlugin } from "./mcp/dev-socket.js";
5
+ import { masonCorePackage, masonEngine } from "./mason-engine.js";
6
+ import { nativeUnicodeRegex } from "./native-regex.js";
7
+ import { resolveTsrxLeaf } from "./tsrx-leaf.js";
8
+ import { transformTsconfig } from "./tsconfig-pin.js";
9
+ import { buildTarget, invocationTarget } from "./vite-target.js";
10
+ import { serverBoundary } from "@octane-xplat/lib/server-boundary";
11
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
12
+ import { createRequire } from "node:module";
13
+ import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
14
+ import { pathToFileURL } from "node:url";
15
+ import postcss from "postcss";
16
+ import valueParser from "postcss-value-parser";
17
+ // ../cli/src/vite.ts
18
+ function linkedTransformConfigs(root) {
19
+ while (!existsSync(join(root, "package.json"))) {
20
+ const parent = dirname(root);
21
+ if (parent === root) return [];
22
+ root = parent;
23
+ }
24
+ const configs = [];
25
+ const visited = /* @__PURE__ */ new Set([realpathSync(root)]);
26
+ const visit = (dir, entry = false) => {
27
+ const { dependencies, optionalDependencies, peerDependencies, devDependencies } = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
28
+ const names = Object.keys({
29
+ ...dependencies,
30
+ ...optionalDependencies,
31
+ ...peerDependencies,
32
+ ...entry ? devDependencies : {}
33
+ });
34
+ for (const name of names) {
35
+ const linked = installedPackageRoot(dir, name);
36
+ if (!linked || visited.has(linked) || linked.replaceAll("\\", "/").includes("/node_modules/")) continue;
37
+ visited.add(linked);
38
+ if (existsSync(join(linked, "tsconfig.json")) && transformTsconfig(linked)) configs.push(linked);
39
+ visit(linked);
40
+ }
41
+ };
42
+ visit(root, true);
43
+ return configs;
44
+ }
45
+ /** Select platform TSRX implementations in custom Vite and Vitest setups. */
46
+ function tsrx(platform = "native") {
47
+ let linkedFallback;
48
+ return {
49
+ name: "xplat-tsrx-resolution",
50
+ enforce: "post",
51
+ async config(config) {
52
+ linkedFallback = void 0;
53
+ if (config.tsconfig !== void 0) return;
54
+ const root = resolve(config.root ?? config.test?.root ?? process.cwd());
55
+ const tsconfig = transformTsconfig(root);
56
+ if (tsconfig) return { tsconfig };
57
+ if (config.oxc === false) return;
58
+ const linked = linkedTransformConfigs(root);
59
+ if (!linked.length) return;
60
+ const { createFilter, transformWithOxc } = await importApp("vite", [root, process.cwd()]);
61
+ const { include, exclude, jsxRefreshInclude, jsxRefreshExclude } = config.oxc ?? {};
62
+ const defaultExclude = exclude ?? /\.js$/;
63
+ const source = createFilter(include ?? /\.(m?ts|[jt]sx)$/, defaultExclude, { resolve: root });
64
+ const refresh = createFilter(jsxRefreshInclude, jsxRefreshExclude, { resolve: root });
65
+ const linkedPaths = linked.map((dir) => dir.replaceAll("\\", "/").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
66
+ const linkedSource = new RegExp(`^(?:${linkedPaths.join("|")})/(?!node_modules/|.*/node_modules/).+`);
67
+ const hasRefreshFilter = Boolean(jsxRefreshInclude || jsxRefreshExclude);
68
+ linkedFallback = {
69
+ source,
70
+ refresh,
71
+ hasRefreshFilter,
72
+ linkedSource,
73
+ transformWithOxc
74
+ };
75
+ return { oxc: {
76
+ exclude: exclude === void 0 ? [defaultExclude, linkedSource] : [linkedSource],
77
+ ...hasRefreshFilter ? { jsxRefreshExclude: [linkedSource] } : {}
78
+ } };
79
+ },
80
+ configResolved(config) {
81
+ for (const environment of Object.values(config.environments)) {
82
+ const options = environment.optimizeDeps.rolldownOptions ??= {};
83
+ const resolve = options.resolve ??= {};
84
+ resolve.extensions ??= [...environment.resolve.extensions];
85
+ }
86
+ },
87
+ resolveId: {
88
+ order: "pre",
89
+ handler(source, importer) {
90
+ return resolveTsrxLeaf(source, importer, platform);
91
+ }
92
+ },
93
+ async transform(code, id) {
94
+ if (!linkedFallback?.linkedSource.test(id)) return;
95
+ const file = id.split("?", 1)[0];
96
+ const { oxc, build, consumer } = this.environment.config;
97
+ const lang = build.rolldownOptions?.moduleTypes?.[extname(file)];
98
+ const mappedTypeScript = lang === "ts" || lang === "tsx";
99
+ const refresh = linkedFallback.hasRefreshFilter && linkedFallback.refresh(id);
100
+ if (!(linkedFallback.source(id) || linkedFallback.source(file) || mappedTypeScript || refresh)) return;
101
+ if (oxc === false) return;
102
+ const { include: _include, exclude: _exclude, jsxInject, jsxRefreshInclude: _jsxRefreshInclude, jsxRefreshExclude: _jsxRefreshExclude, ...options } = oxc;
103
+ const tsconfig = transformTsconfig(dirname(file));
104
+ const jsx = options.jsx;
105
+ if (typeof jsx === "object" && jsx.refresh && (consumer === "server" || linkedFallback.hasRefreshFilter && !refresh || !file.endsWith("x") && !code.includes(`${jsx.importSource ?? "react"}/jsx-runtime`) && !code.includes(`${jsx.importSource ?? "react"}/jsx-dev-runtime`))) options.jsx = {
106
+ ...jsx,
107
+ refresh: false
108
+ };
109
+ const refreshLang = refresh && !/\.(?:m?js|jsx|tsx?)$/.test(file) ? "js" : void 0;
110
+ const result = await linkedFallback.transformWithOxc(code, id, {
111
+ ...options,
112
+ tsconfig,
113
+ lang: mappedTypeScript ? lang : refreshLang,
114
+ sourcemap: this.environment.mode !== "build" || !!build.sourcemap
115
+ });
116
+ for (const path of result.tsconfigFilePaths ?? []) this.addWatchFile(path);
117
+ for (const warning of result.warnings) this.warn(warning);
118
+ return {
119
+ code: jsxInject && /\.[jt]sx$/.test(file) ? `${jsxInject};${result.code}` : result.code,
120
+ map: result.map,
121
+ moduleType: "js"
122
+ };
123
+ }
124
+ };
125
+ }
126
+ var importApp = (spec, paths) => {
127
+ const req = createRequire(join(process.cwd(), "package.json"));
128
+ return import(pathToFileURL(realpathSync(req.resolve(spec, paths && { paths }))).href);
129
+ };
130
+ var NS_REALM = /* @__PURE__ */ new Set(["@nativescript/core", "@nativescript/vite"]);
131
+ /**
132
+ * Every installed package carrying a `nativescript` key in package.json,
133
+ * reachable from the app's dependency graph — the same BFS the `ns` CLI
134
+ * runs at `ns prepare` time (deps of deps, resolved from each package's
135
+ * real .pnpm dir, so plugin-bearing leaf packages like @octane-xplat/gif
136
+ * surface their native plugins here too). The app doesn't have to declare
137
+ * each plugin by hand.
138
+ */
139
+ var collectNsPluginDeps = (rootDir) => {
140
+ const out = /* @__PURE__ */ new Set();
141
+ const visited = /* @__PURE__ */ new Set();
142
+ const queue = [rootDir];
143
+ while (queue.length) {
144
+ const dir = queue.shift();
145
+ let pkg;
146
+ try {
147
+ pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
148
+ } catch {
149
+ continue;
150
+ }
151
+ for (const name of Object.keys(pkg.dependencies ?? {})) {
152
+ if (visited.has(name)) continue;
153
+ visited.add(name);
154
+ const depDir = installedPackageRoot(dir, name);
155
+ if (!depDir) continue;
156
+ if (JSON.parse(readFileSync(join(depDir, "package.json"), "utf8")).nativescript && !NS_REALM.has(name)) out.add(name);
157
+ queue.push(depDir);
158
+ }
159
+ }
160
+ return out;
161
+ };
162
+ /** CSS that NS parses but silently ignores or misreads — the app looks
163
+ * identical in source but diverges at runtime. Warned at build time so the
164
+ * divergence is loud instead of invisible. Each entry: pattern + the
165
+ * portable alternative. */
166
+ var CSS_DIVERGENCES = [
167
+ [/(?<![\w-])env\(\s*safe-area-inset-(?:top|right|bottom|left)\s*[,)]/i, "env(safe-area-inset-*) is unsupported on native and may contribute 0 — use useSafeAreaInsets() from @octane-xplat/ui with an inline style for native insets"],
168
+ [/margin-(?:left|right|top|bottom)\s*:\s*auto|margin\s*:[^;{}]*\bauto\b/, "auto margins are ignored on native — use justify-content, alignSelf, or a <Spacer/>"],
169
+ [/position\s*:\s*(fixed|sticky)\b/, "position: fixed/sticky does not exist on native — overlays go through Overlay/Modal services, not positioning"],
170
+ [/\bfloat\s*:/, "float is unsupported on native — use flex rows"],
171
+ [/\bbox-shadow\s*:/, "box-shadow renders on both platforms — on Mason elements the iOS shadow is a sibling layer that only re-syncs on layout, so animating the element's own transform (translateX/view.animate) leaves it behind; animate position or transform an ancestor instead"],
172
+ [/white-space\s*:\s*pre-wrap\b/, "Label rejects white-space:pre-wrap — \"wrap\" is the native wrap value (no space/newline preservation)"],
173
+ [/letter-spacing\s*:\s*[^;{}]*\d(?:px|dip|pt)\b/, "letter-spacing has no length units on native — Android reads the number as em (setLetterSpacing), iOS as pt; use em so all three agree"]
174
+ ];
175
+ /**
176
+ * Shared stylesheets are authored in web units and web semantics. For the
177
+ * native bundle this transform (a) rewrites `px` lengths to `dip` — NS CSS
178
+ * reads `px` as _device_ pixels, not dips (`width:88px` measures 29 dips on
179
+ * a 3x device); inline `style` props are already dips and untouched — and
180
+ * (b) warns once per file on declarations NS silently ignores, so the
181
+ * divergence is loud at build time.
182
+ */
183
+ function processNativeCss(code, id, warn, options = {}) {
184
+ const warned = options.warned ?? /* @__PURE__ */ new Set();
185
+ code = code.replace(/\/\*\s*xplat-web-only:start[\s\S]*?\*\/[\s\S]*?\/\*\s*xplat-web-only:end[\s\S]*?\*\//g, "");
186
+ const uncommented = code.replace(/\/\*[\s\S]*?\*\//g, "");
187
+ if (/@import\s+['"]/.test(uncommented) && !warned.has(id + "|@import")) {
188
+ warned.add(id + "|@import");
189
+ warn(`${id}: @import inlining bypasses the px→dip rewrite and the xplat-web-only strip — import css files as JS modules instead (import 'pkg/file.css')`);
190
+ }
191
+ const declarations = code.replace(/\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g, "");
192
+ for (const [re, unsupportedHint] of CSS_DIVERGENCES) {
193
+ const hint = options.masonSafeAreaEnvironment && String(unsupportedHint).startsWith("env(") ? "env(safe-area-inset-*) uses the owning window on Mason containers; native inset dispatch/layout is not yet device-qualified. Ordinary NativeScript controls still need useSafeAreaInsets() with inline styles" : unsupportedHint;
194
+ const key = id + "|" + hint;
195
+ if (re.test(declarations) && !warned.has(key)) {
196
+ warned.add(key);
197
+ warn(`${id}: ${hint}`);
198
+ }
199
+ }
200
+ code = code.replace(/(letter-spacing\s*:\s*-?\d+(?:\.\d+)?)em\b/g, "$1");
201
+ const stylesheet = postcss.parse(code, { from: id });
202
+ stylesheet.walkDecls((declaration) => {
203
+ const value = valueParser(declaration.value);
204
+ value.walk((node) => {
205
+ if (node.type === "function" && node.value.toLowerCase() === "url") return false;
206
+ if (node.type !== "word") return;
207
+ const dimension = valueParser.unit(node.value);
208
+ if (dimension && dimension.unit.toLowerCase() === "px") node.value = dimension.number + "dip";
209
+ });
210
+ declaration.value = value.toString();
211
+ });
212
+ return stylesheet.toString();
213
+ }
214
+ function pxToDip(options = {}) {
215
+ const warned = /* @__PURE__ */ new Set();
216
+ let isBuild = false;
217
+ const process = (code, id, warn) => processNativeCss(code, id, warn, {
218
+ ...options,
219
+ warned
220
+ });
221
+ return {
222
+ name: "xplat-native-css",
223
+ enforce: "pre",
224
+ configResolved(config) {
225
+ isBuild = config.command === "build";
226
+ },
227
+ transform(code, id) {
228
+ if (isBuild && id.split("?")[0].endsWith("virtual:bamboo.css")) return;
229
+ if (!id.split("?")[0].endsWith(".css")) return;
230
+ if (cssWrapperQuery.test(id)) return;
231
+ return process(code, id, (m) => this.warn(m));
232
+ },
233
+ generateBundle(_opts, bundle) {
234
+ for (const file of Object.values(bundle)) if (file.type === "asset" && file.fileName.endsWith(".css")) {
235
+ const src = typeof file.source === "string" ? file.source : new TextDecoder().decode(file.source);
236
+ file.source = process(src, file.fileName, (m) => this.warn(m));
237
+ }
238
+ }
239
+ };
240
+ }
241
+ /** Vite merges `resolve.extensions` by concat, and the ns base config lands a
242
+ * generic list (`.tsx,.jsx,.ts,.js,…`) before ours — first-match resolution
243
+ * then prefers `svg.ts` over `svg.mobile.ts`, and `registerElement`-style
244
+ * side effects in platform leaves never load. Splice the platform chain to
245
+ * the front after every merge has run. */
246
+ function nativeExtensionOrder() {
247
+ return {
248
+ name: "xplat-native-extension-order",
249
+ configResolved(config) {
250
+ const ours = new Set(nativePlatformExtensions());
251
+ const rest = (config.resolve?.extensions ?? []).filter((ext) => !ours.has(ext));
252
+ config.resolve = {
253
+ ...config.resolve,
254
+ extensions: [...ours, ...rest]
255
+ };
256
+ }
257
+ };
258
+ }
259
+ /** The ns platform resolver and Vite's extension fallback know nothing of the
260
+ * `.mobile` tier — upstream platform lists only carry `.ios`/`.android`. An
261
+ * unsuffixed relative import (`./svg`) therefore lands on the shared default
262
+ * (`svg.ts`) in dev while builds pick `svg.mobile.ts` — silently skipping
263
+ * `registerElement`-style side effects. Probe the platform chain for every
264
+ * relative specifier before the generic resolvers run.
265
+ *
266
+ * An explicit unsuffixed specifier is still the authored contract, not a
267
+ * literal file: `./Pressable.tsrx` must select `Pressable.<platform>.tsrx`
268
+ * exactly as the extensionless `./Pressable` does. Vite resolves an
269
+ * extensioned specifier literally, so strip the authored script extension
270
+ * and probe the chain on the stem. A platform-tagged request
271
+ * (`./foo.ios.tsrx`) names its leaf and resolves literally. */
272
+ function nativeRelativeResolution() {
273
+ const exts = nativePlatformExtensions();
274
+ return {
275
+ name: "xplat-native-relative-resolution",
276
+ resolveId: {
277
+ order: "pre",
278
+ handler(source, importer) {
279
+ if (!importer || !source.startsWith("./") && !source.startsWith("../")) return null;
280
+ const importerFile = importer.split(/[?#]/, 1)[0].replace(/^\/@fs\//, "/");
281
+ const request = source.split(/[?#]/, 1)[0];
282
+ const base = resolve(dirname(importerFile), request);
283
+ const stem = PLATFORM_TAG.test(base) ? base : base.replace(/\.(tsrx|tsx|ts|mts|jsx|js|json)$/, "");
284
+ if (importerFile.replace(/\.(web|mobile|ios|android|macos|windows|linux|gtk)(\.[^./\\]+)$/, "$2") === base) return existsSync(base) ? base.replaceAll("\\", "/") : null;
285
+ for (const ext of exts) if (existsSync(stem + ext)) return (stem + ext).replaceAll("\\", "/");
286
+ return null;
287
+ }
288
+ }
289
+ };
290
+ }
291
+ /** `native()` sets `preserveSymlinks: false`, so Vite and our own resolvers
292
+ * speak a package's realpath — but @nativescript/vite 8.0.20's pre-enforced
293
+ * bare-package resolvers (`nativescript-package-resolver`,
294
+ * `ns-package-platform-resolver`) locate packages with
295
+ * `findPackageInNodeModules(name, projectRoot)` and never realpath the
296
+ * result. For an extensionless `main` ("index"), its platform-variant rewrite
297
+ * emits `<app>/node_modules/<pkg>/index.ios.js` — the symlink spelling under
298
+ * an isolated linker — while subpath imports of the same package resolve to
299
+ * the real store path. Rolldown keys modules by id, so one package evaluates
300
+ * twice; mason-core's `properties.js` registering `maskSize` on core's shared
301
+ * `Style` twice throws `Cannot redefine property` at app launch.
302
+ * Canonicalize every bare-specifier resolution to its realpath so all
303
+ * spellings agree. */
304
+ function nativeCanonicalPackageIds() {
305
+ return {
306
+ name: "xplat-native-canonical-package-ids",
307
+ resolveId: {
308
+ order: "pre",
309
+ async handler(source, importer, options) {
310
+ if (/^[./\0]/.test(source) || source.includes(":")) return null;
311
+ const resolved = await this.resolve(source, importer, {
312
+ ...options,
313
+ skipSelf: true
314
+ });
315
+ if (!resolved || resolved.external || !isAbsolute(resolved.id)) return resolved;
316
+ const suffixStart = resolved.id.search(/[?#]/);
317
+ const file = suffixStart < 0 ? resolved.id : resolved.id.slice(0, suffixStart);
318
+ const suffix = suffixStart < 0 ? "" : resolved.id.slice(suffixStart);
319
+ let real;
320
+ try {
321
+ real = realpathSync(file);
322
+ } catch {
323
+ return resolved;
324
+ }
325
+ real = real.replaceAll("\\", "/");
326
+ return real === file ? resolved : {
327
+ ...resolved,
328
+ id: real + suffix
329
+ };
330
+ }
331
+ }
332
+ };
333
+ }
334
+ function nativeCoreHttpAliases(appRequire) {
335
+ try {
336
+ const coreRequire = createRequire(realpathSync(appRequire.resolve("@nativescript/core/package.json")));
337
+ return [{
338
+ find: /^\/node_modules\/source-map-js(?=\/|$)/,
339
+ replacement: dirname(coreRequire.resolve("source-map-js/package.json"))
340
+ }];
341
+ } catch (error) {
342
+ if (error?.code === "MODULE_NOT_FOUND") return [];
343
+ throw error;
344
+ }
345
+ }
346
+ /**
347
+ * On-device HMR needs the app's websocket client to attach to /ns-hmr after
348
+ * the HTTP boot. When it never does — the websockets polyfill missing from
349
+ * the bundle, `adb reverse` not covering the vite port, or a boot error
350
+ * before the client import — every save logs `recipients=0` and the device
351
+ * silently stays stale. Warn once when a dev session was fetched but no
352
+ * client ever attached.
353
+ */
354
+ function nsHmrClientWatchdog() {
355
+ return {
356
+ name: "xplat-ns-hmr-client-watchdog",
357
+ configureServer(server) {
358
+ let everConnected = false;
359
+ let timer;
360
+ server.httpServer?.on("request", (req) => {
361
+ if (!everConnected && req.url?.startsWith("/__ns_dev__/session")) {
362
+ clearTimeout(timer);
363
+ timer = setTimeout(() => {
364
+ if (!everConnected) console.warn("[xplat] the app fetched its dev session but no /ns-hmr websocket client connected — edits will not reach the device. Check that @valor/nativescript-websockets is installed, `adb reverse tcp:<port>` covers this vite port (physical Android), and the device log for hmr-client errors.");
365
+ }, 15e3);
366
+ }
367
+ });
368
+ server.httpServer?.on("upgrade", (req) => {
369
+ if (req.url?.startsWith("/ns-hmr")) {
370
+ everConnected = true;
371
+ clearTimeout(timer);
372
+ }
373
+ });
374
+ }
375
+ };
376
+ }
377
+ /** The full extension chain, most-specific first: .ios/.android → .mobile →
378
+ * the unsuffixed native default (windows joins per-platform at build time —
379
+ * its qualifier must never shadow `.mobile` on ios/android builds). NS's
380
+ * own file qualifiers (.land, .minWH600…) still apply to assets on top. */
381
+ var nativeExtensions = [
382
+ ".ios.tsrx",
383
+ ".android.tsrx",
384
+ ".mobile.tsrx",
385
+ ".tsrx",
386
+ ".ios.tsx",
387
+ ".android.tsx",
388
+ ".mobile.tsx",
389
+ ".tsx",
390
+ ".ios.ts",
391
+ ".android.ts",
392
+ ".mobile.ts",
393
+ ".ios.js",
394
+ ".android.js",
395
+ ".mobile.js",
396
+ ".ts",
397
+ ".mts",
398
+ ".ts",
399
+ ".jsx",
400
+ ".js",
401
+ ".json"
402
+ ];
403
+ /** The bundle platform the current invocation targets, read from XPLAT_TARGET,
404
+ * NATIVESCRIPT_BUNDLER_ENV or the ns/vite CLI args — undefined when the
405
+ * caller can't be identified (the generic native chain applies). */
406
+ function nativePlatform() {
407
+ const platform = invocationTarget();
408
+ if (platform === "web" || platform === "macos" || platform === "linux" || platform === "gtk") throw new Error(`The NativeScript preset cannot build target ${platform}`);
409
+ return platform;
410
+ }
411
+ function nativePlatformExtensions() {
412
+ const platform = nativePlatform();
413
+ if (platform !== "android" && platform !== "ios" && platform !== "visionos" && platform !== "windows") return nativeExtensions;
414
+ const target = platform === "android" ? ".android" : platform === "windows" ? ".windows" : ".ios";
415
+ if (platform === "windows") return [
416
+ ".windows.tsrx",
417
+ ".tsrx",
418
+ ".windows.tsx",
419
+ ".tsx",
420
+ ".windows.ts",
421
+ ".ts",
422
+ ".windows.js",
423
+ ".ts",
424
+ ".mts",
425
+ ".jsx",
426
+ ".js",
427
+ ".json"
428
+ ];
429
+ return [
430
+ `${target}.tsrx`,
431
+ ".mobile.tsrx",
432
+ ".tsrx",
433
+ `${target}.tsx`,
434
+ ".mobile.tsx",
435
+ ".tsx",
436
+ `${target}.ts`,
437
+ ".mobile.ts",
438
+ ".ts",
439
+ `${target}.js`,
440
+ ".mobile.js",
441
+ ".ts",
442
+ ".mts",
443
+ ".jsx",
444
+ ".js",
445
+ ".json"
446
+ ];
447
+ }
448
+ /** Platform suffixes a module filename can carry. Unsuffixed modules are the
449
+ * native default — legal in every bundle; only a tag foreign to the target
450
+ * is a leak. */
451
+ var PLATFORM_TAG = /\.(web|mobile|ios|android|macos|windows|linux|gtk)\.[^./\\]+$/;
452
+ var boundaryAllowed = {
453
+ web: /* @__PURE__ */ new Set(["web"]),
454
+ ios: /* @__PURE__ */ new Set([
455
+ "ios",
456
+ "android",
457
+ "mobile"
458
+ ]),
459
+ visionos: /* @__PURE__ */ new Set([
460
+ "ios",
461
+ "android",
462
+ "mobile"
463
+ ]),
464
+ android: /* @__PURE__ */ new Set([
465
+ "ios",
466
+ "android",
467
+ "mobile"
468
+ ]),
469
+ macos: /* @__PURE__ */ new Set(["macos"]),
470
+ windows: /* @__PURE__ */ new Set(["windows"]),
471
+ linux: /* @__PURE__ */ new Set(["linux", "web"]),
472
+ gtk: /* @__PURE__ */ new Set(["gtk"]),
473
+ native: /* @__PURE__ */ new Set([
474
+ "ios",
475
+ "android",
476
+ "mobile",
477
+ "windows"
478
+ ])
479
+ };
480
+ function platformTag(id) {
481
+ const file = id.split(/[?#]/, 1)[0];
482
+ return PLATFORM_TAG.exec(file)?.[1];
483
+ }
484
+ var mergeConfigFragments = (...fragments) => {
485
+ const out = {};
486
+ for (const fragment of fragments) for (const [key, value] of Object.entries(fragment ?? {})) out[key] = typeof out[key] === "object" && out[key] !== null && !Array.isArray(out[key]) && typeof value === "object" && value !== null && !Array.isArray(value) ? mergeConfigFragments(out[key], value) : value;
487
+ return out;
488
+ };
489
+ /** Build-time enforcement of the platform-suffix boundary (invariant #1) —
490
+ * the lint rules catch direct imports, this catches transitive leakage:
491
+ * a `foo.web.tsrx` module reachable in a mobile bundle means the resolver
492
+ * picked a browser leaf into a native graph. Fails `vite build` with the
493
+ * import chain; warns once per module in dev.
494
+ *
495
+ * `platform` names the bundle target — 'web' | 'ios' | 'android' |
496
+ * 'macos' | 'windows' | 'linux' | 'native' (generic: any native tag ok). */
497
+ function boundary(platform = buildTarget(), reusedFiles = /* @__PURE__ */ new Set()) {
498
+ const resolver = tsrx(platform);
499
+ const base = serverBoundary();
500
+ const allowed = boundaryAllowed[platform] ?? boundaryAllowed.native;
501
+ let command = "build";
502
+ let root = "";
503
+ const warned = /* @__PURE__ */ new Set();
504
+ const foreign = /* @__PURE__ */ new Set();
505
+ const chainFor = (getModuleInfo, id) => {
506
+ const chain = [];
507
+ let cur = id;
508
+ const seen = /* @__PURE__ */ new Set();
509
+ while (cur && !seen.has(cur)) {
510
+ seen.add(cur);
511
+ const info = getModuleInfo(cur);
512
+ const next = [...info?.importers ?? [], ...info?.dynamicImporters ?? []][0];
513
+ if (!next) break;
514
+ chain.push(next);
515
+ cur = next;
516
+ }
517
+ return chain;
518
+ };
519
+ return {
520
+ ...base,
521
+ ...resolver,
522
+ name: "xplat-platform-boundary",
523
+ async config(userConfig, env) {
524
+ return mergeConfigFragments(base.config?.(userConfig, env), await resolver.config?.(userConfig, env));
525
+ },
526
+ async transform(code, id, options) {
527
+ const transformed = await resolver.transform.call(this, code, id);
528
+ const checked = await base.transform.call(this, transformed?.code ?? code, id, options);
529
+ return checked ? {
530
+ ...transformed,
531
+ ...checked
532
+ } : transformed;
533
+ },
534
+ configResolved(config) {
535
+ resolver.configResolved(config);
536
+ command = config.command;
537
+ root = config.root;
538
+ },
539
+ moduleParsed(info) {
540
+ const tag = platformTag(info.id);
541
+ if (!tag || allowed.has(tag) || reusedFiles.has(info.id)) return;
542
+ if (command === "serve") {
543
+ if (!warned.has(info.id)) {
544
+ warned.add(info.id);
545
+ const infoOf = typeof this.getModuleInfo === "function" ? (i) => this.getModuleInfo(i) : () => void 0;
546
+ this.warn(`xplat boundary — .${tag} module in a ${platform} graph: ${relative(root, info.id)} (importers: ${chainFor(infoOf, info.id).map((i) => relative(root, i)).join(" → ") || "unknown"})`);
547
+ }
548
+ return;
549
+ }
550
+ foreign.add(info.id);
551
+ },
552
+ buildEnd() {
553
+ for (const id of foreign) {
554
+ const tag = platformTag(id);
555
+ const infoOf = typeof this.getModuleInfo === "function" ? (i) => this.getModuleInfo(i) : () => void 0;
556
+ const chain = chainFor(infoOf, id);
557
+ this.error(`xplat boundary — a .${tag} module is reachable in the ${platform} bundle:\n foreign: ${relative(root, id)}\n chain: ${[...chain.reverse(), id].map((i) => relative(root, i)).join(" → ") || relative(root, id)}\n Platform-suffixed leaves resolve per-target; a foreign tag here means a\n shared module imported a platform file directly — split it behind the\n suffix seam (a .${tag} import must sit in a .${tag} importer's subtree).`);
558
+ }
559
+ }
560
+ };
561
+ }
562
+ /** Every Octane source module in the native graph, including installed
563
+ * packages, compiles under the nativescript renderer.
564
+ * `.web.*` leaves legitimately use DOM globals; they're
565
+ * unreachable from the native entry but must not fail validation, so each
566
+ * rule excludes them. */
567
+ var nativeRules = [{
568
+ include: "**/*.{ts,tsx,tsrx}",
569
+ exclude: "**/*.web.*",
570
+ renderer: "nativescript"
571
+ }];
572
+ /**
573
+ * Linked dependencies can realpath outside the app root even when install
574
+ * hooks leave registry specs in package.json. Vite gates
575
+ * `?inline`/`?raw`/`?url`/`?direct` transforms on `server.fs.allow`
576
+ * (`isServerAccessDeniedForTransform`), and the dev server's `/ns/m` css
577
+ * route compiles shared stylesheets through `?inline` — so a linked
578
+ * framework checkout's css (e.g. @octane-xplat/ui theme tokens) gets
579
+ * ERR_DENIED_ID and the DOM css module is served in its place, which
580
+ * crashes the device on `__vite__updateStyle`. Allow each linked dep's
581
+ * workspace root so content transforms can read it.
582
+ */
583
+ var linkedDepFsRoots = (projectRoot, searchForWorkspaceRoot) => {
584
+ let pkg;
585
+ try {
586
+ pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
587
+ } catch {
588
+ return [];
589
+ }
590
+ const roots = /* @__PURE__ */ new Set();
591
+ for (const section of [
592
+ "dependencies",
593
+ "devDependencies",
594
+ "optionalDependencies",
595
+ "peerDependencies"
596
+ ]) for (const [name, spec] of Object.entries(pkg[section] ?? {})) {
597
+ try {
598
+ const depDir = realpathSync(installedPackageDir(projectRoot, name));
599
+ const rel = relative(realpathSync(projectRoot), depDir).replaceAll("\\", "/");
600
+ if ((rel === ".." || rel.startsWith("../")) && !depDir.replaceAll("\\", "/").includes("/node_modules/") && statSync(depDir).isDirectory()) roots.add(searchForWorkspaceRoot(depDir));
601
+ } catch {}
602
+ const linkTarget = /^(?:link|file|portal):(.+)$/.exec(spec)?.[1];
603
+ if (!linkTarget) continue;
604
+ try {
605
+ const depDir = realpathSync(resolve(projectRoot, linkTarget));
606
+ if (statSync(depDir).isDirectory()) roots.add(searchForWorkspaceRoot(depDir));
607
+ } catch {}
608
+ }
609
+ return [...roots];
610
+ };
611
+ /** Dependencies with subpath-only exports cannot supply the vendor bundle's
612
+ * bare root import. Source-only entries are handled by @nativescript/vite
613
+ * 8.0.20 (NativeScript#11560); retain only this separate rootless case. */
614
+ var sourceOnlyDeps = (projectRoot) => {
615
+ let pkg;
616
+ try {
617
+ pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
618
+ } catch {
619
+ return [];
620
+ }
621
+ const names = /* @__PURE__ */ new Set();
622
+ for (const section of ["dependencies", "optionalDependencies"]) for (const name of Object.keys(pkg[section] ?? {})) try {
623
+ const depRoot = installedPackageRoot(projectRoot, name);
624
+ if (!depRoot) continue;
625
+ const exportsField = JSON.parse(readFileSync(join(depRoot, "package.json"), "utf8")).exports;
626
+ if (exportsField && typeof exportsField === "object" && !("." in exportsField) && Object.keys(exportsField).some((key) => key.startsWith("."))) names.add(name);
627
+ } catch {}
628
+ return [...names].sort();
629
+ };
630
+ /** Flags the NativeScript CLI hands the bundler through
631
+ * NATIVESCRIPT_BUNDLER_ENV (`--env.<name>` on `ns run`/`ns test`). */
632
+ function bundlerEnvFlags() {
633
+ try {
634
+ return JSON.parse(process.env.NATIVESCRIPT_BUNDLER_ENV ?? "{}");
635
+ } catch {
636
+ return {};
637
+ }
638
+ }
639
+ /** `--env.unitTesting` overlay — the vite counterpart of the upstream
640
+ * runner's webpack helper (@nativescript/unit-test-runner's
641
+ * nativescript.webpack.js, which only webpack auto-discovers). It does
642
+ * three things:
643
+ *
644
+ * - Swaps the bundle entry: virtual:entry-with-polyfills' import of the
645
+ * package `main` is redirected to the sibling `test.ts`/`test.js`, so the
646
+ * device boots the coordinator + host page instead of the app.
647
+ * - Aliases bare `vitest` spec imports to the runner's device-safe shim
648
+ * (@vitest/runner + @vitest/expect) — the full vitest package is
649
+ * Node-only and cannot load in the app runtime.
650
+ * - Defines `__NS_TEST_CONFIG__` so the coordinator can read the runner
651
+ * port (`--env.testRunnerPort`) without a network handshake.
652
+ */
653
+ function unitTestingOverlay(projectRoot, appRequire, env) {
654
+ const pkg = JSON.parse(readFileSync(join(projectRoot, "package.json"), "utf8"));
655
+ const mainEntry = resolve(projectRoot, pkg.main ?? "src/index.ts");
656
+ const entryDir = dirname(mainEntry);
657
+ const testEntry = ["test.ts", "test.js"].map((name) => join(entryDir, name)).find((path) => existsSync(path));
658
+ if (!testEntry) throw new Error(`--env.unitTesting requires a test entry (${join(entryDir, "test.ts")}) — create one with \`ns test init --framework vitest\`.`);
659
+ let shimPath;
660
+ try {
661
+ shimPath = realpathSync(appRequire.resolve("@nativescript/unit-test-runner/runtime/shim"));
662
+ } catch {
663
+ throw new Error("--env.unitTesting requires @nativescript/unit-test-runner as a devDependency of the app (the vitest specifier in specs resolves to its device shim).");
664
+ }
665
+ const mainSpecifier = "/" + relative(projectRoot, mainEntry).replaceAll("\\", "/");
666
+ const port = Number(env.testRunnerPort);
667
+ return {
668
+ define: { __NS_TEST_CONFIG__: JSON.stringify({ port: Number.isInteger(port) ? port : void 0 }) },
669
+ resolve: {
670
+ dedupe: ["@nativescript/unit-test-runner"],
671
+ alias: [{
672
+ find: /^vitest$/,
673
+ replacement: shimPath
674
+ }]
675
+ },
676
+ plugins: [{
677
+ name: "xplat-ns-unit-test-entry",
678
+ enforce: "pre",
679
+ resolveId(source, importer) {
680
+ if (importer?.includes("virtual:entry-with-polyfills") && source === mainSpecifier) return testEntry;
681
+ return null;
682
+ }
683
+ }]
684
+ };
685
+ }
686
+ /** `define` for the `process.env.NODE_ENV` npm convention — upstream octane
687
+ * packages (and much of the ecosystem) read it bare and assume the consumer
688
+ * bundler statically rewrites the member expression. The NativeScript
689
+ * runtime has no `process` global, so an unrewritten read throws at module
690
+ * eval; vite's define substitution is what makes the convention work.
691
+ *
692
+ * Scope: only the literal `process.env.NODE_ENV` expression is rewritten —
693
+ * `process.env.FOO`, `process.platform`, and whole-object `process` reads
694
+ * still crash on native. The NS dev server's per-module `globalThis.process`
695
+ * shim picks the value up too (it captures `process.env.*` define entries
696
+ * from the resolved config). */
697
+ var nodeEnvDefine = (mode) => ({ "process.env.NODE_ENV": JSON.stringify(mode === "production" ? "production" : "development") });
698
+ /**
699
+ * Native (iOS/Android) Vite config. `env` is defineConfig's { mode }; `extra`
700
+ * is merged in last for app-specific additions (own plugins, extra
701
+ * optimizeDeps, server options).
702
+ *
703
+ * opts:
704
+ * - deps: extra optimizeDeps.exclude entries — nativescript-keyed deps are
705
+ * already collected automatically; use this for anything else that must
706
+ * stay per-module in dev (e.g. a plugin missed by the scan)
707
+ * - rules: renderer rules override (defaults cover src + packages source)
708
+ */
709
+ async function native(env, opts = {}) {
710
+ const mode = typeof env === "string" ? env : env.mode;
711
+ const pkg = JSON.parse(readFileSync(join(process.cwd(), "package.json"), "utf8"));
712
+ const declared = Object.assign({}, pkg.dependencies, pkg.devDependencies, pkg.optionalDependencies, pkg.peerDependencies);
713
+ const platform = nativePlatform();
714
+ const windowsTarget = pkg.xplat?.targets?.windows;
715
+ const toolchain = windowsTarget?.toolchain;
716
+ const separateWindows = typeof toolchain === "string" && toolchain.trim() !== "";
717
+ const engine = masonEngine(declared, platform === "windows" || platform == null && Boolean(windowsTarget && !separateWindows || declared["@nativescript/windows"]));
718
+ if (engine === "@octane-xplat/nativescript-mason-core" && !declared["@octane-xplat/nativescript-mason-core"]) throw new Error(`${masonCorePackage} is required for iOS/Android container layout; run xplat upgrade to add it.`);
719
+ const vendorExcludes = [.../* @__PURE__ */ new Set([...(process.env.NS_VENDOR_EXCLUDE ?? "").split(",").map((entry) => entry.trim()).filter(Boolean), ...sourceOnlyDeps(process.cwd())])];
720
+ if (vendorExcludes.length > 0) process.env.NS_VENDOR_EXCLUDE = vendorExcludes.join(",");
721
+ const appRequire = createRequire(join(process.cwd(), "package.json"));
722
+ const [{ mergeConfig, searchForWorkspaceRoot }, { octaneConfig }, { nativeScriptRenderer }] = await Promise.all([
723
+ importApp("vite"),
724
+ importApp("@octane-xplat/vite-octane"),
725
+ importApp("@octane-xplat/nativescript-octane/config")
726
+ ]);
727
+ const config = mergeConfig(octaneConfig({ mode }, { octane: { renderers: {
728
+ registry: { nativescript: {
729
+ ...nativeScriptRenderer,
730
+ intrinsics: "@octane-xplat/jsx"
731
+ } },
732
+ rules: opts.rules ?? nativeRules
733
+ } } }), {
734
+ define: {
735
+ ...nodeEnvDefine(process.env.DEBUG ? "development" : mode),
736
+ __WINDOWS__: JSON.stringify(nativePlatform() === "windows")
737
+ },
738
+ oxc: { decorator: { legacy: true } },
739
+ plugins: [
740
+ nativeUnicodeRegex(),
741
+ css(nativePlatform() ?? "native"),
742
+ pxToDip({ masonSafeAreaEnvironment: engine === masonCorePackage }),
743
+ nsHmrClientWatchdog(),
744
+ boundary(nativePlatform() ?? "native"),
745
+ nativeExtensionOrder(),
746
+ nativeRelativeResolution(),
747
+ nativeCanonicalPackageIds(),
748
+ nativeDevSocketPlugin({ deviceRelay: true }) ?? devBridge()
749
+ ],
750
+ server: { fs: { allow: [...new Set([
751
+ searchForWorkspaceRoot(process.cwd()),
752
+ process.cwd(),
753
+ ...linkedDepFsRoots(process.cwd(), searchForWorkspaceRoot)
754
+ ].filter(Boolean))] } },
755
+ build: { rolldownOptions: {
756
+ moduleTypes: { ".tsrx": "tsx" },
757
+ output: { sourcemapExcludeSources: true }
758
+ } },
759
+ optimizeDeps: {
760
+ noDiscovery: true,
761
+ exclude: [...collectNsPluginDeps(process.cwd()), ...opts.deps ?? []]
762
+ },
763
+ resolve: {
764
+ conditions: nativePlatform() === "windows" ? ["windows", "native"] : ["native"],
765
+ dedupe: ["octane", "@octane-xplat/nativescript-octane"],
766
+ alias: [
767
+ {
768
+ find: /^octane$/,
769
+ replacement: "octane/universal/native"
770
+ },
771
+ ...nativeCoreHttpAliases(appRequire),
772
+ ...declared[engine] ? [{
773
+ find: /^@octane-xplat\/nativescript-masonkit(?=\/|$)/,
774
+ replacement: dirname(appRequire.resolve(`${engine}/package.json`))
775
+ }] : []
776
+ ],
777
+ preserveSymlinks: false,
778
+ extensions: nativePlatformExtensions()
779
+ }
780
+ });
781
+ const envFlags = bundlerEnvFlags();
782
+ if (envFlags.unitTesting) return mergeConfig(mergeConfig(config, unitTestingOverlay(process.cwd(), appRequire, envFlags)), opts.extra ?? {});
783
+ return mergeConfig(config, opts.extra ?? {});
784
+ }
785
+ /** @deprecated Use {@link css}. */
786
+ var xplatCss = css;
787
+ /** @deprecated Use {@link devBridge}. */
788
+ var xplatDevBridge = devBridge;
789
+ /** @deprecated Use {@link tsrx}. */
790
+ var xplatTsrx = tsrx;
791
+ /** @deprecated Use {@link boundary}. */
792
+ var xplatBoundary = boundary;
793
+ /** @deprecated Use {@link native}. */
794
+ var xplatNative = native;
795
+ /** @deprecated Use {@link nodeEnvDefine}. */
796
+ var xplatNodeEnvDefine = nodeEnvDefine;
797
+ export { boundary, buildTarget, css, devBridge, linkedDepFsRoots, native, nativeCanonicalPackageIds, nativeExtensions, nativeRelativeResolution, nodeEnvDefine, processNativeCss, pxToDip, sourceOnlyDeps, transformTsconfig, tsrx, xplatBoundary, xplatCss, xplatDevBridge, xplatNative, xplatNodeEnvDefine, xplatTsrx };