Add library documentation

This commit is contained in:
Samuel Elliott
2022-08-21 20:15:11 +01:00
parent ceed9accc2
commit 898cb6f707
8 changed files with 1177 additions and 587 deletions

559
docs/cli.md Normal file
View File

@@ -0,0 +1,559 @@
Nintendo Switch Online
---
### Login to the Nintendo Switch Online app
```sh
# Interactive login
# Generates a link to login with a Nintendo Account, asks for the link then automatically gets a session token
nxapi nso auth
# Login with an existing token
# Use with a token obtained via MITM the app, or with `nxapi nso auth --no-auth`
# The same session token as for the Nintendo Switch Parental Controls app cannot be used
nxapi nso token
# Get the authenticated user
nxapi nso user
```
### Discord Presence
```sh
# Show the authenticated user's presence
nxapi nso presence
# Show a friend's presence
# Use `nxapi nso friends` to show all friend's Nintendo Switch account IDs
nxapi nso presence --friend-nsaid 0123456789abcdef
# Show the authenticated user's friend code in Discord
nxapi nso presence --friend-code
nxapi nso presence --friend-code -
# Show a custom friend code in Discord
# Use this if you are showing presence of a friend of the authenticated user
nxapi nso presence --friend-code 0000-0000-0000
nxapi nso presence --friend-code SW-0000-0000-0000
# Show inactive presence
# This will show a "Not playing" status if any consoles linked to the user's account is online but the user
# is not selected in a game
# Don't enable this if you are not the only user of all consoles linked to your account
nxapi nso presence --show-inactive-presence
# Also show friend notifications (see below)
nxapi nso presence --friend-notifications
nxapi nso presence --user-notifications --friend-notifications
nxapi nso presence --user-notifications
# Set update interval to 60 seconds
nxapi nso presence --update-interval 60
# Fetch presence from a custom URL (see `nxapi nso http-server`)
nxapi nso presence --presence-url "http://[::1]:12345/api/znc/user/presence"
nxapi nso presence --presence-url "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence"
```
### Friend presence notifications
This uses node-notifier to display native desktop notifications.
```sh
# Show notifications for all friends
nxapi nso notify
# Show notifications for all friends + the current user
nxapi nso notify --user-notifications
# Show notifications for only the current user
nxapi nso notify --user-notifications --no-friend-notifications
# Set update interval to 60 seconds
nxapi nso notify --update-interval 60
```
### Friends
```sh
# Show Nintendo Switch friends in a table
nxapi nso friends
# JSON
nxapi nso friends --json
nxapi nso friends --json-pretty-print
```
### Friend codes and friend requests
```sh
# Get a URL that can be used to open your profile in the Nintendo Switch Online app and send a friend request
# This prints an object which includes your friend code and the URL (which contains your friend code)
nxapi nso friendcode
# JSON
nxapi nso friendcode --json
nxapi nso friendcode --json-pretty-print
# Look up a user using a friend code
nxapi nso lookup 0000-0000-0000
# JSON
nxapi nso lookup 0000-0000-0000 --json
nxapi nso lookup 0000-0000-0000 --json-pretty-print
# Send a friend request
nxapi nso add-friend 0000-0000-0000
```
### Nintendo Switch Online app announcements/alerts
```sh
# Show app announcements in a table
nxapi nso announcements
# JSON
nxapi nso announcements --json
nxapi nso announcements --json-pretty-print
```
### Web services/game-specific services
```sh
# Show web services in a table
nxapi nso webservices
# JSON
nxapi nso webservices --json
nxapi nso webservices --json-pretty-print
# Get an access token for a web service
# This should be sent with the first request to the web service URL in the `x-gamewebtoken` header
nxapi nso webservicetoken 5741031244955648
nxapi nso webservicetoken 5741031244955648 --json
nxapi nso webservicetoken 5741031244955648 --json-pretty-print
```
### API proxy server
Use this to access the Nintendo Switch Online app API from a browser/other HTTP client easily.
```sh
# Start the server listening on all interfaces on a random port
nxapi nso http-server
# Start the server listening on a specific address/port
# The `--listen` option can be used multiple times
nxapi nso http-server --listen "[::1]:12345"
# Use the API proxy server in other commands
nxapi nso ... --znc-proxy-url "http://[::1]:12345/api/znc"
ZNC_PROXY_URL=http://[::1]:12345/api/znc nxapi nso ...
# Start the server using another API proxy server
nxapi nso http-server --znc-proxy-url "http://[::1]:12345/api/znc"
ZNC_PROXY_URL=http://[::1]:12345/api/znc nxapi nso http-server
# Allow requests without a Nintendo Account session token
# Anyone connecting to the API proxy server will be able to use any already authenticated user with their Nintendo Account ID
# Don't set this if anyone can connect to the server!
nxapi nso http-server --listen "[::1]:12345" --no-require-token
# Limit the frequency of friends/announcements/web services requests to 60 seconds
nxapi nso http-server --update-interval 60
# Make API requests using curl
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/auth"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/announcements"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friends"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friends/presence"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friend/0123456789abcdef"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friendcode"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friendcode/0000-0000-0000"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/webservices"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/webservice/5741031244955648/token"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/activeevent"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/user"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/user/presence"
# Watch for changes to the user and all friends presence
curl --header "Authorization: na $NA_SESSION_TOKEN" --no-buffer "http://[::1]:12345/api/znc/presence/events"
# Make API requests using curl without a session token
# The `--no-require-token` must be set when running the server, and the user must have previously authenticated to the server, either with the API proxy server or using commands on the server
curl "http://[::1]:12345/api/znc/announcements?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friends?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friends/presence?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friend/0123456789abcdef?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friendcode?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friendcode/0000-0000-0000?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/webservices?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/webservice/5741031244955648/token?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/activeevent?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/user?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/user/presence?user=0123456789abcdef"
curl --no-buffer "http://[::1]:12345/api/znc/presence/events?user=0123456789abcdef"
```
SplatNet 2
---
All SplatNet 2 commands may automatically request a web service token. This will involve the splatnet2statink and flapg APIs (or a custom server). This can be disabled by setting `--no-auto-update-session`, however this will cause commands to fail if there isn't a valid SplatNet 2 token.
### User
```sh
# Show the authenticated SplatNet 2 user
nxapi splatnet2 user
```
### Download user records
```sh
# Download user records to the splatnet2 directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi splatnet2 dump-records
# Download user records to data/splatnet2
nxapi splatnet2 dump-records data/splatnet2
# Don't include user records (when downloading other data)
nxapi splatnet2 dump-records --no-user-records
# Include lifetime inkage challenge images
nxapi splatnet2 dump-records --challenges
# Include profile image (share button on the home page)
nxapi splatnet2 dump-records --profile-image
nxapi splatnet2 dump-records --profile-image --favourite-stage "Starfish Mainstage" --favourite-colour purple
# Download user records even if they already exist and haven't been updated
nxapi splatnet2 dump-records --no-new-records
# Include hero (Octo Canyon) records
# If this option is included hero records will always be downloaded even if they haven't been updated
nxapi splatnet2 dump-records --hero-records
# Only download hero records
nxapi splatnet2 dump-records --no-user-records --hero-records
# Include timeline (CPOD FM on the home page)
# If this option is included the timeline will always be downloaded even if it hasn't been updated
nxapi splatnet2 dump-records --timeline
# Only download the timeline
nxapi splatnet2 dump-records --no-user-records --timeline
```
### Download battle/Salmon Run results
```sh
# Download battle and Salmon Run results to the splatnet2 directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi splatnet2 dump-results
# Download battle and Salmon Run results to data/splatnet2
nxapi splatnet2 dump-results data/splatnet2
# Include battle summary image (share button on the battles list)
nxapi splatnet2 dump-results --battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi splatnet2 dump-results --battle-images
# Only download battle results
nxapi splatnet2 dump-results --no-coop
# Only download Salmon Run results
nxapi splatnet2 dump-results --no-battles
# Download summary data even if user records haven't been updated
# Individual battle results/images/Salmon Run results still won't be redownloaded if they exist
nxapi splatnet2 dump-results --no-check-updated
```
### Monitor SplatNet 2 for new user records/battle/Salmon Run results
This will constantly check SplatNet 2 for new data.
```sh
# Watch for new battle and Salmon Run results and download them to the splatnet2 directory in nxapi's data path
nxapi splatnet2 monitor
# Watch for new battle and Salmon Run results and download them to data/splatnet2
nxapi splatnet2 monitor data/splatnet2
# Include profile image (share button on the home page)
nxapi splatnet2 monitor --profile-image
nxapi splatnet2 monitor --profile-image --favourite-stage "Starfish Mainstage" --favourite-colour purple
# Include battle summary image (share button on the battles list)
nxapi splatnet2 monitor --battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi splatnet2 monitor --battle-images
# Only download battle results
nxapi splatnet2 monitor --no-coop
# Only download Salmon Run results
nxapi splatnet2 monitor --no-battles
# Set update interval to 1800 seconds (30 minutes)
nxapi splatnet2 monitor --update-interval 1800
```
SplatNet 2 monitoring can also be used with `nxapi nso notify` and `nxapi nso presence`. Data will only be downloaded from SplatNet 2 if the authenticated user is playing Splatoon 2 online.
This can be used with `nxapi nso presence --presence-url ...` (the presence URL must return the status of the user authenticating to SplatNet 2). When used with `--friend-nsaid` the friend's presence will be shared on Discord but the authenticated user's presence will still be used to check if SplatNet 2 data should be updated.
```sh
# Watch for new battle and Salmon Run results and download them to the splatnet2 directory in nxapi's data path
# All options support both the notify and presence commands
nxapi nso notify --splatnet2-monitor
nxapi nso presence --splatnet2-monitor
# Watch for new battle and Salmon Run results and download them to data/splatnet2
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-directory data/splatnet2
nxapi nso presence --splatnet2-monitor --sn2-path data/splatnet2
# Include profile image (share button on the home page)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-profile-image
nxapi nso presence --splatnet2-monitor --sn2-profile-image
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-profile-image --splatnet2-monitor-favourite-stage "Starfish Mainstage" --splatnet2-monitor-favourite-colour purple
nxapi nso presence --splatnet2-monitor --sn2-profile-image --sn2-favourite-stage "Starfish Mainstage" --sn2-favourite-colour purple
# Include battle summary image (share button on the battles list)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-battle-summary-image
nxapi nso presence --splatnet2-monitor --sn2-battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-battle-images
nxapi nso presence --splatnet2-monitor --sn2-battle-images
# Only download battle results
nxapi nso presence --splatnet2-monitor --no-splatnet2-monitor-coop
nxapi nso presence --splatnet2-monitor --no-sn2-coop
# Only download Salmon Run results
nxapi nso presence --splatnet2-monitor --no-splatnet2-monitor-battles
nxapi nso presence --splatnet2-monitor --no-sn2-battles
# Set update interval to 60 seconds
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-update-interval 60
nxapi nso presence --splatnet2-monitor --sn2-update-interval 60
```
NookLink
---
All NookLink commands may automatically request a web service token. This will involve the splatnet2statink and flapg APIs (or a custom server). This can be disabled by setting `--no-auto-update-session`, however this will cause commands to fail if there isn't a valid NookLink token.
### User
```sh
# Show NookLink users in a table
nxapi nooklink users
# Show the authenticated NookLink user
nxapi nooklink user
# Show the authenticated NookLink user's island and other players
nxapi nooklink island
# Use a specific NookLink user linked to the selected Nintendo Account
# If more than 1 NookLink users exist by default the first user will be used
nxapi nooklink user --islander 0x0123456789abcdef
# --user can also be used to select a different Nintendo Account
nxapi nooklink user --user 0123456789abcdef
nxapi nooklink user --user 0123456789abcdef --islander 0x0123456789abcdef
```
### Newspapers
```sh
# Show the latest newspaper issue in a table
nxapi nooklink newspaper
# JSON
nxapi nooklink newspaper --json
nxapi nooklink newspaper --json-pretty-print
# List newspaper issues in a table
nxapi nooklink newspapers
# JSON
nxapi nooklink newspapers --json
nxapi nooklink newspapers --json-pretty-print
# Show a specific newspaper issue in a table
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000
# JSON
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000 --json
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000 --json-pretty-print
```
### Download newspapers
```sh
# Download all island newspapers to the nooklink directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi nooklink dump-newspapers
# Download all island newspapers to data/nooklink
nxapi nooklink dump-newspapers data/nooklink
```
### Messages
```sh
# Send a message in an online Animal Crossing: New Horizons session
nxapi nooklink keyboard "Hello"
# Ask for a message interactively
nxapi nooklink keyboard
# List available reactions
nxapi nooklink reactions
# Send a reaction
nxapi nooklink post-reaction happyflower
```
Nintendo Switch Parental Controls
---
### Login to the Nintendo Switch Parental Controls app
```sh
# Interactive login
# Generates a link to login with a Nintendo Account, asks for the link then automatically gets a session token
nxapi pctl auth
# Login with an existing token
# Use with a token obtained via MITM the app, or with `nxapi pctl auth --no-auth`
# The same session token as for the Nintendo Switch Online app cannot be used
nxapi pctl token
# Get the authenticated user
nxapi pctl user
```
### Nintendo Switch consoles
```sh
# Show Nintendo Switch consoles in a table
nxapi pctl devices
# JSON
nxapi pctl devices --json
nxapi pctl devices --json-pretty-print
```
### Daily summaries
```sh
# Show daily summary data in a table
# Use `nxapi pctl devices` to get the device ID
nxapi pctl daily-summaries 0123456789abcdef
# JSON
nxapi pctl daily-summaries 0123456789abcdef --json
nxapi pctl daily-summaries 0123456789abcdef --json-pretty-print
```
### Monthly summaries
```sh
# Show monthly summaries in a table
# Use `nxapi pctl devices` to get the device ID
nxapi pctl monthly-summaries 0123456789abcdef
# JSON
nxapi pctl monthly-summaries 0123456789abcdef --json
nxapi pctl monthly-summaries 0123456789abcdef --json-pretty-print
# Show data for the February 2022 monthly summary in a table
nxapi pctl monthly-summary 0123456789abcdef 2022-02
# JSON
nxapi pctl monthly-summary 0123456789abcdef 2022-02 --json
nxapi pctl monthly-summary 0123456789abcdef 2022-02 --json-pretty-print
```
### Download summary data
```sh
# Download all daily and monthly summary data from all devices to the summaries directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi pctl dump-summaries
# Download all daily and monthly summary data from all devices to data/summaries
nxapi pctl dump-summaries data/summaries
# Download all daily and monthly summary data from a specific device
# Use `nxapi pctl devices` to get the device ID
# The `--device` option can be used multiple times
nxapi pctl dump-summaries --device 0123456789abcdef
```
Misc. commands/options
---
### Users
```sh
# Show all known Nintendo Accounts in a table
# This will only show cached data and does not make any requests to Nintendo servers
nxapi users list
# Use a specific user in a command
nxapi ... --user 0123456789abcdef
nxapi ... --token $NA_SESSION_TOKEN
# Set the default user for commands
nxapi users set 0123456789abcdef
# Remove all data for a user
nxapi users forget 0123456789abcdef
```
### Electron app
When installing nxapi from source the app can be run using this command:
```sh
nxapi app
```
This command has no options, but environment variables can still be used.
### znca API server
A server for controlling the Nintendo Switch Online app on an Android device/emulator using Frida can be used instead of the splatnet2statink and flapg APIs.
This requires:
- adb is installed on the computer running nxapi
- The Android device is running adbd as root or a su-like command can be used to escalate to root
- The frida-server executable is located at `/data/local/tmp/frida-server` on the Android device
- The Nintendo Switch Online app is installed on the Android device
The Android device must be constantly reachable using ADB. The server will exit if the device is unreachable.
```sh
# Start the server using the ADB server "android.local:5555" listening on all interfaces on a random port
nxapi android-znca-api-server-frida android.local:5555
# Start the server listening on a specific address/port
# The `--listen` option can be used multiple times
nxapi android-znca-api-server-frida android.local:5555 --listen "[::1]:12345"
# Use a command to escalate to root to start frida-server and the Nintendo Switch Online app
# "{cmd}" will be replaced with the path to a temporary script in double quotes
nxapi android-znca-api-server-frida android.local:5555 --exec-command "/system/bin/su -c {cmd}"
# Specify a different location to the frida-server executable
nxapi android-znca-api-server-frida android.local:5555 --frida-server-path "/data/local/tmp/frida-server-15.1.17-android-arm"
# Make API requests using curl
curl --header "Content-Type: application/json" --data '{"type": "nso", "token": "...", "timestamp": "...", "uuid": "..."}' "http://[::1]:12345/api/znca/f"
# Use the znca API server in other commands
# This should be set when running any nso commands as the access token will be refreshed automatically when it expires
ZNCA_API_URL=http://[::1]:12345/api/znca nxapi nso ...
```

93
docs/lib/coral.md Normal file
View File

@@ -0,0 +1,93 @@
`nxapi/coral`
---
Using this module requires sending an authentication token (as a JSON Web Token, containing account identifiers itself) to third-party APIs. If you use this module in your own project, you must read https://github.com/frozenpandaman/splatnet2statink/wiki/api-docs and https://github.com/JoneWang/imink/wiki/imink-API-Documentation if you intend to share anything you create, and explain this to your users and provide a link to the [Coral client authentication](../../README.md#coral-client-authentication) section of nxapi's README. Do not contact any service without the user's informed consent.
### `CoralApi`
> This is exported as `default`.
Coral API client. An instance of this class should not be created directly; instead one of the `createWith*` static methods should be used.
Most of this API is intentionally undocumented. Read the source code at [src/api/coral.ts](../../src/api/coral.ts), [src/common/auth/coral.ts](../../src/common/auth/coral.ts) and [src/cli/nso](../../src/cli/nso) for examples of using this API. If you need any help using this API ask in [#coral](https://discordapp.com/channels/998657768594608138/998662583433318440) on Discord.
You should review HTTP captures of the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app. For example, when opening the app it will fetch announcements, friends, web services and the active event; your project should match this.
#### `CoralApi.createWithSessionToken`
Authenticate to the Coral API using a Nintendo Account session token.
> This function should not be called often. If your project will create a new CoralApi object again for the same user before the Coral authentication token expires (usually after two hours), you must store the `data` object this returns and use `CoralApi.createWithSavedToken`.
```ts
import CoralApi, { CoralAuthData } from 'nxapi/coral';
const na_session_token: string;
const {nso, data} = await CoralApi.createWithSessionToken(na_session_token);
// nso instanceof CoralApi
// data is a plain object of type CoralAuthData
// data should be saved and reused
```
#### `CoralApi.createWithSavedToken`
Create a CoralApi instance using cached data from `CoralApi.createWithSessionToken` or `CoralApi.loginWithSessionToken`.
```ts
import CoralApi, { CoralAuthData } from 'nxapi/coral';
const auth_data: CoralAuthData;
const coral = CoralApi.createWithSavedToken(auth_data);
// coral instanceof CoralApi
```
#### `CoralApi.renewToken`
Renew the Coral authentication token. This should be called if any API requests throw a token expired error. This updates the token of the `CoralApi` object and returns a partial `CoralAuthData` object, that should replace properties of the object passed to `CoralApi.createWithSavedToken`.
> This function should not be called often. You must store the object this returns (replacing properties of the previous `CoralAuthData` object).
```ts
import CoralApi, { CoralAuthData, PartialCoralAuthData } from 'nxapi/coral';
const coral: CoralApi;
const auth_data: CoralAuthData;
const data = await coral.renewToken(auth_data);
// data is a plain object of type PartialCoralAuthData
const new_auth_data = Object.assign({}, auth_data, data);
// new_auth_data is a plain object of type CoralAuthData
// new_auth_data should be saved and reused
```
### `ZncProxyApi`
nxapi API proxy server client. Instances of this class are generally compatible with `CoralApi`; nxapi's command line interface and Electron apps internally use either depending on whether the API proxy is enabled.
The API proxy will cache data and will request certain data together to match Nintendo's app, however you should still try to only make requests that would match the behaviour of Nintendo's app as with `CoralApi`.
#### `new ZncProxyApi`
Create a `ZncProxyApi` instance with a Nintendo Account session token.
Because the API proxy server handles Nintendo Account authentication, you do not need to store any data to reuse later, and should call the constructor directly instead of using a helper function.
```ts
import { ZncProxyApi } from 'nxapi/coral';
const znc_proxy_url: string;
const na_session_token: string;
const coral = new ZncProxyApi(znc_proxy_url, na_session_token);
```
### API types
`nxapi/coral` exports all API types from [src/api/coral-types.ts](../../src/api/coral-types.ts).
### Coral client authentication
`nxapi/coral` exports it's API library and types for various APIs used for generating `f` tokens used to authenticate to the Coral API. These functions should generally not be required as they are used by nxapi internally.

114
docs/lib/index.md Normal file
View File

@@ -0,0 +1,114 @@
Usage as a JavaScript library
---
nxapi exports it's API library and types. nxapi is split into several modules that can be imported separately.
> You must set a user agent string using the `addUserAgent` function when using anything that contacts non-Nintendo APIs, such as the splatnet2statink API.
> Please read https://github.com/frozenpandaman/splatnet2statink/wiki/api-docs and https://github.com/JoneWang/imink/wiki/imink-API-Documentation if you intend to share anything you create.
> By default nxapi will fetch certain settings, mostly version numbers to report to Nintendo, from my server. This can be disabled using environment variables.
> nxapi uses native ECMAScript modules. nxapi also uses features like top-level await, so it cannot be converted to CommonJS using Rollup or similar. If you need to use nxapi from CommonJS modules or other module systems, use a [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import).
> If you need any help using nxapi as a library [join the Discord server](https://discord.com/invite/4D82rFkXRv) or [create a discussion](https://github.com/samuelthomas2774/nxapi/discussions/new).
### Install
nxapi should be installed as a project dependency rather than a globally installed package. TypeScript definitions are included as do not need to be installed separately.
```sh
# From registry.npmjs.com
npm install nxapi
# From gitlab.fancy.org.uk
npm install --registry https://gitlab.fancy.org.uk/api/v4/packages/npm/ @samuel/nxapi
# From npm.pkg.github.com
npm install --registry https://npm.pkg.github.com @samuelthomas2774/nxapi
# From gitlab.com
npm install --registry https://gitlab.com/api/v4/packages/npm/ @samuelthomas2774/nxapi
```
### `nxapi`
This module contains some generic utility functions and types.
#### `getTitleIdFromEcUrl`
This function takes a https://ec.nintendo.com/apps/... URL (provided by some Nintendo APIs) and returns the title ID in the URL. `null` is returned if the URL is not a valid Nintendo eShop URL containing a title ID.
```ts
import { getTitleIdFromEcUrl } from 'nxapi';
const title_id = getTitleIdFromEcUrl('https://ec.nintendo.com/apps/0100f8f0000a2000/GB?lang=en-GB');
// title_id === '0100f8f0000a2000'
```
If you are using Nintendo eShop links but do not know the user's Nintendo eShop region, you may use nxapi's Nintendo eShop region selection page.
> https://fancy.org.uk/api/nxapi/title/0100f8f0000a2000/redirect
Please set an appropriate `source` query string parameter containing your project's name and version if you generate these links automatically.
> https://fancy.org.uk/api/nxapi/title/0100f8f0000a2000/redirect?source=myproject-1.0.0
#### `ErrorResponse`
An instance of this class is thrown when an invalid or failure response is received. This class extends from `Error`.
Note that this is only used when the HTTP response is received correctly (including for non-2xx status codes). If a request fails due to a network error or another reason node-fetch will throw a different error.
```ts
import { ErrorResponse } from 'nxapi';
try {
// ...
} catch (err) {
if (err instanceof ErrorResponse) {
// err.body is the response data as a string
// err.data is the decoded JSON response data, or undefined if JSON decoding fails
// err.response is the Response object from node-fetch
// err.name, err.message and err.stack are inherited from Error
}
}
```
#### `addUserAgent`
This function is used to set the user agent string to use for non-Nintendo API requests. Any project using nxapi (including as a dependency of another project) must call this function with an appropriate user agent string segment. See [user agent strings](../../README.md#user-agent-strings).
#### `version`
nxapi's version number.
```ts
import { version } from 'nxapi';
// version === '1.3.0'
```
### `nxapi/coral`
This module exports the Coral (Nintendo Switch Online app) API library and types.
[See docs/lib/coral.md.](coral.md)
### `nxapi/moon`
This module exports the Moon (Nintendo Switch Parental Controls app) API library and types.
[See docs/lib/moon.md.](moon.md)
### `nxapi/splatnet2`
This module exports the SplatNet 2 API library and types, as well as functions for calculating X Rank seasons, as this is done by the SplatNet 2 web app, not the API.
[See docs/lib/splatnet2.md.](splatnet2.md)
### `nxapi/nooklink`
This module exports the NookLink API library and types.
[See docs/lib/nooklink.md.](nooklink.md)

61
docs/lib/moon.md Normal file
View File

@@ -0,0 +1,61 @@
`nxapi/moon`
---
### `MoonApi`
> This is exported as `default`.
Moon API client. An instance of this class should not be created directly; instead one of the `createWith*` static methods should be used.
Most of this API is intentionally undocumented. Read the source code at [src/api/moon.ts](../../src/api/moon.ts), [src/common/auth/moon.ts](../../src/common/auth/moon.ts) and [src/cli/pctl](../../src/cli/pctl) for examples of using this API. If you need any help using this API ask in [#moon](https://discordapp.com/channels/998657768594608138/998662782163628082) on Discord.
You should review HTTP captures of the Nintendo Switch Parental Controls app and attempt to match the behaviour of Nintendo's official app.
#### `MoonApi.createWithSessionToken`
Authenticate to the Moon API using a Nintendo Account session token.
> This function should not be called often. If your project will create a new MoonApi object again for the same user before the Moon authentication token expires (usually after 15 minutes), you must store the `data` object this returns and use `MoonApi.createWithSavedToken`.
```ts
import MoonApi, { MoonAuthData } from 'nxapi/moon';
const na_session_token: string;
const {moon, data} = await MoonApi.createWithSessionToken(na_session_token);
// moon instanceof MoonApi
// data is a plain object of type MoonAuthData
// data should be saved and reused
```
#### `MoonApi.createWithSavedToken`
Create a MoonApi instance using cached data from `MoonApi.createWithSessionToken` or `MoonApi.loginWithSessionToken`.
```ts
import MoonApi, { MoonAuthData } from 'nxapi/moon';
const auth_data: MoonAuthData;
const moon = MoonApi.createWithSavedToken(auth_data);
// moon instanceof MoonApi
```
#### `MoonApi.renewToken`
Renew the Moon authentication token. This should be called if any API requests throw a token expired error. This updates the token of the `MoonApi` object and returns a new `MoonAuthData` object.
```ts
import MoonApi, { MoonAuthData } from 'nxapi/moon';
const moon: MoonApi;
const na_session_token: string;
const data = await moon.renewToken(na_session_token);
// data is a plain object of type MoonAuthData
// data should be saved and reused
```
### API types
`nxapi/moon` exports all API types from [src/api/moon-types.ts](../../src/api/moon-types.ts).

115
docs/lib/nooklink.md Normal file
View File

@@ -0,0 +1,115 @@
`nxapi/nooklink`
---
NookLink is more complex that SplatNet 2 as it supports multiple users linked to the same network account.
- `NooklinkApi` is used at NSA-level, and is solely used to list available NookLink users and authenticate to NookLink at ACNH-level.
- `NooklinkUserApi` is used at ACNH-level, and is used to perform all other actions in the NookLink web app.
### `NooklinkApi`
> This is exported as `default`.
NookLink NSA-level API client. An instance of this class should not be created directly; instead one of the `createWith*` static methods should be used.
Most of this API is intentionally undocumented. Read the source code at [src/api/nooklink.ts](../../src/api/nooklink.ts), [src/common/auth/nooklink.ts](../../src/common/auth/nooklink.ts) and [src/cli/nooklink](../../src/cli/nooklink) for examples of using this API. If you need any help using this API ask in [#nooklink](https://discordapp.com/channels/998657768594608138/998664335062741032) on Discord.
You should review HTTP captures of NookLink in the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app.
#### `NooklinkApi.createWithCoral`
Authenticate to NookLink using a `CoralApi` instance.
> This function should not be called often. If your project will create a new NooklinkApi object again for the same user before the NookLink authentication token expires (usually after two hours), you must store the `data` object this returns and use `NooklinkApi.createWithSavedToken`.
```ts
import CoralApi, { CoralAuthData } from 'nxapi/coral';
import NooklinkApi, { NooklinkAuthData } from 'nxapi/nooklink';
const coral: CoralApi;
const coral_auth_data: CoralAuthData;
const {nooklink, data} = await NooklinkApi.createWithCoral(coral, coral_auth_data.user);
// nooklink instanceof NooklinkApi
// data is a plain object of type NooklinkAuthData
// data should be saved and reused
```
#### `NooklinkApi.createWithSavedToken`
Create a NooklinkApi instance using cached data from `NooklinkApi.createWithCoral` or `NooklinkApi.loginWithCoral`.
```ts
import NooklinkApi, { NooklinkAuthData } from 'nxapi/nooklink';
const auth_data: NooklinkAuthData;
const nooklink = NooklinkApi.createWithSavedToken(auth_data);
// nooklink instanceof NooklinkApi
```
#### `NooklinkApi.getUsers`
Retrieves a list of available NookLink-enabled users.
```ts
import NooklinkApi, { Users } from 'nxapi/nooklink';
const nooklink: Nooklink;
const users = await nooklink.getUsers();
// users is a plain object of type Users
```
#### `NooklinkApi.createUserClient`
Authenticate to NookLink and create a NooklinkUser instance.
```ts
import NooklinkApi, { NooklinkUserApi, NooklinkUserAuthData } from 'nxapi/nooklink';
const nooklink: Nooklink;
const user_id: string;
const {nooklinkuser, data} = await nooklink.createUserClient(user_id);
// nooklinkuser instanceof NooklinkUserApi
// data is a plain object of type NooklinkUserAuthData
```
### `NooklinkUserApi`
NookLink ACNH-level API client. An instance of this class should not be created directly; instead `NooklinkApi.createUserClient` or one of the `createWith*` static methods should be used.
Most of this API is intentionally undocumented. Read the source code at [src/api/nooklink.ts](../../src/api/nooklink.ts), [src/common/auth/nooklink.ts](../../src/common/auth/nooklink.ts) and [src/cli/nooklink](../../src/cli/nooklink) for examples of using this API. If you need any help using this API ask in [#nooklink](https://discordapp.com/channels/998657768594608138/998664335062741032) on Discord.
You should review HTTP captures of NookLink in the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app.
#### `NooklinkUserApi.createWithSavedToken`
Create a NooklinkUserApi instance using cached data from `NooklinkApi.createUserClient`.
```ts
import { NooklinkUserApi, NooklinkUserAuthData } from 'nxapi/nooklink';
const auth_data: NooklinkAuthData;
const nooklinkuser = NooklinkUserApi.createWithSavedToken(auth_data);
// nooklinkuser instanceof NooklinkApi
```
#### `NooklinkUserApi.createWithCliTokenData`
Create a NooklinkUserApi instance using the output of the `nxapi nooklink user-token --json` command.
```ts
import { NooklinkUserApi, NooklinkUserCliTokenData } from 'nxapi/nooklink';
const data: NooklinkUserCliTokenData;
const nooklinkuser = NooklinkUserApi.createWithCliTokenData(data);
// nooklinkuser instanceof NooklinkUserApi
```
### API types
`nxapi/nooklink` exports all API types from [src/api/nooklink-types.ts](../../src/api/nooklink-types.ts).

179
docs/lib/splatnet2.md Normal file
View File

@@ -0,0 +1,179 @@
`nxapi/splatnet2`
---
### `SplatNet2Api`
> This is exported as `default`.
SplatNet 2 API client. An instance of this class should not be created directly; instead one of the `createWith*` static methods should be used.
Most of this API is intentionally undocumented. Read the source code at [src/api/splatnet2.ts](../../src/api/splatnet2.ts), [src/common/auth/splatnet2.ts](../../src/common/auth/splatnet2.ts) and [src/cli/splatnet2](../../src/cli/splatnet2) for examples of using this API. If you need any help using this API ask in [#splatnet2](https://discordapp.com/channels/998657768594608138/998663658781552670) on Discord.
You should review HTTP captures of SplatNet 2 in the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app.
#### `SplatNet2Api.createWithCoral`
Authenticate to SplatNet 2 using a `CoralApi` instance.
> This function should not be called often. If your project will create a new SplatNet2Api object again for the same user before the SplatNet 2 session expires (usually 24 hours after last use), you must store the `data` object this returns and use `SplatNet2Api.createWithSavedToken`.
```ts
import CoralApi, { CoralAuthData } from 'nxapi/coral';
import SplatNet2Api, { SplatNet2AuthData } from 'nxapi/splatnet2';
const coral: CoralApi;
const coral_auth_data: CoralAuthData;
const {splatnet, data} = await SplatNet2Api.createWithCoral(coral, coral_auth_data.user);
// splatnet instanceof SplatNet2Api
// data is a plain object of type SplatNet2AuthData
// data should be saved and reused
```
#### `SplatNet2Api.createWithSavedToken`
Create a SplatNet2Api instance using cached data from `SplatNet2Api.createWithCoral` or `SplatNet2Api.loginWithCoral`.
```ts
import SplatNet2Api, { SplatNet2AuthData } from 'nxapi/splatnet2';
const auth_data: SplatNet2AuthData;
const splatnet = SplatNet2Api.createWithSavedToken(auth_data);
// splatnet instanceof SplatNet2Api
```
#### `SplatNet2Api.createWithCliTokenData`
Create a SplatNet2Api instance using the output of the `nxapi splatnet2 token --json` command.
```ts
import SplatNet2Api, { SplatNet2CliTokenData } from 'nxapi/splatnet2';
const data: SplatNet2CliTokenData;
const splatnet = SplatNet2Api.createWithCliTokenData(data);
// splatnet instanceof SplatNet2Api
```
#### `SplatNet2Api.createWithIksmSession`
Create a SplatNet2Api instance with an `iksm_session` and `unique_id` value.
> `SplatNet2Api.createWithCoral`/`SplatNet2Api.createWithSavedToken` or `SplatNet2Api.createWithCliTokenData` should be preferred over this as they are better able to match SplatNet 2's behaviour.
```ts
import SplatNet2Api from 'nxapi/splatnet2';
const iksm_session: string;
const unique_id: string;
const splatnet = SplatNet2Api.createWithIksmSession(iksm_session, unique_id);
// splatnet instanceof SplatNet2Api
```
### API types
`nxapi/splatnet2` exports all API types from [src/api/splatnet2-types.ts](../../src/api/splatnet2-types.ts).
### `toLeagueId`
Converts a `Date` and `LeagueType` to a string used in league ranking requests (`/league_match_ranking/{id}/{region}` or `SplatNet2Api.getLeagueMatchRanking`).
This function does not usually need to be used with `SplatNet2Api.getLeagueMatchRanking`, as a `Date` and `LeagueType` can be passed directly to it.
```ts
import { LeagueType, toLeagueId } from 'nxapi/splatnet2';
const league_id = toLeagueId(new Date(Date.UTC(2022, 0, 1, 0)), LeagueType.TEAM);
// league_id === '22010100T'
```
### `toXRankSeasonId`
Converts a year and month to a string used in X Rank leaderboard requests (`/league_match_ranking/{id}/{region}` or `SplatNet2Api.getLeagueMatchRanking`).
Months in this function start from 1, instead of 0 like `Date`s.
This function does not usually need to be used with `SplatNet2Api.getLeagueMatchRanking`, as a `Date` and `LeagueType` can be passed directly to it.
```ts
import { toXRankSeasonId } from 'nxapi/splatnet2';
const season_id = toXRankSeasonId(2022, 1);
// season_id === '220101T00_220201T00'
```
### `getXRankSeasons`
Returns a generator that yields all X Rank seasons up to the current season according to the system date.
By default this will start from the current season and continue to the first season. Setting the first argument to `true` will cause this function to start from the first season and continue to the current season.
```ts
import { getXRankSeasons, XRankSeason } from 'nxapi/splatnet2';
for (const season of getXRankSeasons()) {
// season is a plain object of type XRankSeason
}
```
### `getXRankSeason`
Returns an `XRankSeason` object from a `Date`, year and month, or season ID string.
```ts
import { getXRankSeason, XRankSeason } from 'nxapi/splatnet2';
const season = getXRankSeason(2022, 1);
// season is a plain object of type XRankSeason
// season.id === '220101T00_220201T00'
// season.key === '2022_01'
// season.start is a Date object with the UTC timestamp 2022-01-01 00:00:00
// season.end is a Date object with the UTC timestamp 2022-02-01 00:00:00
// season.complete === true, assuming the system time is after 2022-02-01 00:00:00 (UTC)
// This function can also be called like this:
const season = getXRankSeason(new Date(Date.UTC(2022, 1)));
const season = getXRankSeason('220101T00_220201T00');
```
### `getNextXRankSeason`
Returns an `XRankSeason` object for the season following an X Rank season from an `XRankSeason`, `Date`, year and month, or season ID string.
```ts
import { getNextXRankSeason, XRankSeason } from 'nxapi/splatnet2';
const season = getNextXRankSeason(2022, 1);
// season is a plain object of type XRankSeason
// season.id === '220201T00_220301T00'
// season.key === '2022_02'
// season.start is a Date object with the UTC timestamp 2022-02-01 00:00:00
// season.end is a Date object with the UTC timestamp 2022-03-01 00:00:00
// season.complete === true, assuming the system time is after 2022-03-01 00:00:00 (UTC)
// This function can also be called like this:
const season = getNextXRankSeason(new Date(Date.UTC(2022, 1)));
const season = getNextXRankSeason('220101T00_220201T00');
```
### `getPreviousXRankSeason`
Returns an `XRankSeason` object for the season following an X Rank season from an `XRankSeason`, `Date`, year and month, or season ID string.
```ts
import { getNextXRankSeason, XRankSeason } from 'nxapi/splatnet2';
const season = getPreviousXRankSeason(2022, 1);
// season is a plain object of type XRankSeason
// season.id === '211201T00_220101T00'
// season.key === '2021_12'
// season.start is a Date object with the UTC timestamp 2021-12-01 00:00:00
// season.end is a Date object with the UTC timestamp 2022-01-01 00:00:00
// season.complete === true, assuming the system time is after 2022-01-01 00:00:00 (UTC)
// This function can also be called like this:
const season = getPreviousXRankSeason(new Date(Date.UTC(2022, 1)));
const season = getPreviousXRankSeason('220101T00_220201T00');
```