@rbxts/scribe 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +21 -0
  3. package/README.md +100 -0
  4. package/Scribe-source-map.json +1 -0
  5. package/licenses/ProfileStore-Apache-2.0.txt +201 -0
  6. package/package.json +32 -0
  7. package/src/Client/DebugHook.luau +457 -0
  8. package/src/Client/init.luau +1607 -0
  9. package/src/Internal/Addons.luau +68 -0
  10. package/src/Internal/Big.luau +582 -0
  11. package/src/Internal/Budget.luau +377 -0
  12. package/src/Internal/Clock.luau +75 -0
  13. package/src/Internal/Config.luau +17 -0
  14. package/src/Internal/Conform.luau +400 -0
  15. package/src/Internal/Datatypes.luau +653 -0
  16. package/src/Internal/Defaults.luau +12 -0
  17. package/src/Internal/Derived.luau +428 -0
  18. package/src/Internal/Exchange.luau +556 -0
  19. package/src/Internal/ExchangeLeg.luau +1368 -0
  20. package/src/Internal/ExchangeVerdict.luau +179 -0
  21. package/src/Internal/Failure.luau +148 -0
  22. package/src/Internal/Health.luau +320 -0
  23. package/src/Internal/LeaderboardDiagnostics.luau +36 -0
  24. package/src/Internal/Log.luau +378 -0
  25. package/src/Internal/Marker.luau +76 -0
  26. package/src/Internal/Metrics.luau +152 -0
  27. package/src/Internal/Node.luau +3954 -0
  28. package/src/Internal/Profile.luau +69 -0
  29. package/src/Internal/Rng.luau +83 -0
  30. package/src/Internal/Sched.luau +56 -0
  31. package/src/Internal/Signal.luau +199 -0
  32. package/src/Internal/Store/ProfileStore.luau +3019 -0
  33. package/src/Internal/Store/init.luau +18 -0
  34. package/src/Internal/StudioCodec.luau +155 -0
  35. package/src/Internal/Template.luau +1848 -0
  36. package/src/Internal/Transport.luau +169 -0
  37. package/src/Internal/Util.luau +517 -0
  38. package/src/Internal/Version.luau +4 -0
  39. package/src/Internal/Wire.luau +1283 -0
  40. package/src/Server/Analytics.luau +223 -0
  41. package/src/Server/Commands.luau +728 -0
  42. package/src/Server/DebugHook.luau +1490 -0
  43. package/src/Server/Exchanges.luau +737 -0
  44. package/src/Server/Leaderboards.luau +2143 -0
  45. package/src/Server/Monetization.luau +3212 -0
  46. package/src/Server/Persistence.luau +3775 -0
  47. package/src/Server/Replication.luau +1253 -0
  48. package/src/Server/ServerStore.luau +81 -0
  49. package/src/Server/Timed.luau +579 -0
  50. package/src/Server/init.luau +672 -0
  51. package/src/Types.luau +480 -0
  52. package/src/init.luau +2231 -0
  53. package/types/api.d.ts +252 -0
  54. package/types/common.d.ts +355 -0
  55. package/types/index.d.ts +226 -0
  56. package/types/schema.d.ts +276 -0
package/types/api.d.ts ADDED
@@ -0,0 +1,252 @@
1
+ import type { Accessor, PlayerData, ValueOf, InputOf, ClientSchema, SharedSchema, ReadonlyAccessor, NumericPaths, Disconnect, Datatype, BigValue } from "./schema";
2
+ import type { UnknownRecord, ScribeTransport, Signal, LifecycleReason, SessionState, LoadPhase, Status, ProductState, RequestFailure, RequestFailedMarker, OperationResult, SaveInfo, SaveEvent, Anomaly, GiftReceived, VersionRecord, SchemaViolation, FlushOptions, UpdateOfflineOptions, RestoreOptions, CooldownOptions, MigrationContext, LeaderboardEntry, LeaderboardStatusInfo, PassConfig, PurchaseFilter, PurchaseEntry, PurchaseLogOptions, ProductInfo, PolicyInfo, ReceiptInfo, EconomyConfig, ExchangeableSpec, ExchangeAPI, LogLevel, StatusThresholds, PeriodResetOptions, MockState } from "./common";
3
+
4
+ export interface LeaderboardConfig<T = unknown> {
5
+ Stat: NumericPaths<T, true>;
6
+ Limit?: number;
7
+ Scale?: number;
8
+ SigFigs?: number;
9
+ Replicate?: boolean;
10
+ RefreshInterval?: number;
11
+ /** Minimum seconds between changed-score writes per player/store (default 30, minimum 1). Ignored for Server scope. */
12
+ WriteInterval?: number;
13
+ StoreName?: string;
14
+ Period?: "Daily" | "Weekly";
15
+ Mode?: "Gain" | "Peak";
16
+ Scope?: "Global" | "Server";
17
+ }
18
+ export interface ProductConfig<T = unknown> {
19
+ Id: number;
20
+ Category?: string;
21
+ Grant?: (this: void, data: PlayerData<T>) => void;
22
+ Grants?: string;
23
+ PaidRandom?: boolean;
24
+ }
25
+ export interface PurchaseSpec<T = unknown> {
26
+ Cost: { Path: NumericPaths<T, false>; Amount: number };
27
+ Category?: string;
28
+ ItemId: string;
29
+ Grant?: (this: void, data: PlayerData<T>) => void;
30
+ Meta?: UnknownRecord;
31
+ IdempotencyKey?: string;
32
+ PaidRandom?: boolean;
33
+ }
34
+
35
+ /** A shared command contract maps each command name to its arguments and LuaTuple result. */
36
+ export type CommandArguments<F> = F extends (this: void, ...args: infer A) => unknown ? A : never;
37
+ export type CommandReturn<F> = F extends (this: void, ...args: never[]) => infer R ? R extends LuaTuple<unknown[]> ? R : never : never;
38
+ export type CommandHandler<F> = (this: void, player: Player, ...args: CommandArguments<F>) => CommandReturn<F>;
39
+ export interface CommandSpec { Args?: ReadonlyArray<unknown>; Idempotent?: boolean; }
40
+
41
+ /** Uncontracted commands deliberately expose unknown results instead of claiming inferred safety. */
42
+ export type RequestFunction<C> = keyof C extends never
43
+ ? (this: void, name: string, ...args: unknown[]) => LuaTuple<unknown[]>
44
+ : <K extends keyof C & string>(this: void, name: K, ...args: CommandArguments<C[K]>) => CommandReturn<C[K]> | RequestFailure;
45
+ export type RequestOnceFunction<C> = keyof C extends never
46
+ ? (this: void, name: string, key: string, ...args: unknown[]) => LuaTuple<unknown[]>
47
+ : <K extends keyof C & string>(this: void, name: K, key: string, ...args: CommandArguments<C[K]>) => CommandReturn<C[K]> | RequestFailure;
48
+ export type RegisterCommand<C> = keyof C extends never ? {
49
+ <A extends unknown[], R>(this: void, name: string, handler: (this: void, player: Player, ...args: A) => R): void;
50
+ <A extends unknown[], R>(this: void, name: string, spec: CommandSpec, handler: (this: void, player: Player, ...args: A) => R): void;
51
+ } : {
52
+ <K extends keyof C & string>(this: void, name: K, handler: CommandHandler<C[K]>): void;
53
+ <K extends keyof C & string>(this: void, name: K, spec: CommandSpec, handler: CommandHandler<C[K]>): void;
54
+ };
55
+ export type MockCommand<C> = keyof C extends never
56
+ ? <A extends unknown[], R>(this: void, name: string, handler: (this: void, ...args: A) => R) => void
57
+ : <K extends keyof C & string>(this: void, name: K, handler: C[K]) => void;
58
+
59
+ export type ServerStore<S> = { readonly [K in keyof S]: Accessor<S[K]> };
60
+ export type ClientServerStore<S> = { readonly [K in keyof ClientSchema<S>]: ReadonlyAccessor<ClientSchema<S>[K]> };
61
+ type ServerStoreMember<S> = keyof S extends never ? { readonly ServerStore?: never } : { readonly ServerStore: ServerStore<S> };
62
+ type ClientStoreMember<S> = keyof S extends never ? { readonly ServerStore?: never } : { readonly ServerStore: ClientServerStore<S> };
63
+ export type SharedData<T> = ValueOf<SharedSchema<ClientSchema<T>>>;
64
+
65
+ export interface ServerAPI<T, C = {}> {
66
+ readonly Get: (this: void, player: Player) => PlayerData<T>;
67
+ readonly WaitForData: (this: void, player: Player, timeout?: number) => LuaTuple<[PlayerData<T> | undefined, LifecycleReason | undefined]>;
68
+ readonly GetState: (this: void, player: Player) => LuaTuple<[SessionState, LoadPhase | undefined]>;
69
+ readonly Batch: (this: void, player: Player, callback: (this: void) => void) => void;
70
+ readonly Transaction: (this: void, player: Player, callback: (this: void) => void) => OperationResult;
71
+ readonly Flush: (this: void, player: Player, options?: FlushOptions) => boolean;
72
+ readonly GetSaveInfo: (this: void, player: Player) => SaveInfo;
73
+ /** Offline/history reads are packed, potentially old schemas, not live accessor values. */
74
+ readonly GetOffline: (this: void, userId: number) => UnknownRecord | undefined;
75
+ readonly UpdateOffline: (this: void, userId: number, callback: (this: void, rawData: UnknownRecord) => void, options?: UpdateOfflineOptions) => LuaTuple<[boolean, string | undefined, SchemaViolation[] | undefined]>;
76
+ readonly ListVersions: (this: void, userId: number, limit?: number) => VersionRecord[];
77
+ readonly GetVersion: (this: void, userId: number, versionId: string) => UnknownRecord | undefined;
78
+ readonly RestoreVersion: (this: void, userId: number, versionId: string, options?: RestoreOptions) => OperationResult;
79
+ readonly Erase: (this: void, userId: number) => OperationResult;
80
+ readonly Export: (this: void, userId: number) => string | undefined;
81
+ readonly Command: RegisterCommand<C>;
82
+ readonly GetLeaderboard: (this: void, name: string, limit?: number, offset?: number) => LeaderboardEntry[];
83
+ readonly GetMyRank: (this: void, player: Player, name: string) => number | undefined;
84
+ readonly GetLeaderboardRefreshIn: (this: void, name: string) => number | undefined;
85
+ readonly GetLeaderboardStatus: (this: void, name: string) => LeaderboardStatusInfo | undefined;
86
+ readonly GetLeaderboardResetIn: (this: void, name: string) => number | undefined;
87
+ readonly PromptPurchase: (this: void, player: Player, name: string) => OperationResult;
88
+ readonly GetProductState: (this: void, player: Player, name: string) => ProductState;
89
+ readonly PromptGift: (this: void, buyer: Player, productName: string, recipientUserId: number) => OperationResult;
90
+ readonly GetGiftCredits: (this: void, player: Player) => { [product: string]: number };
91
+ readonly HandleReceipt: (this: void, receipt: ReceiptInfo) => Enum.ProductPurchaseDecision;
92
+ readonly TryHandleReceipt: (this: void, receipt: ReceiptInfo) => Enum.ProductPurchaseDecision | undefined;
93
+ readonly Owns: (this: void, player: Player, key: string) => boolean;
94
+ readonly OwnsAsync: (this: void, player: Player, key: string, timeout?: number) => boolean;
95
+ readonly ObserveOwned: (this: void, player: Player, key: string, callback: (this: void, owned: boolean) => void) => Disconnect;
96
+ readonly GrantPerk: (this: void, player: Player, key: string) => void;
97
+ readonly RevokePerk: (this: void, player: Player, key: string) => void;
98
+ readonly Purchase: (this: void, player: Player, spec: PurchaseSpec<T>) => OperationResult;
99
+ readonly RecordPurchase: (this: void, player: Player, entry: UnknownRecord) => void;
100
+ readonly GetPurchases: (this: void, player: Player, filter?: PurchaseFilter) => PurchaseEntry[];
101
+ readonly OnCooldown: (this: void, player: Player, key: string, seconds: number, options?: CooldownOptions) => LuaTuple<[boolean, number]>;
102
+ readonly PeekCooldown: (this: void, player: Player, key: string) => LuaTuple<[boolean, number]>;
103
+ readonly ClearCooldown: (this: void, player: Player, key: string) => void;
104
+ readonly SendMessage: (this: void, userId: number, message: unknown) => boolean;
105
+ readonly Exchange: ExchangeAPI;
106
+ readonly OnSave: Signal<[SaveEvent]>;
107
+ readonly SessionEnded: Signal<[Player, LifecycleReason]>;
108
+ readonly OnAnomaly: Signal<[Anomaly]>;
109
+ readonly OnGiftReceived: Signal<[Player, GiftReceived]>;
110
+ readonly OnGiftCredit: Signal<[Player, string]>;
111
+ readonly OnOwnershipChanged: Signal<[Player, string, boolean]>;
112
+ readonly OnCooldownEnded: Signal<[Player, string]>;
113
+ readonly OnLeaderboard: Signal<[string, LeaderboardEntry[]]>;
114
+ readonly OnMessage: Signal<[Player, unknown]>;
115
+ /** External ProfileStore implementation; narrow to its own public package type before use. */
116
+ readonly ProfileStore: unknown;
117
+ /** Escape hatch requiring explicit validation/assertion at its boundary. */
118
+ readonly Raw: unknown;
119
+ readonly Stop: (this: void) => void;
120
+ }
121
+ export type ServerData<T, S = {}, C = {}> = ServerAPI<T, C> & ServerStoreMember<S>;
122
+
123
+ /** Partial records for Mock; arrays and Roblox engine datatypes remain whole values. */
124
+ export type MockValues<T> = T extends Datatype | buffer | BigValue | ReadonlyArray<unknown> | ReadonlyMap<unknown, unknown> ? T : T extends object ? { [K in keyof T]?: MockValues<T[K]> } : T;
125
+ export interface ClientAPI<T, C = {}> {
126
+ readonly IsReady: (this: void) => boolean;
127
+ readonly WaitForData: (this: void, timeout?: number) => boolean;
128
+ readonly Batch: (this: void, callback: (this: void) => void) => void;
129
+ readonly Request: RequestFunction<C>;
130
+ readonly RequestOnce: RequestOnceFunction<C>;
131
+ readonly GetLeaderboard: (this: void, name: string, limit?: number) => LeaderboardEntry[];
132
+ readonly GetMyRank: (this: void, name: string) => number | undefined;
133
+ readonly OnLeaderboard: Signal<[string, LeaderboardEntry[]]>;
134
+ readonly GetServiceStatus: (this: void) => Status;
135
+ readonly OnServiceStatus: Signal<[Status]>;
136
+ readonly GetShared: (this: void, playerOrUserId: Player | number) => SharedData<T> | undefined;
137
+ readonly OnSharedChanged: Signal<[number, SharedData<T> | undefined]>;
138
+ readonly Owns: (this: void, key: string) => boolean;
139
+ readonly OwnsAsync: (this: void, key: string, timeout?: number) => boolean;
140
+ readonly ObserveOwned: (this: void, key: string, callback: (this: void, owned: boolean) => void) => Disconnect;
141
+ readonly OnOwnershipChanged: Signal<[string, boolean]>;
142
+ readonly GetProductInfo: (this: void, name: string) => ProductInfo | undefined;
143
+ readonly GetPrice: (this: void, name: string) => number | undefined;
144
+ readonly GetProductInfoAsync: (this: void, name: string, timeout?: number) => ProductInfo | undefined;
145
+ readonly GetPriceAsync: (this: void, name: string, timeout?: number) => number | undefined;
146
+ readonly ObserveProductInfo: (this: void, name: string, callback: (this: void, info: ProductInfo | undefined) => void) => Disconnect;
147
+ readonly PrefetchProductInfo: (this: void, names?: ReadonlyArray<string>) => void;
148
+ readonly RefreshProductInfo: (this: void, name?: string) => void;
149
+ /** Asks the server to validate and prompt for the local player. Success is not a completed purchase; a timeout may occur after the prompt opens. No automatic retry. */
150
+ readonly PromptPurchase: (this: void, name: string) => LuaTuple<[boolean, string | undefined, RequestFailedMarker | undefined]>;
151
+ readonly GetProductState: (this: void, name: string) => ProductState;
152
+ readonly ObserveProductState: (this: void, name: string, callback: (this: void, state: ProductState) => void) => Disconnect;
153
+ readonly GetSaveInfo: (this: void) => SaveInfo;
154
+ readonly GetGiftCredits: (this: void) => { [product: string]: number };
155
+ readonly GetPurchases: (this: void, filter?: PurchaseFilter) => PurchaseEntry[];
156
+ readonly Mock: (this: void, values?: MockValues<InputOf<ClientSchema<T>>>, state?: MockState) => void;
157
+ readonly MockCommand: MockCommand<C>;
158
+ readonly Raw: unknown;
159
+ readonly Stop: (this: void) => void;
160
+ }
161
+ /** Client field writes are local optimistic edits; server-owned roots remain read-only. */
162
+ export type ClientData<T, S = {}, C = {}> = Omit<PlayerData<ClientSchema<T>>, Extract<keyof PlayerData<ClientSchema<T>>, keyof ClientAPI<T, C> | "ServerStore">> & ClientAPI<T, C> & ClientStoreMember<S>;
163
+ export interface Bundle<T, S = {}, C = {}> { readonly Server: ServerData<T, S, C>; readonly Client: ClientData<T, S, C>; }
164
+
165
+ /** Both templates share root field IDs. Broad dictionaries are validated at runtime. */
166
+ type DisjointStoreRoots<T, S> = string extends keyof T | keyof S ? unknown : { [K in keyof T & keyof S]?: never };
167
+ export interface ScribeOptions<T, S = {}, C = {}> {
168
+ Template: T;
169
+ ServerStore?: S & DisjointStoreRoots<NoInfer<T>, NoInfer<S>>;
170
+ Transport?: ScribeTransport | "Default";
171
+ Migrations?: { [version: number]: (this: void, data: UnknownRecord) => void };
172
+ UserOwnsGamePassAsync?: (this: void, userId: number, passId: number) => boolean;
173
+ GetProductInfoAsync?: (this: void, assetId: number, infoType: Enum.InfoType) => ProductInfo | undefined;
174
+ GetPolicyInfoAsync?: (this: void, player: Player) => PolicyInfo | undefined;
175
+ DevMode?: boolean;
176
+ IsRunning?: boolean;
177
+ MigrationShadow?: boolean;
178
+ ImportLegacyData?: (this: void, player: Player, userId: number, migration: MigrationContext) => UnknownRecord | undefined;
179
+ MigrationConcurrency?: number;
180
+ OnPlayerInit?: (this: void, player: Player, rawData: UnknownRecord, isNewProfile: boolean, migration: MigrationContext) => void;
181
+ OnPlayerLeaving?: (this: void, player: Player, data: PlayerData<T>, reason: LifecycleReason) => void;
182
+ ProfileStoreIndex: string;
183
+ ProfileKeyPrefix: string;
184
+ SaveInterval?: number;
185
+ /** A supplied ProfileStore module/module script is an external integration boundary. */
186
+ ProfileStore?: unknown;
187
+ Mode?: "Live" | "Mock" | "NoSave";
188
+ TargetUserId?: number;
189
+ UseMock?: boolean;
190
+ ViewedUserId?: number;
191
+ OverriddenUserId?: number;
192
+ DontSave?: boolean;
193
+ ResetData?: boolean;
194
+ LoadFailurePolicy?: "Kick" | "Wait";
195
+ LoadTimeout?: number;
196
+ EraseJoinTimeout?: number;
197
+ VersionAheadPolicy?: "Kick" | "Allow";
198
+ KickOnSessionEnd?: boolean;
199
+ LoadFailureMessage?: string;
200
+ LegacyImportFailureMessage?: string;
201
+ MigrationFailureMessage?: string;
202
+ VersionAheadMessage?: string;
203
+ SchemaFailureMessage?: string;
204
+ RateLimitedMessage?: string;
205
+ ErasingMessage?: string;
206
+ SessionEndMessage?: string;
207
+ SessionStolenMessage?: string;
208
+ SessionInterruptedMessage?: string;
209
+ Leaderboards?: { [name: string]: LeaderboardConfig<T> };
210
+ PeriodReset?: PeriodResetOptions;
211
+ Products?: { [name: string]: ProductConfig<T> };
212
+ /** Historical products still settle receipts and existing gifts, without offering new sales. */
213
+ RetiredProducts?: { [name: string]: ProductConfig<T> };
214
+ Passes?: { [name: string]: PassConfig };
215
+ Perks?: ReadonlyArray<string>;
216
+ OwnReceipts?: boolean;
217
+ Exchangeable?: { [name: string]: ExchangeableSpec };
218
+ PurchaseLog?: PurchaseLogOptions;
219
+ GiftCooldown?: number;
220
+ GiftMaxPending?: number;
221
+ GiftIntentTTL?: number;
222
+ /** Legacy default for purchase-claim and gift-aim retention; receipt history remains fixed at 30 days. */
223
+ PurchaseIdTTL?: number;
224
+ /** @deprecated Ignored. Completed receipt IDs are no longer evicted to meet a count cap. */
225
+ MaxProcessedPurchaseIds?: number;
226
+ /** Receipt-history admission budget, from 1 to 2097152 bytes (default 1048576). */
227
+ MaxReceiptHistoryBytes?: number;
228
+ PurchaseClaimTTL?: number;
229
+ MaxPurchaseClaims?: number;
230
+ AllowDuplicateGifts?: boolean;
231
+ NoGiftIntentPolicy?: "GrantOrCredit" | "Hold";
232
+ Economy?: EconomyConfig;
233
+ CommandRateLimit?: number;
234
+ RequestTimeout?: number;
235
+ MaxInboundBytes?: number;
236
+ MaxInboundRetainedBytes?: number;
237
+ MaxOutboundBytes?: number;
238
+ MaxInboundFrameRate?: number;
239
+ TransportChannel?: string;
240
+ BoundsPolicy?: "Clamp" | "Reject";
241
+ WipeGuardPolicy?: "Warn" | "Block";
242
+ SchemaPolicy?: "Warn" | "Reject";
243
+ BudgetPolicy?: "Defer";
244
+ WipeGuardShrinkRatio?: number;
245
+ LogLevel?: LogLevel;
246
+ /** Severity retained by GetRecentLogs, independently of console and sink filters. */
247
+ LogRingLevel?: LogLevel;
248
+ LogRingSize?: number;
249
+ StatusThresholds?: StatusThresholds;
250
+ Banner?: boolean;
251
+ StudioHook?: boolean;
252
+ }
@@ -0,0 +1,355 @@
1
+ import type { BigValue, Disconnect } from "./schema";
2
+
3
+ /** Arbitrary stored or external data is unknown until the caller validates it. */
4
+ export type UnknownRecord = { [key: string]: unknown };
5
+ export type PathSegment = string | number;
6
+ export type Path = ReadonlyArray<PathSegment>;
7
+ export type OpKind = "Init" | "Set" | "Insert" | "Remove" | "Clear";
8
+ export interface Op { Kind: OpKind; Path: Path; Value?: unknown; Index?: number; }
9
+
10
+ /** Transport functions are genuine colon methods; accessor/API functions are not. */
11
+ export interface ScribeTransport {
12
+ readonly Name: string;
13
+ readonly MaxFrameBytes?: number;
14
+ SendToClient(player: Player, bytes: buffer): void;
15
+ SendToAllClients?(bytes: buffer): void;
16
+ ListenServer(callback: (this: void, player: Player, bytes: buffer) => void): void;
17
+ SendToServer(bytes: buffer): void;
18
+ ListenClient(callback: (this: void, bytes: buffer) => void): void;
19
+ Release?(): void;
20
+ }
21
+
22
+ export interface Connection {
23
+ readonly Connected: boolean;
24
+ Disconnect(): void;
25
+ }
26
+ /** Read-only event surface. Scribe owns firing and destroying these signals. */
27
+ export interface Signal<Args extends unknown[]> {
28
+ Connect(callback: (this: void, ...args: Args) => void): Connection;
29
+ Once(callback: (this: void, ...args: Args) => void): Connection;
30
+ Wait(): LuaTuple<Args>;
31
+ }
32
+
33
+ export type LogLevel = "Debug" | "Info" | "Warn" | "Error" | "Fatal";
34
+ /** Each sink has its own severity filter and bounded callback queue. */
35
+ export interface LogSinkOptions { Level?: LogLevel; MaxQueued?: number; }
36
+ export type LogCategory = "Persistence" | "Replication" | "Transport" | "Commands" | "Leaderboards" | "Monetization" | "Gifting" | "Integrity" | "Lifecycle" | "Derived" | "Exchanges";
37
+ /** Public diagnostic codes, kept in sync with src/Types.luau. */
38
+ export type LogCode =
39
+ | "DATASTORE_CRITICAL"
40
+ | "DATASTORE_RECOVERED"
41
+ | "EXPORT_ENCODE_FAIL"
42
+ | "LEGACY_IMPORTED"
43
+ | "LEGACY_IMPORT_FAIL"
44
+ | "MIGRATED"
45
+ | "MESSAGE_SEND_FAIL"
46
+ | "MESSAGE_QUEUE_FULL"
47
+ | "MESSAGE_NO_LISTENER"
48
+ | "MESSAGE_HANDLER_ERROR"
49
+ | "MESSAGE_HANDLER_STALLED"
50
+ | "MIGRATION_FAIL"
51
+ | "MIGRATION_RECONCILE_DEPENDENT"
52
+ | "MIGRATION_RESERVED_DISCARDED"
53
+ | "MODE_OVERRIDES_LEGACY"
54
+ | "OFFLINE_READ_FAIL"
55
+ | "OFFLINE_WRITE_FAIL"
56
+ | "NOSAVE_WRITE_REFUSED"
57
+ | "PROFILE_ERASED"
58
+ | "PROFILE_ERASE_FAIL"
59
+ | "PROFILE_ERASE_PROGRESS_FAIL"
60
+ | "PROFILE_ERASE_RESUMED"
61
+ | "PROFILE_LOADED"
62
+ | "PROFILE_LOAD_FAIL"
63
+ | "PROFILE_RESET"
64
+ | "PROFILE_RESTORED"
65
+ | "PROFILE_RESTORE_FAIL"
66
+ | "RESTORE_RESERVED_PRESERVED"
67
+ | "PROFILE_SIZE"
68
+ | "SLOW_LOAD"
69
+ | "SLOW_IMPORT"
70
+ | "SAVE_WAIT_TIMEOUT"
71
+ | "PROFILE_STORE_ERROR"
72
+ | "PROFILE_STORE_SIGNAL_MISSING"
73
+ | "PROFILE_TOO_LARGE"
74
+ | "PROFILE_UNPERSISTABLE"
75
+ | "PROFILE_VERSION_AHEAD"
76
+ | "SAVE_INTERVAL_CLAMPED"
77
+ | "WIPE_GUARD_RATIO_CLAMPED"
78
+ | "HEALTH_THRESHOLDS_CONFLICT"
79
+ | "SAVE_INTERVAL_CONFLICT"
80
+ | "SAVE_INTERVAL_FAIL"
81
+ | "SAVE_INTERVAL_SET"
82
+ | "SHUTDOWN_DONE"
83
+ | "SHUTDOWN_FLUSH"
84
+ | "SIM_LOAD_FAILURE"
85
+ | "SIM_SESSION_STEAL"
86
+ | "STATUS_CHANGED"
87
+ | "UNKNOWN_ROOT_KEYS"
88
+ | "VERSION_QUERY_FAIL"
89
+ | "VERSION_READ_FAIL"
90
+ | "ANALYTICS_FAIL"
91
+ | "ANOMALY"
92
+ | "ECONOMY_FIELDS_OVERFLOW"
93
+ | "ECONOMY_FIELD_UNDECLARED"
94
+ | "PROFILE_OVERWRITTEN"
95
+ | "PROFILE_TOO_DEEP"
96
+ | "PROFILE_SCHEMA_VIOLATION"
97
+ | "TIMED_SWEEP_FAIL"
98
+ | "WIPE_GUARD_BLOCKED"
99
+ | "WIPE_GUARD_CLEARED"
100
+ | "WIPE_GUARD_FORCED"
101
+ | "WIPE_GUARD_TRIPPED"
102
+ | "CLIENT_HANDSHAKE_TIMEOUT"
103
+ | "FRAGMENT_REFUSED"
104
+ | "INIT_APPLIED"
105
+ | "INIT_SEND_FAIL"
106
+ | "MIRROR_RESYNC"
107
+ | "INIT_SENT"
108
+ | "INIT_UNDELIVERED"
109
+ | "OP_BEFORE_INIT"
110
+ | "OUTBOUND_OVERSIZE"
111
+ | "PROTOCOL_MISMATCH"
112
+ | "SCHEMA_MISMATCH"
113
+ | "SERIALIZE_FAIL"
114
+ | "SNAPSHOT_ROOT_DROPPED"
115
+ | "INBOUND_OVERSIZE"
116
+ | "INBOUND_OVERSIZE_LIMIT"
117
+ | "INBOUND_RATE_LIMITED"
118
+ | "INBOUND_WORK_LIMIT"
119
+ | "MALFORMED_FRAME"
120
+ | "MALFORMED_FRAME_LIMIT"
121
+ | "SEND_FAIL"
122
+ | "COMMAND_BAD_ARGS"
123
+ | "COMMAND_BAD_IDEMPOTENCY_KEY"
124
+ | "COMMAND_ERROR"
125
+ | "COMMAND_IDEM_EVICTED"
126
+ | "COMMAND_IDEM_SATURATED"
127
+ | "COMMAND_RATE_LIMITED"
128
+ | "COMMAND_REPLY_ENCODE_FAIL"
129
+ | "COMMAND_REPLY_TRUNCATED"
130
+ | "COMMAND_UNKNOWN"
131
+ | "SIM_COMMAND"
132
+ | "GRANT_FAIL"
133
+ | "GRANT_PARTIAL"
134
+ | "GRANT_SEEDED_ELEMENT"
135
+ | "RECEIPT_IN_FLIGHT"
136
+ | "RECEIPT_HISTORY_FULL"
137
+ | "OWNERSHIP_CHECK_FAIL"
138
+ | "PASS_PURCHASE_UNCONFIRMED"
139
+ | "PERK_GRANTED"
140
+ | "PERK_REVOKED"
141
+ | "PRODUCT_INFO_FAIL"
142
+ | "POLICY_READ_FAIL"
143
+ | "PAID_RANDOM_RECEIPT"
144
+ | "PRODUCT_INFO_THROTTLED"
145
+ | "PURCHASE_DUPLICATE"
146
+ | "PURCHASE_CLAIM_EVICTED"
147
+ | "PURCHASE_ID_EVICTED"
148
+ | "RECEIPT_DUPLICATE"
149
+ | "RECEIPT_GRANTED"
150
+ | "RECEIPT_HANDLER_BOUND"
151
+ | "RECEIPT_OFFLINE_RETRY"
152
+ | "RECEIPT_RETRY"
153
+ | "RECEIPT_UNKNOWN_PRODUCT"
154
+ | "SIM_RECEIPT"
155
+ | "UNDECLARED_CATEGORY"
156
+ | "UNDECLARED_PERK"
157
+ | "UNKNOWN_OWNS_KEY"
158
+ | "GIFT_AIM_CAP_REACHED"
159
+ | "GIFT_AIM_EXPIRED"
160
+ | "GIFT_AIM_SETTLED"
161
+ | "GIFT_CREDIT_ISSUED"
162
+ | "GIFT_CREDIT_REFUND_FAIL"
163
+ | "GIFT_CREDIT_UNCONFIRMED"
164
+ | "GIFT_CREDIT_UNKNOWN_PRODUCT"
165
+ | "GIFT_CREDIT_USED"
166
+ | "GIFT_DELIVERY_RETRY"
167
+ | "GIFT_INTENT_EXPIRED"
168
+ | "GIFT_INTENT_WRITE_FAIL"
169
+ | "GIFT_INVALID_RECIPIENT"
170
+ | "GIFT_NO_INTENT"
171
+ | "GIFT_RECEIPT_GRANTED"
172
+ | "GIFT_RECIPIENT_ALREADY_OWNS"
173
+ | "GIFT_UNKNOWN_PRODUCT"
174
+ | "RECEIPT_DECLINED_PENDING_CREDIT"
175
+ | "RECEIPT_HELD"
176
+ | "LB_ERASE_FAIL"
177
+ | "LB_INTERVAL_CLAMPED"
178
+ | "LB_QUEUE_OVERFLOW"
179
+ | "LB_READ_FAIL"
180
+ | "LB_SCORE_OUT_OF_RANGE"
181
+ | "LB_SHUTDOWN_FLUSH"
182
+ | "LB_STAT_RESOLVE_FAIL"
183
+ | "LB_UNKNOWN_BOARD"
184
+ | "LB_BUDGET_DEFERRED"
185
+ | "LB_WRITE_DROPPED"
186
+ | "LB_WRITE_FAIL"
187
+ | "SIM_LB_FLUSH"
188
+ | "EXCHANGE_INIT_TAMPER"
189
+ | "EXCHANGE_PARKED"
190
+ | "EXCHANGE_REGISTRATION_REFUSED"
191
+ | "EXCHANGE_RESET_REFUSED"
192
+ | "EXCHANGE_RESOLVED"
193
+ | "EXCHANGE_RESOLVE_ERROR"
194
+ | "EXCHANGE_STORE_UNAVAILABLE"
195
+ | "EXCHANGE_UNRESOLVED"
196
+ | "DERIVED_ERROR"
197
+ | "DERIVED_FEEDBACK"
198
+ | "DERIVED_MISMATCH"
199
+ | "API_NAME_COLLISION"
200
+ | "DEBUG_HOOK_ATTACHED"
201
+ | "DEBUG_HOOK_ATTRIBUTION"
202
+ | "DEBUG_HOOK_DUPLICATE"
203
+ | "DEBUG_HOOK_ERROR"
204
+ | "DEBUG_HOOK_FAIL"
205
+ | "DEBUG_HOOK_WRITES"
206
+ | "DEV_WARNING"
207
+ | "DYNAMIC_DEFAULT_FAILED"
208
+ | "LISTENER_ERROR"
209
+ | "ON_PLAYER_INIT_ERROR"
210
+ | "PLAYER_LEAVING_HOOK_SLOW"
211
+ | "SANDBOXED"
212
+ | "SERVER_STARTED"
213
+ | "SIM_STATUS"
214
+ | "SUBSYSTEM_HOOK_ERROR"
215
+ | "UNKNOWN_OPTION";
216
+ export interface LogEntry {
217
+ At: number;
218
+ Level: LogLevel;
219
+ Category: LogCategory;
220
+ Code: LogCode;
221
+ Message: string;
222
+ Context?: UnknownRecord;
223
+ }
224
+ export interface LogFilter { Level?: LogLevel; Category?: LogCategory; Code?: LogCode; Limit?: number; }
225
+ export type Status = "Healthy" | "Degraded" | "Outage";
226
+ export type SessionState = "Loading" | "Ready" | "SessionEnded";
227
+ /** The second GetState return is present only while the session is loading. */
228
+ export type LoadPhase = "WaitingForErase" | "AcquiringSession" | "ReadingProfile" | "Retrying" | "Initializing" | "Importing" | "ImportThrottled";
229
+ export type Visibility = "Replicated" | "ServerOnly" | "Shared";
230
+ export type LifecycleReason = "load-failed" | "migration-failed" | "erasing" | "session-ended" | "player-left" | "shutdown" | "still-loading" | "timeout";
231
+ export type RequestReason = "rate-limited" | "not-ready" | "unknown-command" | "bad-args" | "bad-idempotency-key" | "error" | "reply-encode-failed" | "timeout" | "send-failed" | "edit-mode" | "mock-error";
232
+ declare const requestFailedBrand: unique symbol;
233
+ /** Identity token returned only for framework refusals, never a handler result. */
234
+ export interface RequestFailedMarker { readonly [requestFailedBrand]: true; }
235
+ export type RequestFailure = LuaTuple<[false, RequestReason, RequestFailedMarker]>;
236
+ export type ProductState = "purchasable" | "owned" | "paid-random-restricted" | "policy-pending" | "not-loaded";
237
+ export type PurchaseReason = "player data not loaded" | "invalid Cost spec" | "invalid Cost amount" | "invalid cost path" | "cost path is not a spendable number" | "insufficient funds" | "paid random items are not available for this account" | "cannot check account settings right now; try again in a moment";
238
+ export type GiftReason = "buyer data not loaded" | "invalid recipient" | "cannot gift yourself" | "gift cooldown" | "product retired" | "too many pending gifts" | "data services are experiencing issues; try again later" | "recipient already owns this" | "could not reserve gift credit; try again later" | "could not deliver gift; try again later" | "gift delivery could not be confirmed; do not send it again" | "a gift of this item is already pending; try again shortly" | "could not record gift intent; try again later" | "paid random items are not available for this account" | "cannot check account settings right now; try again in a moment";
239
+ export type OperationResult = LuaTuple<[boolean, string | undefined]>;
240
+
241
+ export interface SaveInfo { LastSaveAt?: number; LastResult?: "Ok" | "Fail"; Dirty: boolean; Size?: number; }
242
+ export interface SaveEvent { Player: Player; Ok: boolean; Duration?: number; At: number; }
243
+ export interface Anomaly { Player: Player; Path: Path; Value?: unknown; Reason: string; }
244
+ export interface GiftReceived { FromUserId: number; Product: string; GiftId: string; }
245
+ export interface VersionRecord { VersionId: string; CreatedAt: number; Size?: number; }
246
+ export type ViolationKind = "WrongType" | "OutOfBounds" | "OverMaxLength" | "NotAMember" | "BadEncoding" | "UnknownKey";
247
+ export interface SchemaViolation { Path: Path; Kind: ViolationKind; Detail: string; Advisory?: boolean; }
248
+ export interface FlushOptions { Force?: boolean; Timeout?: number; }
249
+ export interface UpdateOfflineOptions { Validate?: boolean; }
250
+ export interface RestoreOptions { RollBackReserved?: boolean; }
251
+ export interface CooldownOptions { IncludeOfflineTime?: boolean; }
252
+ export interface MigrationContext {
253
+ readonly AwaitBudget: (this: void, requestType: string, count?: number, timeout?: number) => LuaTuple<[boolean, Disconnect]>;
254
+ }
255
+
256
+ export type BigScore = Pick<BigValue, "M" | "E" | "Short" | "ToNumber" | "Log10">;
257
+ export interface LeaderboardEntry { Rank: number; UserId: number; Name: string; Score: number | BigScore; }
258
+ export type LeaderboardStatus = "Starting" | "Healthy" | "Degraded";
259
+ /** Cached board health; reading it makes no DataStore requests. */
260
+ export interface LeaderboardStatusInfo {
261
+ Status: LeaderboardStatus;
262
+ PendingWrites: number;
263
+ RetryingWrites: number;
264
+ RejectedWrites: number;
265
+ LastReadAt?: number;
266
+ ReadAge?: number;
267
+ LastWriteAt?: number;
268
+ LastReadError?: string;
269
+ LastWriteError?: string;
270
+ }
271
+ /** A process-local bundle ID identifies the board's running bundle. */
272
+ export interface LeaderboardSnapshotEntry extends LeaderboardStatusInfo { BundleId: number; Name: string; }
273
+ export interface PassConfig { Id: number; Category?: string; }
274
+ export interface PurchaseFilter { Kind?: "Robux" | "InGame"; Category?: string; ItemId?: string; Since?: number; Limit?: number; }
275
+ /** RecordPurchase accepts game-defined fields, so only Kind is universally present. */
276
+ export interface PurchaseEntry extends UnknownRecord {
277
+ Kind: "Robux" | "InGame";
278
+ Ts?: number;
279
+ Category?: string;
280
+ ItemId?: string;
281
+ Product?: string;
282
+ PurchaseId?: string;
283
+ PriceInRobux?: number;
284
+ Currency?: string;
285
+ Amount?: number;
286
+ Meta?: UnknownRecord;
287
+ }
288
+ export interface PurchaseLogOptions { RobuxCap?: number; InGameCap?: number; ReplicateRobux?: boolean; ReplicateInGame?: boolean; PurchaseLogCategories?: ReadonlyArray<string>; }
289
+ export interface ProductInfo extends UnknownRecord {
290
+ Name?: string;
291
+ Description?: string;
292
+ ProductId?: number;
293
+ AssetId?: number;
294
+ IconImageAssetId?: number;
295
+ IsForSale?: boolean;
296
+ PriceInRobux?: number;
297
+ UserBasePriceInRobux?: number;
298
+ PriceDiscountDetails?: UnknownRecord;
299
+ }
300
+ export interface PolicyInfo extends UnknownRecord { ArePaidRandomItemsRestricted?: boolean; }
301
+ export interface ReceiptInfo {
302
+ PlayerId: number;
303
+ ProductId: number;
304
+ PurchaseId: string;
305
+ CurrencySpent?: number;
306
+ PlaceIdWherePurchased?: number;
307
+ }
308
+
309
+ export interface EconomyMeta {
310
+ Flow?: "Source" | "Sink";
311
+ TransactionType?: Enum.AnalyticsEconomyTransactionType | string;
312
+ ItemSku?: string;
313
+ Currency?: string;
314
+ Fields?: UnknownRecord;
315
+ Source?: string;
316
+ Item?: string;
317
+ }
318
+ export type EconomyFieldSpec = string | { Name: string; Prefix?: boolean };
319
+ export interface EconomyCurrencyConfig { Label?: string; Fields?: ReadonlyArray<EconomyFieldSpec>; Resolve?: (this: void, player: Player) => UnknownRecord; }
320
+ export type EconomyLogFn = (this: void, player: Player, flowType: Enum.AnalyticsEconomyFlowType, currencyType: string, amount: number, endingBalance: number, transactionType: string, itemSku?: string, customFields?: UnknownRecord) => void;
321
+ export interface EconomyConfig { Resolve?: (this: void, player: Player) => UnknownRecord; Prefix?: boolean; Currencies?: { [currency: string]: EconomyCurrencyConfig }; LogEconomyEvent?: EconomyLogFn; }
322
+
323
+ export interface ExchangeableSpec { Path: ReadonlyArray<string>; Kind: "Key" | "Qty" | "Stack"; Count?: string; Identity?: ReadonlyArray<string>; Ignore?: ReadonlyArray<string>; }
324
+ export type ExchangeLeg =
325
+ | { Path: Path; Kind: "Key"; Key: unknown; Amount?: never; Value?: unknown }
326
+ | { Path: Path; Kind: "Qty"; Key?: never; Amount: number; Value?: unknown }
327
+ | { Path: Path; Kind: "Stack"; Key: unknown; Amount: number; Value?: unknown };
328
+ export interface OpenLeg { Path: Path; Kind: "Key" | "Qty" | "Stack"; Key?: unknown; Amount?: number; }
329
+ export interface OpenExchange { Id: string; State: "Claimed" | "Staked" | "Delivering"; Partner?: number; Staked: OpenLeg[]; Owed: OpenLeg[]; Since?: number; }
330
+ export interface ExchangeAPI {
331
+ readonly Attempt: (this: void, playerA: Player, basketA: ReadonlyArray<ExchangeLeg>, playerB: Player, basketB: ReadonlyArray<ExchangeLeg>) => LuaTuple<["Committed" | "Aborted" | undefined, string | undefined]>;
332
+ readonly Open: (this: void, player: Player) => OpenExchange[];
333
+ readonly Discard: (this: void, exchangeId: string) => OperationResult;
334
+ readonly Settle: (this: void, exchangeId: string, verdict: "Commit" | "Abort") => OperationResult;
335
+ readonly Redirect: (this: void, exchangeId: string, userId: number, newKey: string) => OperationResult;
336
+ }
337
+
338
+ export interface BudgetSnapshot { Available: boolean; Reason?: string; Budgets: { [requestType: string]: number }; At: number; }
339
+ export interface MetricObservation { Count: number; Average: number; Max: number; }
340
+ export type Metrics = { [name: string]: number | MetricObservation };
341
+ export interface Percentiles { P50: number; P90: number; P99: number; Samples: number; Age: number; Window: number; }
342
+ export type PercentileSnapshot = { [name: string]: Percentiles };
343
+ export interface AddonAction { Run: (this: void, args: unknown) => unknown; Writes?: boolean; }
344
+ export type AddonActions = { [name: string]: AddonAction };
345
+ export interface ConfigureOptions { AutoSaveInterval?: number; }
346
+ export interface StatusThresholds { FailWindow?: number; FailCount?: number; RecoverStreak?: number; }
347
+ export interface PeriodResetOptions { UtcOffset?: number; WeekStart?: "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday"; }
348
+
349
+ export interface MockState {
350
+ Perks?: ReadonlyArray<string>;
351
+ GiftCredits?: { [product: string]: number };
352
+ PurchaseLogs?: { Robux?: ReadonlyArray<UnknownRecord>; InGame?: ReadonlyArray<UnknownRecord> };
353
+ Leaderboards?: { [name: string]: ReadonlyArray<LeaderboardEntry> };
354
+ }
355
+