liveops

package
v0.4.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 54 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package liveops is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package liveops holds provider-agnostic live operations primitives for NSGo games: crash reports, consent-gated analytics, a cloud-save sync interface, in-app purchases credited into the save, local re-engagement reminders, store review prompt policies, and share cards and payload-carrying invites. It links no third-party analytics, crash-reporting, ad, push or payment SDKs.

Scope (#194)

In scope for the core game module:

  • Crash reports (#195): panic recovery around game.Loop and arbitrary callbacks, with a fixed-size step ring buffer, stack trace, metadata and an optional state snapshot handed to the app's reporter.
  • Analytics (#198): a provider-agnostic, strictly opt-in event API whose consent state persists in core.Storage, durable offline-queued BatchProvider (#1646), and consent-gated LoadFunnel (#1487) recording page-open through first-playable stages. Zero events are sent or buffered before explicit ConsentGranted.
  • Privacy, age gate and parental gate (#1647, #1648): shared per-purpose Consent records, fail-closed AgeGate with regional digital-consent ages, ForceChildMode, platform age-signal hook, ChildMode gating across Consent/BatchProvider/CrashReporter/Account, and ParentalGate enforcement for Purchases.Buy/BuyOffer and OpenURL.
  • Accounts (#1653): Account over core.Secrets (platform keychain / Android Keystore) and accounts.Service, with optional AutoGuest on first Token call, single-flight token refresh with RefreshMargin, Sign in with Apple and mini-program sign-in and linking, Apple credential revocation watching (AppleCredentialRevoked), typed AccountConflict resolution (KeepCurrent / SwitchToExisting), reactive ProfileSignal/CurrentProfile/SignedIn signals for UI, and OnSignedOut callbacks.
  • Cloud saves (#196): the provider-agnostic CloudSync interface, PlatformCloud over NSGo's cloud package (iCloud on macOS/iOS, Google Play Games Saved Games on Android, and the in-memory store in nsgotest), DirCloud for Steam Auto-Cloud and other directory-synced stores, CloudClient (#557) for the self-hosted cloudsave service, and CloudSyncer (#539), which detects slots changed on two devices and resolves them by policy without silently losing either copy.
  • In-app purchases (#369): Purchases over NSGo's purchase services, which credits consumables into the save exactly once through a Ledger saved with them, keeps unlocks and subscriptions from the store's entitlements, restores them, follows purchases waiting for approval and hands transactions to an optional server before delivering them.
  • Local reminders (#1310): Reminders over NSGo's core.Scope.ShowNotification, declared in versioned YAML (RemindersConfig), asking permission only on first Schedule or explicit RequestPermission, honoring a persisted player setting and local-time QuietHours, and cancelling or rescheduling active reminders when the app comes to the front.
  • Store review prompts (#1767): ReviewPrompt over core.Storage and core.Scope.RequestReview, gating in-app rating prompts on minimum sessions, days since first launch, positive moments, cooldown and once-per-version rules, suppressing prompts after negative moments, and failing closed on corrupt state or unsupported platforms.
  • Share cards and invites (#1738): Invites over a small ShareHost interface (PlatformShareHost for mobile, desktop and web via core.Scope.Share, core.Scope.OnOpenLinks and core.Scope.AppURL, plus MiniGameShareHost ready for NSGo's mini-game share cards in nsgo-dev/nsgo#2672), with bounded canonical key=value payloads, optional HMAC-SHA256 signing and verification, at-most-once cold-launch and warm-resume delivery, and a 5:4 frame snapshot helper.
  • Mini-game ads (#1739): Ads over a small AdHost interface, reporting a reward only for a rewarded video watched to the end and at most once per show, no-fill and failure results, one ad at a time, an interstitial per-session cap, minimum interval and Disabled predicate, banners shown until HideBanner, and Pause and ResetInput hooks around each show. MiniGameAdHost drives WeChat and Douyin ad objects through a MiniGameAdDriver, which NSGo will provide with its mini-game ad API (nsgo-dev/nsgo#2672).
  • Web portal SDKs (#1766): Portal and NewPortal over hostbridge.Bridge (#1486) and input.Actions, binding Poki (PokiSDK) and CrazyGames SDK v3 (CrazyGames.SDK) on js/wasm with automatic script loading, game.yaml or page-host provider selection, loading/gameplay lifecycle forwarding, CrazyGames muteAudio handling, non-overlapping commercial and rewarded breaks that pause, mute and reset input before calling the SDK and recover after timeout, and a no-op PortalNone off the web.
  • News, player inbox and redeemable codes (#1644): News fetches GET /v1/news with ETag conditional requests, caches to the data directory or core.Storage and tracks read state; InboxClient lists, marks read and claims player inbox attachments and redeems gift and promo codes against pkg/online/liveops/inbox.

Pending upstream:

  • Remote push (#1310): a thin Push wrapper for device-token registration and remote payload routing waits on NSGo shipping remote push (nsgo-dev/nsgo#59) and settling its design decisions (nsgo-dev/nsgo#1323). Until then, remote push is unavailable everywhere.

Out of scope for the core game module:

  • Native ad SDKs (#199): ad networks (AdMob, AppLovin and similar) require proprietary native SDKs with store-policy and privacy obligations that do not belong in the core game layer. Games that use them embed native SDK views directly through NSGo.

Index

Examples

Constants

View Source
const (
	// DefaultAgeGateKey is the storage key used by AgeGate when no key is provided.
	DefaultAgeGateKey = consent.DefaultAgeGateKey
	// AgeRecordVersion is the schema version stored in the JSON age-gate record.
	AgeRecordVersion = 1
	// DefaultConsentAge is the US COPPA / UK baseline digital-consent age (13).
	DefaultConsentAge = consent.DefaultConsentAge
	// DefaultMinorAge is the conservative age threshold (18, requiring Adult) used when no
	// explicit ConsentAge or known Region is configured.
	DefaultMinorAge = consent.DefaultMinorAge
)
View Source
const (
	// Under13 is the band for players under 13 years old.
	Under13 = consent.Under13
	// Age13To15 is the band for players aged 13 through 15.
	Age13To15 = consent.Age13To15
	// Age16To17 is the band for players aged 16 through 17.
	Age16To17 = consent.Age16To17
	// Adult is the band for players aged 18 or older.
	Adult = consent.Adult
)
View Source
const (
	// PlatformAgeSignalNone indicates no platform age signal source.
	PlatformAgeSignalNone = consent.PlatformAgeSignalNone
	// PlatformAgeSignalApple identifies Apple's Declared Age Range API.
	PlatformAgeSignalApple = consent.PlatformAgeSignalApple
	// PlatformAgeSignalGooglePlay identifies Google Play's Age Signals API.
	PlatformAgeSignalGooglePlay = consent.PlatformAgeSignalGooglePlay
	// PlatformAgeSignalCustom identifies a custom host-provided age signal.
	PlatformAgeSignalCustom = consent.PlatformAgeSignalCustom
)
View Source
const (
	DefaultBatchMaxBytes       = 1 << 20 // 1 MiB
	DefaultBatchMaxAge         = 7 * 24 * time.Hour
	DefaultBatchMaxEvents      = 100
	DefaultBatchQueueBuffer    = 256
	DefaultBatchFlushInterval  = 30 * time.Second
	DefaultBatchInitialBackoff = 1 * time.Second
	DefaultBatchMaxBackoff     = 5 * time.Minute
	DefaultBatchJitterFraction = 0.25
	DefaultSessionTimeout      = 30 * time.Minute
)

Default limits and timings for BatchOptions.

View Source
const (
	// ConsentSourcePrompt records a choice made on the first-launch or policy-update prompt.
	ConsentSourcePrompt = consent.ConsentSourcePrompt
	// ConsentSourceSettings records a choice changed from the in-game privacy settings screen.
	ConsentSourceSettings = consent.ConsentSourceSettings
	// ConsentSourceDefault records a choice applied by a default or regional preset.
	ConsentSourceDefault = consent.ConsentSourceDefault
	// ConsentSourceGPC records an opt-out honoured from a browser Global Privacy Control signal.
	ConsentSourceGPC = consent.ConsentSourceGPC
	// ConsentSourceMigration records a choice migrated from a legacy Analytics consent key.
	ConsentSourceMigration = consent.ConsentSourceMigration
)

Standard consent record sources recorded in ConsentRecord.Source.

View Source
const (
	// DefaultMaxInvitePayloadBytes is the default maximum byte length of an encoded invite query string.
	// It fits comfortably within mini-game share query limits (such as WeChat's shareAppMessage query) as well as mobile deep-link and web URLs.
	DefaultMaxInvitePayloadBytes = 1024

	// MaxInvitePayloadKeys bounds the number of key-value pairs in a single invite payload (excluding the optional signature field).
	MaxInvitePayloadKeys = 32

	// MaxInviteKeyBytes bounds the length of an individual invite payload key in bytes.
	MaxInviteKeyBytes = 64

	// MaxInviteSignatureBytes bounds the length of an encoded signature field in bytes.
	MaxInviteSignatureBytes = 128

	// InviteIDKey is the standard payload key carrying the unique invite identifier used as a server reward-grant idempotency key.
	InviteIDKey = "id"

	// InviteSigKey is the reserved payload key carrying the optional base64url raw HMAC-SHA256 signature.
	InviteSigKey = "sig"
)
View Source
const (
	// CardSnapshotAspectWidth and CardSnapshotAspectHeight define the 5:4 aspect ratio used by mini-game share cards.
	CardSnapshotAspectWidth  = 5
	CardSnapshotAspectHeight = 4

	// DefaultCardSnapshotWidth and DefaultCardSnapshotHeight are the default 5:4 share-card snapshot dimensions in pixels.
	DefaultCardSnapshotWidth  = 500
	DefaultCardSnapshotHeight = 400
)
View Source
const (
	// LoadStagePageOpen marks navigation start (0 ms on the web).
	LoadStagePageOpen = "page_open"
	// LoadStageDownloadStart marks when the loader starts fetching the Wasm module.
	LoadStageDownloadStart = "download_start"
	// LoadStageDownloadEnd marks when the Wasm module finishes downloading.
	LoadStageDownloadEnd = "download_end"
	// LoadStageCompileEnd marks when WebAssembly compilation and instantiation finish.
	LoadStageCompileEnd = "compile_end"
	// LoadStageGoStart marks when Go package initialization starts running.
	LoadStageGoStart = "go_start"
	// LoadStageFirstUpdate marks the first completed game.Loop.Update callback.
	LoadStageFirstUpdate = "first_update"
	// LoadStageFirstFrame marks the first completed rendered frame (game.Loop.Draw).
	LoadStageFirstFrame = "first_frame"
	// LoadStageFirstAssetGroup marks when the first assets.Group finishes loading.
	LoadStageFirstAssetGroup = "first_asset_group"
	// LoadStagePlayable marks when the game first accepts player input.
	LoadStagePlayable = "playable"
)

Canonical load funnel stage names in expected chronological order from page open through module download and Go startup to first playable.

View Source
const (
	// DefaultReviewPromptKey is the core.Storage key under which ReviewPrompt persists its versioned JSON state when ReviewPromptOptions.StorageKey is empty.
	DefaultReviewPromptKey = "liveops.review_prompt"

	// ReviewPromptStateVersion is the schema version of the JSON state persisted by ReviewPrompt.
	ReviewPromptStateVersion = 1

	// DefaultReviewMinSessions is the default minimum number of sessions before MaybeAsk may request a review.
	DefaultReviewMinSessions = 3

	// DefaultReviewMinDays is the default minimum number of days since first launch before MaybeAsk may request a review.
	DefaultReviewMinDays = 3

	// DefaultReviewMinPositiveMoments is the default minimum number of positive moments in the current app version before MaybeAsk may request a review.
	DefaultReviewMinPositiveMoments = 3

	// DefaultReviewCooldown is the default minimum duration between review requests across app versions.
	// 122 days ensures at most three prompts in any rolling 365-day window, staying within Apple's StoreKit limit.
	DefaultReviewCooldown = 122 * 24 * time.Hour
)
View Source
const AdsSchemaURL = "https://nsgo.games/schemas/ads.v1.json"

AdsSchemaURL is the JSON Schema URL emitted by EncodeAds.

View Source
const AdsVersion = 1

AdsVersion is the schema version of an ads.yaml file.

View Source
const BatchStateVersion = 1

BatchStateVersion is the schema version of BatchProvider's JSON state sidecar file.

View Source
const CloudSaveFormat = "nsgo-cloud-save"

CloudSaveFormat is the "format" value that marks a cloud payload written by CloudSyncer. A payload without it is read as a plain save written by a game that used CloudSync directly, at revision 0.

View Source
const CloudSaveVersion = 1

CloudSaveVersion is the schema version of the cloud payload CloudSyncer writes and the newest one it reads.

View Source
const ConsentRecordVersion = 1

ConsentRecordVersion is the schema version stored in the JSON consent envelope.

View Source
const DefaultCloudPrefix = "save."

DefaultCloudPrefix is the file-name prefix PlatformCloud prepends to each save slot when PlatformCloudOptions.Prefix is empty, storing slot "main" as "save.main.json". A flat dot-separated name without slashes works in both Apple iCloud ubiquity containers and Google Play Games Saved Games snapshots, and keeps save slots separate from other files in the container.

View Source
const DefaultConsentKey = "liveops.analytics.consent"

DefaultConsentKey is the core.Storage key used by NewAnalytics when key is empty.

View Source
const DefaultConsentManagerKey = consent.DefaultConsentManagerKey

DefaultConsentManagerKey is the storage key used by Consent when no key is provided.

View Source
const DefaultHistorySize = 120

DefaultHistorySize is the number of recent steps a CrashReporter keeps when CrashOptions.HistorySize is 0 or negative.

View Source
const DefaultNewsCacheFile = "news-cache.json"

DefaultNewsCacheFile is the cache file name created inside NewsOptions.CacheDir when NewsOptions.CachePath is empty.

View Source
const DefaultNewsCacheKey = "liveops.news.cache"

DefaultNewsCacheKey is the core.Storage key used when NewsOptions.Storage is set and NewsOptions.StorageKey is empty.

View Source
const DefaultReminderPrefix = "liveops.reminder:"

DefaultReminderPrefix is the prefix Reminders prepends to reminder IDs passed to core.Scope.ShowNotification when RemindersOptions.Prefix is empty, keeping reminder notifications separate from the app's other notifications.

View Source
const DefaultRemindersKey = "liveops.reminders"

DefaultRemindersKey is the core.Storage key prefix under which Reminders persists the player's enabled setting, custom quiet hours and active reminder IDs when RemindersOptions.StorageKey is empty.

View Source
const DefaultRemoteConfigCacheKey = "liveops.remoteconfig.cache"

DefaultRemoteConfigCacheKey is the core.Storage key used by RemoteConfig when Storage is set and StorageKey is empty.

View Source
const DefaultRemoteConfigMaxBytes = 1 << 20

DefaultRemoteConfigMaxBytes caps the HTTP response body RemoteConfig.Fetch reads (1 MiB).

View Source
const DefaultRemoteConfigTimeout = 10 * time.Second

DefaultRemoteConfigTimeout is the default HTTP timeout for RemoteConfig.Fetch.

View Source
const DefaultSyncStateKey = "liveops.cloudsync"

DefaultSyncStateKey is the core.Storage key prefix under which CloudSyncer keeps each slot's sync state when CloudSyncOptions.StateKey is empty.

View Source
const EventLoad = "load"

EventLoad is the analytics event name emitted once per session by LoadFunnel.

View Source
const ExposureEventName = "experiment_exposure"

ExposureEventName is the analytics event name emitted when a player is exposed to an active A/B experiment variant.

View Source
const HostEventLoadStage = "loadStage"

HostEventLoadStage is the host-bridge event name (sent by a web host module via player.hostEvent) carrying loader stage timings and environment metadata to LoadFunnel.AttachHost.

View Source
const LedgerLimit = 1024

LedgerLimit is how many transaction IDs each list of a Ledger keeps; the oldest are dropped past it to bound the save's size. A store hands a game only its unfinished transactions again, and a finished transaction is never far back in the list, so no credit repeats. A refund, though, can come weeks after its purchase: one whose ID has been dropped, after LedgerLimit newer consumables were credited, is finished without running Revoke.

View Source
const MiniGameAdNoFillCode = 1004

MiniGameAdNoFillCode is the errCode WeChat mini games report when no suitable ad is available (无合适的广告).

View Source
const NewsCacheVersion = 1

NewsCacheVersion is the schema version of the JSON cache file liveops.News writes to the app's data directory or core.Storage.

View Source
const RemindersSchemaComment = "# yaml-language-server: $schema=" + RemindersSchemaURL

RemindersSchemaComment is the first line EncodeReminders writes: a YAML comment pointing a YAML language server at RemindersSchemaURL. ParseReminders ignores it like any other comment.

View Source
const RemindersSchemaURL = "https://nsgo.games/schemas/reminders.v1.json"

RemindersSchemaURL is where the JSON Schema of version 1 reminders files is published. EncodeReminders writes it in a yaml-language-server comment on the first line so editors and AI tools validate and complete reminders files as they are written.

View Source
const RemindersVersion = 1

RemindersVersion is the schema version of a YAML reminders file (reminders.yaml) this package reads and writes.

View Source
const RemoteConfigCacheVersion = 1

RemoteConfigCacheVersion is the JSON schema version of RemoteConfig's on-disk and core.Storage cache envelope.

Variables

View Source
var (
	// ErrAdNoFill is the error an AdHost returns or passes to done when the platform has no ad to show; Ads reports it as AdNoFill.
	ErrAdNoFill = errors.New("liveops: no ad fill")
	// ErrAdBusy is returned when a show is requested while another ad is still showing.
	ErrAdBusy = errors.New("liveops: an ad is already showing")
	// ErrAdPlacement is returned when Ads was built from an AdsConfig with placements and a show names a placement the config does not declare, or one declared with another kind.
	ErrAdPlacement = errors.New("liveops: unknown ad placement")
	// ErrAdUnsupported is returned by HideBanner when the host cannot hide banners.
	ErrAdUnsupported = errors.New("liveops: ad host cannot hide banners")
)
View Source
var (
	// ErrInvalidAgeBand is returned when an unknown AgeBand value is passed to SetBand.
	ErrInvalidAgeBand = consent.ErrInvalidAgeBand
	// ErrInvalidBirthDate is returned when SetBirthDate or AgeBandForBirthDate receives an impossible or future date.
	ErrInvalidBirthDate = consent.ErrInvalidBirthDate
	// ErrChildModeRestricted is returned when a feature (such as analytics, email account registration
	// or granting restricted consent purposes) is refused because child mode is active.
	ErrChildModeRestricted = consent.ErrChildModeRestricted
	// ErrParentalGateRequired is returned by Purchases.Buy and Purchases.BuyOffer when child mode is active
	// and no ParentalGate callback is configured.
	ErrParentalGateRequired = consent.ErrParentalGateRequired
	// ErrParentalGateFailed is returned by Purchases.Buy and Purchases.BuyOffer when the parental gate
	// challenge is cancelled or failed.
	ErrParentalGateFailed = consent.ErrParentalGateFailed
)

Sentinel errors returned by age-gate, child-mode and parental-gate checks.

View Source
var (
	ErrBatchClosed    = errors.New("liveops: batch provider closed")
	ErrBatchQueueFull = errors.New("liveops: batch provider in-memory queue full")
)

Sentinel errors returned by BatchProvider.

View Source
var (
	// ErrCorruptCloudSave reports a cloud payload marked with CloudSaveFormat that does not decode: an unknown field, a newer schema version, a hash that does not match its data, or a malformed value. The slot is left untouched on both sides.
	ErrCorruptCloudSave = errors.New("liveops: corrupt cloud save")
	// ErrCorruptSyncState reports a slot's stored sync state that does not decode. The slot is left untouched on both sides.
	ErrCorruptSyncState = errors.New("liveops: corrupt cloud sync state")
	// ErrCloudChanged reports that the cloud copy of a slot changed between CloudSyncer reading it and writing it, such as when another device uploaded at the same moment. Nothing was written; the next sync sees the new copy.
	ErrCloudChanged = errors.New("liveops: cloud save changed during sync")
	// ErrConflictChanged reports that a slot passed to CloudSyncer.Resolve no longer holds the copies of the Conflict it was given, because a save or a sync changed either side since. Nothing was written; sync again to see the current conflict, if any.
	ErrConflictChanged = errors.New("liveops: save changed since the conflict was reported")
	// ErrInvalidDevice reports a device ID that is empty, longer than 64 bytes or not made of ASCII letters, digits, '-' and '_'.
	ErrInvalidDevice = errors.New("liveops: invalid device id")
)
View Source
var (
	// ErrEconomyInsufficient reports that a balance or item count was too low for an exchange.
	ErrEconomyInsufficient = errors.New("liveops: economy insufficient balance")
	// ErrEconomyCapExceeded reports that an exchange or purchase would exceed a currency or item cap.
	ErrEconomyCapExceeded = errors.New("liveops: economy balance cap exceeded")
	// ErrEconomyDuplicateKey reports that an idempotency key was already used for a different change.
	ErrEconomyDuplicateKey = errors.New("liveops: economy idempotency key already used")
	// ErrEconomyNotFound reports an unknown exchange, product, currency or item ID.
	ErrEconomyNotFound = errors.New("liveops: economy resource not found")
	// ErrEconomyPurchaseClaimed reports that a store transaction ID was already credited to another account.
	ErrEconomyPurchaseClaimed = errors.New("liveops: economy purchase already claimed")
	// ErrEconomyPurchaseRevoked reports that a store transaction has been refunded or revoked.
	ErrEconomyPurchaseRevoked = errors.New("liveops: economy purchase revoked")
	// ErrEconomyInvalidPurchase reports that the store transaction payload was malformed or failed verification.
	ErrEconomyInvalidPurchase = errors.New("liveops: economy invalid purchase")
	// ErrEconomyUnavailable reports a network, token, authentication or server failure.
	ErrEconomyUnavailable = errors.New("liveops: economy service unavailable")
)
View Source
var (
	// ErrInboxNotFound reports that the requested inbox message does not exist for the signed-in player.
	ErrInboxNotFound = errors.New("liveops: inbox message not found")
	// ErrInboxExpired reports that the requested inbox message has expired.
	ErrInboxExpired = errors.New("liveops: inbox message expired")
	// ErrInboxUnavailable reports a network, token or server error while calling the inbox or code service.
	ErrInboxUnavailable = errors.New("liveops: inbox service unavailable")
	// ErrCodeUnknown reports that a gift or promo code is unknown or failed validation.
	ErrCodeUnknown = errors.New("liveops: unknown code")
	// ErrCodeUsed reports that a unique gift code has already been redeemed.
	ErrCodeUsed = errors.New("liveops: code already used")
	// ErrCodeExpired reports that a code campaign is outside its validity window.
	ErrCodeExpired = errors.New("liveops: code expired")
	// ErrCodeLimit reports that a code campaign's total or per-account redemption limit was reached.
	ErrCodeLimit = errors.New("liveops: code redemption limit reached")
	// ErrCodeDisabled reports that a code campaign has been disabled.
	ErrCodeDisabled = errors.New("liveops: code campaign disabled")
	// ErrCodeRateLimited reports that the player or IP exceeded the code redemption rate limit.
	ErrCodeRateLimited = errors.New("liveops: code redemption rate limited")
)
View Source
var (
	// ErrInvitePayloadTooLarge reports an invite payload whose encoded "key=value&..." representation exceeds the host or configured byte limit.
	ErrInvitePayloadTooLarge = errors.New("liveops: invite payload exceeds size limit")

	// ErrInvalidInvitePayload reports a malformed invite payload (invalid key, control character, duplicate key, bad percent-encoding, or too many keys).
	ErrInvalidInvitePayload = errors.New("liveops: invalid invite payload")

	// ErrInvalidInviteSignature reports an invite payload whose HMAC-SHA256 signature is missing (when required) or does not match.
	ErrInvalidInviteSignature = errors.New("liveops: invalid invite signature")

	// ErrMissingHMACKey reports InvitesOptions or InvitePayloadOptions with RequireSignature set but an empty HMACKey.
	ErrMissingHMACKey = errors.New("liveops: RequireSignature requires a non-empty HMACKey")

	// ErrInvalidInviteURL reports a malformed invite base URL or incoming link.
	ErrInvalidInviteURL = errors.New("liveops: invalid invite URL")

	// ErrInvalidCard reports a share card with invalid fields (such as conflicting InviteID/Payload["id"], control characters, or conflicting Signature/HMACKey).
	ErrInvalidCard = errors.New("liveops: invalid share card")

	// ErrShareUnavailable reports that the current platform or host does not support sharing.
	ErrShareUnavailable = errors.New("liveops: sharing is unavailable on this platform")
)
View Source
var (
	// ErrReminderNotFound is returned by Schedule and ScheduleWith when id is not declared in RemindersConfig.
	ErrReminderNotFound = errors.New("liveops: reminder not found")
	// ErrInvalidSchedule is returned by ScheduleWith when ScheduleOptions sets both Delay and At, sets a negative Delay, or schedules a non-repeating reminder in the past.
	ErrInvalidSchedule = errors.New("liveops: invalid reminder schedule")
)
View Source
var (
	// ErrRemoteConfigTooLarge is returned when a remote config HTTP response exceeds MaxResponseBytes.
	ErrRemoteConfigTooLarge = errors.New("liveops: remote config response exceeds size cap")
	// ErrRemoteConfigUnavailable is returned when fetching remote config fails over the network or with a non-200/304 status.
	ErrRemoteConfigUnavailable = errors.New("liveops: remote config unavailable")
)

Sentinel errors returned by RemoteConfig.

View Source
var ErrAdUnavailable = errors.New("liveops: mini-game ads are unavailable")

ErrAdUnavailable is returned by MiniGameAdHost when it has no driver, as on every target until NSGo ships mini-game ads (nsgo-dev/nsgo#2672).

View Source
var ErrCloudConflict = errors.New("liveops: platform cloud save conflict")

ErrCloudConflict is returned by PlatformCloud when the native cloud backend (iCloud NSFileVersion or Google Play Games Saved Games) holds unresolved conflicting versions of a slot. Resolve it through PlatformCloud.OnConflict or by writing the winning payload.

View Source
var ErrCloudUnavailable = errors.New("liveops: cloud save backend unavailable")

ErrCloudUnavailable is returned by a CloudSync implementation when cloud storage is signed out, offline or unsupported on the current target.

View Source
var ErrConflictResolved = errors.New("liveops: account conflict already resolved")

ErrConflictResolved reports that ResolveConflict was called on an AccountConflict that has already been resolved.

View Source
var ErrInvalidConsent = errors.New("liveops: invalid consent state")

ErrInvalidConsent is returned by Analytics.SetConsent when given an unknown ConsentState value.

View Source
var ErrInvalidConsentRecord = consent.ErrInvalidConsentRecord

ErrInvalidConsentRecord is returned when a consent mutation specifies an undeclared purpose, an invalid ConsentChoice, or an empty source.

View Source
var ErrNewsUnavailable = errors.New("liveops: news feed unavailable")

ErrNewsUnavailable reports a network or server error while fetching the news feed.

View Source
var ErrNoLedger = errors.New("liveops: purchases need a ledger")

ErrNoLedger is what Buy and every delivery answer when PurchasesOptions has no Ledger to record credits in.

View Source
var ErrNoScope = errors.New("liveops: account has no NSGo scope")

ErrNoScope reports that a platform sign-in or credential check requires an Account created with NewAccountForScope.

View Source
var ErrPortalBusy = errors.New("liveops: a portal break is already active")

ErrPortalBusy is returned when Break, Rewarded, BreakAsync, or RewardedAsync is called while another portal ad break is already active.

View Source
var ErrPortalTimeout = context.DeadlineExceeded

ErrPortalTimeout is the error of a portal SDK call that ran past Portal.Timeout.

View Source
var ErrSignedOut = errors.New("liveops: signed out")

ErrSignedOut reports that the Account has no session, or that the account service answered 401 because it no longer accepts the session or the credentials.

View Source
var ErrSlotNotFound = errors.New("liveops: cloud save slot not found")

ErrSlotNotFound is returned by CloudSync.Load when the requested save slot does not exist.

View Source
var ErrSlotTooLarge = errors.New("liveops: cloud save slot too large")

ErrSlotTooLarge is returned by a CloudSync implementation whose backend refuses a save payload over its size limit. The slot is left as it was.

View Source
var ErrTooManySlots = errors.New("liveops: too many cloud save slots")

ErrTooManySlots is returned by a CloudSync implementation whose backend refuses a new slot because the player already has as many as it keeps. The slot is not created.

Functions

func CaptureCardSnapshot

func CaptureCardSnapshot(cx *core.Scope, target *core.Ref, opts CardSnapshotOptions, done func(core.ImageSource, error))

CaptureCardSnapshot captures target (or the owning surface when target is nil) through core.Scope.Capture, center-crops and scales it into a 5:4 PNG image, and returns a core.ImageSource ready for Card.Image.

func ConsentAgeForRegion

func ConsentAgeForRegion(region string, overrides map[string]int) int

ConsentAgeForRegion returns the digital consent age for an ISO 3166-1 alpha-2 region code.

func CropCardSnapshot

func CropCardSnapshot(src image.Image, maxWidth int) (*image.RGBA, error)

CropCardSnapshot center-crops src to a 5:4 rectangle and scales it down to at most maxWidth pixels wide (DefaultCardSnapshotWidth when <= 0).

func DefaultRegionConsentAges

func DefaultRegionConsentAges() map[string]int

DefaultRegionConsentAges returns a copy of the built-in per-region digital consent ages.

func EncodeAds

func EncodeAds(cfg *AdsConfig) ([]byte, error)

EncodeAds writes canonical YAML with a stable field and placement order.

func EncodeCardSnapshotPNG

func EncodeCardSnapshotPNG(src image.Image, maxWidth int) ([]byte, error)

EncodeCardSnapshotPNG center-crops src to 5:4, scales to at most maxWidth pixels wide, and encodes the result as PNG bytes.

func EncodeCloudSave

func EncodeCloudSave(v SaveVersion) ([]byte, error)

EncodeCloudSave returns the JSON text CloudSyncer stores in the cloud for v: format, version, revision, hash, modified time (RFC 3339, UTC), device and the save data, in that fixed order. Data that is valid UTF-8, such as a save.Store payload, is kept as a readable string; other data is base64 in data_base64. v.Hash is recomputed from v.Data and v.Summary is not stored.

func EncodeInvitePayload

func EncodeInvitePayload(payload map[string]string, opts InvitePayloadOptions) (string, error)

EncodeInvitePayload encodes payload as a deterministic, lexicographically sorted "key=value&..." string within opts.MaxBytes. When opts.HMACKey is non-empty, it appends a base64url raw HMAC-SHA256 signature under InviteSigKey ("sig") computed over the canonical unsigned query and checks the final signed length against opts.MaxBytes.

func EncodeReminders

func EncodeReminders(cfg *RemindersConfig) ([]byte, error)

EncodeReminders validates cfg and writes deterministic 2-space YAML prefixed with RemindersSchemaComment that ParseReminders reads back unchanged.

func ExtractInviteQuery

func ExtractInviteQuery(rawURL string, opts InviteLinkOptions) (rawQuery string, matched bool, err error)

ExtractInviteQuery checks whether rawURL matches opts.BaseURL and extracts its raw invite payload string according to opts.Encoding. It returns matched == false with a nil error when rawURL is empty, uses a different scheme/host/path, or carries no payload.

func FormatInviteURL

func FormatInviteURL(baseURL, rawQuery string, encoding InviteEncoding) (string, error)

FormatInviteURL attaches rawQuery to baseURL according to encoding (InviteEncodeQuery or InviteEncodeFragment). baseURL must have a valid scheme and must not already carry a query (for InviteEncodeQuery) or fragment (for InviteEncodeFragment).

func OpenURL

func OpenURL(cx *core.Scope, u string, ageGate *AgeGate, parentalGate ParentalGateFunc, done func(opened bool))

OpenURL opens external URL u through cx.OpenURL, requiring parentalGate when child mode is active.

func PayloadHash

func PayloadHash(payload []byte) string

PayloadHash identifies a raw cloud payload for ConditionalCloudSync: "sha256:" followed by the lowercase hex SHA-256 of payload.

func SignInvitePayload

func SignInvitePayload(payload map[string]string, hmacKey []byte, maxBytes int) (string, error)

SignInvitePayload encodes payload and signs it with HMAC-SHA256 using hmacKey. It is intended for both game clients and game servers minting verifiable invite payloads.

func ValidateRemindersConfig

func ValidateRemindersConfig(cfg *RemindersConfig) error

ValidateRemindersConfig checks cfg against the version 1 reminders schema.

Types

type Account

type Account struct {
	// contains filtered or unexported fields
}

Account is a game client's session with the account service: it signs in, keeps the session secret in the keychain, watches for Apple credential revocation, links platform identities with conflict resolution, and hands out game-server tokens, refreshing them once for concurrent callers. Its network methods are safe for concurrent use and should be called off the engine goroutine; ProfileSignal, CurrentProfile and SignedIn read reactive signals on the scope's goroutine.

func NewAccount

func NewAccount(opts AccountOptions) *Account

NewAccount returns an account for opts, restoring the session saved in opts.Secrets, if any.

func NewAccountForScope

func NewAccountForScope(cx *core.Scope, opts AccountOptions) *Account

NewAccountForScope constructs an Account using NSGo's protected keychain (cx.Secrets()), reactive signals for UI, and lifecycle-driven Sign in with Apple revocation checks. Secrets are accessed through the supplied scope's secure store and never mirrored into ordinary storage.

func (*Account) CheckAppleCredential

func (a *Account) CheckAppleCredential()

CheckAppleCredential asks Sign in with Apple for the state of the linked Apple user (if any) and signs out with SignOutAppleRevoked when Apple reports AppleCredentialRevoked. NewAccountForScope runs this automatically on startup and whenever the app returns to the foreground.

func (*Account) ChildMode

func (a *Account) ChildMode() bool

ChildMode reports whether this Account is linked to an AgeGate currently in child mode. While true, email registration, email sign-in and email linking are refused so only email-free guest accounts are created.

func (*Account) CreateGuest

func (a *Account) CreateGuest(ctx context.Context) error

CreateGuest creates a guest account and saves the new session to the keychain.

func (*Account) CurrentProfile

func (a *Account) CurrentProfile() accounts.Profile

CurrentProfile returns the currently cached account profile. On a scope-backed Account it reads ProfileSignal so views and effects update on sign-in, linking, conflict switches and sign-out.

func (*Account) LinkEmail

func (a *Account) LinkEmail(ctx context.Context, email, password string) error

LinkEmail adds an email/password login to the current account. Returns ErrChildModeRestricted when AccountOptions.AgeGate is in child mode.

func (*Account) LinkIdentity

func (a *Account) LinkIdentity(ctx context.Context, provider, credential string) error

LinkIdentity links a provider credential to the current account. It returns an *AccountConflict holding both accounts' profiles when the identity already belongs to another account; pass that conflict to ResolveConflict with KeepCurrent or SwitchToExisting to apply the player's choice.

func (*Account) LinkMiniProgram

func (a *Account) LinkMiniProgram(ctx context.Context, opts core.MiniProgramSignInOptions) error

LinkMiniProgram asks the mini program host for a login code through the scope and links it to the current account. It returns an *AccountConflict when another account already owns the mini program identity. Call off the engine goroutine.

func (*Account) LinkWithApple

func (a *Account) LinkWithApple(ctx context.Context, opts core.AppleSignInOptions) error

LinkWithApple runs Sign in with Apple through the scope and links the identity token to the current account. It returns an *AccountConflict when another account already owns the Apple identity, and records the Apple user ID for revocation checks when linked or switched to. Call off the engine goroutine. In child mode, Email and FullName scopes are cleared before invoking the system sheet.

func (*Account) OnSignedOut

func (a *Account) OnSignedOut(fn func(SignOutReason)) (stop func())

OnSignedOut registers fn to be called whenever the account signs out (explicitly, because the service rejected the session, or because Apple revoked the credential). It returns a stop function that unregisters fn.

func (*Account) Profile

func (a *Account) Profile(ctx context.Context) (accounts.Profile, error)

Profile returns the signed-in account profile from the account service and updates the cached profile signal.

func (*Account) ProfileID

func (a *Account) ProfileID() string

ProfileID returns the signed-in account's ID, or "" before the first token or after SignOut.

func (*Account) ProfileSignal

func (a *Account) ProfileSignal() *core.Signal[accounts.Profile]

ProfileSignal returns the reactive signal holding the current account profile for NSGo views, or nil when Account was created without a *core.Scope.

func (*Account) Register

func (a *Account) Register(ctx context.Context, email, password string) error

Register creates an email account and signs it in. Returns ErrChildModeRestricted when AccountOptions.AgeGate is in child mode.

func (*Account) ResolveConflict

func (a *Account) ResolveConflict(ctx context.Context, conflict *AccountConflict, choice ConflictChoice) error

ResolveConflict applies choice (KeepCurrent or SwitchToExisting) to an AccountConflict returned by LinkIdentity, LinkWithApple or LinkMiniProgram. KeepCurrent leaves the current account signed in and revokes any temporary session opened to inspect the existing account. SwitchToExisting saves the existing account's session in the keychain, updates the profile signal and revokes the previous session.

func (*Account) SignInEmail

func (a *Account) SignInEmail(ctx context.Context, email, password string) error

SignInEmail signs in with an email address and password and saves the new session. Returns ErrChildModeRestricted when AccountOptions.AgeGate is in child mode.

func (*Account) SignInIdentity

func (a *Account) SignInIdentity(ctx context.Context, provider, credential string) error

SignInIdentity signs in with a provider credential and saves the new session.

func (*Account) SignInMiniProgram

func (a *Account) SignInMiniProgram(ctx context.Context, opts core.MiniProgramSignInOptions) error

SignInMiniProgram asks the mini program host (WeChat, QQ, Douyin or Alipay) for a login code through the scope, signs in to the account service and saves the session. Call off the engine goroutine.

func (*Account) SignInWithApple

func (a *Account) SignInWithApple(ctx context.Context, opts core.AppleSignInOptions) error

SignInWithApple shows the system Sign in with Apple flow through the scope, signs in to the account service with the identity token, saves the session and records the Apple user ID for revocation checks. Call off the engine goroutine. In child mode, Email and FullName scopes are cleared before invoking the system sheet.

func (*Account) SignOut

func (a *Account) SignOut(ctx context.Context) error

SignOut forgets the session and token, deletes the saved session from the keychain, notifies OnSignedOut listeners and revokes the session on the service.

func (*Account) SignedIn

func (a *Account) SignedIn() bool

SignedIn reports whether the account currently holds a session. On a scope-backed Account it reads a signal so views and effects update on sign-in and sign-out.

func (*Account) Token

func (a *Account) Token(ctx context.Context) (string, error)

Token returns a game-server token, refreshing it when it expires within the refresh margin; concurrent callers wait for one refresh. When AutoGuest is enabled and no session has been stored or signed out, the first Token call creates a guest account once for concurrent callers. It returns ErrSignedOut without a session, and signs out when the service no longer accepts the session.

type AccountConflict

type AccountConflict struct {
	Provider string
	Current  accounts.Profile
	Existing accounts.Profile
	// contains filtered or unexported fields
}

AccountConflict identifies a provider identity already owned by another account. Current holds the currently signed-in account's profile and Existing holds the profile of the account that already owns the identity.

func (*AccountConflict) Error

func (e *AccountConflict) Error() string

Error names the provider whose identity belongs to another account.

type AccountOptions

type AccountOptions struct {
	URL           string
	Audience      string
	Secrets       SecretStore
	SecretsKey    string
	Client        *http.Client
	RefreshMargin time.Duration
	// AutoGuest creates a guest account on the first Token call when no session is stored in Secrets and the account has not been signed out.
	AutoGuest bool
	// OnSignedOut is called when a signed-in Account becomes signed out (explicitly, because the service rejected the session, or because Apple revoked the credential). On a scope-backed Account it runs on the scope's goroutine.
	OnSignedOut func(SignOutReason)
	// AppleProvider names the account service identity provider for SignInWithApple and LinkWithApple; "apple" when empty.
	AppleProvider string
	// MiniProgramProvider maps a core.MiniProgramPlatform to the account service identity provider name for SignInMiniProgram and LinkMiniProgram; when nil or returning "", string(platform) ("wechat", "qq", "alipay", "douyin") is used.
	MiniProgramProvider func(core.MiniProgramPlatform) string
	// AgeGate, when set and in ChildMode, restricts the account client to email-free guest accounts:
	// Register, SignInEmail and LinkEmail return ErrChildModeRestricted, SignInWithApple and LinkWithApple
	// clear Email and FullName scopes, and CreateGuest/AutoGuest create guests without email.
	AgeGate *AgeGate
	// Now returns the clock time used to check token expiry; time.Now when nil.
	Now func() time.Time
}

AccountOptions configures an Account: the account service's URL, the audience its game-server tokens are for, the keychain and key that keep the session across launches, the HTTP client (http.DefaultClient when nil), how long before a token expires it is refreshed (30 seconds when zero), optional guest creation on first Token call, sign-out notifications, and platform provider name mapping.

type AdBannerHost

type AdBannerHost interface {
	HideBanner(placement string) error
}

AdBannerHost is an AdHost that can hide a banner it showed, such as MiniGameAdHost. placement is the same name or unitId Show received.

type AdHost

type AdHost interface {
	Show(kind AdKind, placement string, done func(ended bool, err error)) error
}

AdHost is the host platform bridge. placement is the placement's unitId when Ads was built by NewAds from an AdsConfig that declares placements, and the name the game passed otherwise. Show must invoke done at most once, with ended true only when a rewarded video played to the end; Ads ignores any further calls. An error wrapping ErrAdNoFill means the platform had no ad to show.

type AdKind

type AdKind string

AdKind identifies a host ad placement.

const (
	Rewarded     AdKind = "rewarded"
	Interstitial AdKind = "interstitial"
)

Ad kinds an AdHost can be asked to show.

type AdPlacement

type AdPlacement struct {
	// Name is the placement name the game passes to ShowRewarded, ShowInterstitial or ShowBanner; each name appears once in a file.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Kind is the ad kind the placement shows: rewarded, interstitial or banner.
	Kind AdKind `yaml:"kind" schema:"required,enum=rewarded|interstitial|banner"`
	// UnitID is the platform's ad unit ID, which Ads passes to AdHost.Show in place of Name.
	UnitID string `yaml:"unitId" schema:"required,minLength=1"`
}

AdPlacement declares a host placement and its platform unit ID.

type AdResult

type AdResult string

AdResult is what Ads reports to the game once a show finishes.

const (
	AdRewarded AdResult = "rewarded"
	AdShown    AdResult = "shown"
	AdSkipped  AdResult = "skipped"
	AdNoFill   AdResult = "no_fill"
	AdFailed   AdResult = "failed"
	AdCapped   AdResult = "capped"
)

Ad results. AdRewarded is reported only for a rewarded ad watched to the end; AdShown for an interstitial that closed normally.

type Ads

type Ads struct {
	Host                 AdHost
	InterstitialInterval time.Duration
	InterstitialCap      int
	Disabled             func() bool
	Now                  func() time.Time
	Pause                func(bool)
	Mute                 func(bool)
	ResetInput           func()
	// contains filtered or unexported fields
}

Ads enforces reward correctness and interstitial frequency limits around a host ad API. Only one ad shows at a time: a show requested while another is active reports AdFailed and returns ErrAdBusy.

func NewAds

func NewAds(options AdsOptions) *Ads

NewAds constructs an Ads lifecycle wrapper from a validated configuration. When Config declares placements, every show must name one of them with the matching kind, and the host receives its unitId.

func (*Ads) HideBanner

func (a *Ads) HideBanner(placement string) error

HideBanner hides a banner placement ShowBanner showed. It returns ErrAdUnsupported when the host does not implement AdBannerHost, and ErrAdPlacement for a placement the config does not declare as a banner.

func (*Ads) ShowBanner

func (a *Ads) ShowBanner(placement string, done func(AdResult)) error

ShowBanner asks the host to show a banner placement, which stays on screen until HideBanner. Banners do not consume the interstitial frequency budget, but share the same pause/mute/overlap lifecycle while the host reports the show operation.

func (*Ads) ShowInterstitial

func (a *Ads) ShowInterstitial(placement string, done func(AdResult)) error

ShowInterstitial enforces Disabled, the per-session cap and the minimum interval, reporting AdCapped when any of them blocks the show.

func (*Ads) ShowRewarded

func (a *Ads) ShowRewarded(placement string, done func(AdResult)) error

ShowRewarded shows a rewarded placement and reports AdRewarded only when the host says playback ended, at most once per show.

type AdsConfig

type AdsConfig struct {
	// Version is the schema version; it must equal AdsVersion (1).
	Version int `yaml:"version" schema:"required"`
	// InterstitialInterval is the minimum time between two interstitials, written as a Go duration such as "30s" or "2m0s"; 0 or omitted means no interval.
	InterstitialInterval time.Duration `yaml:"interstitialInterval,omitempty"`
	// InterstitialCap is the most interstitials shown in one session; 0 or omitted means no cap.
	InterstitialCap int `yaml:"interstitialCap,omitempty" schema:"minimum=0"`
	// Placements lists the game's ad placements in declaration order.
	Placements []AdPlacement `yaml:"placements,omitempty"`
}

AdsConfig is the root of a versioned, platform-neutral ads.yaml file.

func LoadAdsConfigFS

func LoadAdsConfigFS(fsys fs.FS, name string) (*AdsConfig, error)

LoadAdsConfigFS reads name from fsys and parses it as a versioned ads.yaml file, attaching name to parse and validation errors.

func ParseAds

func ParseAds(data []byte) (*AdsConfig, error)

ParseAds parses a strict versioned ads.yaml document. Unknown fields, trailing YAML documents, a missing or unsupported version, an invalid interval and invalid placements are refused with a *loaderr.Error that names the line and a fix.

func (*AdsConfig) Validate

func (c *AdsConfig) Validate() error

Validate checks the ads file's version, caps, durations and placement vocabulary.

type AdsOptions

type AdsOptions struct {
	Host       AdHost
	Config     *AdsConfig
	Disabled   func() bool
	Now        func() time.Time
	Pause      func(bool)
	Mute       func(bool)
	ResetInput func()
}

AdsOptions wires an AdHost to the game lifecycle. Config supplies the interstitial cap, interval and placements declared in ads.yaml.

type AgeBand

type AgeBand = consent.AgeBand

AgeBand is the age group a player declares to an AgeGate; it never records a date of birth.

func AgeBandForAge

func AgeBandForAge(age int) AgeBand

AgeBandForAge maps a whole-year age in years to its AgeBand.

func AgeBandForBirthDate

func AgeBandForBirthDate(year int, month time.Month, day int, now time.Time) (AgeBand, error)

AgeBandForBirthDate derives an AgeBand from a birth date relative to now without retaining the date.

type AgeGate

type AgeGate = consent.AgeGate

AgeGate tracks a player's age band and child-mode state in versioned JSON storage.

func NewAgeGate

func NewAgeGate(storage AgeStorage, key string) *AgeGate

NewAgeGate creates an AgeGate backed by storage under key (DefaultAgeGateKey when empty).

func NewAgeGateWithOptions

func NewAgeGateWithOptions(opts AgeGateOptions) *AgeGate

NewAgeGateWithOptions creates an AgeGate from opts.

type AgeGateOptions

type AgeGateOptions = consent.AgeGateOptions

AgeGateOptions configures an AgeGate.

type AgeRecord

type AgeRecord = consent.AgeRecord

AgeRecord is the persisted age-band record stored by an AgeGate.

type AgeStorage

type AgeStorage = consent.AgeStorage

AgeStorage is the key-value storage an AgeGate keeps its record in.

func CoreAgeStorage

func CoreAgeStorage(store core.Storage) AgeStorage

CoreAgeStorage adapts a core.Storage to AgeStorage. It returns nil for a zero core.Storage.

type Analytics

type Analytics struct {
	// contains filtered or unexported fields
}

Analytics gates event tracking on explicit player consent and optionally persists the consent choice in core.Storage or delegates consent checks to a shared Consent manager for a chosen Purpose.

Events tracked while consent is not allowed are dropped immediately — they are never sent and never buffered for later replay.

Example

Analytics drops every event until the player grants consent, and never sends the ones it dropped.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/online/liveops"
)

// printProvider stands in for an analytics SDK: it prints each event it receives.
type printProvider struct{}

func (printProvider) Send(e liveops.Event) error {
	fmt.Println("sent:", e.Name, e.Properties)
	return nil
}

func (printProvider) Flush() error { return nil }

func main() {
	a := liveops.NewMemoryAnalytics(printProvider{})
	fmt.Println(a.Consent(), a.Track("level_start", map[string]any{"level": 1}))
	if err := a.SetConsent(liveops.ConsentGranted); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(a.Track("level_start", map[string]any{"level": 2}))
	a.Flush()
}
Output:
unknown false
sent: level_start map[level:2]
true

func NewAnalytics

func NewAnalytics(store core.Storage, key string, provider AnalyticsProvider) *Analytics

NewAnalytics returns an Analytics gate backed by store under key (DefaultConsentKey when empty) and dispatching consented events to provider. It maps to AnalyticsPurpose and loads any previously persisted consent choice from store immediately, failing closed to ConsentUnknown when absent or unrecognized.

func NewAnalyticsWithConsent

func NewAnalyticsWithConsent(consent *Consent, purpose Purpose, provider AnalyticsProvider) *Analytics

NewAnalyticsWithConsent returns an Analytics gate backed by a shared Consent manager for purpose (AnalyticsPurpose when empty). Track and Flush proceed only while consent.Allowed(purpose) is true. Revoking consent through SetConsent or directly on consent purges any provider implementing ConsentRevoker. A nil consent manager fails closed.

func NewMemoryAnalytics

func NewMemoryAnalytics(provider AnalyticsProvider) *Analytics

NewMemoryAnalytics returns an Analytics gate that keeps its consent state in memory only, starting in ConsentUnknown.

func (*Analytics) Close

func (a *Analytics) Close()

Close releases any listener registered on a shared Consent manager.

func (*Analytics) Consent

func (a *Analytics) Consent() ConsentState

Consent returns the current ConsentState. When backed by core.Storage or a storage-backed Consent manager, reading Consent inside a reactive computation subscribes it to storage changes.

func (*Analytics) Flush

func (a *Analytics) Flush() error

Flush flushes the configured provider when consent allows collection. When consent is not allowed or no provider is set, Flush is a no-op returning nil.

func (*Analytics) Purpose

func (a *Analytics) Purpose() Purpose

Purpose returns the consent purpose gated by this Analytics instance (AnalyticsPurpose by default).

func (*Analytics) SetClock

func (a *Analytics) SetClock(now func() time.Time)

SetClock sets the clock function used for Event.Time; time.Now is used when nil.

func (*Analytics) SetConsent

func (a *Analytics) SetConsent(state ConsentState) error

SetConsent updates the consent choice and persists it when backed by core.Storage or a Consent manager. Revoking consent (ConsentDenied or ConsentUnknown) immediately stops all subsequent Track calls.

func (*Analytics) SetProvider

func (a *Analytics) SetProvider(provider AnalyticsProvider)

SetProvider replaces the AnalyticsProvider that receives consented events.

func (*Analytics) Track

func (a *Analytics) Track(name string, props map[string]any) bool

Track dispatches an event to the configured provider only when consent allows collection. When consent is not allowed, or when no provider is configured, Track drops the event immediately without buffering and returns false. When consent is allowed, props is defensively copied before dispatch and Track returns whether provider.Send succeeded.

type AnalyticsProvider

type AnalyticsProvider interface {
	Send(Event) error
	Flush() error
}

AnalyticsProvider receives analytics events after explicit opt-in consent. Provider implementations live outside the core game module so no third-party analytics SDK is linked unless chosen by the app.

type BatchOptions

type BatchOptions struct {
	// Path is the durable JSON Lines queue file in the app's data directory. Required.
	Path string
	// StatePath stores the install ID, monotonic sequence counter and session state as versioned JSON.
	// Defaults to Path + ".state.json" when empty.
	StatePath string
	// Sink delivers one JSON Lines batch. Required unless Endpoint is set.
	Sink BatchSink
	// Endpoint is the collector's POST /v1/events URL. When set and Sink is nil,
	// BatchProvider uploads gzipped JSON Lines batches to Endpoint.
	Endpoint string
	// HTTPClient is used with Endpoint (defaults to a 15s timeout client).
	HTTPClient *http.Client
	// Token optionally returns the player's current bearer token for Endpoint.
	Token func() string
	// MaxBytes caps the on-disk queue file size in bytes (DefaultBatchMaxBytes when <= 0).
	// Oldest whole events are dropped first when exceeded.
	MaxBytes int
	// MaxAge drops queued events older than MaxAge (DefaultBatchMaxAge when 0; negative disables age expiry).
	MaxAge time.Duration
	// MaxBatchEvents is the maximum number of events uploaded per batch (DefaultBatchMaxEvents when <= 0).
	MaxBatchEvents int
	// QueueBuffer is the capacity of the non-blocking in-memory channel feeding the background worker (DefaultBatchQueueBuffer when <= 0).
	QueueBuffer int
	// FlushInterval triggers periodic background uploads (DefaultBatchFlushInterval when 0; negative disables periodic uploads).
	FlushInterval time.Duration
	// InitialBackoff is the initial retry delay after a failed upload (DefaultBatchInitialBackoff when <= 0).
	InitialBackoff time.Duration
	// MaxBackoff caps the exponential retry delay (DefaultBatchMaxBackoff when <= 0).
	MaxBackoff time.Duration
	// JitterFraction sets symmetric jitter on backoff delays in [0, 1] (DefaultBatchJitterFraction when 0; negative disables jitter).
	JitterFraction float64
	// SessionTimeout starts a new session ID after this much time in the background or idle (DefaultSessionTimeout when <= 0).
	SessionTimeout time.Duration
	// AppVersion, Platform and Locale are attached to every queued event (Platform defaults to runtime.GOOS when empty).
	AppVersion string
	Platform   string
	Locale     string
	// Limits optionally overrides property validation caps; zero uses analytics.DefaultLimits().
	Limits analytics.Limits
	// Now overrides the clock for tests (defaults to time.Now).
	Now func() time.Time
	// Rand overrides randomness for install/session IDs and retry jitter in tests (defaults to crypto/rand.Reader).
	Rand io.Reader
	// AgeGate, when set and in ChildMode, causes BatchProvider to send nothing (Send returns
	// ErrChildModeRestricted, Flush and background uploads become no-ops, and entering child mode
	// purges queued events and state).
	AgeGate *AgeGate
	// OnError optionally receives asynchronous disk or upload errors.
	OnError func(error)
}

BatchOptions configures a durable, non-blocking BatchProvider created by NewBatchProviderWithOptions.

type BatchProvider

type BatchProvider struct {
	// contains filtered or unexported fields
}

BatchProvider is an AnalyticsProvider backed by a bounded JSON-lines queue. Providers created with NewBatchProviderWithOptions never block Send/Track on disk or network I/O, stamp install/session/seq/app/platform/locale context, enforce size and age caps, upload batches in the background with exponential backoff and jitter, flush on going to the background, and purge + rotate the install ID when consent is revoked.

func NewBatchProvider

func NewBatchProvider(path string, maxBytes int, sink BatchSink) (*BatchProvider, error)

NewBatchProvider returns a synchronous provider that queues events as JSON lines in the file at path, creating its directory, keeps at most maxBytes of them (1 MiB when zero), dropping the oldest whole events, and hands the queue to sink on Flush.

For non-blocking background delivery, session/install context, backoff with jitter, age caps and HTTP collector upload, use NewBatchProviderWithOptions.

func NewBatchProviderWithOptions

func NewBatchProviderWithOptions(opts BatchOptions) (*BatchProvider, error)

NewBatchProviderWithOptions returns an asynchronous durable BatchProvider configured by opts. Call Close when the app exits to persist any remaining in-memory events to disk and stop the background worker.

func (*BatchProvider) AttachLifecycle

func (b *BatchProvider) AttachLifecycle(cx *core.Scope)

AttachLifecycle wires NSGo's app lifecycle into OnBackground and OnForeground so queued events flush when the app goes to the background and a new session starts after SessionTimeout spent in the background.

func (*BatchProvider) Close

func (b *BatchProvider) Close() error

Close flushes all in-memory events to the durable queue file on disk and stops the background worker goroutine. Safe to call more than once.

func (*BatchProvider) Dropped

func (b *BatchProvider) Dropped() uint64

Dropped returns how many events were dropped because the in-memory channel filled before the background writer could drain it.

func (*BatchProvider) Flush

func (b *BatchProvider) Flush() error

Flush drains queued events to disk and uploads all pending batches to the sink, returning the first sink error while leaving failed batches intact. When BatchOptions.AgeGate is in ChildMode, Flush is a no-op returning nil.

func (*BatchProvider) InstallID

func (b *BatchProvider) InstallID() string

InstallID returns the current random per-install identifier. It is rotated whenever Purge is called on consent revocation.

func (*BatchProvider) OnBackground

func (b *BatchProvider) OnBackground()

OnBackground records the background timestamp and schedules an immediate non-blocking upload flush of queued events.

func (*BatchProvider) OnForeground

func (b *BatchProvider) OnForeground()

OnForeground marks the app active again and rotates the session ID when the time spent in the background reached or exceeded SessionTimeout.

func (*BatchProvider) Pending

func (b *BatchProvider) Pending() int

Pending returns how many events are currently queued (in memory and on disk).

func (*BatchProvider) Purge

func (b *BatchProvider) Purge() error

Purge discards all buffered and on-disk queued events without sending them, deletes the queue and state files, resets the sequence counter and rotates the install ID, as required when a player revokes analytics consent.

func (*BatchProvider) Send

func (b *BatchProvider) Send(ev Event) error

Send validates ev, attaches install/session/seq/app/platform/locale context (in async mode), and queues it without blocking on disk or network I/O. When BatchOptions.AgeGate is in ChildMode, Send drops the event and returns ErrChildModeRestricted.

func (*BatchProvider) SessionID

func (b *BatchProvider) SessionID() string

SessionID returns the current active session identifier (empty until the first event is queued or after Purge).

func (*BatchProvider) SetAgeGate

func (b *BatchProvider) SetAgeGate(g *AgeGate)

SetAgeGate attaches or replaces the AgeGate guarding this BatchProvider. When g is in ChildMode, Send returns ErrChildModeRestricted, Flush and background uploads send nothing, and transitioning into child mode purges queued events and persisted state.

type BatchSink

type BatchSink func([]byte) error

BatchSink receives a durable JSON-lines batch. Returning an error leaves the queue intact for a later retry.

type BuyResult

type BuyResult int

BuyResult is how a Buy ended without an error.

const (
	// BuyFailed is the result that goes with an error.
	BuyFailed BuyResult = iota
	// Bought: the purchase went through and was delivered, its credit saved or its unlock owned.
	Bought
	// BuyPending: the purchase waits for approval, as Ask to Buy's does; Pending reports it until its transaction arrives through the store's updates, which deliver it as Buy would have.
	BuyPending
	// BuyCancelled: the user closed the store's sheet.
	BuyCancelled
)

func (BuyResult) String

func (r BuyResult) String() string

String returns "failed", "bought", "pending" or "cancelled".

type Card

type Card struct {
	// Title is the short headline shown on the share card or prepended to the native/web share message.
	Title string
	// Image is the card's image (for example a 5:4 snapshot from CaptureCardSnapshot or an embedded PNG/JPEG).
	Image core.ImageSource
	// ImageID is an optional platform-reviewed image identifier (such as WeChat mini game's imageUrlId).
	ImageID string
	// InviteID is an optional unique identifier for this invite, encoded under InviteIDKey ("id").
	// Servers use Invite.ID as the idempotency key for invite reward grants.
	InviteID string
	// Payload holds key-value parameters carried to whoever opens the game from the card (for example room or party IDs).
	// Unknown keys are preserved on decode.
	Payload map[string]string
	// Signature is an optional pre-computed base64url raw HMAC-SHA256 signature minted by a server.
	// When InvitesOptions.HMACKey is configured, Invites computes the signature itself and refuses a non-empty Card.Signature.
	Signature string
	// Anchor is the optional UI element anchoring a popover share sheet on macOS and iPadOS.
	Anchor *core.Ref
}

Card describes a share card or invite passed to Invites.Share or returned by a menu-share callback.

type CardSnapshotOptions

type CardSnapshotOptions struct {
	// MaxWidth caps the output snapshot width in pixels while preserving the 5:4 aspect ratio (height = MaxWidth * 4 / 5).
	// Values <= 0 default to DefaultCardSnapshotWidth (500, giving 500x400).
	// Snapshots narrower than MaxWidth are center-cropped to 5:4 without upscaling.
	MaxWidth int
}

CardSnapshotOptions configures CaptureCardSnapshot.

type Choice

type Choice int

Choice is the answer to a Conflict under PolicyAsk.

const (
	// ChoiceDefer leaves the conflict unresolved: nothing is written on either side and the next sync asks again.
	ChoiceDefer Choice = iota
	// ChoiceLocal keeps this device's copy and overwrites (or deletes) the cloud copy.
	ChoiceLocal
	// ChoiceCloud keeps the cloud copy and overwrites (or deletes) this device's copy. SlotResult.Discarded holds the replaced copy; when it was a valid save envelope and the cloud copy exists, the local save backend also keeps it as its backup.
	ChoiceCloud
	// ChoiceBoth keeps the cloud copy in the slot and moves this device's copy into a fork slot on both sides. When one side deleted the slot it keeps the copy that exists.
	ChoiceBoth
)

func (Choice) String

func (c Choice) String() string

String returns "defer", "local", "cloud", "both" or "unknown".

type CloudChange

type CloudChange struct {
	// Slots lists the sorted save slot names affected by this change. It may be empty on account-change or initial-sync notifications that did not enumerate individual files.
	Slots []string
	// Reason explains why the external change arrived.
	Reason cloud.ChangeReason
}

CloudChange reports save slots updated or deleted externally in platform cloud storage (such as from another device).

type CloudClient

type CloudClient struct {
	// contains filtered or unexported fields
}

CloudClient is the CloudSync of the self-hosted cloud save service in package cloudsave, over HTTPS. It implements ConditionalCloudSync, so a CloudSyncer on it never overwrites another device's upload, and adds the service's version history: Versions, LoadVersion, Restore and Purge.

Its errors wrap the liveops sentinels: ErrSlotNotFound, ErrCloudChanged when a conditional write lost to another device, ErrSlotTooLarge (with the service's limit in the message), ErrTooManySlots, and ErrCloudUnavailable when the network, the service or the token fails, which a sync treats as offline. A done context's error is returned as it is. A CloudClient is safe for concurrent use.

func NewCloudClient

func NewCloudClient(opts CloudClientOptions) (*CloudClient, error)

NewCloudClient returns a client for opts, or an error when the URL or the token source is missing or invalid.

func (*CloudClient) Delete

func (c *CloudClient) Delete(ctx context.Context, slot string) error

Delete implements CloudSync. The service keeps the slot's history, so Restore can bring it back.

func (*CloudClient) DeleteIf

func (c *CloudClient) DeleteIf(ctx context.Context, slot, match string) error

DeleteIf implements ConditionalCloudSync.

func (*CloudClient) List

func (c *CloudClient) List(ctx context.Context) ([]string, error)

List implements CloudSync: the names of the player's live slots, in byte order.

func (*CloudClient) Load

func (c *CloudClient) Load(ctx context.Context, slot string) ([]byte, error)

Load implements CloudSync. It checks the payload against the service's ETag.

func (*CloudClient) LoadVersion

func (c *CloudClient) LoadVersion(ctx context.Context, slot string, number int64) ([]byte, error)

LoadVersion returns the payload of kept version number of slot, as Load returns the current one. It returns ErrSlotNotFound when the version is not kept or is a deletion.

func (*CloudClient) Purge

func (c *CloudClient) Purge(ctx context.Context, slot string) error

Purge removes slot and its whole history from the service for good; a slot that does not exist is not an error.

func (*CloudClient) Restore

func (c *CloudClient) Restore(ctx context.Context, slot string, number int64) error

Restore makes kept version number the slot's current copy, as a new version written only while the slot still holds the copy Restore read (ErrCloudChanged otherwise). Restoring a deletion deletes the slot.

A payload written by CloudSyncer is re-stamped with the next revision and the current time, so every device sees the restore as the newest copy: one whose copy is unchanged since its last sync downloads it on the next sync, and one with unsynced changes gets a conflict its policy resolves. Other payloads are restored byte for byte.

func (*CloudClient) Save

func (c *CloudClient) Save(ctx context.Context, slot string, data []byte) error

Save implements CloudSync: it replaces the slot whatever it holds.

func (*CloudClient) SaveIf

func (c *CloudClient) SaveIf(ctx context.Context, slot string, data []byte, match string) error

SaveIf implements ConditionalCloudSync.

func (*CloudClient) Versions

func (c *CloudClient) Versions(ctx context.Context, slot string) ([]CloudVersion, error)

Versions lists the kept versions of slot, newest first, deletions included. It returns ErrSlotNotFound for a slot with no history.

type CloudClientOptions

type CloudClientOptions struct {
	// URL is the base URL of the cloud save service (package cloudsave), such as "https://saves.example.com". It must use https, except on a loopback host (localhost, 127.0.0.1, ::1) during development. Required.
	URL string
	// Token returns a current bearer token from the account service for the signed-in player and the cloud save service's audience ("cloudsave" by default: POST /v1/refresh with that audience), getting a new one when the last has expired. The token a sign-in returns is for game servers, and the service refuses it. Every device signed in to the same account reads and writes the same slots. Required.
	Token func(ctx context.Context) (string, error)
	// HTTPClient sends the requests; http.DefaultClient when nil. The client uses a copy that does not follow redirects. On the web its requests go through the browser's fetch, so the page's origin must be in the service's allowedOrigins.
	HTTPClient *http.Client
	// Now stamps payloads Restore re-writes; time.Now when nil.
	Now func() time.Time
}

CloudClientOptions configures NewCloudClient.

type CloudProvider

type CloudProvider uint8

CloudProvider names a platform cloud-save service.

const (
	// CloudProviderNone means the platform has no built-in OS cloud-save service through NSGo's cloud package (Windows, Linux, the web).
	CloudProviderNone CloudProvider = iota
	// CloudProviderICloud is Apple's iCloud ubiquity container on macOS and iOS (including iPadOS and tvOS).
	CloudProviderICloud
	// CloudProviderPlayGames is Google Play Games Saved Games on Android.
	CloudProviderPlayGames
	// CloudProviderSteam is Steam Auto-Cloud on desktop targets, which syncs a local directory (such as cx.DataDir() or a subdirectory via DirCloud).
	CloudProviderSteam
)

func CloudProviderFor

func CloudProviderFor(env *core.Env) CloudProvider

CloudProviderFor returns the built-in OS cloud-save service NSGo's cloud package reaches in env: CloudProviderNone when env is nil or Simulated (such as a mini program or a web build with --nsgo-os), CloudProviderICloud on native macOS and iOS, CloudProviderPlayGames on native Android, and CloudProviderNone elsewhere.

func (CloudProvider) String

func (p CloudProvider) String() string

String returns "none", "icloud", "play-games" or "steam".

type CloudSync

type CloudSync interface {
	// Load reads the raw bytes stored in slot, returning ErrSlotNotFound if slot does not exist.
	Load(ctx context.Context, slot string) ([]byte, error)
	// Save writes data to slot, replacing any previous contents.
	Save(ctx context.Context, slot string, data []byte) error
	// Delete removes slot if it exists.
	Delete(ctx context.Context, slot string) error
	// List returns the names of all save slots stored for the current player.
	List(ctx context.Context) ([]string, error)
}

CloudSync is the provider-agnostic cloud-save interface for NSGo games (#196).

PlatformCloud adapts NSGo's cloud package (iCloud on macOS and iOS, Google Play Games Saved Games on Android, and the in-memory store under nsgotest); DirCloud adapts a local directory synced by a desktop storefront such as Steam Auto-Cloud; CloudClient talks to the self-hosted backend in package cloudsave; and games can also supply their own backend or an in-memory mock against this interface.

type CloudSyncOptions

type CloudSyncOptions struct {
	// Local is this device's save backend, such as save.StorageBackend or save.FileBackend. Required.
	Local save.Backend
	// Cloud is the player's cloud storage. Required.
	Cloud CloudSync
	// State holds each slot's sync state on this device, as JSON text under StateKey. Required.
	State core.Storage
	// StateKey is the key prefix CloudSyncer owns in State; DefaultSyncStateKey when empty.
	StateKey string
	// Device identifies this device in cloud payloads and fork slot names: 1 to 64 ASCII letters, digits, '-' or '_'. Required.
	Device string
	// SaveVersion is the game's save schema version (the Store.Version passed to save.NewStore). When greater than 0, a cloud copy whose save envelope version exceeds SaveVersion is never written locally and is reported as OutcomeNeedsUpdate with both versions, and an older client never overwrites or deletes a newer-version cloud copy. When 0, version gating against SaveVersion is disabled, though mixed-version conflicts still refuse to resolve in favour of the older envelope version.
	SaveVersion int
	// Policy resolves conflicts; PolicyNewest when zero.
	Policy ConflictPolicy
	// Ask answers each conflict under PolicyAsk. It is required with PolicyAsk. It runs inside the sync, on the app's thread, so it must return without waiting for the player: to ask through a dialog, keep the Conflict, return ChoiceDefer, show both summaries, and apply the answer with CloudSyncer.Resolve. An error leaves the slot untouched and is returned by the sync.
	Ask func(ctx context.Context, c Conflict) (Choice, error)
	// Summarize returns a short, player-facing description of a save payload for Conflict summaries. Optional.
	Summarize func(slot string, data []byte) string
	// Now returns the current time, used to stamp local writes made through Backend; time.Now when nil.
	Now func() time.Time
}

CloudSyncOptions configures NewCloudSyncer.

type CloudSyncer

type CloudSyncer struct {
	// contains filtered or unexported fields
}

CloudSyncer reconciles a device's save slots with cloud storage, detecting slots that changed on both sides since the last sync and resolving them by policy without silently losing either copy.

It remembers, per slot, the content hash and cloud revision both sides agreed on at the last sync (the base). On each sync it compares the local copy, the cloud copy and the base: when only one side differs from the base that side is copied to the other, and when both differ (and from each other) the slot is a conflict. Cloud payloads are JSON text carrying the revision, content hash, modified time and writing device next to the save data.

Write saves through Backend so that each local write is stamped with its time for PolicyNewest and conflict summaries. A CloudSyncer is not safe for concurrent use; call Sync, SyncSlot and Resolve where the app's code runs, as core.Storage requires, or use SyncAsync, SyncSlotAsync and ResolveAsync to run cloud I/O off the engine goroutine while marshaling local storage, sync state and Ask callbacks onto cx's engine goroutine (required with PlatformCloud on Apple and Android devices, and recommended with CloudClient so network I/O does not stall frames).

Before every cloud write it reads the cloud copy again and refuses to write when it changed (ErrCloudChanged). When Cloud implements ConditionalCloudSync, as CloudClient and DirCloud do, the write itself is conditional on that copy, so an upload by another device can never be overwritten: the losing write fails with ErrCloudChanged and the next sync sees both copies as a conflict for the policy to resolve. A plain CloudSync has no conditional write, so an upload by another device that lands between the re-read and the write can still be overwritten; the window is a single Load and Save apart.

func NewCloudSyncer

func NewCloudSyncer(opts CloudSyncOptions) (*CloudSyncer, error)

NewCloudSyncer returns a CloudSyncer for opts, or an error when a required option is missing or invalid.

func (*CloudSyncer) Backend

func (s *CloudSyncer) Backend() save.Backend

Backend returns the local save backend wrapped so that every Write and Delete is stamped with the current time in the slot's sync state. Pass it to save.NewStore so PolicyNewest and conflict summaries know when each local copy was written. Its Unwrap method returns the local backend, so a save.SettingsStore built on it keeps settings where the local backend does.

func (*CloudSyncer) Resolve

func (s *CloudSyncer) Resolve(ctx context.Context, c Conflict, choice Choice) (SlotResult, error)

Resolve applies choice to a conflict reported earlier, typically one that Ask answered with ChoiceDefer so the game could show the player both copies outside the sync. It reads both sides again and applies choice only while they still hold the copies in c (the same existence, content hash and cloud revision); otherwise it writes nothing and returns ErrConflictChanged. ChoiceDefer writes nothing. Resolve works under every policy and does not call Ask.

func (*CloudSyncer) ResolveAsync

func (s *CloudSyncer) ResolveAsync(cx *core.Scope, ctx context.Context, c Conflict, choice Choice, done func(SlotResult, error))

ResolveAsync runs Resolve asynchronously as SyncAsync does for Sync.

func (*CloudSyncer) Sync

func (s *CloudSyncer) Sync(ctx context.Context) (SyncResult, error)

Sync reconciles every slot known locally, in the cloud or in the sync state, in slot-name order.

A slot that fails is skipped and its error joined into the returned error while the others still sync, except when the cloud is unavailable or ctx is done, which stops the sync.

func (*CloudSyncer) SyncAsync

func (s *CloudSyncer) SyncAsync(cx *core.Scope, ctx context.Context, done func(SyncResult, error))

SyncAsync runs Sync with cloud I/O off cx's engine goroutine while marshaling local backend, sync state, Summarize, Now and Ask calls onto cx's engine goroutine through cx.Post, then delivers the result to done on the engine goroutine. Use it on Apple and Android devices with PlatformCloud (whose callbacks arrive via cx.Post) and with CloudClient so network I/O does not block frames.

Concurrent SyncAsync, SyncSlotAsync and ResolveAsync calls on the same CloudSyncer are serialized in order. If a local save changes a slot while its cloud read is in flight, SyncAsync refuses to overwrite the local copy (ErrConflictChanged) so the next sync resolves both copies cleanly. Disposing cx stops the sync and skips done.

func (*CloudSyncer) SyncSlot

func (s *CloudSyncer) SyncSlot(ctx context.Context, slot string) (SlotResult, error)

SyncSlot reconciles one slot. On error nothing has been written for the slot, except that a failure after a conflict fork was created leaves the fork in place; the next sync uploads it and reuses it rather than creating another.

func (*CloudSyncer) SyncSlotAsync

func (s *CloudSyncer) SyncSlotAsync(cx *core.Scope, ctx context.Context, slot string, done func(SlotResult, error))

SyncSlotAsync runs SyncSlot asynchronously as SyncAsync does for Sync.

type CloudVersion

type CloudVersion struct {
	// Number counts the slot's versions from 1; each write or delete adds one.
	Number int64
	// Deleted marks a version that deleted the slot.
	Deleted bool
	// Hash is the PayloadHash of the version's payload, empty for a deletion.
	Hash string
	// Size is the payload's length in bytes.
	Size int64
	// Created is when the service stored the version.
	Created time.Time
}

CloudVersion describes one kept version of a slot in the service's history.

type CodeRedeemResult

type CodeRedeemResult struct {
	CampaignID string       `json:"campaignId"`
	Code       string       `json:"code"`
	Entry      EconomyEntry `json:"entry"`
}

CodeRedeemResult is the outcome of InboxClient.Redeem.

type ConditionalCloudSync

type ConditionalCloudSync interface {
	CloudSync
	// SaveIf writes data to slot only while the slot holds the payload whose PayloadHash is match, or, when match is empty, only while the slot does not exist. Otherwise it writes nothing and returns an error wrapping ErrCloudChanged.
	SaveIf(ctx context.Context, slot string, data []byte, match string) error
	// DeleteIf removes slot only while it holds the payload whose PayloadHash is match. Otherwise it removes nothing and returns an error wrapping ErrCloudChanged. An empty match succeeds, removing nothing, while slot does not exist.
	DeleteIf(ctx context.Context, slot, match string) error
}

ConditionalCloudSync is a CloudSync whose backend can write and delete a slot only while it still holds the payload the caller last read, so two devices writing the same slot at once cannot overwrite each other. CloudSyncer uses these methods whenever its Cloud implements them; CloudClient does.

A payload is identified by PayloadHash of its raw bytes, as Load returned them.

type Conflict

type Conflict struct {
	// Slot is the save slot name.
	Slot string
	// Local is this device's copy.
	Local SaveVersion
	// Cloud is the copy in cloud storage.
	Cloud SaveVersion
}

Conflict is a slot whose local and cloud copies both changed since this device last synced it, passed to CloudSyncOptions.Ask under PolicyAsk and reported in SlotResult.Conflict. Pass it back to CloudSyncer.Resolve to apply the player's choice later.

type ConflictChoice

type ConflictChoice int

ConflictChoice chooses how ResolveConflict handles an AccountConflict.

const (
	// KeepCurrent keeps the currently signed-in account (for example the guest) and discards the conflicting sign-in.
	KeepCurrent ConflictChoice = iota
	// SwitchToExisting switches the device to the account that already owns the provider identity, leaving the current account behind.
	SwitchToExisting
)

func (ConflictChoice) String

func (c ConflictChoice) String() string

String returns "keep-current", "switch-to-existing" or "unknown".

type ConflictPolicy

type ConflictPolicy int

ConflictPolicy chooses how CloudSyncer resolves a slot whose local and cloud copies both changed since the last sync.

const (
	// PolicyNewest keeps the copy with the later modified time and overwrites the other. When either time is unknown or both are equal it keeps both, as PolicyKeepBoth does, and when one side deleted the slot and the other changed it, it keeps the changed copy. When both sides carry save envelopes of different versions, it never resolves in favour of the older envelope version and falls back to keeping both.
	PolicyNewest ConflictPolicy = iota
	// PolicyKeepBoth keeps the cloud copy in the slot and moves the local copy into a new fork slot on both sides, so neither is lost. When one side deleted the slot and the other changed it, it keeps the changed copy.
	PolicyKeepBoth
	// PolicyAsk passes each conflict, with a summary and envelope version of both copies, to CloudSyncOptions.Ask and applies the player's Choice.
	PolicyAsk
)

func (ConflictPolicy) String

func (p ConflictPolicy) String() string

String returns "newest", "keep-both", "ask" or "unknown".

type Consent = consent.Consent

Consent keeps a player's consent per purpose under one privacy-policy version, in a versioned JSON record in its storage. An answer given under another policy version counts as no answer, so a policy change asks again. Any corrupt or unrecognised stored payload fails closed.

func NewConsent

func NewConsent(store ConsentStorage, key, policy string, regime Regime) *Consent

NewConsent returns the consent stored in store under key (DefaultConsentManagerKey when empty) for the privacy policy version policy, defaulting to regime where the player has not answered.

func NewConsentWithOptions

func NewConsentWithOptions(opts ConsentOptions) *Consent

NewConsentWithOptions creates a Consent manager from opts, loading any existing versioned JSON record, migrating a legacy bare Analytics consent value when present, and honouring Global Privacy Control when opts.GPC is true.

type ConsentChoice

type ConsentChoice = consent.ConsentChoice

ConsentChoice is a player's answer for one purpose.

const (
	// UnknownChoice means the player has not answered for this purpose under the current policy.
	UnknownChoice ConsentChoice = consent.UnknownChoice
	// GrantedChoice means the player explicitly allowed this purpose.
	GrantedChoice ConsentChoice = consent.GrantedChoice
	// DeniedChoice means the player declined, revoked, or opted out of this purpose.
	DeniedChoice ConsentChoice = consent.DeniedChoice
)

type ConsentOptions

type ConsentOptions = consent.ConsentOptions

ConsentOptions configures a Consent manager.

type ConsentRecord

type ConsentRecord = consent.ConsentRecord

ConsentRecord is one stored answer: the choice, when it was made, the version of the privacy policy it was made under and where it was made, such as "prompt", "settings", "default" or "gpc".

type ConsentRevoker

type ConsentRevoker interface {
	Purge() error
}

ConsentRevoker is optionally implemented by providers that buffer events. Purge is called when consent is revoked so already queued events cannot be sent later.

type ConsentState

type ConsentState int

ConsentState represents the player's analytics consent choice.

const (
	// ConsentUnknown is the default before the player chooses. No events are sent or buffered.
	ConsentUnknown ConsentState = iota
	// ConsentDenied records that the player declined or revoked analytics. No events are sent or buffered.
	ConsentDenied
	// ConsentGranted records explicit opt-in consent. Only in this state may events be dispatched to the provider.
	ConsentGranted
)

func (ConsentState) String

func (s ConsentState) String() string

String returns "unknown", "denied" or "granted".

type ConsentStorage

type ConsentStorage = consent.ConsentStorage

ConsentStorage is the key-value storage a Consent keeps its records in, such as core.Storage adapted via CoreConsentStorage.

func CoreConsentStorage

func CoreConsentStorage(store core.Storage) ConsentStorage

CoreConsentStorage adapts a core.Storage to ConsentStorage. It returns nil for a zero core.Storage.

type CrashOptions

type CrashOptions struct {
	// HistorySize is how many recent steps the ring buffer keeps; DefaultHistorySize (120) when <= 0.
	HistorySize int
	// Reporter receives every CrashReport produced by a recovered panic.
	Reporter func(CrashReport)
	// CaptureState optionally returns a JSON-marshalable snapshot of the game's state when a panic is caught.
	// When Consent is set and does not allow ConsentPurpose, CaptureState is never invoked.
	CaptureState func() any
	// Metadata holds initial key-value pairs copied into every CrashReport (such as app version, target OS or scene name).
	Metadata map[string]string
	// Rethrow re-panics with the recovered value after Reporter returns.
	Rethrow bool
	// QueueDir persists reports before Reporter runs so a process exit does not lose them. Empty disables the queue.
	QueueDir string
	// Now returns the clock time for CrashReport.Timestamp; time.Now when nil.
	Now func() time.Time
	// Consent optionally gates crash diagnostics on player consent. When non-nil and
	// Consent.Allowed(ConsentPurpose) is false, panics are still recovered (and rethrown when Rethrow is true),
	// but CaptureState is not called, no report is persisted to QueueDir, and Reporter is not invoked.
	Consent *Consent
	// ConsentPurpose is the purpose checked on Consent; CrashPurpose when empty.
	ConsentPurpose Purpose
	// AgeGate, when set and in ChildMode (or when Consent is linked to an AgeGate in ChildMode),
	// prevents CaptureState from being called and drops State snapshots from crash reports.
	AgeGate *AgeGate
}

CrashOptions configures a CrashReporter.

type CrashReport

type CrashReport = crashreport.CrashReport

CrashReport is a JSON-marshalable snapshot built when a guarded callback panics. It is an alias for crashreport.CrashReport, so headless servers build the same schema without importing liveops.

func LoadQueuedReports

func LoadQueuedReports(dir string) ([]CrashReport, error)

LoadQueuedReports reads persisted JSON reports in lexical order. Invalid files are skipped.

type CrashReporter

type CrashReporter struct {
	// contains filtered or unexported fields
}

CrashReporter records recent simulation steps in a fixed-size ring buffer and catches panics in guarded callbacks or game.Loop runs, building a CrashReport for the app's Reporter.

Example

A CrashReporter keeps the last steps of the simulation and, when a guarded callback panics, reports them with the panic instead of crashing the game.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/liveops"
)

func main() {
	c := liveops.NewCrashReporter(liveops.CrashOptions{
		HistorySize: 2,
		Metadata:    map[string]string{"version": "1.4.0"},
		Now:         func() time.Time { return time.Unix(0, 0) },
		Reporter: func(r liveops.CrashReport) {
			fmt.Println("crash:", r.Message, "at step", r.Step, r.Metadata["version"])
			for _, s := range r.LastSteps {
				fmt.Println(" ", s.Step, s.Summary)
			}
		},
	})
	for i := range 3 {
		c.RecordStep(time.Second/60, fmt.Sprint("wave ", i))
	}
	panicked := c.RunSafe(func() {
		enemies := []string{}
		_ = enemies[3]
	})
	fmt.Println("panicked:", panicked)
}
Output:
crash: runtime error: index out of range [3] with length 0 at step 3 1.4.0
  2 wave 1
  3 wave 2
panicked: true

func NewCrashReporter

func NewCrashReporter(opts CrashOptions) *CrashReporter

NewCrashReporter returns a CrashReporter configured by opts, pre-allocating its step ring buffer so steady-state RecordStep calls perform no heap allocations.

func (*CrashReporter) DeleteMetadata

func (c *CrashReporter) DeleteMetadata(key string)

DeleteMetadata removes a metadata key from subsequent CrashReports.

func (*CrashReporter) GuardLoop

func (c *CrashReporter) GuardLoop(l *game.Loop)

GuardLoop wraps l.Update and l.Draw in place with panic recovery and step recording. If l.Update does not call RecordStep itself during a step, the guard records an "update" step automatically (including for a step that panics).

func (*CrashReporter) LastSteps

func (c *CrashReporter) LastSteps() []StepRecord

LastSteps returns a chronological copy (oldest to newest) of the buffered steps.

func (*CrashReporter) RecordStep

func (c *CrashReporter) RecordStep(dt time.Duration, summary string) uint64

RecordStep appends a step to the ring buffer and returns its monotonic step number. It allocates nothing in steady state.

func (*CrashReporter) RecordStepData

func (c *CrashReporter) RecordStepData(dt time.Duration, summary string, data any) uint64

RecordStepData appends a step with optional structured data to the ring buffer and returns its monotonic step number. It allocates nothing in steady state.

func (*CrashReporter) Reset

func (c *CrashReporter) Reset()

Reset clears the buffered steps without reallocating the ring buffer. The monotonic step counter continues from its current value.

func (*CrashReporter) RunSafe

func (c *CrashReporter) RunSafe(fn func()) (panicked bool)

RunSafe runs fn and recovers any panic into a CrashReport passed to Reporter. It reports whether fn panicked. When CrashOptions.Rethrow is true, RunSafe re-panics with the original value after Reporter returns.

func (*CrashReporter) SetMetadata

func (c *CrashReporter) SetMetadata(key, value string)

SetMetadata sets or updates a metadata key included in subsequent CrashReports.

func (*CrashReporter) Step

func (c *CrashReporter) Step() uint64

Step returns the reporter's current monotonic step count.

func (*CrashReporter) WrapLoop

func (c *CrashReporter) WrapLoop(l *game.Loop) *game.Loop

WrapLoop returns a new *game.Loop that delegates to l.Update and l.Draw with panic recovery and step recording. If l.Update does not call RecordStep itself during a step, the wrapper records an "update" step automatically (including for a step that panics). Returns nil when l is nil.

type CrashUploader

type CrashUploader struct {
	QueueDir string
	Consent  func() bool
	AgeGate  *AgeGate
	Upload   func(CrashReport) error
	Scrub    func(*CrashReport)
}

CrashUploader delivers queued reports after the game starts again. Consent is checked before reading or uploading any report. When AgeGate is set and in ChildMode, State snapshots are cleared before Scrub and Upload. A failed upload leaves the queue intact for a later retry.

func (CrashUploader) Flush

func (u CrashUploader) Flush() error

Flush uploads every queued report in lexical order and removes each file only after Upload succeeds. It is a no-op without consent or an uploader.

type DecodedInvitePayload

type DecodedInvitePayload struct {
	// ID is the value of InviteIDKey ("id") when present in Payload.
	ID string
	// Payload contains every decoded key-value pair except InviteSigKey ("sig"), preserving unknown keys.
	Payload map[string]string
	// Signature is the raw InviteSigKey ("sig") value if present in the input, empty otherwise.
	Signature string
	// Verified is true only when a non-empty HMACKey was provided and Signature matched Payload under HMAC-SHA256.
	Verified bool
}

DecodedInvitePayload is the validated result of DecodeInvitePayload or VerifyInvitePayload.

func DecodeInvitePayload

func DecodeInvitePayload(raw string, opts InvitePayloadOptions) (DecodedInvitePayload, error)

DecodeInvitePayload parses, validates and optionally verifies an encoded "key=value&..." invite payload.

Malformed percent-encoding, empty segments, missing "=" separators, duplicate keys, invalid key names, control characters, invalid UTF-8, excessive key counts and payloads exceeding opts.MaxBytes are rejected safely. Unknown keys that satisfy validation are preserved in DecodedInvitePayload.Payload.

When opts.HMACKey is non-empty:

  • a valid signature sets Verified = true;
  • a present but mismatched signature is rejected with ErrInvalidInviteSignature;
  • a missing signature is rejected with ErrInvalidInviteSignature when opts.RequireSignature is true, and otherwise returns Verified = false.

func VerifyInvitePayload

func VerifyInvitePayload(raw string, hmacKey []byte, maxBytes int) (DecodedInvitePayload, error)

VerifyInvitePayload decodes raw and requires a valid HMAC-SHA256 signature under hmacKey. A game server receiving Invite.RawQuery calls VerifyInvitePayload before granting invite rewards or honoring privileged invite payloads.

type DirCloud

type DirCloud struct {
	// contains filtered or unexported fields
}

DirCloud implements ConditionalCloudSync over a directory on disk, storing each slot as "<slot>.json" with atomic temp-file writes and directory sync.

It is designed for desktop storefronts such as Steam Auto-Cloud, which synchronize a configured directory (such as a subdirectory of cx.DataDir()) across machines without a native cloud SDK. Pairing DirCloud with CloudSyncer gives Steam builds the same CloudSync and conflict-resolution pipeline as iCloud and Google Play Games builds; games that do not need CloudSyncer's conflict envelopes can also point Steam Auto-Cloud directly at save.FileBackend(cx.DataDir()).

DirCloud is safe for concurrent use within a process.

func NewDirCloud

func NewDirCloud(dir string) (*DirCloud, error)

NewDirCloud returns a DirCloud storing slot files inside dir, or an error when dir is empty (such as cx.DataDir() on the web). The directory is created on the first write.

func (*DirCloud) Delete

func (c *DirCloud) Delete(ctx context.Context, slot string) error

Delete implements CloudSync.

func (*DirCloud) DeleteIf

func (c *DirCloud) DeleteIf(ctx context.Context, slot, match string) error

DeleteIf implements ConditionalCloudSync.

func (*DirCloud) Dir

func (c *DirCloud) Dir() string

Dir returns the cleaned directory path where DirCloud keeps slot files.

func (*DirCloud) List

func (c *DirCloud) List(ctx context.Context) ([]string, error)

List implements CloudSync. It returns the sorted names of all valid save slots in the directory, or nil if the directory does not exist yet.

func (*DirCloud) Load

func (c *DirCloud) Load(ctx context.Context, slot string) ([]byte, error)

Load implements CloudSync.

func (*DirCloud) Save

func (c *DirCloud) Save(ctx context.Context, slot string, data []byte) error

Save implements CloudSync.

func (*DirCloud) SaveIf

func (c *DirCloud) SaveIf(ctx context.Context, slot string, data []byte, match string) error

SaveIf implements ConditionalCloudSync.

type EconomyBalanceDelta

type EconomyBalanceDelta struct {
	Currency string `json:"currency"`
	Amount   int64  `json:"amount"`
	Balance  int64  `json:"balance"`
}

EconomyBalanceDelta is one currency change in an EconomyEntry or EconomyPurchase.

type EconomyClient

type EconomyClient struct {
	// contains filtered or unexported fields
}

EconomyClient talks to the self-hosted economy service (pkg/online/economy) over HTTPS as the signed-in player. It imports no server packages, works on every target including the web, and is safe for concurrent use.

func NewEconomyClient

func NewEconomyClient(opts EconomyClientOptions) (*EconomyClient, error)

NewEconomyClient returns a client for opts, or an error when URL or Token is missing or invalid.

func (*EconomyClient) Exchange

func (c *EconomyClient) Exchange(ctx context.Context, exchangeID, key string) (EconomyEntry, error)

Exchange runs a catalog-defined exchange declared in economy.yaml under idempotency key.

func (*EconomyClient) History

func (c *EconomyClient) History(ctx context.Context, limit int, beforeSeq int64) (EconomyHistory, error)

History reads one page of the signed-in player's append-only transaction history, newest first. Pass limit 0 for the server default and beforeSeq 0 for the newest page.

func (*EconomyClient) PurchaseVerifier

func (c *EconomyClient) PurchaseVerifier() func(tr core.Transaction, done func(error))

PurchaseVerifier returns a PurchasesOptions.Verify callback that verifies and credits consumable transactions on the economy service via VerifyPurchase, while accepting device-verified non-consumables and subscriptions.

func (*EconomyClient) VerifyPurchase

func (c *EconomyClient) VerifyPurchase(ctx context.Context, signedTransaction string) (EconomyPurchase, error)

VerifyPurchase submits a StoreKit 2 signed transaction JWS to POST /v1/purchases/verify so the economy service verifies it and credits the product's contents to the player's server wallet idempotently.

func (*EconomyClient) Wallet

func (c *EconomyClient) Wallet(ctx context.Context) (EconomyWallet, error)

Wallet reads the signed-in player's server-owned balances and inventory.

type EconomyClientOptions

type EconomyClientOptions struct {
	// URL is the base URL of the self-hosted economy service (package economy), such as "https://economy.example.com". Must use https, except on a loopback host during development. Required.
	URL string
	// Token returns a current bearer token from the account service for the economy audience ("economy" by default: POST /v1/refresh {"session", "audience": "economy"}). Required.
	Token func(ctx context.Context) (string, error)
	// HTTPClient sends requests; http.DefaultClient when nil. The client uses a copy that does not follow redirects.
	HTTPClient *http.Client
}

EconomyClientOptions configures NewEconomyClient.

type EconomyEntry

type EconomyEntry struct {
	Seq        int64                 `json:"seq"`
	Kind       string                `json:"kind"`
	Key        string                `json:"key"`
	CatalogID  string                `json:"catalogId,omitempty"`
	ProductID  string                `json:"productId,omitempty"`
	Reason     string                `json:"reason,omitempty"`
	Actor      string                `json:"actor,omitempty"`
	Currencies []EconomyBalanceDelta `json:"currencies,omitempty"`
	Items      []EconomyItemDelta    `json:"items,omitempty"`
	Created    time.Time             `json:"created"`
}

EconomyEntry is one entry from the player's append-only server transaction history.

type EconomyHistory

type EconomyHistory struct {
	Entries    []EconomyEntry `json:"entries"`
	NextCursor int64          `json:"nextCursor,omitempty"`
}

EconomyHistory is one page of the player's transaction history, newest first.

type EconomyItemDelta

type EconomyItemDelta struct {
	Item     string `json:"item"`
	Amount   int64  `json:"amount"`
	Quantity int64  `json:"quantity"`
}

EconomyItemDelta is one item quantity change in an EconomyEntry or EconomyPurchase.

type EconomyPurchase

type EconomyPurchase struct {
	TransactionID string                `json:"transactionId"`
	ProductID     string                `json:"productId,omitempty"`
	Account       string                `json:"account,omitempty"`
	Status        string                `json:"status"`
	Quantity      int                   `json:"quantity,omitempty"`
	Currencies    []EconomyBalanceDelta `json:"currencies,omitempty"`
	Items         []EconomyItemDelta    `json:"items,omitempty"`
	Entry         *EconomyEntry         `json:"entry,omitempty"`
}

EconomyPurchase is the server's confirmation of a verified in-app purchase credit.

type EconomyWallet

type EconomyWallet struct {
	Account   string           `json:"account"`
	Balances  map[string]int64 `json:"balances"`
	Inventory map[string]int64 `json:"inventory"`
	Sequence  int64            `json:"sequence"`
}

EconomyWallet is the player's server-owned balances and inventory.

type Event

type Event = analytics.Event

Event is one analytics event delivered to an AnalyticsProvider after explicit consent. It is an alias for analytics.Event so game clients and headless servers share one wire schema.

type InboxAmount

type InboxAmount struct {
	ID     string `json:"id"`
	Amount int64  `json:"amount"`
}

InboxAmount names a currency or item reward quantity inside an InboxAttachment.

type InboxAttachment

type InboxAttachment struct {
	Currencies []InboxAmount `json:"currencies,omitempty"`
	Items      []InboxAmount `json:"items,omitempty"`
}

InboxAttachment is the economy reward bundle attached to an InboxMessage.

type InboxClaimResult

type InboxClaimResult struct {
	Message InboxMessage  `json:"message"`
	Entry   *EconomyEntry `json:"entry,omitempty"`
	Already bool          `json:"already,omitempty"`
}

InboxClaimResult is the outcome of InboxClient.Claim.

type InboxClient

type InboxClient struct {
	// contains filtered or unexported fields
}

InboxClient talks to the server's player inbox and redeemable code routes over HTTPS as the signed-in player. It imports no server packages, works on every target including the web, and is safe for concurrent use.

func NewInboxClient

func NewInboxClient(opts InboxClientOptions) (*InboxClient, error)

NewInboxClient returns a client for opts, or an error when URL or Token is missing or invalid.

func (*InboxClient) Claim

func (c *InboxClient) Claim(ctx context.Context, messageID string) (InboxClaimResult, error)

Claim atomically claims the economy attachments of messageID for the signed-in player.

func (*InboxClient) List

func (c *InboxClient) List(ctx context.Context) ([]InboxMessage, error)

List returns the signed-in player's non-expired inbox messages, newest first.

func (*InboxClient) MarkRead

func (c *InboxClient) MarkRead(ctx context.Context, messageID string) (InboxMessage, error)

MarkRead marks messageID as read for the signed-in player.

func (*InboxClient) Redeem

func (c *InboxClient) Redeem(ctx context.Context, code string) (CodeRedeemResult, error)

Redeem submits a gift or promo code to POST /v1/codes/redeem and returns the granted economy ledger entry or a typed error (ErrCodeUnknown, ErrCodeUsed, ErrCodeExpired, ErrCodeLimit, ErrCodeDisabled, ErrCodeRateLimited).

type InboxClientOptions

type InboxClientOptions struct {
	// URL is the base URL of the service serving /v1/inbox and /v1/codes/redeem, such as "https://economy.example.com". Must use https except on a loopback host during development. Required.
	URL string
	// Token returns a current bearer token for the economy audience. Required.
	Token func(ctx context.Context) (string, error)
	// HTTPClient sends requests; http.DefaultClient when nil. A copy that refuses redirects is used.
	HTTPClient *http.Client
}

InboxClientOptions configures NewInboxClient.

type InboxMessage

type InboxMessage struct {
	ID         string           `json:"id"`
	Account    string           `json:"account,omitempty"`
	Segment    string           `json:"segment,omitempty"`
	Broadcast  bool             `json:"broadcast,omitempty"`
	TitleKey   string           `json:"titleKey,omitempty"`
	BodyKey    string           `json:"bodyKey,omitempty"`
	Title      string           `json:"title,omitempty"`
	Body       string           `json:"body,omitempty"`
	Attachment *InboxAttachment `json:"attachment,omitempty"`
	Created    time.Time        `json:"created"`
	Expires    *time.Time       `json:"expires,omitempty"`
	Read       bool             `json:"read"`
	ReadAt     *time.Time       `json:"readAt,omitempty"`
	Claimed    bool             `json:"claimed"`
	ClaimedAt  *time.Time       `json:"claimedAt,omitempty"`
}

InboxMessage is one player inbox message returned by GET /v1/inbox.

type Invite

type Invite struct {
	// ID is the invite identifier from InviteIDKey ("id"), empty when not present.
	// Pass ID to the game server as the idempotency key for invite reward grants.
	ID string
	// Payload holds all decoded payload fields except InviteSigKey ("sig"), preserving unknown keys.
	Payload map[string]string
	// RawQuery is the raw "key=value&..." payload received from the host, suitable for forwarding to a game server for VerifyInvitePayload.
	RawQuery string
	// RawURL is the full URL that opened the game on native/web hosts (empty on mini games).
	RawURL string
	// Signature is the raw signature from InviteSigKey ("sig"), empty when unsigned.
	Signature string
	// Verified is true only when InvitesOptions.HMACKey was configured and Signature matched Payload under HMAC-SHA256.
	Verified bool
	// Scene is the platform launch scene code (0 when unused).
	Scene int
	// ShareTicket is the opaque group-share ticket supplied by mini-game hosts (empty otherwise).
	ShareTicket string
	// Source reports whether the invite arrived on cold launch (InviteSourceLaunch) or while running (InviteSourceResume).
	Source InviteSource
}

Invite is a decoded, validated invite received when a player opens or resumes the game from a share card or invite link.

func (Invite) Clone

func (inv Invite) Clone() Invite

Clone returns a copy of inv with an independent Payload map.

func (Invite) Get

func (inv Invite) Get(key string) (string, bool)

Get returns the value of key from Invite.Payload.

type InviteEncoding

type InviteEncoding uint8

InviteEncoding chooses where a link-based ShareHost places the encoded invite payload in a URL.

const (
	// InviteEncodeQuery places the encoded payload in the URL query component ("?k=v&...").
	InviteEncodeQuery InviteEncoding = iota
	// InviteEncodeFragment places the encoded payload in the URL fragment component ("#k=v&..."), avoiding server access logs and cache-key fragmentation on the web.
	InviteEncodeFragment
)

func (InviteEncoding) String

func (e InviteEncoding) String() string

String returns "query", "fragment" or "unknown".

type InviteLinkOptions

type InviteLinkOptions struct {
	// BaseURL is the invite URL prefix (for example "mygame://invite" on mobile/desktop or "https://play.example.com/invite" on the web).
	// When non-empty, ExtractInviteQuery matches incoming URLs against BaseURL's scheme, host (case-insensitive) and path (ignoring trailing slashes).
	BaseURL string
	// Encoding selects query (default) or fragment encoding.
	Encoding InviteEncoding
	// AcceptFragment, when true with InviteEncodeQuery, falls back to reading the URL fragment when the query string is empty.
	AcceptFragment bool
}

InviteLinkOptions configures how invite URLs are built and matched on native and web platforms.

type InvitePayloadOptions

type InvitePayloadOptions struct {
	// MaxBytes caps the encoded "key=value&..." payload length in bytes.
	// Values <= 0 use DefaultMaxInvitePayloadBytes (1024).
	MaxBytes int
	// HMACKey, when non-empty, signs encoded payloads with HMAC-SHA256 under InviteSigKey ("sig")
	// and verifies decoded payloads in constant time.
	HMACKey []byte
	// RequireSignature, when true during decoding, rejects unsigned payloads with ErrInvalidInviteSignature.
	// Requires a non-empty HMACKey; otherwise DecodeInvitePayload returns ErrMissingHMACKey.
	RequireSignature bool
}

InvitePayloadOptions configures EncodeInvitePayload and DecodeInvitePayload.

type InviteSource

type InviteSource uint8

InviteSource reports whether an invite reached the game at cold launch or while already running.

const (
	// InviteSourceLaunch indicates the game was cold-started from the invite.
	InviteSourceLaunch InviteSource = iota + 1
	// InviteSourceResume indicates the invite arrived while the game was already running (for example via OnOpenLinks, web URL change or mini-game onShow).
	InviteSourceResume
)

func (InviteSource) String

func (s InviteSource) String() string

String returns "launch", "resume" or "unknown".

type Invites

type Invites struct {
	// contains filtered or unexported fields
}

Invites sends payload-carrying share cards and invites over a ShareHost and reads incoming invites back on cold launch and warm resume.

Outgoing payloads are canonically encoded as "key=value&...", bounded by the host's payload limit and refused before sharing if invalid or oversized. Incoming invites are delivered at most once: Opened consumes the cold-start invite once, and Consume / OnInvite deliver each warm resume invite once. When created with a non-nil core.Scope, Incoming, Consume and PendingCount integrate with NSGo's reactive signal graph.

func NewInvites

func NewInvites(cx *core.Scope, opts InvitesOptions) (*Invites, error)

NewInvites creates an Invites manager backed by opts.Host (or PlatformShareHost on cx when opts.Host is nil). It reads any cold-start launch invite immediately and subscribes to warm resume invites while the scope (or manager, until Close) lives.

func (*Invites) Close

func (i *Invites) Close()

Close unsubscribes from the ShareHost and stops further resume invite delivery. Safe to call more than once.

func (*Invites) Consume

func (i *Invites) Consume() (Invite, bool)

Consume reactively pops and returns the oldest unconsumed invite that arrived while the game was running, delivering each resume invite at most once. Calling Consume inside a core.Effect re-runs the effect whenever a new resume invite arrives.

func (*Invites) Incoming

func (i *Invites) Incoming() (Invite, bool)

Incoming reactively peeks at the oldest unconsumed invite that arrived while the game was running, without consuming it.

func (*Invites) MaxPayloadBytes

func (i *Invites) MaxPayloadBytes() int

MaxPayloadBytes returns the effective byte limit enforced on encoded invite payloads.

func (*Invites) OnInvite

func (i *Invites) OnInvite(fn func(Invite)) (stop func())

OnInvite subscribes fn to invites that arrive while the game is running (warm re-open / onShow) and returns a stop function to unsubscribe.

func (*Invites) Opened

func (i *Invites) Opened() (Invite, bool)

Opened returns the invite that cold-started the game and consumes it so subsequent calls return (Invite{}, false).

func (*Invites) PendingCount

func (i *Invites) PendingCount() int

PendingCount reactively returns the number of unconsumed invites that arrived while the game was running.

func (*Invites) PrepareCard

func (i *Invites) PrepareCard(card Card) (PreparedCard, error)

PrepareCard validates card, encodes its payload as a canonical "key=value&..." string, signs it when HMACKey is set, and enforces MaxPayloadBytes.

func (*Invites) SetMenuCard

func (i *Invites) SetMenuCard(fn func() Card)

SetMenuCard sets the callback supplying the card when the player uses the host's built-in share menu (such as a mini game's Forward button). Passing nil clears and disables the menu card. Each returned Card is validated, size-checked and signed before reaching the host.

func (*Invites) Share

func (i *Invites) Share(card Card, done func(shown bool, err error))

Share validates, encodes and optionally signs card, then asks the ShareHost to present it. Oversized or malformed cards are refused before calling the host and reported immediately to done(false, err).

type InvitesOptions

type InvitesOptions struct {
	// Host is the ShareHost used to send cards and receive launch/resume invites.
	// When nil, NewInvites creates a PlatformShareHost on cx using Platform.
	Host ShareHost
	// Platform configures the default PlatformShareHost when Host is nil.
	Platform PlatformShareHostOptions
	// HMACKey, when non-empty, signs outgoing cards with HMAC-SHA256 under InviteSigKey ("sig")
	// and verifies incoming invites, setting Invite.Verified.
	HMACKey []byte
	// RequireSignature rejects incoming invites that lack a valid HMAC-SHA256 signature under HMACKey.
	// Setting RequireSignature with an empty HMACKey causes NewInvites to return ErrMissingHMACKey.
	RequireSignature bool
	// MaxPayloadBytes caps encoded invite payloads in bytes.
	// When <= 0, the host's MaxPayloadBytes() (or DefaultMaxInvitePayloadBytes) applies.
	// When larger than the host's limit, the smaller host limit still wins.
	MaxPayloadBytes int
	// OnInvite, when non-nil, runs once for each invite that arrives while the game is running.
	OnInvite func(Invite)
	// OnError, when non-nil, receives errors from malformed, oversized or unverified incoming invites or menu-card preparation failures.
	OnError func(error)
}

InvitesOptions configures NewInvites.

type LaunchInvite

type LaunchInvite struct {
	// RawQuery is the encoded "key=value&..." invite payload extracted by the host.
	RawQuery string
	// RawURL is the full link that opened the game on native/web hosts (empty on mini games).
	RawURL string
	// Scene is the platform launch scene code (such as WeChat's launch/onShow scene value; 0 when unused).
	Scene int
	// ShareTicket is the opaque group-share ticket provided by mini-game hosts when opened from a group chat (empty otherwise).
	ShareTicket string
	// Source identifies whether this invite arrived on cold launch or while running.
	Source InviteSource
}

LaunchInvite is the raw invite event delivered by a ShareHost at launch or on resume.

type Ledger

type Ledger struct {
	// Credited are the IDs of consumable transactions credited, oldest first.
	Credited []string `json:"credited,omitempty"`
	// Revoked are the IDs of credited consumable transactions whose refund or revocation was taken back, oldest first.
	Revoked []string `json:"revoked,omitempty"`
}

Ledger records the transactions a game has credited and revoked, so each is applied once across runs. Keep it inside the state PurchasesOptions.Save writes, beside the coins, lives or other state a credit changes: the credit and its record then reach the disk in one write, so a kill before that write loses both and the store's redelivery credits it again, and a kill after it finds the record and only finishes the transaction.

func (Ledger) HasCredited

func (l Ledger) HasCredited(id string) bool

HasCredited reports whether the transaction whose ID is id was credited.

func (Ledger) HasRevoked

func (l Ledger) HasRevoked(id string) bool

HasRevoked reports whether the refund or revocation of the transaction whose ID is id was taken back.

type LoadFunnel

type LoadFunnel struct {
	// contains filtered or unexported fields
}

LoadFunnel records web and native startup stages and emits at most one consent-gated "load" event per session through Analytics.

Nothing is sent from Go before consent allows analytics collection. If Finish runs while consent is still ConsentUnknown, the finalized payload is held in memory and flushed automatically once consent is granted (or when Flush is called after an external consent update); if consent is denied or revoked, the pending payload is dropped cleanly.

LoadFunnel is safe for concurrent use.

func NewLoadFunnel

func NewLoadFunnel(a *Analytics) *LoadFunnel

NewLoadFunnel creates a load-funnel recorder backed by a. A nil Analytics instance records stages safely and never emits.

func (*LoadFunnel) AttachHost

func (f *LoadFunnel) AttachHost(cx *core.Scope)

AttachHost subscribes the funnel to HostEventLoadStage events on cx's host bridge (#1486) and watches cx's lifecycle so moving to the background during loading latches page_hidden to true. It is a no-op when f or cx is nil.

func (*LoadFunnel) Close

func (f *LoadFunnel) Close()

Close discards any pending unsent load payload and releases any consent listener held by the funnel.

func (*LoadFunnel) Finish

func (f *LoadFunnel) Finish() bool

Finish marks the playable stage (if not already recorded), freezes the funnel timings, and attempts to emit the session's single "load" event through Analytics.

It returns true only on the call that actually sends the event. If consent is ConsentUnknown, Finish queues the finalized payload in memory (sending nothing yet), subscribes to consent updates on Analytics so granting consent flushes it automatically, and returns false. If consent is ConsentDenied (or Analytics is nil), Finish drops the payload cleanly and returns false.

func (*LoadFunnel) Flush

func (f *LoadFunnel) Flush() bool

Flush attempts to emit a finished-and-pending "load" event if Analytics consent now allows collection. If consent is explicitly denied, Flush drops the pending payload cleanly. At most one "load" event is ever emitted per funnel instance.

func (*LoadFunnel) HandleHostEvent

func (f *LoadFunnel) HandleHostEvent(data any)

HandleHostEvent ingests a HostEventLoadStage payload delivered over the host bridge (#1486). It accepts:

  • a stage object: {"stage": "download_end", "ms": 840, "bytes": 6291456}
  • a metadata/batch object: {"stages": {"download_start": 40, ...}, "bytes": 6291456, "gpuBackend": "webgpu", "pageHidden": true}
  • a slice of stage objects: [{"stage": "download_start", "ms": 40}, ...]

Malformed, non-finite or unknown fields are ignored safely without panicking.

func (*LoadFunnel) Mark

func (f *LoadFunnel) Mark(stage string)

Mark records a Go-side stage once using the funnel's clock. Repeated marks for the same stage and marks after Finish are ignored so a session's timings stay stable when callbacks retry.

func (*LoadFunnel) MarkLoader

func (f *LoadFunnel) MarkLoader(stage string, elapsedMs float64)

MarkLoader records a loader-side stage timestamp in elapsed milliseconds since navigation start (page_open). Non-finite (NaN or Inf) and overflowing timestamps are ignored; negative timestamps are clamped to 0. Repeated marks for the same stage and marks after Finish are ignored.

func (*LoadFunnel) RecordStartup

func (f *LoadFunnel) RecordStartup(s LoadStartup)

RecordStartup imports Go-side startup milestones (#1625) into the funnel. Stages already recorded are left unchanged, and calls after Finish are ignored.

func (*LoadFunnel) SetBytes

func (f *LoadFunnel) SetBytes(n int64)

SetBytes records the number of bytes downloaded during startup. Negative values and calls after Finish are ignored; repeated positive updates keep the largest observed byte count.

func (*LoadFunnel) SetClock

func (f *LoadFunnel) SetClock(now func() time.Time)

SetClock sets the clock used by Mark; time.Now is used when nil.

func (*LoadFunnel) SetFirstAssetGroupDuration

func (f *LoadFunnel) SetFirstAssetGroupDuration(d time.Duration)

SetFirstAssetGroupDuration records the load duration of the first asset group loaded during startup. Negative durations are clamped to 0. Repeated calls and calls after Finish are ignored.

func (*LoadFunnel) SetGPUBackend

func (f *LoadFunnel) SetGPUBackend(backend string)

SetGPUBackend records the active GPU backend name (for example "webgpu", "webgl2", "metal", "vulkan", or "software"). Empty strings and calls after Finish are ignored.

func (*LoadFunnel) SetPageHidden

func (f *LoadFunnel) SetPageHidden(hidden bool)

SetPageHidden records whether the page or app was hidden during loading. Once hidden is observed as true before Finish, the flag remains latched true even if the page later becomes visible again. Calls after Finish are ignored.

func (*LoadFunnel) SyncStartup

func (f *LoadFunnel) SyncStartup()

SyncStartup copies the process's recorded startup milestones from the internal startup recorder (#1625) into the funnel. In release builds where the development startup recorder is stripped, SyncStartup is a no-op.

type LoadStartup

type LoadStartup struct {
	GoStart         LoadStartupMark
	FirstUpdate     LoadStartupMark
	FirstFrame      LoadStartupMark
	FirstAssetGroup LoadStartupMark
	Playable        LoadStartupMark
}

LoadStartup holds the Go-side startup milestones (#1625): Go initialization, first update, first rendered frame, first asset group load duration, and first playable.

When GoStart.Recorded is true, GoStart, FirstUpdate, FirstFrame and Playable are interpreted as elapsed durations from browser navigation start (page_open); otherwise they are interpreted as elapsed durations from Go startup and anchored after any loader stages. FirstAssetGroup is always the load duration of the first assets.Group.

type LoadStartupMark

type LoadStartupMark struct {
	Elapsed  time.Duration
	Recorded bool
}

LoadStartupMark is one startup milestone's elapsed duration and whether it was recorded.

type MiniGameAd

type MiniGameAd interface {
	// Load fetches an ad (ad.load()) and calls done with the promise's rejection, or nil once it resolves. MiniGameAdHost never calls it on a banner, as banner and custom ad objects have no load() and load themselves when created.
	Load(done func(err error))
	// Show displays the ad (ad.show()) and calls done with the promise's rejection, or nil once it resolves.
	Show(done func(err error))
	// Hide hides a banner or custom ad (ad.hide()); rewarded and interstitial ads close only through the player.
	Hide()
	// OnClose registers fn for the ad's close event (ad.onClose). ended is the event's isEnded: true only when a rewarded video played to the end. A driver passes true when the event carries no result at all, which WeChat documents for base libraries before 2.1.0.
	OnClose(fn func(ended bool))
	// OnError registers fn for the ad's error event (ad.onError), with a *MiniGameAdError or an error wrapping ErrAdNoFill for no fill.
	OnError(fn func(err error))
}

MiniGameAd is one ad object a mini-game runtime created, such as WeChat's wx.createRewardedVideoAd, wx.createInterstitialAd and wx.createCustomAd (wx.createBannerAd before base library 3.5.5), or Douyin's tt equivalents.

type MiniGameAdDriver

type MiniGameAdDriver interface {
	// CreateAd creates the platform ad object for kind and unitID. MiniGameAdHost calls it once per kind and unit ID and keeps the object, as WeChat keeps one rewarded video ad per unit.
	CreateAd(kind AdKind, unitID string) (MiniGameAd, error)
}

MiniGameAdDriver creates ad objects in a mini-game runtime; NSGo provides one once nsgo-dev/nsgo#2672 adds mini-game ads, and a game or a test may supply its own.

type MiniGameAdError

type MiniGameAdError struct {
	Code    int
	Message string
}

MiniGameAdError is an error a mini-game runtime reported for an ad, with the errCode and errMsg of its onError event or rejected promise. It matches ErrAdNoFill when Code is MiniGameAdNoFillCode; a driver for a platform that reports no fill with another code wraps ErrAdNoFill itself.

func (*MiniGameAdError) Error

func (e *MiniGameAdError) Error() string

Error returns the code and message.

func (*MiniGameAdError) Is

func (e *MiniGameAdError) Is(target error) bool

Is reports whether the error is a no fill.

type MiniGameAdHost

type MiniGameAdHost struct {
	// contains filtered or unexported fields
}

MiniGameAdHost is the AdHost for mini games. It creates each ad object once and registers its close and error handlers once, so a reused ad never reports one close to several shows; it retries a failed rewarded or interstitial show once after loading, as WeChat recommends; and it reports a banner shown once it is on screen, leaving it there until HideBanner.

func NewMiniGameAdHost

func NewMiniGameAdHost(driver MiniGameAdDriver) *MiniGameAdHost

NewMiniGameAdHost returns an AdHost over driver. With a nil driver every show fails with ErrAdUnavailable.

func (*MiniGameAdHost) HideBanner

func (h *MiniGameAdHost) HideBanner(unitID string) error

HideBanner implements AdBannerHost, hiding the banner shown for unitID; it does nothing when no banner was created for it.

func (*MiniGameAdHost) Prepare

func (h *MiniGameAdHost) Prepare(cfg *AdsConfig) error

Prepare creates the ad object of every placement cfg declares, so the platform starts loading them before the first show. It returns the first error the driver reports.

func (*MiniGameAdHost) Show

func (h *MiniGameAdHost) Show(kind AdKind, unitID string, done func(ended bool, err error)) error

Show implements AdHost. It returns ErrAdBusy when the same ad object is already showing.

type MiniGameLaunchOptions

type MiniGameLaunchOptions struct {
	// Query is the raw "key=value&..." string. When empty and QueryMap is non-empty, MiniGameShareHost encodes QueryMap canonically.
	Query string
	// QueryMap is the decoded key-value object supplied by runtimes like WeChat mini games.
	QueryMap map[string]string
	// Scene is the platform launch/resume scene code.
	Scene int
	// ShareTicket is the opaque group-share ticket delivered when opened from a group chat with WithShareTicket enabled.
	ShareTicket string
}

MiniGameLaunchOptions mirrors a mini-game runtime's launch and onShow payloads (such as WeChat's wx.getLaunchOptionsSync and wx.onShow).

type MiniGameShareCard

type MiniGameShareCard struct {
	Title      string
	ImageURL   string
	ImageData  []byte
	ImageURLID string
	Query      string
}

MiniGameShareCard is the share-card payload passed to a MiniGameShareDriver (matching WeChat mini game's wx.shareAppMessage and wx.onShareAppMessage fields).

type MiniGameShareDriver

type MiniGameShareDriver interface {
	// ShareAppMessage opens the mini-game forward dialog with card.
	ShareAppMessage(card MiniGameShareCard, done func(shown bool, err error))
	// ShowShareMenu enables or disables the mini-game menu's Forward item (wx.showShareMenu / wx.hideShareMenu).
	ShowShareMenu(enabled bool, withShareTicket bool)
	// OnShareAppMessage registers the handler invoked when the player taps Forward in the mini-game menu. Passing nil clears it.
	OnShareAppMessage(fn func() MiniGameShareCard)
	// LaunchOptions returns the cold-start launch options (wx.getLaunchOptionsSync).
	LaunchOptions() (MiniGameLaunchOptions, bool)
	// OnShow subscribes fn to resume events (wx.onShow) and returns an unsubscribe function.
	OnShow(fn func(MiniGameLaunchOptions)) (stop func())
}

MiniGameShareDriver is the platform runtime hook implemented by mini-game hosts (and by NSGo once nsgo-dev/nsgo#2672 adds mini-game share cards and launch options).

type MiniGameShareHost

type MiniGameShareHost struct {
	// contains filtered or unexported fields
}

MiniGameShareHost adapts a MiniGameShareDriver to ShareHost. Passing a nil driver yields a safe unavailable host (returning ErrShareUnavailable from Share) until NSGo ships mini-game share cards (nsgo-dev/nsgo#2672).

func NewMiniGameShareHost

func NewMiniGameShareHost(driver MiniGameShareDriver, opts MiniGameShareHostOptions) *MiniGameShareHost

NewMiniGameShareHost wraps driver as a ShareHost. If driver is nil, Share fails with ErrShareUnavailable and LaunchInvite/OnInvite/SetMenuCard are safe no-ops.

func (*MiniGameShareHost) LaunchInvite

func (h *MiniGameShareHost) LaunchInvite() (LaunchInvite, bool)

LaunchInvite reads the mini game's cold-start LaunchOptions once.

func (*MiniGameShareHost) MaxPayloadBytes

func (h *MiniGameShareHost) MaxPayloadBytes() int

MaxPayloadBytes returns the host's maximum encoded payload size in bytes.

func (*MiniGameShareHost) OnInvite

func (h *MiniGameShareHost) OnInvite(fn func(LaunchInvite)) (stop func())

OnInvite subscribes to MiniGameShareDriver.OnShow, ignoring ordinary foreground resumes that carry no query payload.

func (*MiniGameShareHost) SetMenuCard

func (h *MiniGameShareHost) SetMenuCard(fn func() (PreparedCard, error))

SetMenuCard enables the mini-game Forward menu (ShowShareMenu + OnShareAppMessage) when fn is non-nil, or disables it when fn is nil.

func (*MiniGameShareHost) Share

func (h *MiniGameShareHost) Share(card PreparedCard, done func(shown bool, err error))

Share forwards card to MiniGameShareDriver.ShareAppMessage, or answers ErrShareUnavailable when driver is nil.

type MiniGameShareHostOptions

type MiniGameShareHostOptions struct {
	// WithShareTicket requests group-chat shareTicket delivery when enabling the share menu.
	WithShareTicket bool
	// MaxPayloadBytes overrides DefaultMaxInvitePayloadBytes (1024) when positive.
	MaxPayloadBytes int
	// FallbackMenuCard is returned to the mini-game menu if the game's SetMenuCard callback returns an invalid or oversized Card.
	FallbackMenuCard MiniGameShareCard
}

MiniGameShareHostOptions configures NewMiniGameShareHost.

type News

type News struct {
	// contains filtered or unexported fields
}

News fetches the game's announcement feed from GET /v1/news using ETag conditional requests, caches the feed to the app's data directory (or core.Storage), and tracks per-post read state. It is safe for concurrent use and works on every target including web.

func NewNews

func NewNews(opts NewsOptions) (*News, error)

NewNews creates a News client for opts and loads any previously cached feed and read state.

func (*News) ETag

func (n *News) ETag() string

ETag returns the cached ETag sent in If-None-Match on the next Fetch.

func (*News) Fetch

func (n *News) Fetch(ctx context.Context) ([]NewsPost, error)

Fetch requests GET /v1/news with the configured platform, appVersion, locale and cached ETag. When the server replies 304 Not Modified, cached posts are returned untouched. When the server replies 200 OK, the cache is updated and persisted before returning the new posts. On network or HTTP errors, previously cached posts remain available via Posts().

func (*News) IsRead

func (n *News) IsRead(id string) bool

IsRead reports whether the post with ID id has been marked read.

func (*News) MarkRead

func (n *News) MarkRead(id string) error

MarkRead records id as read and persists the updated read state to the cache.

func (*News) Posts

func (n *News) Posts() []NewsPost

Posts returns a copy of the currently cached news posts.

func (*News) ReadIDs

func (n *News) ReadIDs() []string

ReadIDs returns a sorted copy of all post IDs marked read.

func (*News) Unread

func (n *News) Unread() []NewsPost

Unread returns the cached news posts that have not yet been marked read via MarkRead.

func (*News) UnreadCount

func (n *News) UnreadCount() int

UnreadCount returns the number of cached news posts not yet marked read.

type NewsOptions

type NewsOptions struct {
	// URL is the base URL of the service serving GET /v1/news, such as "https://economy.example.com". Must use https, except on a loopback host during development. Required.
	URL string
	// CacheDir is the app's data directory where DefaultNewsCacheFile stores the cached feed, ETag and read post IDs. Ignored when CachePath is set.
	CacheDir string
	// CachePath is the explicit JSON cache file path. Takes precedence over CacheDir.
	CachePath string
	// Storage optionally persists the JSON cache in core.Storage when CachePath and CacheDir are empty (for example on web builds without a local filesystem).
	Storage core.Storage
	// StorageKey is the core.Storage key when Storage is used; defaults to DefaultNewsCacheKey.
	StorageKey string
	// Platform identifies the client platform ("ios", "android", "darwin", "linux", "windows", "web"). Defaults to "web" on js/wasm and runtime.GOOS otherwise.
	Platform string
	// AppVersion is the client's semantic version sent as the appVersion query parameter (for example "1.2.0").
	AppVersion string
	// Locale is the client's BCP 47 locale tag sent as the locale query parameter (for example "en-US", "zh-Hans").
	Locale string
	// HTTPClient sends requests; http.DefaultClient when nil. A copy that refuses redirects is used.
	HTTPClient *http.Client
	// Now overrides the clock for tests; defaults to time.Now.
	Now func() time.Time
}

NewsOptions configures NewNews.

type NewsPost

type NewsPost struct {
	ID       string            `json:"id"`
	TitleKey string            `json:"titleKey,omitempty"`
	BodyKey  string            `json:"bodyKey,omitempty"`
	Title    map[string]string `json:"title,omitempty"`
	Body     map[string]string `json:"body,omitempty"`
	Image    string            `json:"image,omitempty"`
	EventID  string            `json:"eventId,omitempty"`
	Start    *time.Time        `json:"start,omitempty"`
	End      *time.Time        `json:"end,omitempty"`
}

NewsPost is one announcement returned by GET /v1/news.

func (NewsPost) ResolveBody

func (p NewsPost) ResolveBody(locale string, localize func(string) string) string

ResolveBody returns the localized body for locale, preferring localize(BodyKey) when both are non-empty and falling back to the inline Body map.

func (NewsPost) ResolveTitle

func (p NewsPost) ResolveTitle(locale string, localize func(string) string) string

ResolveTitle returns the localized title for locale, preferring localize(TitleKey) when both are non-empty and falling back to the inline Title map.

type ParentalGateFunc

type ParentalGateFunc = consent.ParentalGateFunc

ParentalGateFunc runs an adult-check challenge and calls done with whether it passed.

type PlatformAgeSignal

type PlatformAgeSignal = consent.PlatformAgeSignal

PlatformAgeSignal carries an age range reported by a platform API.

type PlatformAgeSignalSource

type PlatformAgeSignalSource = consent.PlatformAgeSignalSource

PlatformAgeSignalSource identifies the OS or store API that produced a PlatformAgeSignal.

type PlatformCloud

type PlatformCloud struct {
	// contains filtered or unexported fields
}

PlatformCloud implements CloudSync over NSGo's package cloud: Apple iCloud ubiquity containers on macOS and iOS, Google Play Games Saved Games on Android, and an isolated per-app in-memory store in nsgotest. On platforms without a built-in OS cloud store (Windows, Linux, the web), every operation fails with ErrCloudUnavailable and never silently drops writes.

Each save slot is stored as "<Prefix><slot>.json" (default "save.<slot>.json") and validated with save.ValidateSlot. Errors wrap liveops's sentinels alongside package cloud's sentinels: ErrCloudUnavailable (cloud.ErrUnavailable), ErrSlotNotFound (cloud.ErrNotFound), and ErrCloudConflict (cloud.ErrConflict / *cloud.ConflictError).

On real Apple and Android targets (where cx.CloudStore() is nil), package cloud delivers its callbacks on cx's engine goroutine through cx.Post, so blocking CloudSync methods (Load, Save, Delete, List) must be called off the engine goroutine—such as through CloudSyncer.SyncAsync—or they would block the goroutine needed to deliver their answer. Under nsgotest (where cx.CloudStore() is non-nil), operations run directly against the per-app store and are safe from any goroutine, including synchronous CloudSyncer.Sync calls in tests.

func NewPlatformCloud

func NewPlatformCloud(cx *core.Scope, opts PlatformCloudOptions) (*PlatformCloud, error)

NewPlatformCloud returns a PlatformCloud bound to cx, or an error if cx is nil or opts.Prefix is invalid. Call it on cx's engine goroutine with a scope that lives as long as cloud sync runs (such as the app's root scope).

func (*PlatformCloud) Available

func (c *PlatformCloud) Available() bool

Available reports whether platform cloud storage is reachable right now (cx.Env().CanUseCloudStorage() on a non-simulated host). Read in a reactive computation on the engine goroutine, it updates when availability changes.

func (*PlatformCloud) Delete

func (c *PlatformCloud) Delete(ctx context.Context, slot string) error

Delete implements CloudSync. Deleting an absent slot succeeds when cloud storage is available and returns ErrCloudUnavailable when it is not.

func (*PlatformCloud) FileName

func (c *PlatformCloud) FileName(slot string) (string, error)

FileName returns the platform cloud file or snapshot name for slot ("<Prefix><slot>.json"), or an error wrapping save.ErrInvalidSlot when slot is invalid.

func (*PlatformCloud) List

func (c *PlatformCloud) List(ctx context.Context) ([]string, error)

List implements CloudSync. It lists the sorted names of valid save slots matching this PlatformCloud's prefix, ignoring other files in the cloud container.

func (*PlatformCloud) Load

func (c *PlatformCloud) Load(ctx context.Context, slot string) ([]byte, error)

Load implements CloudSync. It returns ErrSlotNotFound when slot does not exist, ErrCloudUnavailable when cloud storage is unavailable or cx is disposed, and ErrCloudConflict (also wrapping *cloud.ConflictError) when unresolved native platform conflicts exist.

func (*PlatformCloud) OnConflict

func (c *PlatformCloud) OnConflict(resolve func(PlatformConflict)) (stop func())

OnConflict subscribes resolve to native platform version conflicts for slots matching this PlatformCloud's prefix. Notifications are delivered on cx's engine goroutine and stop automatically when stop is called or cx is disposed.

func (*PlatformCloud) Prefix

func (c *PlatformCloud) Prefix() string

Prefix returns the file-name prefix prepended to each slot name.

func (*PlatformCloud) Provider

func (c *PlatformCloud) Provider() CloudProvider

Provider returns the built-in OS cloud-save service of the platform cx runs on (CloudProviderICloud, CloudProviderPlayGames, or CloudProviderNone), whether or not the player is signed in.

func (*PlatformCloud) Save

func (c *PlatformCloud) Save(ctx context.Context, slot string, data []byte) error

Save implements CloudSync. It writes data to slot and returns ErrCloudUnavailable rather than silently dropping writes when cloud storage is unavailable.

func (*PlatformCloud) WatchChanges

func (c *PlatformCloud) WatchChanges(onChange func(CloudChange)) (stop func())

WatchChanges subscribes onChange to external cloud-save changes for slots matching this PlatformCloud's prefix. Notifications are delivered on cx's engine goroutine and stop automatically when stop is called or cx is disposed. Account-change notifications (cloud.ChangeAccount) and container-wide initial-sync notifications are delivered even when the platform did not enumerate individual file names.

type PlatformCloudOptions

type PlatformCloudOptions struct {
	// Prefix is prepended to each slot name to form its cloud file or snapshot name ("<Prefix><slot>.json"); DefaultCloudPrefix ("save.") when empty. Must not start with '/' or '.', or contain "..", '\', "//" or control characters. Avoid '/' when targeting Android, where Google Play Games snapshot names do not accept path separators.
	Prefix string
}

PlatformCloudOptions configures NewPlatformCloud.

type PlatformConflict

type PlatformConflict struct {
	// Slot is the save slot name.
	Slot string
	// Local holds the local cloud payload bytes (which may be a CloudSyncer JSON envelope decodable with DecodeCloudSave).
	Local []byte
	// Remote holds the conflicting remote cloud payload bytes.
	Remote []byte
	// LocalTime is the modification time reported for Local, if known.
	LocalTime time.Time
	// RemoteTime is the modification time reported for Remote, if known.
	RemoteTime time.Time
	// Resolve commits the winning payload bytes to platform cloud storage, clearing the native conflict.
	Resolve func(chosen []byte) error
}

PlatformConflict describes a version conflict reported by the native platform cloud backend (iCloud NSFileVersion or Google Play Games Saved Games) for one save slot.

type PlatformShareHost

type PlatformShareHost struct {
	// contains filtered or unexported fields
}

PlatformShareHost implements ShareHost on mobile (iOS, Android), desktop (macOS, Windows, Linux) and the web (core.OSWeb) using NSGo's core.Scope.Share, core.Scope.OnOpenLinks, core.Scope.AppURL and core.Scope.OnAppURLChange.

func NewPlatformShareHost

func NewPlatformShareHost(cx *core.Scope, opts PlatformShareHostOptions) (*PlatformShareHost, error)

NewPlatformShareHost creates a ShareHost backed by cx's native/web share sheet and link-opening hooks.

func (*PlatformShareHost) LaunchInvite

func (h *PlatformShareHost) LaunchInvite() (LaunchInvite, bool)

LaunchInvite inspects cx.AppURL() once for a cold-start invite link matching PlatformShareHostOptions.

func (*PlatformShareHost) MaxPayloadBytes

func (h *PlatformShareHost) MaxPayloadBytes() int

MaxPayloadBytes returns the host's maximum encoded payload size in bytes.

func (*PlatformShareHost) OnInvite

func (h *PlatformShareHost) OnInvite(fn func(LaunchInvite)) (stop func())

OnInvite subscribes to incoming deep links (core.Scope.OnOpenLinks) and web address/hash changes (core.Scope.OnAppURLChange).

func (*PlatformShareHost) SetMenuCard

func (h *PlatformShareHost) SetMenuCard(func() (PreparedCard, error))

SetMenuCard is a no-op on native and web platforms, which have no host-managed Forward menu.

func (*PlatformShareHost) Share

func (h *PlatformShareHost) Share(card PreparedCard, done func(shown bool, err error))

Share builds the invite link for card and presents it through core.Scope.Share (attaching card.Image when it carries image bytes, pixels or a local file path).

type PlatformShareHostOptions

type PlatformShareHostOptions struct {
	// BaseURL is the invite URL prefix used to build shared invite links and match incoming links
	// (for example "mygame://invite" on mobile/desktop or "https://play.example.com/invite" on the web).
	// On core.OSWeb, when BaseURL is empty, NewPlatformShareHost derives it from cx.AppURL() by stripping its query and fragment.
	BaseURL string
	// Encoding chooses whether the invite payload is placed in the URL query ("?k=v", default) or fragment ("#k=v").
	Encoding InviteEncoding
	// AcceptFragment, when true with InviteEncodeQuery, also extracts payloads from the URL fragment when the query string is empty.
	AcceptFragment bool
	// MaxPayloadBytes overrides DefaultMaxInvitePayloadBytes (1024) when positive.
	MaxPayloadBytes int
	// FallbackToClipboard, when true, copies the formatted share text/link to the clipboard via cx.SetClipboard
	// if cx.Share reports core.CodeUnavailable (for example on desktop browsers without navigator.share).
	FallbackToClipboard bool
	// FormatText builds the share text from the card's title and formatted invite link.
	// When nil, non-empty title formats as "<title>\n<link>" and empty title formats as "<link>".
	FormatText func(title, link string) string
}

PlatformShareHostOptions configures NewPlatformShareHost for mobile, desktop and web targets over NSGo's core APIs.

type Portal

type Portal struct {
	Provider PortalProvider
	SDK      PortalSDK
	Hooks    PortalHooks
	Timeout  time.Duration
	// contains filtered or unexported fields
}

Portal coordinates portal SDK calls with the game pause, audio and input lifecycle. Provider and SDK select the portal; Timeout bounds each SDK call (10 seconds when zero), and Portal restores game state even if the SDK never returns before Timeout elapses.

func NewPortal

func NewPortal(cx *core.Scope, opts PortalOptions) (*Portal, error)

NewPortal constructs a Portal configured by opts and binds its cleanup to cx when cx is non-nil.

On non-web targets when opts.SDK is nil, any configured provider degrades to PortalNone so desktop, mobile, and test builds run unchanged without a web SDK. When opts.Bridge is provided, NewPortal composes break pause/mute holds through Bridge.HoldPause and Bridge.SuspendAudio, forwards Bridge's loaded, gameplayStart, and gameplayStop events to the portal SDK in FIFO order, and applies CrazyGames muteAudio updates through Bridge.SuspendAudio.

func (*Portal) AudioMuted

func (p *Portal) AudioMuted() bool

AudioMuted reports whether the portal currently requests the game to mute audio (for example, CrazyGames' SDK.game.settings.muteAudio).

func (*Portal) Break

func (p *Portal) Break(ctx context.Context) error

Break runs a commercial break and restores game state even when the SDK fails or times out. Concurrent calls while a break is active return ErrPortalBusy.

func (*Portal) BreakAsync

func (p *Portal) BreakAsync(cx *core.Scope, done func(error))

BreakAsync runs a commercial break without blocking cx's engine goroutine. Pause, mute, and input reset run immediately on the caller's turn; the SDK call runs off the engine goroutine under Portal.Timeout, and unmute, resume, and done run on cx's engine goroutine once the break finishes or times out.

func (*Portal) Close

func (p *Portal) Close() error

Close releases listeners, audio mute holds, and any resources owned by SDK (such as syscall/js callbacks on js/wasm).

func (*Portal) GameplayStart

func (p *Portal) GameplayStart(ctx context.Context) error

GameplayStart tells the web portal's SDK that gameplay has started; it does nothing without a portal.

func (*Portal) GameplayStop

func (p *Portal) GameplayStop(ctx context.Context) error

GameplayStop tells the web portal's SDK that gameplay has stopped, so the portal may show ads; it does nothing without a portal.

func (*Portal) Happytime

func (p *Portal) Happytime(ctx context.Context) error

Happytime signals a celebratory moment (such as beating a level or setting a high score) on portals that support it (CrazyGames SDK.game.happytime). It is a no-op elsewhere.

func (*Portal) Init

func (p *Portal) Init(ctx context.Context) error

Init explicitly initializes the portal SDK (loading its script on web targets if needed) under Portal.Timeout. It is a no-op when the provider needs no separate initialization or when Provider is PortalNone.

func (*Portal) LoadingFinished

func (p *Portal) LoadingFinished(ctx context.Context) error

LoadingFinished reports that the first playable scene is ready.

func (*Portal) LoadingStart

func (p *Portal) LoadingStart(ctx context.Context) error

LoadingStart reports that asset loading has started on portals that track it (such as CrazyGames SDK.game.loadingStart). It is a no-op elsewhere.

func (*Portal) Rewarded

func (p *Portal) Rewarded(ctx context.Context) (bool, error)

Rewarded runs an opt-in break and returns true only when the provider grants the reward before Timeout elapses. SDK errors, cancellations, timeouts, and overlapping calls never grant it.

func (*Portal) RewardedAsync

func (p *Portal) RewardedAsync(cx *core.Scope, done func(granted bool, err error))

RewardedAsync runs an opt-in rewarded break without blocking cx's engine goroutine. Pause, mute, and input reset run immediately; unmute, resume, and done run on cx's engine goroutine once the break finishes or times out. granted is true only when the provider reports verified success before Timeout elapses.

func (*Portal) Validate

func (p *Portal) Validate() error

Validate rejects an incomplete configured portal.

type PortalAudioState

type PortalAudioState interface {
	AudioMuted() bool
	OnAudioMuteChange(fn func(muted bool)) (unsubscribe func())
}

PortalAudioState is an optional extension of PortalSDK for portals such as CrazyGames that expose a host-controlled audio mute flag (muteAudio) and notify the game when it changes.

type PortalBridge

type PortalBridge interface {
	HoldPause() func()
	SuspendAudio() func()
	OnEvent(fn func(event string)) func()
}

PortalBridge is the subset of hostbridge.Bridge that Portal composes with so web portal breaks, CrazyGames muteAudio, and loading/gameplay events build on the #1486 host contract rather than duplicating it. *hostbridge.Bridge satisfies PortalBridge directly.

type PortalHappytime

type PortalHappytime interface {
	Happytime(context.Context) error
}

PortalHappytime is an optional extension of PortalSDK for portals such as CrazyGames that expose a positive-moment celebration call (SDK.game.happytime).

type PortalHooks

type PortalHooks struct {
	Pause      func()
	Resume     func()
	Mute       func()
	Unmute     func()
	ResetInput func()
}

PortalHooks owns game-side state that must be suspended during an ad break. Before a break Portal calls Pause, Mute and ResetInput, in that order; after it, whether the break succeeded, failed or timed out, Unmute and Resume. A nil hook is skipped.

type PortalInitializer

type PortalInitializer interface {
	Init(context.Context) error
}

PortalInitializer is an optional extension of PortalSDK for adapters that load a remote script or run an asynchronous SDK init handshake.

type PortalLoadingStarter

type PortalLoadingStarter interface {
	LoadingStart(context.Context) error
}

PortalLoadingStarter is an optional extension of PortalSDK for portals such as CrazyGames that distinguish loading start from loading stop.

type PortalOptions

type PortalOptions struct {
	// Provider explicitly selects a portal provider. When PortalNone, Config
	// (from game.yaml's portal.provider) or AutoDetect selects the provider.
	Provider PortalProvider
	// Config is the provider name from game.yaml: "auto", "none", "poki", or
	// "crazygames". Empty behaves like "none" unless AutoDetect is true.
	Config string
	// ScriptURL optionally overrides the web SDK script URL loaded on js/wasm.
	ScriptURL string
	// AutoDetect enables browser page-host detection on js/wasm when Provider
	// is PortalNone and Config is empty or "auto".
	AutoDetect bool
	// SDK overrides the provider SDK adapter (useful in tests). When nil,
	// NewPortal creates the web adapter on js/wasm and falls back to PortalNone
	// off the web so desktop, mobile, and test builds are a safe no-op.
	SDK PortalSDK
	// Bridge connects the portal to the game's hostbridge.Bridge so pause,
	// audio mute, loading, and gameplay start/stop build on #1486 instead of
	// duplicating lifecycle wiring.
	Bridge PortalBridge
	// Actions is reset before every commercial or rewarded break so held keys
	// or touch buttons never leak across ads.
	Actions *input.Actions
	// Hooks supplies or augments pause, mute, and input-reset hooks. When
	// Bridge or Actions are set, NewPortal composes them with Hooks.
	Hooks PortalHooks
	// Timeout bounds each SDK call (10 seconds when zero).
	Timeout time.Duration
}

PortalOptions configures a Portal created by NewPortal.

type PortalProvider

type PortalProvider uint8

PortalProvider identifies a web-game hosting portal. PortalNone is safe on native targets and in tests.

const (
	// PortalNone is no portal: every Portal method does nothing.
	PortalNone PortalProvider = iota
	// PortalPoki is Poki (HTML5 SDK).
	PortalPoki
	// PortalCrazyGames is CrazyGames (SDK v3).
	PortalCrazyGames
)

The supported portals.

func DetectPortalProvider

func DetectPortalProvider(hostOrURL string) PortalProvider

DetectPortalProvider identifies a known web portal from a hostname or URL. It returns PortalNone for local hosts, unknown sites, or empty input.

func ParsePortalProvider

func ParsePortalProvider(name string) (PortalProvider, error)

ParsePortalProvider parses a portal provider name ("none", "poki", or "crazygames", case-insensitive). Empty string maps to PortalNone.

func (PortalProvider) String

func (p PortalProvider) String() string

String returns the canonical lowercase portal provider name: "none", "poki", or "crazygames".

type PortalSDK

type PortalSDK interface {
	LoadingFinished(context.Context) error
	GameplayStart(context.Context) error
	GameplayStop(context.Context) error
	CommercialBreak(context.Context) error
	RewardedBreak(context.Context) (bool, error)
}

PortalSDK is the small provider seam used by Portal. Web adapters call the corresponding JavaScript SDK methods, while tests can use a deterministic fake.

type PreparedCard

type PreparedCard struct {
	// Title is the validated card title.
	Title string
	// Image is the card's image source.
	Image core.ImageSource
	// ImageID is the optional platform-reviewed image identifier.
	ImageID string
	// Query is the canonical encoded "key=value&..." payload (including id and sig when present), guaranteed to fit within the host's byte limit.
	Query string
	// Anchor is the optional popover anchor for native share sheets.
	Anchor *core.Ref
}

PreparedCard is a validated, payload-encoded card ready for a ShareHost to present.

type Purchases

type Purchases struct {
	// contains filtered or unexported fields
}

Purchases sells a game's in-app products over NSGo's purchase services: it credits consumables into the save exactly once, keeps unlocks and subscriptions from the store's entitlements, restores them, follows purchases waiting for approval and hands each transaction to an optional server before delivering it. Its methods run on the scope's goroutine, as NSGo's callbacks do.

func NewPurchases

func NewPurchases(cx *core.Scope, opts PurchasesOptions) *Purchases

NewPurchases starts selling with opts under cx: it registers for the store's transaction updates, which hand over unfinished transactions as the app starts, and reads the user's current entitlements. Call it as the app starts, before the first frame, so no update waits.

func (*Purchases) Available

func (p *Purchases) Available() bool

Available reports whether this platform and build reach a store, core.Env.CanPurchase; read in a reactive computation, it follows it.

func (*Purchases) Buy

func (p *Purchases) Buy(product string, quantity int, done func(BuyResult, error))

Buy buys quantity of product (0 is 1) through the store's sheet and answers done once: Bought after the transaction is verified and delivered, BuyPending or BuyCancelled, or BuyFailed with the error. When PurchasesOptions.AgeGate is in ChildMode, Buy requires PurchasesOptions.ParentalGate to pass first (failing with ErrParentalGateRequired when nil or ErrParentalGateFailed when declined). When PreCheck or PreCheckAsync returns an error, Buy answers BuyFailed before opening the store sheet. done may be nil.

func (*Purchases) BuyOffer

func (p *Purchases) BuyOffer(product string, offer *core.PromotionalOffer, done func(BuyResult, error))

BuyOffer buys a subscription with a server-signed promotional offer. The offer is passed through to StoreKit; other targets may reject it as unsupported. When PurchasesOptions.AgeGate is in ChildMode, BuyOffer requires PurchasesOptions.ParentalGate to pass first. When PreCheck or PreCheckAsync returns an error, BuyOffer answers BuyFailed before opening the store sheet.

func (*Purchases) Entitlement

func (p *Purchases) Entitlement(product string) (core.Transaction, bool)

Entitlement returns the latest transaction that gives the user product, and whether there is one, whatever its expiration date.

func (*Purchases) Owned

func (p *Purchases) Owned(product string) bool

Owned reports whether the user owns product now: a non-consumable or a subscription that is neither refunded nor past its expiration date at the scope's wall time. Read in a reactive computation, it follows purchases, refunds and restores.

func (*Purchases) Pending

func (p *Purchases) Pending(product string) bool

Pending reports whether a purchase of product waits for approval. Read in a reactive computation, it follows the approval. A request the approver declines produces no transaction, so Pending stays true until a transaction for product arrives, from a later Buy too, or the app restarts.

func (*Purchases) Refresh

func (p *Purchases) Refresh(done func(error))

Refresh reads the user's current entitlements from the store and makes them what Owned reports, then answers done, which may be nil. An unlock delivered while the answer was on its way stays, unless the answer holds a later transaction for it, and one refunded meanwhile stays gone. NewPurchases calls it; call it again as the app returns to the foreground, which is also when Owned next notices a subscription that expired. An error goes to done, or to OnError when done is nil.

func (*Purchases) Restore

func (p *Purchases) Restore(done func(error))

Restore has the store bring the user's purchases up to date, which may ask them to sign in, then refreshes what Owned reports, and answers done, which may be nil: nil, or the store's error, core.PurchaseCancelled when the user declined to sign in. Call it only from a Restore Purchases button the user presses.

type PurchasesOptions

type PurchasesOptions struct {
	// Ledger is the game's record of credited transactions, which Save must persist along with the state Credit and Revoke change. Required unless Economy is set.
	Ledger *Ledger
	// Credit applies a consumable transaction to the game's state, tr.Quantity of tr.ProductID. It runs at most once per transaction ID, across runs too, as long as Save persists Ledger with that state. Not used when Economy is set.
	Credit func(tr core.Transaction)
	// Revoke takes back what a credited consumable gave when the store refunds or revokes it; nil keeps the credit. It runs at most once per transaction ID, as Credit does. Not used when Economy is set.
	Revoke func(tr core.Transaction)
	// Save persists the game's save, Ledger included, after Credit or Revoke changed it. A transaction is finished only once Save returns nil: after an error it stays unfinished, the store hands it to the app again at its next launch, and the ledger kept in memory or on disk keeps Credit from running twice. Required for consumables unless Economy is set.
	Save func() error
	// Verify hands tr, whose Signed is the store's JWS, to the game's server and calls done once with nil to accept it or an error to refuse it, from any goroutine. A refused transaction is neither delivered nor finished. nil accepts what the device verified, Transaction.Verified (or uses Economy for consumables when Economy is set).
	Verify func(tr core.Transaction, done func(error))
	// Economy, when set, verifies and credits consumable transactions directly into the player's server-owned wallet via EconomyClient.VerifyPurchase instead of crediting them into a client-side Ledger and Save. Ledger, Credit, Revoke and Save are not required when Economy is set.
	Economy *EconomyClient
	// AccountToken is the UUID of the game's own that each purchase carries to the store and the game's server, "" for none.
	AccountToken string
	// PreCheck, when set, is consulted synchronously before Buy or BuyOffer opens the store's purchase sheet. Returning a non-nil error (such as a minor spending-cap refusal) aborts the purchase immediately with BuyFailed without invoking the store sheet.
	PreCheck func(product string) error
	// PreCheckAsync, when set, runs after PreCheck before Buy or BuyOffer opens the store's purchase sheet (for example, to call a server-side spend-cap endpoint). Call done once with nil to proceed or an error to refuse the purchase, from any goroutine.
	PreCheckAsync func(product string, quantity int, done func(error))
	// OnError hears failures that no Buy or Restore answers: a transaction from the store's updates refused, unsaved or not finished, or entitlements the store could not answer.
	OnError func(tr core.Transaction, err error)
	// AgeGate, when set and in ChildMode, requires ParentalGate to succeed before Buy or BuyOffer
	// opens the store's sheet. If ChildMode is true and ParentalGate is nil, Buy and BuyOffer refuse
	// immediately with ErrParentalGateRequired.
	AgeGate *AgeGate
	// ParentalGate challenges the user (for example gameui.ParentalGate.Ask) before Buy or BuyOffer
	// proceeds while AgeGate is in ChildMode. A failed or cancelled gate answers BuyFailed with
	// ErrParentalGateFailed without opening the store sheet.
	ParentalGate ParentalGateFunc
}

PurchasesOptions configures NewPurchases.

type Purpose

type Purpose = consent.Purpose

Purpose is what a player's data is collected for, each consented to separately.

const (
	// AnalyticsPurpose covers gameplay telemetry and product analytics.
	AnalyticsPurpose Purpose = consent.AnalyticsPurpose
	// CrashPurpose covers crash diagnostics, stack traces and optional state snapshots.
	CrashPurpose Purpose = consent.CrashPurpose
	// PersonalizationPurpose covers tailored in-game offers, recommendations and content.
	PersonalizationPurpose Purpose = consent.PersonalizationPurpose
	// MarketingPurpose covers campaign attribution, promotional messaging and third-party sharing.
	MarketingPurpose Purpose = consent.MarketingPurpose
)

type PurposeSpec

type PurposeSpec = consent.PurposeSpec

PurposeSpec declares one consent purpose that the game presents to players and gates features on.

func DefaultPurposes

func DefaultPurposes() []PurposeSpec

DefaultPurposes returns the four built-in consent purposes (analytics, crash, personalization and marketing) with default English copy, l10n keys and Global Privacy Control rules.

type QuietHours

type QuietHours struct {
	// Start is the inclusive local start time in 24-hour "HH:MM" form, such as "22:00".
	Start string `yaml:"start" schema:"required,minLength=5"`
	// End is the exclusive local end time in 24-hour "HH:MM" form, such as "08:00".
	End string `yaml:"end" schema:"required,minLength=5"`
}

QuietHours defines a daily local-time window [Start, End) during which reminders are not delivered. Any reminder that would fire inside QuietHours is deferred to End (on the same day, or the following morning when Start is later than End).

func (*QuietHours) Clone

func (q *QuietHours) Clone() *QuietHours

Clone returns a copy of q, or nil when q is nil.

func (QuietHours) Contains

func (q QuietHours) Contains(t time.Time) bool

Contains reports whether t falls inside q's local-time window [Start, End). Returns false if q is not valid.

func (QuietHours) NextAllowed

func (q QuietHours) NextAllowed(t time.Time) time.Time

NextAllowed returns t if t is outside QuietHours, or the local time when QuietHours ends otherwise. If q is not valid, t is returned unchanged.

func (QuietHours) Validate

func (q QuietHours) Validate() error

Validate checks that q has well-formed, distinct Start and End wall-clock times.

type Regime

type Regime = consent.Regime

Regime is the default a Consent applies before the player chooses: OptIn allows nothing until the player grants it, OptOut allows everything until the player denies it.

const (
	// OptIn denies data collection until the player explicitly grants consent (GDPR / ePrivacy default).
	OptIn Regime = consent.OptIn
	// OptOut allows data collection until the player opts out or a Global Privacy Control signal applies (CCPA / CPRA).
	OptOut Regime = consent.OptOut
)

type ReminderDef

type ReminderDef struct {
	// ID uniquely names the reminder: 1 to 128 ASCII letters, digits, '.', '_' or '-'.
	ID string `yaml:"id" schema:"required,minLength=1"`
	// Title is the localization key for the notification title.
	Title string `yaml:"title" schema:"required,minLength=1"`
	// Body is the optional localization key for the notification body.
	Body string `yaml:"body,omitempty"`
	// Delay schedules the reminder this positive Go duration after Schedule is called, such as "4h0m0s" or "30m0s". Mutually exclusive with At.
	Delay time.Duration `yaml:"delay,omitempty"`
	// At schedules the reminder at the next occurrence of this 24-hour local wall-clock time ("HH:MM"), such as "09:00". Mutually exclusive with Delay.
	At string `yaml:"at,omitempty"`
	// Weekday restricts an At-based reminder to a specific day of the week (sunday through saturday); requires At and cannot be paired with daily repeat.
	Weekday string `yaml:"weekday,omitempty" schema:"enum=sunday|monday|tuesday|wednesday|thursday|friday|saturday"`
	// Repeat sets how often the reminder repeats after its first firing: omitted for once, "daily", or "weekly".
	Repeat ReminderRepeat `yaml:"repeat,omitempty" schema:"enum=daily|weekly"`
	// OnOpen controls what happens to this reminder when the app comes to the front: "cancel" (default when omitted), "reschedule", or "keep".
	OnOpen ReminderOnOpen `yaml:"onOpen,omitempty" schema:"enum=cancel|reschedule|keep"`
	// Silent delivers the notification without the system's sound or vibration.
	Silent bool `yaml:"silent,omitempty"`
}

ReminderDef declares one local re-engagement reminder in a RemindersConfig file.

func (ReminderDef) EffectiveOnOpen

func (d ReminderDef) EffectiveOnOpen() ReminderOnOpen

EffectiveOnOpen returns d.OnOpen, defaulting to ReminderOnOpenCancel when omitted.

type ReminderOnOpen

type ReminderOnOpen string

ReminderOnOpen controls what happens to a scheduled reminder when the app launches or returns to the foreground.

const (
	// ReminderOnOpenCancel cancels the pending reminder when the app comes to the front (the default when omitted).
	ReminderOnOpenCancel ReminderOnOpen = "cancel"
	// ReminderOnOpenReschedule reschedules the reminder from the current wall time when the app comes to the front.
	ReminderOnOpenReschedule ReminderOnOpen = "reschedule"
	// ReminderOnOpenKeep leaves the pending reminder scheduled unchanged when the app comes to the front.
	ReminderOnOpenKeep ReminderOnOpen = "keep"
)

func (ReminderOnOpen) Valid

func (o ReminderOnOpen) Valid() bool

Valid reports whether o is a supported ReminderOnOpen value (empty, cancel, reschedule, or keep).

type ReminderPress

type ReminderPress struct {
	// ID is the reminder's ID from RemindersConfig (without RemindersOptions.Prefix).
	ID string
}

ReminderPress is the event reported to RemindersOptions.OnPress when the player presses a delivered reminder notification.

type ReminderRepeat

type ReminderRepeat string

ReminderRepeat describes how often a scheduled reminder fires.

const (
	// ReminderRepeatNone fires the reminder once.
	ReminderRepeatNone ReminderRepeat = ""
	// ReminderRepeatDaily fires the reminder every day at its scheduled local wall-clock time.
	ReminderRepeatDaily ReminderRepeat = "daily"
	// ReminderRepeatWeekly fires the reminder every week on its scheduled weekday and local wall-clock time.
	ReminderRepeatWeekly ReminderRepeat = "weekly"
)

func (ReminderRepeat) Valid

func (r ReminderRepeat) Valid() bool

Valid reports whether r is a supported ReminderRepeat value (empty, daily, or weekly).

type Reminders

type Reminders struct {
	// contains filtered or unexported fields
}

Reminders schedules, cancels and reschedules local re-engagement notifications over NSGo's core.Scope.ShowNotification.

Reminders never asks for notification permission at launch: it requests permission only when the game first calls Schedule (or ScheduleWith) or an explicit RequestPermission. It honors a persisted player toggle (Enabled/SetEnabled), local-time QuietHours, and each reminder's OnOpen rule (cancel, reschedule or keep) when the app comes to the front.

Remote push notifications are not part of Reminders and are unavailable everywhere until NSGo ships remote push (nsgo-dev/nsgo#59, nsgo-dev/nsgo#1323).

Reminders methods run on the scope's goroutine, as NSGo's callbacks do.

func NewReminders

func NewReminders(cx *core.Scope, opts RemindersOptions) (*Reminders, error)

NewReminders creates a local reminder manager bound to cx. It never prompts for or queries notification permission at launch; it loads persisted player settings and reconciles any previously scheduled reminders with their OnOpen rules when the app starts in the foreground.

func (*Reminders) CanScheduleNotifications

func (r *Reminders) CanScheduleNotifications() bool

CanScheduleNotifications reports whether this platform schedules local notifications (core.Env.CanScheduleNotifications). Read in a reactive computation, it follows environment changes so games can hide reminder settings where scheduled notifications do nothing.

func (*Reminders) Cancel

func (r *Reminders) Cancel(id string)

Cancel cancels the scheduled or shown notification for id and stops any in-flight Schedule call for id.

func (*Reminders) CancelAll

func (r *Reminders) CancelAll()

CancelAll cancels every scheduled or shown reminder notification tracked by Reminders or declared in RemindersConfig, and stops any in-flight Schedule calls. Unrelated notifications belonging to other parts of the app are left untouched.

func (*Reminders) Definition

func (r *Reminders) Definition(id string) (ReminderDef, bool)

Definition returns the declared ReminderDef for id.

func (*Reminders) Enabled

func (r *Reminders) Enabled() bool

Enabled reports whether the player's in-game reminder setting is turned on. Read in a reactive computation, it follows SetEnabled.

func (*Reminders) IsScheduled

func (r *Reminders) IsScheduled(id string) bool

IsScheduled reports whether id is currently scheduled (and, for a one-shot reminder scheduled in this run, still in the future). Read in a reactive computation, it follows Schedule, Cancel, CancelAll and foreground reconciliation.

func (*Reminders) NextFireTime

func (r *Reminders) NextFireTime(id string) (time.Time, bool)

NextFireTime returns the scheduled wall-clock fire time for id when scheduled during this run. Read in a reactive computation, it follows Schedule, Cancel, SetQuietHours and foreground reconciliation.

func (*Reminders) Permission

func (r *Reminders) Permission() core.NotificationPermission

Permission returns the last notification permission status observed by RequestPermission or Schedule. It starts at core.NotificationsNotAsked without querying the OS at launch. Read in a reactive computation, it updates when permission changes.

func (*Reminders) QuietHours

func (r *Reminders) QuietHours() *QuietHours

QuietHours returns a copy of the active local-time quiet hours window, or nil when quiet hours are disabled. Read in a reactive computation, it follows SetQuietHours.

func (*Reminders) RequestPermission

func (r *Reminders) RequestPermission(done func(core.NotificationPermission))

RequestPermission explicitly asks the OS for notification permission through core.Scope.RequestNotificationPermission and answers done with the result. Concurrent calls share a single permission request. done may be nil.

func (*Reminders) Schedule

func (r *Reminders) Schedule(id string, done func(scheduled bool)) error

Schedule schedules the declared reminder named id according to its YAML definition and the active QuietHours, answering done (when non-nil) with whether the platform accepted it.

When reminders are disabled by the player or CanScheduleNotifications is false, Schedule answers false without asking for permission. Otherwise, if notification permission has not yet been granted, Schedule requests it first and schedules only when granted. Returns ErrReminderNotFound (without calling done) if id is not declared in RemindersConfig.

func (*Reminders) ScheduleWith

func (r *Reminders) ScheduleWith(id string, opts ScheduleOptions, done func(scheduled bool)) error

ScheduleWith schedules the declared reminder named id with per-call overrides in opts. Returns ErrReminderNotFound or ErrInvalidSchedule (without calling done) when the arguments are invalid.

func (*Reminders) Scheduled

func (r *Reminders) Scheduled() []string

Scheduled returns the sorted IDs of all currently scheduled reminders. Read in a reactive computation, it follows Schedule, Cancel, CancelAll and foreground reconciliation.

func (*Reminders) SetEnabled

func (r *Reminders) SetEnabled(enabled bool) error

SetEnabled persists the player's reminder setting. Disabling immediately cancels all scheduled reminders and prevents future Schedule calls from prompting or scheduling.

func (*Reminders) SetQuietHours

func (r *Reminders) SetQuietHours(qh *QuietHours) error

SetQuietHours updates and persists the player's quiet-hours window (nil disables quiet hours even when RemindersConfig defines defaults). Any currently scheduled reminder whose known fire time falls inside the new window is immediately deferred to the window's end without prompting for permission.

type RemindersConfig

type RemindersConfig struct {
	// Version is the schema version; it must equal RemindersVersion (1).
	Version int `yaml:"version" schema:"required"`
	// QuietHours is the optional default daily local-time window during which reminders are deferred until the window ends.
	QuietHours *QuietHours `yaml:"quietHours,omitempty"`
	// Reminders lists the game's local re-engagement reminder definitions in declaration order.
	Reminders []ReminderDef `yaml:"reminders,omitempty"`
}

RemindersConfig is the root of a versioned YAML reminders file (reminders.yaml).

func LoadRemindersFS

func LoadRemindersFS(fsys fs.FS, name string) (*RemindersConfig, error)

LoadRemindersFS reads name from fsys and parses it with ParseReminders.

func ParseReminders

func ParseReminders(data []byte) (*RemindersConfig, error)

ParseReminders decodes and validates a versioned YAML reminders document. Unknown fields, trailing YAML documents, duplicate keys, YAML anchors/aliases/merge keys, missing or unsupported versions, and invalid schedules or quiet hours are refused with *loaderr.Error line info.

Example

ParseReminders loads a versioned reminders YAML document and QuietHours defers a reminder that would fire during quiet hours until they end.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/liveops"
)

func main() {
	cfg, err := liveops.ParseReminders([]byte(`
version: 1
quietHours:
  start: "22:00"
  end: "08:00"
reminders:
  - id: energy_full
    title: reminder.energy.title
    body: reminder.energy.body
    delay: 2h
    onOpen: keep
`))
	if err != nil {
		fmt.Println(err)
		return
	}
	def, _ := cfg.Lookup("energy_full")
	fireAt := time.Date(2026, 1, 1, 21, 0, 0, 0, time.UTC).Add(def.Delay)
	allowed := cfg.QuietHours.NextAllowed(fireAt)
	fmt.Println(def.ID, def.EffectiveOnOpen(), allowed.Format("2006-01-02 15:04"))
}
Output:
energy_full keep 2026-01-02 08:00

func (*RemindersConfig) Clone

func (c *RemindersConfig) Clone() *RemindersConfig

Clone returns a deep copy of c.

func (*RemindersConfig) Lookup

func (c *RemindersConfig) Lookup(id string) (ReminderDef, bool)

Lookup returns the reminder definition with ID id.

type RemindersOptions

type RemindersOptions struct {
	// Config holds the game's declared reminders and optional default quiet hours (loaded with ParseReminders or LoadRemindersFS).
	Config *RemindersConfig
	// Localize resolves a reminder's Title and Body localization keys into display text.
	// When nil, keys are used as written.
	Localize func(key string) string
	// Storage persists the player's enabled toggle, custom quiet hours and active reminder IDs across runs.
	// When zero, cx.Storage() is used.
	Storage core.Storage
	// StorageKey is the prefix for keys written to Storage; DefaultRemindersKey is used when empty.
	StorageKey string
	// QuietHours overrides Config.QuietHours as the default quiet-hours window when the player has not saved a custom window.
	QuietHours *QuietHours
	// DefaultDisabled makes reminders start disabled until the player enables them with SetEnabled(true).
	DefaultDisabled bool
	// Prefix is prepended to reminder IDs passed to core.Scope.ShowNotification; DefaultReminderPrefix is used when empty.
	Prefix string
	// OnPress runs when the player presses a delivered reminder notification.
	OnPress func(ReminderPress)
}

RemindersOptions configures NewReminders.

type RemoteConfig

type RemoteConfig struct {
	// contains filtered or unexported fields
}

RemoteConfig fetches, verifies, caches and activates signed remote configuration and A/B experiments on game clients.

Fetched updates are verified against pinned Ed25519 PublicKeys, checked against serial rollback, cached for offline launches, and staged without altering active values until the game calls Activate at a safe boundary (such as between levels or on the title screen).

RemoteConfig is safe for concurrent use.

func NewRemoteConfig

func NewRemoteConfig(opts RemoteConfigOptions) (*RemoteConfig, error)

NewRemoteConfig creates a RemoteConfig client, validating pinned public keys, endpoint security, and embedded defaults, and immediately activating the last verified cached config when present so offline launches work on frame 1.

func (*RemoteConfig) Activate

func (rc *RemoteConfig) Activate() bool

Activate atomically swaps any staged config (or identity/schedule update) into the active set so getters reflect the new values and exposure events are dispatched through Analytics (when consent permits). It returns true if active state was updated.

func (*RemoteConfig) Bool

func (rc *RemoteConfig) Bool(key string) bool

Bool returns the active boolean value for key, falling back to the YAML default or false when undeclared or of another type.

func (*RemoteConfig) Exposures

func (rc *RemoteConfig) Exposures() []remoteconfig.Exposure

Exposures returns a copy of the active experiment assignments.

func (*RemoteConfig) Fetch

func (rc *RemoteConfig) Fetch(ctx context.Context) (bool, error)

Fetch downloads the latest signed remote config using ETag conditional requests (If-None-Match), enforces MaxResponseBytes and Ed25519 signature verification against PublicKeys, refuses serial rollbacks, updates the local cache, and stages the update for the next Activate call without modifying currently active values.

It returns changed=true when a new verified config was staged, or changed=false, err=nil when the server returned 304 Not Modified.

func (*RemoteConfig) FetchAndActivate

func (rc *RemoteConfig) FetchAndActivate(ctx context.Context) (bool, error)

FetchAndActivate fetches the latest signed config and activates it when new data arrived. Intended for app startup before gameplay begins.

func (*RemoteConfig) Float

func (rc *RemoteConfig) Float(key string) float64

Float returns the active float64 value for key, falling back to the YAML default or 0 when undeclared or of another type.

func (*RemoteConfig) HasPending

func (rc *RemoteConfig) HasPending() bool

HasPending reports whether Fetch, SetIdentity or SetSchedule has staged changes waiting for Activate.

func (*RemoteConfig) Int

func (rc *RemoteConfig) Int(key string) int64

Int returns the active int64 value for key, falling back to the YAML default or 0 when undeclared or of another type.

func (*RemoteConfig) Lookup

func (rc *RemoteConfig) Lookup(key string) (remoteconfig.ResolvedValue, bool)

Lookup returns the active resolved value and provenance for key.

func (*RemoteConfig) ReportExposures

func (rc *RemoteConfig) ReportExposures() int

ReportExposures attempts to emit ExposureEventName ("experiment_exposure") events for any active experiment assignments that have not yet been reported to Analytics (for example after the player grants analytics consent). It returns the number of newly sent exposure events.

func (*RemoteConfig) Serial

func (rc *RemoteConfig) Serial() int64

Serial returns the serial number of the currently active config (0 when unset).

func (*RemoteConfig) SetIdentity

func (rc *RemoteConfig) SetIdentity(id remoteconfig.Identity)

SetIdentity updates the player identity for subsequent Fetch calls and stages a local re-evaluation for the next Activate call without mutating currently active values mid-level.

func (*RemoteConfig) SetSchedule

func (rc *RemoteConfig) SetSchedule(sched *schedule.Schedule)

SetSchedule updates the #1333 schedule used to evaluate experiment event windows and stages a re-evaluation for the next Activate call.

func (*RemoteConfig) String

func (rc *RemoteConfig) String(key string) string

String returns the active string value for key, falling back to the YAML default or "" when undeclared or of another type.

func (*RemoteConfig) UpdateRequired

func (rc *RemoteConfig) UpdateRequired() (remoteconfig.UpdateInfo, bool)

UpdateRequired reports whether the active config's minAppVersion requires the player to update, along with the minimum version and store link.

type RemoteConfigOptions

type RemoteConfigOptions struct {
	// Endpoint is the HTTPS URL of either a signed remoteconfig.yaml document
	// (such as on a CDN or GET /v1/config/document) or a per-player GET /v1/config
	// server when ServerEvaluated is true. Loopback http:// (localhost, 127.0.0.1,
	// ::1) is permitted for local development and tests. Optional; when empty,
	// RemoteConfig operates offline from Defaults and any verified cache.
	Endpoint string
	// ServerEvaluated switches Fetch to call Endpoint as GET /v1/config returning
	// a signed remoteconfig.ServerResponse JSON payload instead of raw signed YAML.
	ServerEvaluated bool
	// PublicKeys pins one or more Ed25519 public keys used to verify fetched and
	// cached configs. At least one valid 32-byte Ed25519 public key is required.
	PublicKeys []ed25519.PublicKey
	// Defaults supplies embedded fallback keys and defaults shipped with the game
	// binary so offline first launches still return typed YAML defaults.
	Defaults *remoteconfig.Document
	// DefaultsYAML is an alternative to Defaults that parses embedded remoteconfig.yaml bytes.
	DefaultsYAML []byte
	// Identity describes the player and client environment for local evaluation
	// and server targeting hints.
	Identity remoteconfig.Identity
	// Schedule optionally resolves #1333 experiment event windows during local evaluation.
	Schedule *schedule.Schedule
	// CachePath is the file path in the app's data directory used to cache the
	// last verified signed config and ETag across launches.
	CachePath string
	// Storage is an optional core.Storage cache backend used when CachePath is empty
	// (for example on the web target).
	Storage core.Storage
	// StorageKey overrides DefaultRemoteConfigCacheKey when using Storage.
	StorageKey string
	// Analytics optionally receives consent-gated ExposureEventName ("experiment_exposure")
	// events for active experiment assignments. When nil or when consent is not granted,
	// zero exposure events are sent or buffered.
	Analytics *Analytics
	// Token optionally supplies a bearer token attached as Authorization: Bearer <token>.
	Token func(ctx context.Context) (string, error)
	// HTTPClient sends fetch requests; a client with Timeout is used when nil.
	// Redirects are refused on a copy of the client so tokens never leak and HTTPS
	// cannot be downgraded.
	HTTPClient *http.Client
	// Timeout sets the HTTP client timeout when HTTPClient is nil (DefaultRemoteConfigTimeout when <= 0).
	Timeout time.Duration
	// MaxResponseBytes caps the HTTP body size read by Fetch (DefaultRemoteConfigMaxBytes when <= 0).
	MaxResponseBytes int
	// Now overrides the evaluation clock for tests (defaults to time.Now).
	Now func() time.Time
	// OnError optionally receives non-fatal cache load or persistence errors.
	OnError func(error)
}

RemoteConfigOptions configures NewRemoteConfig.

type ReviewMoment

type ReviewMoment int

ReviewMoment classifies an in-game outcome reported to ReviewPrompt.Moment.

const (
	// MomentPositive records a rewarding event such as clearing a level or setting a personal record.
	MomentPositive ReviewMoment = iota + 1
	// MomentNegative records a frustrating event such as losing a level, failing a purchase or hitting an error.
	// Recording a negative moment suppresses review prompts for the rest of the current session.
	MomentNegative
)

func (ReviewMoment) String

func (m ReviewMoment) String() string

String returns "positive", "negative" or "unknown".

type ReviewPrompt

type ReviewPrompt struct {
	// contains filtered or unexported fields
}

ReviewPrompt decides when to call core.Scope.RequestReview using persisted session, elapsed-day, positive-moment, cooldown and once-per-version rules.

State is stored in core.Storage as strict versioned JSON text and fails closed on any corrupt, unrecognised or future-version payload without overwriting it. On platforms where core.Env.CanRequestReview is false, MaybeAsk is a no-op returning false so a game can call it unconditionally.

func NewReviewPrompt

func NewReviewPrompt(store core.Storage, opts ReviewPromptOptions) *ReviewPrompt

NewReviewPrompt creates a review prompt policy backed by store and records the start of a new session. If store is the zero core.Storage, or if the persisted JSON state is corrupt or unrecognised, the policy fails closed and MaybeAsk never prompts.

func (*ReviewPrompt) Eligible

func (r *ReviewPrompt) Eligible() bool

Eligible reports whether all policy rules currently allow asking for a review (independent of whether the platform supports core.Scope.RequestReview). It returns false on corrupt state, after a negative moment in the current session, while suppressed, or before thresholds and cooldown are satisfied.

func (*ReviewPrompt) MaybeAsk

func (r *ReviewPrompt) MaybeAsk(cx *core.Scope) bool

MaybeAsk requests an in-app store rating through cx.RequestReview when the platform supports it (cx.Env().CanRequestReview()) and all policy rules allow it, returning whether it asked.

On platforms without a store prompt, MaybeAsk is a no-op returning false without modifying state. When asking, ReviewPrompt persists the prompt timestamp and version before calling cx.RequestReview so a storage failure fails closed and never causes repeated prompts.

func (*ReviewPrompt) Moment

func (r *ReviewPrompt) Moment(kind ReviewMoment)

Moment records a positive or negative gameplay moment. MomentPositive increments the current version's positive-moment counter in storage. MomentNegative suppresses prompts for the remainder of the current session. Unrecognised moment values are ignored.

func (*ReviewPrompt) RecordSession

func (r *ReviewPrompt) RecordSession()

RecordSession starts a new session on an existing ReviewPrompt (for example when a mobile app returns to the foreground after a long pause), clearing any session-scoped negative moment suppression and incrementing the persisted session count.

type ReviewPromptOptions

type ReviewPromptOptions struct {
	// AppVersion is the current release version (for example project.File.AppVersion).
	// ReviewPrompt asks at most once per AppVersion and resets per-version positive moments when AppVersion changes so a new release earns fresh engagement before asking again.
	AppVersion string

	// StorageKey is the core.Storage key holding the versioned JSON state.
	// DefaultReviewPromptKey is used when empty.
	StorageKey string

	// MinSessions is the minimum number of sessions before MaybeAsk may prompt.
	// Values <= 0 use DefaultReviewMinSessions (3). Stores advise against prompting in the first session.
	MinSessions int

	// MinDays is the minimum number of whole 24-hour days since first launch before MaybeAsk may prompt.
	// Values <= 0 use DefaultReviewMinDays (3).
	MinDays int

	// MinPositiveMoments is the minimum number of positive moments recorded in the current AppVersion before MaybeAsk may prompt.
	// Values <= 0 use DefaultReviewMinPositiveMoments (3).
	MinPositiveMoments int

	// Cooldown is the minimum time between store review requests across all app versions.
	// Values <= 0 use DefaultReviewCooldown (122 days).
	Cooldown time.Duration

	// Now returns the current wall-clock time; time.Now is used when nil.
	// Pass cx.WallTime in NSGo apps so nsgotest.WallTime and app.FastForward control the clock.
	Now func() time.Time

	// Suppress, when non-nil and returning true, prevents MaybeAsk from requesting a review
	// (for example while a purchase sheet, ad flow or modal dialog is open).
	Suppress func() bool
}

ReviewPromptOptions configures NewReviewPrompt.

type SaveVersion

type SaveVersion struct {
	// Exists is false when this side deleted the slot; the other fields are then zero.
	Exists bool
	// Revision is the cloud revision: the cloud copy's own, or for the local copy the revision it was last synced at (0 when never synced).
	Revision int64
	// Hash is "sha256:" followed by the hex SHA-256 of Data.
	Hash string
	// Modified is when the copy was last written, zero when unknown (a local write that bypassed CloudSyncer.Backend, or a plain cloud payload). A local time counts only for the exact copy it was recorded with: a later write that bypassed Backend makes it unknown.
	Modified time.Time
	// Device is the ID of the device that wrote the copy, empty when unknown.
	Device string
	// EnvelopeVersion is the save.Store schema version parsed from Data's save envelope, or 0 when Data is absent or not a save envelope.
	EnvelopeVersion int
	// Summary is CloudSyncOptions.Summarize's text for Data, such as "Level 12, 3h 40m played".
	Summary string
	// Data is the raw save payload.
	Data []byte
}

SaveVersion describes one side's copy of a slot in a Conflict or a SlotResult.

func DecodeCloudSave

func DecodeCloudSave(raw []byte) (SaveVersion, error)

DecodeCloudSave reads a cloud payload. A JSON object whose "format" is CloudSaveFormat is decoded strictly (unknown fields, a newer version, a revision below 1 or at math.MaxInt64, a hash that does not match the data or a malformed value return an error wrapping ErrCorruptCloudSave); any other payload is a plain save written without CloudSyncer and is returned as revision 0 with no modified time or device.

type ScheduleOptions

type ScheduleOptions struct {
	// Delay, when positive, overrides the reminder's declared Delay or At with a relative delay from now. Mutually exclusive with At.
	Delay time.Duration
	// At, when non-zero, overrides the reminder's declared Delay or At with a specific wall-clock time. Mutually exclusive with Delay.
	At time.Time
	// Title, when non-empty, overrides the localized title for this scheduled reminder (for example when interpolating parameters with l10n).
	Title string
	// Body, when non-empty, overrides the localized body for this scheduled reminder.
	Body string
}

ScheduleOptions overrides parts of a declared ReminderDef for a single ScheduleWith call.

type SecretStore

type SecretStore interface {
	Get(string) (string, bool)
	Set(string, string) error
	Delete(string) error
}

SecretStore is the small keychain interface Account needs. core.Secrets can be adapted without making the HTTP client depend on a particular host.

type ShareHost

type ShareHost interface {
	// MaxPayloadBytes returns the maximum allowed byte length of PreparedCard.Query.
	// Returning <= 0 uses DefaultMaxInvitePayloadBytes (1024).
	MaxPayloadBytes() int

	// Share presents the platform share card or system share sheet for card and invokes done when complete.
	Share(card PreparedCard, done func(shown bool, err error))

	// SetMenuCard registers a callback supplying the card for the host's built-in share menu (such as a mini game's Forward item).
	// Passing nil disables/clears the menu card. Hosts without a system share menu treat this as a no-op.
	SetMenuCard(fn func() (PreparedCard, error))

	// LaunchInvite returns the invite that cold-started the game, if any.
	LaunchInvite() (LaunchInvite, bool)

	// OnInvite subscribes fn to invites that arrive while the game is running (warm re-open / onShow) and returns an unsubscribe function.
	OnInvite(fn func(LaunchInvite)) (stop func())
}

ShareHost is the small platform boundary underneath Invites. Built-in implementations are PlatformShareHost (mobile, desktop and web over NSGo's core APIs) and MiniGameShareHost (mini-game bridge ready for nsgo-dev/nsgo#2672); tests supply a fake ShareHost.

type SignOutReason

type SignOutReason string

SignOutReason explains why an Account became signed out.

const (
	// SignOutExplicit means the game called Account.SignOut.
	SignOutExplicit SignOutReason = "explicit"
	// SignOutSessionRevoked means the account service rejected the session with HTTP 401.
	SignOutSessionRevoked SignOutReason = "session_revoked"
	// SignOutAppleRevoked means Sign in with Apple reported AppleCredentialRevoked for the linked Apple user.
	SignOutAppleRevoked SignOutReason = "apple_revoked"
)

type SlotResult

type SlotResult struct {
	// Slot is the save slot name.
	Slot string
	// Outcome is what was done.
	Outcome SyncOutcome
	// Conflict is set when both copies had changed, whatever the outcome.
	Conflict *Conflict
	// Fork is the slot the local copy was moved to under OutcomeKeptBoth, or under OutcomeNeedsUpdate when a mixed-version conflict forked the local copy without overwriting the local slot.
	Fork string
	// Discarded is the copy a resolution replaced under OutcomeKeptLocal or OutcomeKeptCloud, so a game can show or archive it.
	Discarded *SaveVersion
	// LocalVersion is this client's configured CloudSyncOptions.SaveVersion when Outcome is OutcomeNeedsUpdate, and 0 otherwise.
	LocalVersion int
	// CloudVersion is the cloud copy's save envelope version when Outcome is OutcomeNeedsUpdate, and 0 otherwise.
	CloudVersion int
}

SlotResult reports what a sync did to one slot.

type StepRecord

type StepRecord = crashreport.StepRecord

StepRecord describes one recorded step in a CrashReporter's fixed-size ring buffer. It is an alias for crashreport.StepRecord, so headless servers build the same schema without importing liveops.

type SyncOutcome

type SyncOutcome int

SyncOutcome says what CloudSyncer did to one slot.

const (
	// OutcomeUpToDate means both sides already held the same copy.
	OutcomeUpToDate SyncOutcome = iota
	// OutcomeUploaded means only the local copy had changed, and it was uploaded.
	OutcomeUploaded
	// OutcomeDownloaded means only the cloud copy had changed, and it was written locally.
	OutcomeDownloaded
	// OutcomeDeletedCloud means the slot was deleted locally and unchanged in the cloud, so the cloud copy was deleted.
	OutcomeDeletedCloud
	// OutcomeDeletedLocal means the slot was deleted in the cloud and unchanged locally, so the local copy was deleted.
	OutcomeDeletedLocal
	// OutcomeKeptLocal means a conflict was resolved in favour of the local copy; SlotResult.Discarded holds the cloud copy it replaced.
	OutcomeKeptLocal
	// OutcomeKeptCloud means a conflict was resolved in favour of the cloud copy; SlotResult.Discarded holds the local copy it replaced. When that copy was a valid save envelope and the cloud copy exists, the local save backend also keeps it as its backup; otherwise Discarded is the only copy left.
	OutcomeKeptCloud
	// OutcomeKeptBoth means a conflict was resolved by keeping the cloud copy in the slot and moving the local copy to SlotResult.Fork on both sides.
	OutcomeKeptBoth
	// OutcomeDeferred means a conflict was left unresolved, by ChoiceDefer under PolicyAsk or passed to CloudSyncer.Resolve; nothing was written.
	OutcomeDeferred
	// OutcomeNeedsUpdate means the cloud copy carries a save envelope version newer than CloudSyncOptions.SaveVersion, so it was not written locally; SlotResult.LocalVersion and SlotResult.CloudVersion report both versions so the game can ask the player to update. When a mixed-version conflict forked an older local copy to preserve it without overwriting either slot, SlotResult.Fork names the fork slot.
	OutcomeNeedsUpdate
)

func (SyncOutcome) String

func (o SyncOutcome) String() string

String returns a lowercase, hyphenated name such as "up-to-date" or "kept-both".

type SyncResult

type SyncResult struct {
	// Slots holds one entry for each slot that synced without error.
	Slots []SlotResult
}

SyncResult reports what CloudSyncer.Sync did to each slot, sorted by slot name.

func (SyncResult) Conflicts

func (r SyncResult) Conflicts() []SlotResult

Conflicts returns the slot results that held a conflict.

func (SyncResult) NeedsUpdate

func (r SyncResult) NeedsUpdate() []SlotResult

NeedsUpdate returns the slot results whose cloud copy carries a newer save envelope version than CloudSyncOptions.SaveVersion.

Directories

Path Synopsis
Package analytics is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package analytics is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
pgstore
Package pgstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package pgstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package consent is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package consent is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package crashreport is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package crashreport is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package inbox is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package inbox is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
storetest
Package storetest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package storetest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package remoteconfig is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package remoteconfig is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package schedule is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package schedule is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL