@gjsify/node-gi 0.26.1 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,104 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // @gjsify/node-gi — WHERE the native addon lives. ONE definition, shared by the
3
+ // two decisions that must never disagree about it:
4
+ //
5
+ // 1. `index.js#loadNative()` — which binary a CONSUMER loads at runtime.
6
+ // 2. `scripts/install.mjs` — whether the `install` lifecycle script has to run
7
+ // a node-gyp source build at all.
8
+ //
9
+ // WHY THIS MODULE EXISTS: those two used to be one implementation and one
10
+ // hard-coded string in a different file. `prebuilds/<platform>-<arch>/node_gi.node`
11
+ // spelled twice is the setup for the two silent failures nobody sees in CI — a
12
+ // guard that skips the build because it looked in a directory the loader does not
13
+ // probe (install succeeds, the first `import` throws), or a guard that rebuilds on
14
+ // every install while a perfectly good prebuild sits right beside it (the defect
15
+ // the guard was added to remove). Sharing the probe makes both impossible by
16
+ // construction: the target-dir spelling, the addon filename and the candidate
17
+ // ORDER exist exactly once, here.
18
+ //
19
+ // NOT the same question as `resolveAddonPath()` in
20
+ // packages/infra/rolldown-plugin-gjsify (the `@gjsify/napi` bundler seam). That
21
+ // one replicates node-gyp-build's probe order for ARBITRARY third-party addons
22
+ // being bundled for `--app gjs`: `build/Release` → `build/Debug` → prebuild, with
23
+ // node-gyp-build's `<runtime>.<abi|napi>.node` tag grammar. node-gi's own default
24
+ // is deliberately the OPPOSITE way round (prebuild FIRST — see nativeCandidates
25
+ // below) and its artifact is a plain `node_gi.node`. Two different questions, two
26
+ // definitions; this file is the authority for node-gi's own binary, and the third
27
+ // copy is the one that must never be written.
28
+ import { fileURLToPath } from 'node:url';
29
+ import { dirname, join } from 'node:path';
30
+
31
+ /**
32
+ * The package root. This module sits beside `index.js`, so its own directory IS
33
+ * the root — the same anchor `index.js` used before the extraction.
34
+ */
35
+ export const packageRoot = dirname(fileURLToPath(import.meta.url));
36
+
37
+ /**
38
+ * The addon's file name, identical in `build/{Release,Debug}/` and in a staged
39
+ * `prebuilds/<target>/` (scripts/stage-prebuild.mjs copies it verbatim). NOT
40
+ * node-gyp-build's tag grammar — nothing in this package parses tags.
41
+ */
42
+ export const ADDON_FILENAME = 'node_gi.node';
43
+
44
+ /**
45
+ * The `<os>-<arch>` prebuild target spelling — `${process.platform}-${process.arch}`,
46
+ * the ONE spelling used across the whole workspace (see AGENTS.md § Runtime &
47
+ * platform model: it is what a running process computes about itself, so
48
+ * resolution needs no translation).
49
+ *
50
+ * A pure function of its arguments so the darwin/win32 branches of anything
51
+ * built on it stay testable from a Linux host; the host values are read only at
52
+ * the outermost call site, as defaults.
53
+ * @param {string} [platform] defaults to `process.platform`
54
+ * @param {string} [arch] defaults to `process.arch`
55
+ * @returns {string} e.g. `linux-x64`, `win32-x64`, `darwin-arm64`
56
+ */
57
+ export function hostTarget(platform = process.platform, arch = process.arch) {
58
+ return `${platform}-${arch}`;
59
+ }
60
+
61
+ /**
62
+ * Absolute path of the SHIPPED prebuild for a target. This is the path
63
+ * `scripts/stage-prebuild.mjs` writes, `files: ["prebuilds"]` publishes,
64
+ * `loadNative()` prefers, and `scripts/install.mjs` tests for.
65
+ * @param {string} [target] defaults to the running host's target
66
+ * @returns {string}
67
+ */
68
+ export function prebuildAddonPath(target = hostTarget()) {
69
+ return join(packageRoot, 'prebuilds', target, ADDON_FILENAME);
70
+ }
71
+
72
+ /**
73
+ * Absolute path of a LOCALLY BUILT addon — what `node-gyp rebuild` writes.
74
+ * @param {'Release' | 'Debug'} [flavor]
75
+ * @returns {string}
76
+ */
77
+ export function buildAddonPath(flavor = 'Release') {
78
+ return join(packageRoot, 'build', flavor, ADDON_FILENAME);
79
+ }
80
+
81
+ /**
82
+ * The ordered list of addon paths to try, most-preferred first.
83
+ *
84
+ * `NODE_GI_NATIVE` pins which binary loads. The package's own test scripts set
85
+ * `build` so local verification always exercises the JUST-BUILT addon — a stale
86
+ * staged prebuild would otherwise shadow build/Release and silently validate the
87
+ * wrong binary (the consumer-facing default below prefers the prebuild).
88
+ *
89
+ * Default order: prefer a shipped prebuild so a consumer needs no C toolchain and
90
+ * no node-gyp — the only install path Deno supports (it runs no postinstall build
91
+ * script). Fall back to a locally built addon (Release, then Debug).
92
+ * @param {Record<string, string | undefined>} [env] defaults to `process.env`
93
+ * @returns {string[]}
94
+ */
95
+ export function nativeCandidates(env = process.env) {
96
+ const prebuild = prebuildAddonPath();
97
+ const release = buildAddonPath('Release');
98
+ const debug = buildAddonPath('Debug');
99
+ const prefer = env.NODE_GI_NATIVE;
100
+ if (prefer === 'build') return [release, debug, prebuild];
101
+ if (prefer === 'prebuild') return [prebuild];
102
+ if (prefer) return [prefer]; // an explicit path to a node_gi.node
103
+ return [prebuild, release, debug];
104
+ }
@@ -16,152 +16,149 @@
16
16
  // connections, but they may be to different signal names
17
17
 
18
18
  function _connectFull(name, callback, after) {
19
- // be paranoid about callback arg since we'd start to throw from emit()
20
- // if it was messed up
21
- if (typeof callback !== 'function')
22
- throw new Error('When connecting signal must give a callback that is a function');
23
-
24
- // we instantiate the "signal machinery" only on-demand if anything
25
- // gets connected.
26
- if (this._signalConnections === undefined) {
27
- this._signalConnections = Object.create(null);
28
- this._signalConnectionsByName = Object.create(null);
29
- this._nextConnectionId = 1;
30
- }
31
-
32
- const id = this._nextConnectionId;
33
- this._nextConnectionId += 1;
34
-
35
- this._signalConnections[id] = {
36
- name,
37
- callback,
38
- after,
39
- };
40
-
41
- const connectionsByName = this._signalConnectionsByName[name] ?? [];
42
-
43
- if (!connectionsByName.length)
44
- this._signalConnectionsByName[name] = connectionsByName;
45
- connectionsByName.push(id);
46
-
47
- return id;
19
+ // be paranoid about callback arg since we'd start to throw from emit()
20
+ // if it was messed up
21
+ if (typeof callback !== 'function')
22
+ throw new Error('When connecting signal must give a callback that is a function');
23
+
24
+ // we instantiate the "signal machinery" only on-demand if anything
25
+ // gets connected.
26
+ if (this._signalConnections === undefined) {
27
+ this._signalConnections = Object.create(null);
28
+ this._signalConnectionsByName = Object.create(null);
29
+ this._nextConnectionId = 1;
30
+ }
31
+
32
+ const id = this._nextConnectionId;
33
+ this._nextConnectionId += 1;
34
+
35
+ this._signalConnections[id] = {
36
+ name,
37
+ callback,
38
+ after,
39
+ };
40
+
41
+ const connectionsByName = this._signalConnectionsByName[name] ?? [];
42
+
43
+ if (!connectionsByName.length) this._signalConnectionsByName[name] = connectionsByName;
44
+ connectionsByName.push(id);
45
+
46
+ return id;
48
47
  }
49
48
 
50
49
  export function _connect(name, callback) {
51
- return _connectFull.call(this, name, callback, false);
50
+ return _connectFull.call(this, name, callback, false);
52
51
  }
53
52
 
54
53
  export function _connectAfter(name, callback) {
55
- return _connectFull.call(this, name, callback, true);
54
+ return _connectFull.call(this, name, callback, true);
56
55
  }
57
56
 
58
57
  export function _disconnect(id) {
59
- const connection = this._signalConnections?.[id];
58
+ const connection = this._signalConnections?.[id];
60
59
 
61
- if (!connection)
62
- throw new Error(`No signal connection ${id} found`);
60
+ if (!connection) throw new Error(`No signal connection ${id} found`);
63
61
 
64
- if (connection.disconnected)
65
- throw new Error(`Signal handler id ${id} already disconnected`);
62
+ if (connection.disconnected) throw new Error(`Signal handler id ${id} already disconnected`);
66
63
 
67
- connection.disconnected = true;
68
- delete this._signalConnections[id];
64
+ connection.disconnected = true;
65
+ delete this._signalConnections[id];
69
66
 
70
- const ids = this._signalConnectionsByName[connection.name];
71
- if (!ids)
72
- return;
67
+ const ids = this._signalConnectionsByName[connection.name];
68
+ if (!ids) return;
73
69
 
74
- const indexOfId = ids.indexOf(id);
75
- if (indexOfId !== -1)
76
- ids.splice(indexOfId, 1);
70
+ const indexOfId = ids.indexOf(id);
71
+ if (indexOfId !== -1) ids.splice(indexOfId, 1);
77
72
 
78
- if (ids.length === 0)
79
- delete this._signalConnectionsByName[connection.name];
73
+ if (ids.length === 0) delete this._signalConnectionsByName[connection.name];
80
74
  }
81
75
 
82
76
  export function _signalHandlerIsConnected(id) {
83
- const connection = this._signalConnections?.[id];
84
- return !!connection && !connection.disconnected;
77
+ const connection = this._signalConnections?.[id];
78
+ return !!connection && !connection.disconnected;
85
79
  }
86
80
 
87
81
  export function _disconnectAll() {
88
- Object.values(this._signalConnections ?? {}).forEach(c => (c.disconnected = true));
89
- delete this._signalConnections;
90
- delete this._signalConnectionsByName;
82
+ Object.values(this._signalConnections ?? {}).forEach((c) => (c.disconnected = true));
83
+ delete this._signalConnections;
84
+ delete this._signalConnectionsByName;
91
85
  }
92
86
 
93
87
  export function _emit(name, ...args) {
94
- const connections = this._signalConnectionsByName?.[name];
95
-
96
- // may not be any signal handlers at all, if not then return
97
- if (!connections)
98
- return;
99
-
100
- // To deal with re-entrancy (removal/addition while
101
- // emitting), we copy out a list of what was connected
102
- // at emission start; and just before invoking each
103
- // handler we check its disconnected flag.
104
- const handlers = connections.map(id => this._signalConnections[id]);
105
-
106
- // create arg array which is emitter + everything passed in except
107
- // signal name. Would be more convenient not to pass emitter to
108
- // the callback, but trying to be 100% consistent with GObject
109
- // which does pass it in. Also if we pass in the emitter here,
110
- // people don't create closures with the emitter in them,
111
- // which would be a cycle.
112
- const argArray = [this, ...args];
113
-
114
- const afterHandlers = [];
115
- const beforeHandlers = handlers.filter(c => {
116
- if (!c.after)
117
- return true;
118
-
119
- afterHandlers.push(c);
120
- return false;
121
- });
122
-
123
- if (!_callHandlers(beforeHandlers, argArray))
124
- _callHandlers(afterHandlers, argArray);
88
+ const connections = this._signalConnectionsByName?.[name];
89
+
90
+ // may not be any signal handlers at all, if not then return
91
+ if (!connections) return;
92
+
93
+ // To deal with re-entrancy (removal/addition while
94
+ // emitting), we copy out a list of what was connected
95
+ // at emission start; and just before invoking each
96
+ // handler we check its disconnected flag.
97
+ const handlers = connections.map((id) => this._signalConnections[id]);
98
+
99
+ // create arg array which is emitter + everything passed in except
100
+ // signal name. Would be more convenient not to pass emitter to
101
+ // the callback, but trying to be 100% consistent with GObject
102
+ // which does pass it in. Also if we pass in the emitter here,
103
+ // people don't create closures with the emitter in them,
104
+ // which would be a cycle.
105
+ const argArray = [this, ...args];
106
+
107
+ const afterHandlers = [];
108
+ const beforeHandlers = handlers.filter((c) => {
109
+ if (!c.after) return true;
110
+
111
+ afterHandlers.push(c);
112
+ return false;
113
+ });
114
+
115
+ if (!_callHandlers(beforeHandlers, argArray)) _callHandlers(afterHandlers, argArray);
125
116
  }
126
117
 
127
118
  function _callHandlers(handlers, argArray) {
128
- for (const handler of handlers) {
129
- if (handler.disconnected)
130
- continue;
131
-
132
- try {
133
- // since we pass "null" for this, the global object will be used.
134
- const ret = handler.callback.apply(null, argArray);
135
-
136
- // if the callback returns true, we don't call the next
137
- // signal handlers
138
- if (ret === true)
139
- return true;
140
- } catch (e) {
141
- // just log any exceptions so that callbacks can't disrupt
142
- // signal emission
143
- logError(e, `Exception in callback for signal: ${handler.name}`);
119
+ for (const handler of handlers) {
120
+ if (handler.disconnected) continue;
121
+
122
+ try {
123
+ // since we pass "null" for this, the global object will be used.
124
+ const ret = handler.callback.apply(null, argArray);
125
+
126
+ // if the callback returns true, we don't call the next
127
+ // signal handlers
128
+ if (ret === true) return true;
129
+ } catch (e) {
130
+ // just log any exceptions so that callbacks can't disrupt
131
+ // signal emission
132
+ logError(e, `Exception in callback for signal: ${handler.name}`);
133
+ }
144
134
  }
145
- }
146
135
 
147
- return false;
136
+ return false;
148
137
  }
149
138
 
150
139
  function _addSignalMethod(proto, functionName, func) {
151
- if (proto[functionName] && proto[functionName] !== func)
152
- log(`WARNING: addSignalMethods is replacing existing ${proto} ${functionName} method`);
140
+ if (proto[functionName] && proto[functionName] !== func)
141
+ log(`WARNING: addSignalMethods is replacing existing ${proto} ${functionName} method`);
153
142
 
154
- proto[functionName] = func;
143
+ proto[functionName] = func;
155
144
  }
156
145
 
157
146
  export function addSignalMethods(proto) {
158
- _addSignalMethod(proto, 'connect', _connect);
159
- _addSignalMethod(proto, 'connectAfter', _connectAfter);
160
- _addSignalMethod(proto, 'disconnect', _disconnect);
161
- _addSignalMethod(proto, 'emit', _emit);
162
- _addSignalMethod(proto, 'signalHandlerIsConnected', _signalHandlerIsConnected);
163
- // this one is not in GObject, but useful
164
- _addSignalMethod(proto, 'disconnectAll', _disconnectAll);
147
+ _addSignalMethod(proto, 'connect', _connect);
148
+ _addSignalMethod(proto, 'connectAfter', _connectAfter);
149
+ _addSignalMethod(proto, 'disconnect', _disconnect);
150
+ _addSignalMethod(proto, 'emit', _emit);
151
+ _addSignalMethod(proto, 'signalHandlerIsConnected', _signalHandlerIsConnected);
152
+ // this one is not in GObject, but useful
153
+ _addSignalMethod(proto, 'disconnectAll', _disconnectAll);
165
154
  }
166
155
 
167
- export default { addSignalMethods, _connect, _connectAfter, _disconnect, _emit, _signalHandlerIsConnected, _disconnectAll };
156
+ export default {
157
+ addSignalMethods,
158
+ _connect,
159
+ _connectAfter,
160
+ _disconnect,
161
+ _emit,
162
+ _signalHandlerIsConnected,
163
+ _disconnectAll,
164
+ };