@pipelab/steamworks.js 0.7.3

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) 2022 Gabriel Francisco Dos Santos
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 ADDED
@@ -0,0 +1,115 @@
1
+ # steamworks.js (Community Fork)
2
+
3
+ > **Note**: This is an actively maintained community fork of [steamworks.js](https://github.com/CynToolkit/steamworks.js).
4
+ > We're keeping the project active by reviewing and merging pending PRs and addressing issues.
5
+
6
+ ## Why This Fork?
7
+
8
+ - ✅ Actively reviewing and merging PRs
9
+ - ✅ Regular updates and bug fixes
10
+ - ✅ Community-driven development
11
+ - ✅ NW.js support improvements
12
+ - ✅ Incorporating pending PRs from upstream
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ # npm - use our scoped package
18
+ npm install @mikaldev/steamworks.js
19
+
20
+ # Or reference directly from GitHub
21
+ npm install github:MikalDev/steamworks.js
22
+
23
+ # For Electron/NW.js projects
24
+ npm install github:MikalDev/steamworks.js --runtime=electron --target=27.0.0
25
+ npm install github:MikalDev/steamworks.js --runtime=node-webkit --target=0.75.0
26
+
27
+
28
+ [![Build Status](https://github.com/CynToolkit/steamworks.js/actions/workflows/publish.yml/badge.svg)](https://github.com/CynToolkit/steamworks.js/actions/workflows/publish.yml)
29
+ [![npm](https://img.shields.io/npm/v/steamworks.js.svg)](https://npmjs.com/package/steamworks.js)
30
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
31
+ [![Chat](https://img.shields.io/discord/663831597690257431?label=chat&logo=discord)](https://discord.gg/H6B7UE7fMY)
32
+
33
+ # Steamworks.js
34
+
35
+ A modern implementation of the Steamworks SDK for HTML/JS and NodeJS based applications.
36
+
37
+ ## Why
38
+
39
+ I used [greenworks](https://github.com/greenheartgames/greenworks) for a long time and it's great, but I gave up for the following reasons.
40
+
41
+ * It's not being maintained anymore.
42
+ * It's not up to date.
43
+ * It's not context-aware.
44
+ * You have to build the binaries by yourself.
45
+ * Don't have typescript definitions.
46
+ * The API it's not trustful.
47
+ * The API implement callbacks instead of return flags or promises.
48
+ * I hate C++.
49
+
50
+ ## API
51
+
52
+ ```js
53
+ const steamworks = require('steamworks.js')
54
+
55
+ // You can pass an appId, or don't pass anything and use a steam_appid.txt file
56
+ const client = steamworks.init(480)
57
+
58
+ // Print Steam username
59
+ console.log(client.localplayer.getName())
60
+
61
+ // Tries to activate an achievement
62
+ if (client.achievement.activate('ACHIEVEMENT')) {
63
+ // ...
64
+ }
65
+ ```
66
+
67
+ You can refer to the [declarations file](https://github.com/CynToolkit/steamworks.js/blob/main/client.d.ts) to check the API support and get more detailed documentation of each function.
68
+
69
+ ## Installation
70
+
71
+ To use steamworks.js you don't have to build anything, just install it from npm:
72
+
73
+ ```sh
74
+ $: npm i steamworks.js
75
+ ```
76
+
77
+ ### Electron
78
+
79
+ Steamworks.js is a native module and cannot be used by default in the renderer process. To enable the usage of native modules on the renderer process, the following configurations should be made on `main.js`:
80
+
81
+ ```js
82
+ const mainWindow = new BrowserWindow({
83
+ // ...
84
+ webPreferences: {
85
+ // ...
86
+ contextIsolation: false,
87
+ nodeIntegration: true
88
+ }
89
+ })
90
+ ```
91
+
92
+ To make the steam overlay working, call the `electronEnableSteamOverlay` on the end of your `main.js` file:
93
+
94
+ ```js
95
+ require('steamworks.js').electronEnableSteamOverlay()
96
+ ```
97
+
98
+ For the production build, copy the relevant distro files from `sdk/redistributable_bin/{YOUR_DISTRO}` into the root of your build. If you are using electron-forge, look for [#75](https://github.com/CynToolkit/steamworks.js/issues/75).
99
+
100
+
101
+ ## How to build
102
+
103
+ > You **only** need to build if you are going to change something on steamworks.js code, if you are looking to just consume the library or use it in your game, refer to the [installation section](#installation).
104
+
105
+ Make sure you have the latest [node.js](https://nodejs.org/en/), [Rust](https://www.rust-lang.org/tools/install) and [Clang](https://rust-lang.github.io/rust-bindgen/requirements.html). We also need [Steam](https://store.steampowered.com/about/) installed and running.
106
+
107
+ Install dependencies with `npm install` and then run `npm run build:debug` to build the library.
108
+
109
+ There is no way to build for all targets easily. The good news is that you don't need to. You can develop and test on your current target, and open a PR. When the code is merged to main, a github action will build for all targets and publish a new version.
110
+
111
+ ### Testing Electron
112
+
113
+ Go to the [test/electron](./test/electron) directory. There, you can run `npm install` and then `npm start` to run the Electron app.
114
+
115
+ Click "activate overlay" to test the overlay.
package/callbacks.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import client = require('./client')
2
+
3
+ export const enum ChatMemberStateChange {
4
+ /** This user has joined or is joining the lobby. */
5
+ Entered,
6
+ /** This user has left or is leaving the lobby. */
7
+ Left,
8
+ /** User disconnected without leaving the lobby first. */
9
+ Disconnected,
10
+ /** The user has been kicked. */
11
+ Kicked,
12
+ /** The user has been kicked and banned. */
13
+ Banned,
14
+ }
15
+
16
+ export interface CallbackReturns {
17
+ [client.callback.SteamCallback.PersonaStateChange]: {
18
+ steam_id: bigint
19
+ flags: { bits: number }
20
+ }
21
+ [client.callback.SteamCallback.SteamServersConnected]: {}
22
+ [client.callback.SteamCallback.SteamServersDisconnected]: {
23
+ reason: number
24
+ }
25
+ [client.callback.SteamCallback.SteamServerConnectFailure]: {
26
+ reason: number
27
+ still_retrying: boolean
28
+ }
29
+ [client.callback.SteamCallback.LobbyDataUpdate]: {
30
+ lobby: bigint
31
+ member: bigint
32
+ success: boolean
33
+ }
34
+ [client.callback.SteamCallback.LobbyChatUpdate]: {
35
+ lobby: bigint
36
+ user_changed: bigint
37
+ making_change: bigint
38
+ member_state_change: ChatMemberStateChange
39
+ }
40
+ [client.callback.SteamCallback.P2PSessionRequest]: {
41
+ remote: bigint
42
+ }
43
+ [client.callback.SteamCallback.P2PSessionConnectFail]: {
44
+ remote: bigint
45
+ error: number
46
+ }
47
+ [client.callback.SteamCallback.GameLobbyJoinRequested]: {
48
+ lobby_steam_id: bigint
49
+ friend_steam_id: bigint
50
+ }
51
+ [client.callback.SteamCallback.MicroTxnAuthorizationResponse]: {
52
+ app_id: number
53
+ order_id: number | bigint
54
+ authorized: boolean
55
+ }
56
+ }
package/client.d.ts ADDED
@@ -0,0 +1,519 @@
1
+ export declare function init(appId?: number | undefined | null): void
2
+ export declare function restartAppIfNecessary(appId: number): boolean
3
+ export declare function runCallbacks(): void
4
+ export interface PlayerSteamId {
5
+ steamId64: bigint
6
+ steamId32: string
7
+ accountId: number
8
+ }
9
+ export declare namespace achievement {
10
+ export function activate(achievement: string): boolean
11
+ export function isActivated(achievement: string): boolean
12
+ export function clear(achievement: string): boolean
13
+ export function names(): Array<string>
14
+ }
15
+ export declare namespace apps {
16
+ export function isSubscribedApp(appId: number): boolean
17
+ export function isAppInstalled(appId: number): boolean
18
+ export function isDlcInstalled(appId: number): boolean
19
+ export function isSubscribedFromFreeWeekend(): boolean
20
+ export function isVacBanned(): boolean
21
+ export function isCybercafe(): boolean
22
+ export function isLowViolence(): boolean
23
+ export function isSubscribed(): boolean
24
+ export function appBuildId(): number
25
+ export function appInstallDir(appId: number): string
26
+ export function appOwner(): PlayerSteamId
27
+ export function availableGameLanguages(): Array<string>
28
+ export function currentGameLanguage(): string
29
+ export function currentBetaName(): string | null
30
+ }
31
+ export declare namespace auth {
32
+ /**
33
+ * @param steamId64 - The user steam id or game server steam id. Use as NetworkIdentity of the remote system that will authenticate the ticket. If it is peer-to-peer then the user steam ID. If it is a game server, then the game server steam ID may be used if it was obtained from a trusted 3rd party
34
+ * @param timeoutSeconds - The number of seconds to wait for the ticket to be validated. Default value is 10 seconds.
35
+ */
36
+ export function getSessionTicketWithSteamId(steamId64: bigint, timeoutSeconds?: number | undefined | null): Promise<Ticket>
37
+ /**
38
+ * @param ip - The string of IPv4 or IPv6 address. Use as NetworkIdentity of the remote system that will authenticate the ticket.
39
+ * @param timeoutSeconds - The number of seconds to wait for the ticket to be validated. Default value is 10 seconds.
40
+ */
41
+ export function getSessionTicketWithIp(ip: string, timeoutSeconds?: number | undefined | null): Promise<Ticket>
42
+ export function getAuthTicketForWebApi(identity: string, timeoutSeconds?: number | undefined | null): Promise<Ticket>
43
+ export class Ticket {
44
+ cancel(): void
45
+ getBytes(): Buffer
46
+ }
47
+ }
48
+ export declare namespace callback {
49
+ export const enum SteamCallback {
50
+ PersonaStateChange = 0,
51
+ SteamServersConnected = 1,
52
+ SteamServersDisconnected = 2,
53
+ SteamServerConnectFailure = 3,
54
+ LobbyDataUpdate = 4,
55
+ LobbyChatUpdate = 5,
56
+ P2PSessionRequest = 6,
57
+ P2PSessionConnectFail = 7,
58
+ GameLobbyJoinRequested = 8,
59
+ MicroTxnAuthorizationResponse = 9
60
+ }
61
+ export function register<C extends keyof import('./callbacks').CallbackReturns>(steamCallback: C, handler: (value: import('./callbacks').CallbackReturns[C]) => void): Handle
62
+ export class Handle {
63
+ disconnect(): void
64
+ }
65
+ }
66
+ export declare namespace cloud {
67
+ export function isEnabledForAccount(): boolean
68
+ export function isEnabledForApp(): boolean
69
+ export function setEnabledForApp(enabled: boolean): void
70
+ export function readFile(name: string): string
71
+ export function writeFile(name: string, content: string): boolean
72
+ export function deleteFile(name: string): boolean
73
+ export function fileExists(name: string): boolean
74
+ export function listFiles(): Array<FileInfo>
75
+ export class FileInfo {
76
+ name: string
77
+ size: bigint
78
+ }
79
+ }
80
+ export declare namespace friends {
81
+ export function getFriendName(steamId64: bigint): string
82
+ }
83
+ export declare namespace input {
84
+ export const enum InputType {
85
+ Unknown = 'Unknown',
86
+ SteamController = 'SteamController',
87
+ XBox360Controller = 'XBox360Controller',
88
+ XBoxOneController = 'XBoxOneController',
89
+ GenericGamepad = 'GenericGamepad',
90
+ PS4Controller = 'PS4Controller',
91
+ AppleMFiController = 'AppleMFiController',
92
+ AndroidController = 'AndroidController',
93
+ SwitchJoyConPair = 'SwitchJoyConPair',
94
+ SwitchJoyConSingle = 'SwitchJoyConSingle',
95
+ SwitchProController = 'SwitchProController',
96
+ MobileTouch = 'MobileTouch',
97
+ PS3Controller = 'PS3Controller',
98
+ PS5Controller = 'PS5Controller',
99
+ SteamDeckController = 'SteamDeckController'
100
+ }
101
+ export interface AnalogActionVector {
102
+ x: number
103
+ y: number
104
+ }
105
+ export function init(): void
106
+ export function getControllers(): Array<Controller>
107
+ export function getActionSet(actionSetName: string): bigint
108
+ export function getDigitalAction(actionName: string): bigint
109
+ export function getAnalogAction(actionName: string): bigint
110
+ export function shutdown(): void
111
+ export class Controller {
112
+ activateActionSet(actionSetHandle: bigint): void
113
+ isDigitalActionPressed(actionHandle: bigint): boolean
114
+ getAnalogActionVector(actionHandle: bigint): AnalogActionVector
115
+ getType(): InputType
116
+ getHandle(): bigint
117
+ }
118
+ }
119
+ export declare namespace leaderboards {
120
+ export interface LeaderboardEntry {
121
+ globalRank: number
122
+ score: number
123
+ steamId: bigint
124
+ details: Array<number>
125
+ }
126
+ export const enum SortMethod {
127
+ Ascending = 0,
128
+ Descending = 1
129
+ }
130
+ export const enum DisplayType {
131
+ Numeric = 0,
132
+ TimeSeconds = 1,
133
+ TimeMilliSeconds = 2
134
+ }
135
+ export const enum DataRequest {
136
+ Global = 0,
137
+ GlobalAroundUser = 1,
138
+ Friends = 2
139
+ }
140
+ export const enum UploadScoreMethod {
141
+ KeepBest = 0,
142
+ ForceUpdate = 1
143
+ }
144
+ export function findLeaderboard(name: string): Promise<string | null>
145
+ export function findOrCreateLeaderboard(name: string, sortMethod: SortMethod, displayType: DisplayType): Promise<string | null>
146
+ export function uploadScore(leaderboardName: string, score: number, uploadMethod: UploadScoreMethod, details?: Array<number> | undefined | null): Promise<LeaderboardEntry | null>
147
+ export function downloadScores(leaderboardName: string, dataRequest: DataRequest, rangeStart: number, rangeEnd: number): Promise<Array<LeaderboardEntry>>
148
+ export function getLeaderboardName(leaderboardName: string): string | null
149
+ export function getLeaderboardEntryCount(leaderboardName: string): number | null
150
+ export function getLeaderboardSortMethod(leaderboardName: string): SortMethod | null
151
+ export function getLeaderboardDisplayType(leaderboardName: string): DisplayType | null
152
+ export function clearLeaderboardHandle(leaderboardName: string): boolean
153
+ export function getCachedLeaderboardNames(): Array<string>
154
+ }
155
+ export declare namespace localplayer {
156
+ export function getSteamId(): PlayerSteamId
157
+ export function getName(): string
158
+ export function getLevel(): number
159
+ /** @returns the 2 digit ISO 3166-1-alpha-2 format country code which client is running in, e.g. "US" or "UK". */
160
+ export function getIpCountry(): string
161
+ export function setRichPresence(key: string, value?: string | undefined | null): void
162
+ }
163
+ export declare namespace matchmaking {
164
+ export const enum LobbyType {
165
+ Private = 0,
166
+ FriendsOnly = 1,
167
+ Public = 2,
168
+ Invisible = 3
169
+ }
170
+ export function createLobby(lobbyType: LobbyType, maxMembers: number): Promise<Lobby>
171
+ export function joinLobby(lobbyId: bigint): Promise<Lobby>
172
+ export function getLobbies(): Promise<Array<Lobby>>
173
+ export class Lobby {
174
+ id: bigint
175
+ join(): Promise<Lobby>
176
+ leave(): void
177
+ openInviteDialog(): void
178
+ getMemberCount(): bigint
179
+ getMemberLimit(): bigint | null
180
+ getMembers(): Array<PlayerSteamId>
181
+ getOwner(): PlayerSteamId
182
+ setJoinable(joinable: boolean): boolean
183
+ getData(key: string): string | null
184
+ setData(key: string, value: string): boolean
185
+ deleteData(key: string): boolean
186
+ /** Get an object containing all the lobby data */
187
+ getFullData(): Record<string, string>
188
+ /**
189
+ * Merge current lobby data with provided data in a single batch
190
+ * @returns true if all data was set successfully
191
+ */
192
+ mergeFullData(data: Record<string, string>): boolean
193
+ }
194
+ }
195
+ export declare namespace networking {
196
+ export interface P2PPacket {
197
+ data: Buffer
198
+ size: number
199
+ steamId: PlayerSteamId
200
+ }
201
+ /** The method used to send a packet */
202
+ export const enum SendType {
203
+ /**
204
+ * Send the packet directly over udp.
205
+ *
206
+ * Can't be larger than 1200 bytes
207
+ */
208
+ Unreliable = 0,
209
+ /**
210
+ * Like `Unreliable` but doesn't buffer packets
211
+ * sent before the connection has started.
212
+ */
213
+ UnreliableNoDelay = 1,
214
+ /**
215
+ * Reliable packet sending.
216
+ *
217
+ * Can't be larger than 1 megabyte.
218
+ */
219
+ Reliable = 2,
220
+ /**
221
+ * Like `Reliable` but applies the nagle
222
+ * algorithm to packets being sent
223
+ */
224
+ ReliableWithBuffering = 3
225
+ }
226
+ export function sendP2PPacket(steamId64: bigint, sendType: SendType, data: Buffer): boolean
227
+ export function sendP2PPacketOnChannel(steamId64: bigint, sendType: SendType, data: Buffer, channel: number): boolean
228
+ export function isP2PPacketAvailable(): number
229
+ export function isP2PPacketAvailableOnChannel(channel: number): number
230
+ export function readP2PPacket(size: number): P2PPacket
231
+ export function readP2PPacketFromChannel(size: number, channel: number): P2PPacket
232
+ export function acceptP2PSession(steamId64: bigint): void
233
+ }
234
+ export declare namespace networking_messages {
235
+ export interface Message {
236
+ data: Buffer
237
+ steamId?: PlayerSteamId
238
+ }
239
+ export function sendMessageToUser(steamId64: bigint, data: Buffer): void
240
+ export function receiveMessagesOnChannel(): Array<Message>
241
+ }
242
+ export declare namespace overlay {
243
+ export const enum Dialog {
244
+ Friends = 0,
245
+ Community = 1,
246
+ Players = 2,
247
+ Settings = 3,
248
+ OfficialGameGroup = 4,
249
+ Stats = 5,
250
+ Achievements = 6
251
+ }
252
+ export const enum StoreFlag {
253
+ None = 0,
254
+ AddToCart = 1,
255
+ AddToCartAndShow = 2
256
+ }
257
+ export function activateDialog(dialog: Dialog): void
258
+ export function activateDialogToUser(dialog: Dialog, steamId64: bigint): void
259
+ export function activateInviteDialog(lobbyId: bigint): void
260
+ export function activateToWebPage(url: string): void
261
+ export function activateToStore(appId: number, flag: StoreFlag): void
262
+ }
263
+ export declare namespace stats {
264
+ export function getInt(name: string): number | null
265
+ export function setInt(name: string, value: number): boolean
266
+ export function store(): boolean
267
+ export function resetAll(achievementsToo: boolean): boolean
268
+ }
269
+ export declare namespace utils {
270
+ export function getAppId(): number
271
+ export function getServerRealTime(): number
272
+ export function isSteamRunningOnSteamDeck(): boolean
273
+ export const enum GamepadTextInputMode {
274
+ Normal = 0,
275
+ Password = 1
276
+ }
277
+ export const enum GamepadTextInputLineMode {
278
+ SingleLine = 0,
279
+ MultipleLines = 1
280
+ }
281
+ /** @returns the entered text, or null if cancelled or could not show the input */
282
+ export function showGamepadTextInput(inputMode: GamepadTextInputMode, inputLineMode: GamepadTextInputLineMode, description: string, maxCharacters: number, existingText?: string | undefined | null): Promise<string | null>
283
+ export const enum FloatingGamepadTextInputMode {
284
+ SingleLine = 0,
285
+ MultipleLines = 1,
286
+ Email = 2,
287
+ Numeric = 3
288
+ }
289
+ /** @returns true if the floating keyboard was shown, otherwise, false */
290
+ export function showFloatingGamepadTextInput(keyboardMode: FloatingGamepadTextInputMode, x: number, y: number, width: number, height: number): Promise<boolean>
291
+ }
292
+ export declare namespace workshop {
293
+ export interface UgcResult {
294
+ itemId: bigint
295
+ needsToAcceptAgreement: boolean
296
+ }
297
+ export const enum UgcItemVisibility {
298
+ Public = 0,
299
+ FriendsOnly = 1,
300
+ Private = 2,
301
+ Unlisted = 3
302
+ }
303
+ export interface UgcUpdate {
304
+ title?: string
305
+ description?: string
306
+ changeNote?: string
307
+ previewPath?: string
308
+ contentPath?: string
309
+ tags?: Array<string>
310
+ visibility?: UgcItemVisibility
311
+ }
312
+ export interface InstallInfo {
313
+ folder: string
314
+ sizeOnDisk: bigint
315
+ timestamp: number
316
+ }
317
+ export interface DownloadInfo {
318
+ current: bigint
319
+ total: bigint
320
+ }
321
+ export const enum UpdateStatus {
322
+ Invalid = 0,
323
+ PreparingConfig = 1,
324
+ PreparingContent = 2,
325
+ UploadingContent = 3,
326
+ UploadingPreviewFile = 4,
327
+ CommittingChanges = 5
328
+ }
329
+ export interface UpdateProgress {
330
+ status: UpdateStatus
331
+ progress: bigint
332
+ total: bigint
333
+ }
334
+ export function createItem(appId?: number | undefined | null): Promise<UgcResult>
335
+ export function updateItem(itemId: bigint, updateDetails: UgcUpdate, appId?: number | undefined | null): Promise<UgcResult>
336
+ export function updateItemWithCallback(itemId: bigint, updateDetails: UgcUpdate, appId: number | undefined | null, successCallback: (data: UgcResult) => void, errorCallback: (err: any) => void, progressCallback?: (data: UpdateProgress) => void, progressCallbackIntervalMs?: number | undefined | null): void
337
+ /**
338
+ * Subscribe to a workshop item. It will be downloaded and installed as soon as possible.
339
+ *
340
+ * {@link https://partner.steamgames.com/doc/api/ISteamUGC#SubscribeItem}
341
+ */
342
+ export function subscribe(itemId: bigint): Promise<void>
343
+ /**
344
+ * Unsubscribe from a workshop item. This will result in the item being removed after the game quits.
345
+ *
346
+ * {@link https://partner.steamgames.com/doc/api/ISteamUGC#UnsubscribeItem}
347
+ */
348
+ export function unsubscribe(itemId: bigint): Promise<void>
349
+ /**
350
+ * Gets the current state of a workshop item on this client. States can be combined.
351
+ *
352
+ * @returns a number with the current item state, e.g. 9
353
+ * 9 = 1 (The current user is subscribed to this item) + 8 (The item needs an update)
354
+ *
355
+ * {@link https://partner.steamgames.com/doc/api/ISteamUGC#GetItemState}
356
+ * {@link https://partner.steamgames.com/doc/api/ISteamUGC#EItemState}
357
+ */
358
+ export function state(itemId: bigint): number
359
+ /**
360
+ * Gets info about currently installed content on the disc for workshop item.
361
+ *
362
+ * @returns an object with the the properties {folder, size_on_disk, timestamp}
363
+ *
364
+ * {@link https://partner.steamgames.com/doc/api/ISteamUGC#GetItemInstallInfo}
365
+ */
366
+ export function installInfo(itemId: bigint): InstallInfo | null
367
+ /**
368
+ * Get info about a pending download of a workshop item.
369
+ *
370
+ * @returns an object with the properties {current, total}
371
+ *
372
+ * {@link https://partner.steamgames.com/doc/api/ISteamUGC#GetItemDownloadInfo}
373
+ */
374
+ export function downloadInfo(itemId: bigint): DownloadInfo | null
375
+ /**
376
+ * Download or update a workshop item.
377
+ *
378
+ * @param highPriority - If high priority is true, start the download in high priority mode, pausing any existing in-progress Steam downloads and immediately begin downloading this workshop item.
379
+ * @returns true or false
380
+ *
381
+ * {@link https://partner.steamgames.com/doc/api/ISteamUGC#DownloadItem}
382
+ */
383
+ export function download(itemId: bigint, highPriority: boolean): boolean
384
+ /**
385
+ * Get all subscribed workshop items.
386
+ * @returns an array of subscribed workshop item ids
387
+ */
388
+ export function getSubscribedItems(includeLocallyDisabled: boolean): Array<bigint>
389
+ export function deleteItem(itemId: bigint): Promise<void>
390
+ export const enum UGCQueryType {
391
+ RankedByVote = 0,
392
+ RankedByPublicationDate = 1,
393
+ AcceptedForGameRankedByAcceptanceDate = 2,
394
+ RankedByTrend = 3,
395
+ FavoritedByFriendsRankedByPublicationDate = 4,
396
+ CreatedByFriendsRankedByPublicationDate = 5,
397
+ RankedByNumTimesReported = 6,
398
+ CreatedByFollowedUsersRankedByPublicationDate = 7,
399
+ NotYetRated = 8,
400
+ RankedByTotalVotesAsc = 9,
401
+ RankedByVotesUp = 10,
402
+ RankedByTextSearch = 11,
403
+ RankedByTotalUniqueSubscriptions = 12,
404
+ RankedByPlaytimeTrend = 13,
405
+ RankedByTotalPlaytime = 14,
406
+ RankedByAveragePlaytimeTrend = 15,
407
+ RankedByLifetimeAveragePlaytime = 16,
408
+ RankedByPlaytimeSessionsTrend = 17,
409
+ RankedByLifetimePlaytimeSessions = 18,
410
+ RankedByLastUpdatedDate = 19
411
+ }
412
+ export const enum UGCType {
413
+ Items = 0,
414
+ ItemsMtx = 1,
415
+ ItemsReadyToUse = 2,
416
+ Collections = 3,
417
+ Artwork = 4,
418
+ Videos = 5,
419
+ Screenshots = 6,
420
+ AllGuides = 7,
421
+ WebGuides = 8,
422
+ IntegratedGuides = 9,
423
+ UsableInGame = 10,
424
+ ControllerBindings = 11,
425
+ GameManagedItems = 12,
426
+ All = 13
427
+ }
428
+ export const enum UserListType {
429
+ Published = 0,
430
+ VotedOn = 1,
431
+ VotedUp = 2,
432
+ VotedDown = 3,
433
+ Favorited = 4,
434
+ Subscribed = 5,
435
+ UsedOrPlayed = 6,
436
+ Followed = 7
437
+ }
438
+ export const enum UserListOrder {
439
+ CreationOrderAsc = 0,
440
+ CreationOrderDesc = 1,
441
+ TitleAsc = 2,
442
+ LastUpdatedDesc = 3,
443
+ SubscriptionDateDesc = 4,
444
+ VoteScoreDesc = 5,
445
+ ForModeration = 6
446
+ }
447
+ export interface WorkshopItemStatistic {
448
+ numSubscriptions?: bigint
449
+ numFavorites?: bigint
450
+ numFollowers?: bigint
451
+ numUniqueSubscriptions?: bigint
452
+ numUniqueFavorites?: bigint
453
+ numUniqueFollowers?: bigint
454
+ numUniqueWebsiteViews?: bigint
455
+ reportScore?: bigint
456
+ numSecondsPlayed?: bigint
457
+ numPlaytimeSessions?: bigint
458
+ numComments?: bigint
459
+ numSecondsPlayedDuringTimePeriod?: bigint
460
+ numPlaytimeSessionsDuringTimePeriod?: bigint
461
+ }
462
+ export interface WorkshopItem {
463
+ publishedFileId: bigint
464
+ creatorAppId?: number
465
+ consumerAppId?: number
466
+ title: string
467
+ description: string
468
+ owner: PlayerSteamId
469
+ /** Time created in unix epoch seconds format */
470
+ timeCreated: number
471
+ /** Time updated in unix epoch seconds format */
472
+ timeUpdated: number
473
+ /** Time when the user added the published item to their list (not always applicable), provided in Unix epoch format (time since Jan 1st, 1970). */
474
+ timeAddedToUserList: number
475
+ visibility: UgcItemVisibility
476
+ banned: boolean
477
+ acceptedForUse: boolean
478
+ tags: Array<string>
479
+ tagsTruncated: boolean
480
+ url: string
481
+ numUpvotes: number
482
+ numDownvotes: number
483
+ numChildren: number
484
+ previewUrl?: string
485
+ statistics: WorkshopItemStatistic
486
+ }
487
+ export interface WorkshopPaginatedResult {
488
+ items: Array<WorkshopItem | undefined | null>
489
+ returnedResults: number
490
+ totalResults: number
491
+ wasCached: boolean
492
+ }
493
+ export interface WorkshopItemsResult {
494
+ items: Array<WorkshopItem | undefined | null>
495
+ wasCached: boolean
496
+ }
497
+ export interface WorkshopItemQueryConfig {
498
+ cachedResponseMaxAge?: number
499
+ includeMetadata?: boolean
500
+ includeLongDescription?: boolean
501
+ includeAdditionalPreviews?: boolean
502
+ onlyIds?: boolean
503
+ onlyTotal?: boolean
504
+ language?: string
505
+ matchAnyTag?: boolean
506
+ requiredTags?: Array<string>
507
+ excludedTags?: Array<string>
508
+ searchText?: string
509
+ rankedByTrendDays?: number
510
+ }
511
+ export interface AppIDs {
512
+ creator?: number
513
+ consumer?: number
514
+ }
515
+ export function getItem(item: bigint, queryConfig?: WorkshopItemQueryConfig | undefined | null): Promise<WorkshopItem | null>
516
+ export function getItems(items: Array<bigint>, queryConfig?: WorkshopItemQueryConfig | undefined | null): Promise<WorkshopItemsResult>
517
+ export function getAllItems(page: number, queryType: UGCQueryType, itemType: UGCType, creatorAppId: number, consumerAppId: number, queryConfig?: WorkshopItemQueryConfig | undefined | null): Promise<WorkshopPaginatedResult>
518
+ export function getUserItems(page: number, accountId: number, listType: UserListType, itemType: UGCType, sortOrder: UserListOrder, appIds: AppIDs, queryConfig?: WorkshopItemQueryConfig | undefined | null): Promise<WorkshopPaginatedResult>
519
+ }
Binary file
package/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export function init(appId?: number): Omit<Client, "init" | "runCallbacks">;
2
+ export function restartAppIfNecessary(appId: number): boolean;
3
+ export function electronEnableSteamOverlay(disableEachFrameInvalidation?: boolean): void;
4
+ export function electronEnableSteamOverlay2(fpsLimit?: number): void;
5
+ export type Client = typeof import("./client.d");
6
+ export const SteamCallback: typeof import("./client.d").callback.SteamCallback;
package/index.js ADDED
@@ -0,0 +1,153 @@
1
+ const { platform, arch } = process
2
+
3
+ /** @typedef {typeof import('./client.d')} Client */
4
+ /** @type {Client} */
5
+ let nativeBinding = undefined
6
+
7
+ if (platform === 'win32' && arch === 'x64') {
8
+ nativeBinding = require('./dist/win64/steamworksjs.win32-x64-msvc.node')
9
+ } else if (platform === 'linux' && arch === 'x64') {
10
+ nativeBinding = require('./dist/linux64/steamworksjs.linux-x64-gnu.node')
11
+ } else if (platform === 'darwin') {
12
+ if (arch === 'x64') {
13
+ nativeBinding = require('./dist/osx/steamworksjs.darwin-x64.node')
14
+ } else if (arch === 'arm64') {
15
+ nativeBinding = require('./dist/osx/steamworksjs.darwin-arm64.node')
16
+ }
17
+ } else {
18
+ throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`)
19
+ }
20
+
21
+ let runCallbacksInterval = undefined
22
+ let steamOverlayInitialized = false
23
+
24
+ /**
25
+ * Initialize the steam client or throw an error if it fails
26
+ * @param {number} [appId] - App ID of the game to load, if undefined, will search for a steam_appid.txt file
27
+ * @returns {Omit<Client, 'init' | 'runCallbacks'>}
28
+ */
29
+ module.exports.init = (appId) => {
30
+ const { init: internalInit, runCallbacks, restartAppIfNecessary, ...api } = nativeBinding
31
+
32
+ internalInit(appId)
33
+
34
+ clearInterval(runCallbacksInterval)
35
+ runCallbacksInterval = setInterval(runCallbacks, 1000 / 30)
36
+
37
+ return api
38
+ }
39
+
40
+ /**
41
+ * @param {number} appId - App ID of the game to load
42
+ * {@link https://partner.steamgames.com/doc/api/steam_api#SteamAPI_RestartAppIfNecessary}
43
+ * @returns {boolean}
44
+ */
45
+ module.exports.restartAppIfNecessary = (appId) => nativeBinding.restartAppIfNecessary(appId);
46
+
47
+ /**
48
+ * Enable the steam overlay on electron
49
+ * @param {boolean} [disableEachFrameInvalidation] - Should attach a single pixel to be rendered each frame
50
+ */
51
+ module.exports.electronEnableSteamOverlay = (disableEachFrameInvalidation) => {
52
+ const electron = require('electron')
53
+ if (!electron) {
54
+ throw new Error('Electron module not found')
55
+ }
56
+
57
+ electron.app.commandLine.appendSwitch('in-process-gpu')
58
+ electron.app.commandLine.appendSwitch('disable-direct-composition')
59
+
60
+ if (!disableEachFrameInvalidation) {
61
+ /** @param {electron.BrowserWindow} browserWindow */
62
+ const attachFrameInvalidator = (browserWindow) => {
63
+ browserWindow.steamworksRepaintInterval = setInterval(() => {
64
+ if (browserWindow.isDestroyed()) {
65
+ clearInterval(browserWindow.steamworksRepaintInterval)
66
+ } else if (!browserWindow.webContents.isPainting()) {
67
+ browserWindow.webContents.invalidate()
68
+ }
69
+ }, 1000 / 60)
70
+ }
71
+
72
+ electron.BrowserWindow.getAllWindows().forEach(attachFrameInvalidator)
73
+ electron.app.on('browser-window-created', (_, bw) => attachFrameInvalidator(bw))
74
+ }
75
+ }
76
+
77
+ module.exports.electronEnableSteamOverlay2 = (fpsLimit = 30) => {
78
+ if (steamOverlayInitialized) {
79
+ console.log('Steam overlay already initialized');
80
+ return;
81
+ }
82
+
83
+ const electron = require('electron')
84
+ if (!electron) {
85
+ throw new Error('Electron module not found')
86
+ }
87
+ const app = electron.app
88
+
89
+ // Check if app is ready
90
+ if (!app.isReady()) {
91
+ throw new Error('Electron app is not ready');
92
+ }
93
+
94
+ // Wrap switch appending in try-catch
95
+ try {
96
+ app.commandLine.appendSwitch('in-process-gpu');
97
+ app.commandLine.appendSwitch('disable-direct-composition');
98
+ app.commandLine.appendSwitch('disable-gpu-shader-disk-cache');
99
+ app.commandLine.appendSwitch('disable-http-cache');
100
+ app.commandLine.appendSwitch('use-angle', 'd3d11');
101
+ app.commandLine.appendSwitch('disable-renderer-backgrounding');
102
+ app.commandLine.appendSwitch('disable-background-timer-throttling');
103
+ } catch (error) {
104
+ console.error('Error appending command line switches:', error);
105
+ throw error;
106
+ }
107
+
108
+ /** @param {electron.BrowserWindow} browserWindow */
109
+ const attachOverlayInvalidator = (window) => {
110
+ // Validate window and webContents existence
111
+ if (!window || !window.webContents) {
112
+ console.error('Invalid window or webContents');
113
+ return;
114
+ }
115
+
116
+ const FPS_LIMIT = fpsLimit;
117
+
118
+ try {
119
+ const intervalId = setInterval(() => {
120
+ try {
121
+ if (!window.isDestroyed() && window.isVisible()) {
122
+ // Invalidation "douce" sans forcer si le compositeur est déjà occupé
123
+ const { webContents } = window;
124
+ if (webContents && !webContents.isPainting()) {
125
+ webContents.invalidate();
126
+ }
127
+ }
128
+ } catch (error) {
129
+ console.error('Error in overlay invalidator interval:', error);
130
+ }
131
+ }, 1000 / FPS_LIMIT);
132
+
133
+ window.once('closed', () => {
134
+ clearInterval(intervalId);
135
+ });
136
+ } catch (error) {
137
+ console.error('Error setting up overlay invalidator:', error);
138
+ }
139
+ };
140
+
141
+ try {
142
+ electron.BrowserWindow.getAllWindows().forEach(attachOverlayInvalidator)
143
+ electron.app.on('browser-window-created', (_, bw) => attachOverlayInvalidator(bw))
144
+ } catch (error) {
145
+ console.error('Error attaching overlay invalidator:', error);
146
+ throw error;
147
+ }
148
+
149
+ steamOverlayInitialized = true;
150
+ }
151
+
152
+ const SteamCallback = nativeBinding.callback.SteamCallback
153
+ module.exports.SteamCallback = SteamCallback
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@pipelab/steamworks.js",
3
+ "version": "0.7.3",
4
+ "main": "index.js",
5
+ "types": "index.d.ts",
6
+ "publishConfig": {
7
+ "registry": "https://registry.npmjs.org/",
8
+ "access": "public"
9
+ },
10
+ "napi": {
11
+ "name": "steamworksjs",
12
+ "triples": {
13
+ "additional": [
14
+ "x86_64-pc-windows-msvc",
15
+ "x86_64-unknown-linux-gnu",
16
+ "x86_64-apple-darwin",
17
+ "aarch64-apple-darwin"
18
+ ]
19
+ }
20
+ },
21
+ "files": [
22
+ "dist/*",
23
+ "index.js",
24
+ "*.d.ts",
25
+ "README.md"
26
+ ],
27
+ "license": "MIT",
28
+ "devDependencies": {
29
+ "@napi-rs/cli": "2.18.4",
30
+ "electron": "24.2.0",
31
+ "rimraf": "6.0.1",
32
+ "typescript": "5.5.3"
33
+ },
34
+ "dependencies": {
35
+ "@types/node": "*"
36
+ },
37
+ "engines": {
38
+ "node": ">= 14"
39
+ },
40
+ "scripts": {
41
+ "build": "npm run types && node build --release",
42
+ "build:debug": "node build",
43
+ "prune": "rimraf dist target client.d.ts",
44
+ "format": "cargo clippy --fix --allow-staged && cargo fmt",
45
+ "types": "tsc index.js --allowJs --declaration --emitDeclarationOnly"
46
+ },
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "https://github.com/CynToolkit/steamworks.js"
50
+ }
51
+ }