@pwaos.net/runtime-client-api 0.0.0-stage → 0.2.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 daqingzd@pwaos.net
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,138 @@
1
- # Temporary Holding Version
1
+ # @pwaos.net/runtime-client-api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **JavaScript wrapper for the PwaOS RuntimeClient API.**
4
+
5
+ Calls PwaOS Runtime features through a Node.js native addon and resolves the PwaOS
6
+ Runtime SDK distribution for your platform at install time. On load, it automatically
7
+ configures the dynamic-library search path, loads the native addon, and resolves the Runtime path.
8
+
9
+ ---
10
+
11
+ ## Installation
12
+
13
+ ```sh
14
+ npm install @pwaos.net/runtime-client-api
15
+ ```
16
+
17
+ This package automatically pulls in
18
+ [`@pwaos.net/runtime`](https://www.npmjs.com/package/@pwaos.net/runtime), which installs
19
+ the prebuilt Runtime SDK distribution for your platform. The native addon is built automatically
20
+ at install time (or loaded from prebuilt binaries). No manual download or compilation is required.
21
+
22
+ ## Platform Support
23
+
24
+ | OS | Architecture | Status |
25
+ | ------- | ----------------------------- | ------ |
26
+ | Linux | x64 | \u2705 |
27
+ | Windows | x64 (x86 runtime via WOW64) | \u2705 |
28
+
29
+ > Requires Node.js >= 18.
30
+
31
+ **Support:** For questions or to request the SDK for other platforms or CPU
32
+ architectures, please contact [daqingzd@pwaos.net](mailto:daqingzd@pwaos.net).
33
+
34
+ ## What loading the package does
35
+
36
+ `require('@pwaos.net/runtime-client-api')` returns the native addon object
37
+ itself and, at require time:
38
+
39
+ 1. **Sets up the dynamic-library search path** - the platform package's
40
+ `lib/<os>` directory is prepended to `LD_LIBRARY_PATH` (Linux) or
41
+ `PATH` (Windows), so `libpwaos_runtime_api.so` /
42
+ `pwaos_runtime_api.dll` resolves everywhere (and child processes
43
+ inherit it).
44
+ 2. **Loads the native addon** - compiled at install time by the
45
+ `install` script (`node-gyp rebuild`).
46
+ 3. **Calls `pwaos_setRuntimeExecutablePath`** - bound to the installed
47
+ platform package's runtime directory (also exported as
48
+ `process.env.PWAOS_RUNTIME_PATH`).
49
+
50
+ ## Usage
51
+
52
+ The module's export surface IS the addon - there is no additional JS
53
+ wrapper layer. Use the native API directly:
54
+
55
+ ```js
56
+ const pwaos = require('@pwaos.net/runtime-client-api');
57
+
58
+ // The runtime executable path is already set (see above). Init:
59
+ await pwaos.init();
60
+
61
+ // One instance per process:
62
+ const instance = pwaos.createInstance({
63
+ type: pwaos.PWAOS_TYPE_INSTANCE_CREATE_INFO,
64
+ runtimeType: pwaos.runtimeTypePwa,
65
+ serverUrl: 'http://localhost',
66
+ dataPath: '',
67
+ });
68
+
69
+ // Pump events until the instance is working, then open apps.
70
+ let ev;
71
+ while (!(ev = instance.pollEvent())
72
+ || ev.type !== pwaos.PWAOS_TYPE_EVENT_DATA_INSTANCE_STATUS_CHANGED
73
+ || ev.status !== pwaos.Instance.instanceStatusWorking) { /* ... */ }
74
+
75
+ const app = instance.createPwa({
76
+ type: pwaos.PWAOS_TYPE_PWA_CREATE_INFO,
77
+ appType: pwaos.App.appTypePwa,
78
+ appUrl: 'https://example.com',
79
+ width: 800,
80
+ height: 600,
81
+ });
82
+
83
+ // Exercise the App surface:
84
+ app.executeJavaScript('1+1');
85
+ app.setFPS(60);
86
+ app.setBounds({ type: pwaos.PWAOS_TYPE_WINDOW_BOUNDS_INFO,
87
+ x: 0, y: 0, width: 400, height: 300 });
88
+ console.log(app.getDensity(), app.getBounds());
89
+ ```
90
+
91
+ ## Documentation
92
+
93
+ For the full API reference, configuration options, event list, and
94
+ advanced usage, please visit
95
+ [https://www.pwaos.net/api/index.html](https://www.pwaos.net/api/index.html).
96
+
97
+ ## How Runtime Resolution Works
98
+
99
+ At require time the runtime directory is resolved in this order:
100
+
101
+ 1. The installed platform subpackage
102
+ `@pwaos.net/runtime-<platform>-<arch>/runtime` in `node_modules`
103
+ (primary; on win32-x64 the `win32-x86` package is a fallback via
104
+ WOW64).
105
+ 2. An upward `node_modules` walk from this module's directory, covering
106
+ non-standard layouts.
107
+
108
+ If neither succeeds, a clear error with installation instructions is
109
+ printed to stderr and the addon keeps its build-time default - you can
110
+ always bind a directory explicitly with
111
+ `pwaos.setRuntimeExecutablePath(dir)`.
112
+
113
+ The resolution does not rely on a postinstall script, so it also works
114
+ under `--ignore-scripts`. This is the same pattern used by packages such
115
+ as esbuild, Biome, and Sentry CLI.
116
+
117
+ ## Relationship to @pwaos.net/runtime
118
+
119
+ ```text
120
+ Your Node.js code
121
+ └─ require('@pwaos.net/runtime-client-api') ← returns the native addon
122
+ ├─ native addon: .node module (the export surface itself)
123
+ ├─ setup at require time:
124
+ │ dynamic-library search path + pwaos_setRuntimeExecutablePath
125
+ └─ resolved and loaded from
126
+ └─ @pwaos.net/runtime ← runtime distributor
127
+ └─ @pwaos.net/runtime-<platform>-<arch>
128
+ ├─ runtime/pwaos_server ← the actual executable
129
+ └─ lib/<os>/libpwaos_runtime_api.so ← linked at build
130
+ ```
131
+
132
+ You should not `require('@pwaos.net/runtime')` directly. It is an internal
133
+ dependency of `@pwaos.net/runtime-client-api` that distributes Runtime
134
+ binaries by platform.
135
+
136
+ ## License
137
+
138
+ MIT
package/binding.gyp ADDED
@@ -0,0 +1,83 @@
1
+ {
2
+ "targets": [
3
+ {
4
+ "target_name": "pwaos_addon",
5
+ # Sources live in this repo's src/ (upstream pwaos-node-addon C++
6
+ # client). Client-side build fixes live here in binding.gyp: the
7
+ # upstream sources use std::unique_ptr/make_unique without <memory>
8
+ # and are built with C++20 upstream, so the include/standard are
9
+ # forced below. The same relative paths work in the monorepo
10
+ # submodule checkout and in the published npm tarball.
11
+ "sources": [
12
+ "src/addon_main.cc",
13
+ "src/app_obj.cc",
14
+ "src/instance_obj.cc",
15
+ "src/interface_obj.cc"
16
+ ],
17
+ "include_dirs": [
18
+ "<!(node scripts/sdk-dir.cjs)/include",
19
+ "src"
20
+ ],
21
+ "defines": [
22
+ "NAPI_CPP_EXCEPTIONS"
23
+ ],
24
+ "conditions": [
25
+ # Link the SDK import library from the platform lib dir. Linux loads
26
+ # the .so via embedded rpath; Windows needs the DLL beside the addon,
27
+ # so the copies section drops it into build/Release.
28
+ ["OS=='linux'", {
29
+ "libraries": [
30
+ "-Wl,-rpath,<!(node scripts/sdk-dir.cjs)/lib/linux"
31
+ ],
32
+ "library_dirs": [
33
+ "<!(node scripts/sdk-dir.cjs)/lib/linux"
34
+ ],
35
+ "libraries!": [
36
+ "-ldl",
37
+ "-lpthread"
38
+ ],
39
+ "libraries+": [
40
+ "-lpwaos_runtime_api"
41
+ ],
42
+
43
+ "defines+": [
44
+ "LONGSTRINGS"
45
+ ],
46
+ # Upstream src/ (pwaos-node-addon#main) uses std::unique_ptr /
47
+ # std::make_unique in common.h macros without including <memory>,
48
+ # and is built with C++20 upstream. Force the include here so the
49
+ # client package compiles the untouched upstream sources.
50
+ "cflags_cc+": [
51
+ "-std=c++20",
52
+ "-include", "memory"
53
+ ]
54
+ }],
55
+ ["OS=='win'", {
56
+ "library_dirs": [
57
+ "<!(node scripts/sdk-dir.cjs)/lib/win"
58
+ ],
59
+ "libraries": [
60
+ "pwaos_runtime_api.lib"
61
+ ],
62
+ "defines+": [
63
+ "WIN32"
64
+ ],
65
+ "msvs_settings": {
66
+ "VCCLCompilerTool": {
67
+ "AdditionalOptions": ["/std:c++20"],
68
+ "ForcedIncludeFiles": ["memory"]
69
+ }
70
+ },
71
+ "copies": [
72
+ {
73
+ "destination": "<(PRODUCT_DIR)",
74
+ "files": [
75
+ "<!(node scripts/sdk-dir.cjs)/lib/win/pwaos_runtime_api.dll"
76
+ ]
77
+ }
78
+ ]
79
+ }]
80
+ ]
81
+ }
82
+ ]
83
+ }
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "@pwaos.net/runtime-client-api",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.2",
4
+ "type": "module",
5
+ "description": "Node.js native addon for the PwaOS RuntimeClient API. Automatically resolves the matching Runtime SDK for your platform.",
6
+ "engines": {
7
+ "node": ">=18"
8
+ },
9
+ "homepage": "https://www.pwaos.net/api",
10
+ "author": {
11
+ "name": "daqingzd",
12
+ "url": "https://github.com/daqingzd"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/daqingzd/pwaos-node-addon.git"
17
+ },
18
+ "license": "MIT",
19
+ "publishConfig": {
20
+ "registry": "https://registry.npmjs.org/",
21
+ "access": "public"
22
+ },
23
+ "files": [
24
+ "runtime.cjs",
25
+ "runtime.js",
26
+ "scripts",
27
+ "src",
28
+ "test",
29
+ "binding.gyp",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "main": "runtime.cjs",
34
+ "exports": {
35
+ ".": {
36
+ "import": "./runtime.js",
37
+ "require": "./runtime.cjs"
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "dependencies": {
42
+ "@pwaos.net/runtime": "0.2.2"
43
+ },
44
+ "devDependencies": {
45
+ "node-gyp": "^10.0.0"
46
+ },
47
+ "scripts": {
48
+ "install": "node-gyp rebuild",
49
+ "build": "node-gyp configure && node-gyp build",
50
+ "test": "node --test test/test.cjs",
51
+ "test:unit": "node --test test/test.cjs"
52
+ },
53
+ "bugs": {
54
+ "url": "https://github.com/daqingzd/pwaos-node-addon/issues"
55
+ },
56
+ "keywords": [
57
+ "pwaos",
58
+ "runtime",
59
+ "client",
60
+ "pwa",
61
+ "webview",
62
+ "webapp",
63
+ "webapplication",
64
+ "browser",
65
+ "napi"
66
+ ],
67
+ "os": [
68
+ "linux",
69
+ "win32"
70
+ ],
71
+ "cpu": [
72
+ "x64",
73
+ "ia32"
74
+ ],
75
+ "gypfile": true
76
+ }
package/runtime.cjs ADDED
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @pwaos.net/runtime-client-api - CommonJS entry (runtime.cjs).
5
+ *
6
+ * Setup-only entry. The ONLY export surface is the native addon itself:
7
+ * module.exports = addon. No extra classes or functions are exposed -
8
+ * consumers use the addon's native API directly
9
+ * (init / shutDown / createInstance / Instance / App / ...).
10
+ *
11
+ * On load this module performs the required setup, in order:
12
+ *
13
+ * 1. Sets up the dynamic-library search path (动态库搜索路径): the
14
+ * platform package's lib/<os> directory is prepended to
15
+ * LD_LIBRARY_PATH (Linux) / PATH (Windows) BEFORE the addon is
16
+ * required, so libpwaos_runtime_api.so / pwaos_runtime_api.dll
17
+ * resolves even where the addon's embedded rpath is not usable
18
+ * (and child processes inherit it).
19
+ *
20
+ * 2. Loads the native addon (built at install time by `install`:
21
+ * node-gyp rebuild).
22
+ *
23
+ * 3. Calls pwaos_setRuntimeExecutablePath with the resolved runtime
24
+ * directory - the installed platform package's runtime/ bundle
25
+ * (the directory containing pwaos_server). Consumers can still
26
+ * re-point it later via addon.setRuntimeExecutablePath(dir).
27
+ */
28
+
29
+ const fs = require('fs');
30
+ const path = require('path');
31
+
32
+ const { resolveRuntimePath, getPlatformPackageName } =
33
+ require('./scripts/runtime-resolver.cjs');
34
+
35
+ // --- 1. dynamic-library search path (must precede the addon require) ------
36
+ try {
37
+ const pkgJson = require.resolve(`${getPlatformPackageName()}/package.json`);
38
+ const libDir = process.platform === 'win32'
39
+ ? path.join(path.dirname(pkgJson), 'lib', 'win')
40
+ : path.join(path.dirname(pkgJson), 'lib', process.platform);
41
+ if (fs.existsSync(libDir)) {
42
+ if (process.platform === 'win32') {
43
+ process.env.PATH = `${libDir};${process.env.PATH}`;
44
+ } else {
45
+ process.env.LD_LIBRARY_PATH = process.env.LD_LIBRARY_PATH
46
+ ? `${libDir}:${process.env.LD_LIBRARY_PATH}`
47
+ : libDir;
48
+ }
49
+ }
50
+ } catch (_) {
51
+ // Platform package not installed - the addon falls back to its
52
+ // embedded rpath (set at build time by binding.gyp).
53
+ }
54
+
55
+ // --- 2. load the native addon ---------------------------------------------
56
+ const addon = require('./build/Release/pwaos_addon.node');
57
+
58
+ // --- 3. pwaos_setRuntimeExecutablePath -------------------------------------
59
+ try {
60
+ const runtimeDir = resolveRuntimePath();
61
+ process.env.PWAOS_RUNTIME_PATH = runtimeDir;
62
+ addon.setRuntimeExecutablePath(runtimeDir);
63
+ } catch (e) {
64
+ process.stderr.write(
65
+ '[pwaos.net/runtime-client-api] no runtime directory resolved: '
66
+ + e.message + '\n');
67
+ }
68
+
69
+ module.exports = addon;
package/runtime.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @pwaos.net/runtime-client-api - ESM entry (runtime.js).
3
+ *
4
+ * The setup flow (dynamic-library search path, addon load,
5
+ * pwaos_setRuntimeExecutablePath) lives in runtime.cjs - the default
6
+ * export IS the native addon object; access everything as properties of
7
+ * the default export (pwaos.init, pwaos.Instance, ...). No additional
8
+ * class or function is defined here.
9
+ *
10
+ * The .cjs module performs setup exactly once per process (Node caches
11
+ * module instances), so importing this file and requiring runtime.cjs in
12
+ * the same program share one addon instance.
13
+ */
14
+
15
+ import addon from './runtime.cjs';
16
+
17
+ export default addon;
@@ -0,0 +1,129 @@
1
+ 'use strict';
2
+ /**
3
+ * resolve-sdk.js - locate the pwaos SDK (headers + client lib) and the
4
+ * runtime bundle for this package.
5
+ *
6
+ * Shared by scripts/sdk-dir.js (build time) and test code. Sources, in order:
7
+ *
8
+ * 1. $PWAOS_SDK_DIR (an explicit SDK root, validated)
9
+ * 2. the installed @pwaos.net/runtime-<platform>-<arch> package
10
+ * (include/ + lib/<os>/ + runtime/ ship inside that package; this
11
+ * is what makes `npm install @pwaos.net/runtime` self-contained - the
12
+ * addon compiles against the shipped headers with no network)
13
+ *
14
+ * There is NO download/cache fallback: if the platform package is not
15
+ * installed, resolution fails. Platform payloads are produced by the
16
+ * monorepo's `npm run build -- runtime-<platform>` (scripts/
17
+ * build-platform-pkg.js), which always runs before the client in build
18
+ * order. In a consumer install npm places the platform package next to
19
+ * this one (optionalDependencies of @pwaos.net/runtime), so the require.resolve
20
+ * walk below finds it.
21
+ *
22
+ * Runtime validity: the runtime dir is the platform package's runtime/
23
+ * subdir and is only reported when runtime/pwaos_server exists and is NOT
24
+ * an un-smudged git-lfs pointer (starts with the LFS version url).
25
+ */
26
+
27
+ const fs = require('fs');
28
+ const path = require('path');
29
+
30
+ // Installed platform subpackage that carries the SDK consumer files
31
+ // (include/ + lib/<os>/). Written as a function so tests can stub it.
32
+ function platformPackageName() {
33
+ if (process.platform === 'linux') return '@pwaos.net/runtime-linux-x64';
34
+ if (process.platform === 'win32') return '@pwaos.net/runtime-win32-x86';
35
+ return null;
36
+ }
37
+
38
+ const HEADER_NAME = 'runtime_client_api.h';
39
+ const LIB_SRC = {
40
+ linux: 'lib/linux/libpwaos_runtime_api.so',
41
+ win: 'lib/win/pwaos_runtime_api.dll',
42
+ };
43
+ const SERVER_BASENAME = process.platform === 'win32'
44
+ ? 'pwaos_server.exe' : 'pwaos_server';
45
+ const LFS_POINTER_MAGIC = 'version https://git-lfs';
46
+
47
+ // Platform -> LIB_SRC key.
48
+ function sdkOs() {
49
+ if (process.platform === 'linux') return 'linux';
50
+ if (process.platform === 'win32') return 'win';
51
+ return null;
52
+ }
53
+
54
+ function dirHasSdkFiles(dir, osName) {
55
+ return (
56
+ fs.existsSync(path.join(dir, 'include', HEADER_NAME)) &&
57
+ fs.existsSync(path.join(dir, LIB_SRC[osName]))
58
+ );
59
+ }
60
+
61
+ /** True when the file exists but is an un-smudged git-lfs pointer. */
62
+ function isLfsPointer(file) {
63
+ try {
64
+ const st = fs.statSync(file);
65
+ if (st.size >= 512) return false; // pointers are ~130 bytes
66
+ const head = fs.readFileSync(file, 'utf8');
67
+ return head.startsWith(LFS_POINTER_MAGIC);
68
+ } catch (_) {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ /** The runtime subdir of an SDK dir, or null when it has no usable server. */
74
+ function runtimeDirOf(sdkDir) {
75
+ const rt = path.join(sdkDir, 'runtime');
76
+ const server = path.join(rt, SERVER_BASENAME);
77
+ try {
78
+ if (!fs.statSync(server).isFile()) return null;
79
+ } catch (_) {
80
+ return null;
81
+ }
82
+ if (isLfsPointer(server)) return null;
83
+ return rt;
84
+ }
85
+
86
+ /**
87
+ * The SDK root of the installed platform subpackage, or null.
88
+ * require.resolve is used from THIS file's directory so the same
89
+ * node_modules walk applies (the client's own node_modules or any
90
+ * ancestor's - matching how npm hoists optionalDependencies).
91
+ * On failure every error is swallowed: "not installed" is normal.
92
+ */
93
+ function installedSdkDir(osName) {
94
+ const pkg = platformPackageName();
95
+ if (!pkg) return null;
96
+ let pkgRoot;
97
+ try {
98
+ pkgRoot = path.dirname(require.resolve(`${pkg}/package.json`));
99
+ } catch (_) {
100
+ return null;
101
+ }
102
+ return dirHasSdkFiles(pkgRoot, osName) ? pkgRoot : null;
103
+ }
104
+
105
+ function resolveSdkDir(osName) {
106
+ const explicit = process.env.PWAOS_SDK_DIR;
107
+ if (explicit) {
108
+ return dirHasSdkFiles(explicit, osName) ? explicit : null;
109
+ }
110
+ // The installed platform subpackage: the single source of truth for
111
+ // include/, lib/<os>/ and runtime/.
112
+ return installedSdkDir(osName);
113
+ }
114
+
115
+ /** Resolve {sdkDir, runtimeDir} per the documented order; either may be null. */
116
+ function resolve() {
117
+ const osName = sdkOs();
118
+ if (!osName) return { sdkDir: null, runtimeDir: null };
119
+ const sdkDir = resolveSdkDir(osName);
120
+ return { sdkDir, runtimeDir: sdkDir ? runtimeDirOf(sdkDir) : null };
121
+ }
122
+
123
+ module.exports = {
124
+ resolve,
125
+ runtimeDirOf,
126
+ isLfsPointer,
127
+ installedSdkDir,
128
+ SERVER_BASENAME,
129
+ };
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @pwaos.net/runtime-client-api - Runtime directory resolution.
5
+ *
6
+ * Locates the PwaOS Runtime directory (the directory CONTAINING the
7
+ * pwaos_server executable plus its resources) in the following order:
8
+ *
9
+ * 1. An explicit `runtimePath` provided by the caller.
10
+ * 2. `@pwaos.net/runtime-<platform>-<arch>/runtime` inside node_modules
11
+ * (installed via @pwaos.net/runtime's optionalDependencies).
12
+ *
13
+ * The resolved path is what `pwaos_setRuntimeExecutablePath` expects: the
14
+ * runtime DIRECTORY itself, never the pwaos_server file - the client library
15
+ * appends /runtime internally and the server loads its resources relative to
16
+ * that directory.
17
+ *
18
+ * The resolution does not rely on a postinstall script, so it also works
19
+ * under `--ignore-scripts` - the same pattern used by packages such as
20
+ * esbuild, Biome, and Sentry CLI.
21
+ */
22
+
23
+ 'use strict';
24
+
25
+ const fs = require('fs');
26
+ const path = require('path');
27
+
28
+ const PACKAGE_PREFIX = '@pwaos.net/runtime-';
29
+
30
+ /**
31
+ * Platform subpackage candidates for the current process, in preference
32
+ * order. The primary candidate is the strictly-derived
33
+ * @pwaos.net/runtime-<platform>-<arch>; on win32 the only upstream runtime is
34
+ * 32-bit (x86), which also runs on 64-bit Windows (WOW64), so the x86
35
+ * package is a secondary candidate for x64 hosts.
36
+ */
37
+ function getPlatformPackageCandidates() {
38
+ const primary = `${PACKAGE_PREFIX}${process.platform}-${process.arch}`;
39
+ if (process.platform === 'win32' && process.arch === 'x64') {
40
+ return [primary, `${PACKAGE_PREFIX}win32-x86`];
41
+ }
42
+ return [primary];
43
+ }
44
+
45
+ /** Primary platform subpackage name, e.g. @pwaos.net/runtime-linux-x64. */
46
+ function getPlatformPackageName() {
47
+ return getPlatformPackageCandidates()[0];
48
+ }
49
+
50
+ /** Name of the server executable inside the runtime directory. */
51
+ function getBinaryName() {
52
+ return process.platform === 'win32' ? 'pwaos_server.exe' : 'pwaos_server';
53
+ }
54
+
55
+ /**
56
+ * Resolve the Runtime directory (the directory containing the pwaos_server
57
+ * executable and its resources).
58
+ *
59
+ * @param {object} [options]
60
+ * @param {string} [options.runtimePath] Explicit path to the Runtime directory.
61
+ * @returns {string} Absolute path to the Runtime directory.
62
+ * @throws {Error} When no usable Runtime directory can be found for this platform.
63
+ */
64
+ function resolveRuntimePath(options = {}) {
65
+ // 1. Explicit override.
66
+ if (options.runtimePath) {
67
+ if (fs.existsSync(options.runtimePath)) {
68
+ return path.resolve(options.runtimePath);
69
+ }
70
+ throw new Error(
71
+ `PwaOS Runtime not found at the provided runtimePath: ${options.runtimePath}\n` +
72
+ 'Check that the path points at the directory containing pwaos_server.'
73
+ );
74
+ }
75
+
76
+ // 2. Platform subpackage installed via @pwaos.net/runtime's optionalDependencies.
77
+ // Search upwards from this module's directory (standard node_modules
78
+ // walk) with plain fs, so a stale require cache cannot produce a
79
+ // false "installed but empty" result.
80
+ let installedWithoutRuntime = null;
81
+ for (const pkg of getPlatformPackageCandidates()) {
82
+ // Primary: standard node_modules resolution (handles symlinked/hoisted
83
+ // installs - e.g. a linked @pwaos.net/runtime whose own deps resolve inside
84
+ // the monorepo that provided the link).
85
+ try {
86
+ const pkgJsonPath = require.resolve(`${pkg}/package.json`);
87
+ const candidate = path.join(path.dirname(pkgJsonPath), 'runtime');
88
+ if (fs.existsSync(path.join(candidate, getBinaryName()))) {
89
+ return candidate;
90
+ }
91
+ // A platform package without its runtime bundle is corrupted; the
92
+ // @pwaos.net/runtime META package legitimately has no bundle (it only
93
+ // declares the platform subpackages) - keep searching.
94
+ if (pkg !== '@pwaos.net/runtime') {
95
+ installedWithoutRuntime = { pkg, pkgJsonPath };
96
+ break;
97
+ }
98
+ } catch (_) { /* not installed - try the fs walk */ }
99
+
100
+ // Backup: manual walk (covers non-standard layouts without require
101
+ // visibility, e.g. the runtime dir placed next to node_modules).
102
+ let dir = __dirname;
103
+ while (true) {
104
+ const candidate = path.join(dir, 'node_modules', pkg, 'runtime');
105
+ if (fs.existsSync(path.join(candidate, getBinaryName()))) {
106
+ return candidate;
107
+ }
108
+ const parent = path.dirname(dir);
109
+ if (parent === dir) break;
110
+ dir = parent;
111
+ }
112
+ }
113
+
114
+ if (installedWithoutRuntime) {
115
+ const { pkg, pkgJsonPath } = installedWithoutRuntime;
116
+ throw new Error(
117
+ `The platform package ${pkg} is installed but has no runtime directory ` +
118
+ `at ${path.join(path.dirname(pkgJsonPath), 'runtime')}.\n` +
119
+ `The package contents may be corrupted - try reinstalling: npm install ${pkg}`
120
+ );
121
+ }
122
+
123
+ // 3. Nothing found - explain how to fix it.
124
+ throw new Error(
125
+ `PwaOS Runtime not found for ${process.platform}-${process.arch}.\n\n` +
126
+ 'Try installing the Runtime distribution package first:\n' +
127
+ ' npm install @pwaos.net/runtime\n\n' +
128
+ 'If it still fails, check whether your platform is supported and whether\n' +
129
+ 'your package manager has disabled optionalDependencies\n' +
130
+ '(e.g. --no-optional or --omit=optional).'
131
+ );
132
+ }
133
+
134
+ module.exports = { resolveRuntimePath, getPlatformPackageName,
135
+ getPlatformPackageCandidates, getBinaryName };