@quenty/saveslot 2.7.1 → 2.8.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.
@@ -0,0 +1,170 @@
1
+ --!strict
2
+ --[=[
3
+ A player's save slots opened without that player, and the obligation to close them again.
4
+
5
+ Wraps a borrowed [PlayerDataStoreHandle] and a [HasSaveSlotsDataStore] built over it, so admin
6
+ tooling can act on someone who is not in this server. Destroying this releases the session -- see
7
+ [PlayerDataStoreHandle] for why that matters, and [SaveSlotService.PromiseOfflineSaveSlots] for
8
+ how one is opened.
9
+
10
+ :::warning
11
+ Opening this **steals the player's session lock**, which kicks them from wherever they were
12
+ playing. It is for admin tooling acting on an absent player; never open one for a player who is
13
+ in this server -- use their bound [HasSaveSlots] instead, or you will be writing to a second,
14
+ stale copy of their data.
15
+ :::
16
+
17
+ The value objects backing the slot state are detached rather than replicated: there is no player
18
+ to replicate to, and the slot roster stays unparented for the same reason.
19
+
20
+ ```lua
21
+ local offline = saveSlotService:PromiseOfflineSaveSlots(userId):Yield()
22
+ local slots = offline:GetSlotsDataStore()
23
+ print(slots:GetSlotList())
24
+ offline:Destroy()
25
+ ```
26
+
27
+ @server
28
+ @class OfflineSaveSlots
29
+ ]=]
30
+
31
+ local require = require(script.Parent.loader).load(script)
32
+
33
+ local HasSaveSlotsDataStore = require("HasSaveSlotsDataStore")
34
+ local Maid = require("Maid")
35
+ local Promise = require("Promise")
36
+ local SaveSlotCodeUtils = require("SaveSlotCodeUtils")
37
+ local ValueObject = require("ValueObject")
38
+
39
+ --[=[
40
+ @interface OfflineSaveSlotsOptions
41
+ .SharedDataStoreService any -- SaveSlotSharedDataStoreService
42
+ .MaxSlotCount number
43
+ .CodeGenerator SaveSlotCodeUtils.CodeGenerator?
44
+ .UserId number?
45
+ .UserName string?
46
+ @within OfflineSaveSlots
47
+ ]=]
48
+ export type OfflineSaveSlotsOptions = {
49
+ SharedDataStoreService: any,
50
+ MaxSlotCount: number,
51
+ CodeGenerator: SaveSlotCodeUtils.CodeGenerator?,
52
+ UserId: number?,
53
+ UserName: string?,
54
+ }
55
+
56
+ local OfflineSaveSlots = {}
57
+ OfflineSaveSlots.ClassName = "OfflineSaveSlots"
58
+ OfflineSaveSlots.__index = OfflineSaveSlots
59
+
60
+ export type OfflineSaveSlots = typeof(setmetatable(
61
+ {} :: {
62
+ _maid: Maid.Maid,
63
+ _handle: any,
64
+ _slotsDataStore: any,
65
+ },
66
+ {} :: typeof({ __index = OfflineSaveSlots })
67
+ ))
68
+
69
+ --[=[
70
+ Builds the slot system over a borrowed datastore handle. Takes ownership of the handle: destroying
71
+ this destroys it.
72
+
73
+ @param handle PlayerDataStoreHandle
74
+ @param options OfflineSaveSlotsOptions
75
+ @return OfflineSaveSlots
76
+ ]=]
77
+ function OfflineSaveSlots.new(handle: any, options: OfflineSaveSlotsOptions): OfflineSaveSlots
78
+ local self: OfflineSaveSlots = setmetatable({} :: any, OfflineSaveSlots)
79
+
80
+ self._handle = assert(handle, "No handle")
81
+ assert(options, "No options")
82
+
83
+ self._maid = Maid.new()
84
+
85
+ -- Bound rather than asserted inline: assert returns its message as a second value, which
86
+ -- ValueObject.new would take as a type check.
87
+ local maxSlotCount = options.MaxSlotCount
88
+ assert(type(maxSlotCount) == "number", "No MaxSlotCount")
89
+
90
+ local slotsDataStore = HasSaveSlotsDataStore.new(Promise.resolved(handle:GetDataStore()), {
91
+ ActiveSlotId = self._maid:Add(ValueObject.new(nil)),
92
+ LastActiveSlotId = self._maid:Add(ValueObject.new(nil)),
93
+ ActiveTransferableEphemeralKey = self._maid:Add(ValueObject.new(nil)),
94
+ MaxSlotCount = self._maid:Add(ValueObject.new(maxSlotCount)),
95
+ SharedDataStoreService = options.SharedDataStoreService,
96
+ -- No parent: there is nobody to replicate the roster to.
97
+ -- No pre-select veto either: those callbacks are written against a live player.
98
+ UserId = options.UserId,
99
+ UserName = options.UserName,
100
+ -- An admin editing a slot from a console is not someone playing it, so no play session is
101
+ -- ever begun and nothing accrues into TimePlayed or PlayCount.
102
+ TrackPlaytime = false,
103
+ })
104
+
105
+ if options.CodeGenerator then
106
+ slotsDataStore:SetCodeGenerator(options.CodeGenerator)
107
+ end
108
+
109
+ self._slotsDataStore = slotsDataStore
110
+
111
+ return self
112
+ end
113
+
114
+ --[=[
115
+ Returns whether the value is an OfflineSaveSlots.
116
+
117
+ @param value any
118
+ @return boolean
119
+ ]=]
120
+ function OfflineSaveSlots.isOfflineSaveSlots(value: any): boolean
121
+ return type(value) == "table" and getmetatable(value) == OfflineSaveSlots
122
+ end
123
+
124
+ --[=[
125
+ Resolves once the slots have loaded from the datastore.
126
+
127
+ @return Promise
128
+ ]=]
129
+ function OfflineSaveSlots.PromiseSlotsLoaded(self: OfflineSaveSlots): Promise.Promise<any>
130
+ return self._slotsDataStore:PromiseSlotsLoaded()
131
+ end
132
+
133
+ --[=[
134
+ Returns the slot system, a [HasSaveSlotsDataStore]. Valid until this is destroyed.
135
+
136
+ @return HasSaveSlotsDataStore
137
+ ]=]
138
+ function OfflineSaveSlots.GetSlotsDataStore(self: OfflineSaveSlots): any
139
+ -- Bound before asserting, so the assert's message does not ride along as a second return value.
140
+ local slotsDataStore = self._slotsDataStore
141
+ assert(slotsDataStore, "Destroyed")
142
+
143
+ return slotsDataStore
144
+ end
145
+
146
+ --[=[
147
+ Tears the slot system down and releases the borrowed session, which saves and unlocks it so the
148
+ player can rejoin. Destroying twice is safe.
149
+ ]=]
150
+ function OfflineSaveSlots.Destroy(self: OfflineSaveSlots): ()
151
+ local slotsDataStore = self._slotsDataStore
152
+ local handle = self._handle
153
+
154
+ self._slotsDataStore = nil
155
+ self._handle = nil
156
+
157
+ -- Order matters: the slot system writes into the datastore the handle owns, so it has to be torn
158
+ -- down before the handle releases -- which is what saves and unlocks the session.
159
+ if slotsDataStore then
160
+ slotsDataStore:Destroy()
161
+ end
162
+
163
+ self._maid:DoCleaning()
164
+
165
+ if handle then
166
+ handle:Destroy()
167
+ end
168
+ end
169
+
170
+ return OfflineSaveSlots
@@ -0,0 +1,174 @@
1
+ --!strict
2
+ --[[
3
+ Save slots opened for a player who is not in this server. What is worth pinning down is that the
4
+ roster read is the same one the player would have seen, that writes land in their real datastore,
5
+ and that the borrowed session is handed back -- a session left open is a player who cannot rejoin.
6
+
7
+ @class OfflineSaveSlots.spec.lua
8
+ ]]
9
+ local require = require(script.Parent.loader).load(script)
10
+
11
+ local DataStoreMock = require("DataStoreMock")
12
+ local DataStoreTestUtils = require("DataStoreTestUtils")
13
+ local Jest = require("Jest")
14
+ local Maid = require("Maid")
15
+ local PlayerDataStoreService = require("PlayerDataStoreService")
16
+ local PromiseTestUtils = require("PromiseTestUtils")
17
+ local SaveSlotService = require("SaveSlotService")
18
+ local ServiceBag = require("ServiceBag")
19
+
20
+ local describe = Jest.Globals.describe
21
+ local expect = Jest.Globals.expect
22
+ local it = Jest.Globals.it
23
+
24
+ local ABSENT_USER_ID = 90210
25
+
26
+ local function setup()
27
+ local maid = Maid.new()
28
+ local serviceBag = maid:Add(ServiceBag.new())
29
+ local playerDataStoreService: PlayerDataStoreService.PlayerDataStoreService =
30
+ serviceBag:GetService(PlayerDataStoreService) :: any
31
+ local saveSlotService: SaveSlotService.SaveSlotService = serviceBag:GetService(SaveSlotService) :: any
32
+ serviceBag:Init()
33
+
34
+ local mock = DataStoreMock.new()
35
+ playerDataStoreService:SetRobloxDataStore(mock)
36
+ saveSlotService:SetMaxSlotCount(5)
37
+ serviceBag:Start()
38
+
39
+ local function await(promise, label: string): any
40
+ if not PromiseTestUtils.awaitSettled(promise, 10) then
41
+ expect(`{label} hung`).toEqual(`{label} settled`)
42
+ return nil
43
+ end
44
+ local ok, value = promise:Yield()
45
+ if not ok then
46
+ expect(`{label} rejected: {tostring(value)}`).toEqual(`{label} fulfilled`)
47
+ return nil
48
+ end
49
+ return value
50
+ end
51
+
52
+ return {
53
+ serviceBag = serviceBag,
54
+ saveSlotService = saveSlotService,
55
+ mock = mock,
56
+ await = await,
57
+ -- Opens the offline slots and waits for the roster to load, which is what every caller wants;
58
+ -- the sync read accessors see an empty roster until it has.
59
+ openSlots = function(userId: number?): any
60
+ local offline = await(saveSlotService:PromiseOfflineSaveSlots(userId or ABSENT_USER_ID), "open")
61
+ if offline then
62
+ await(offline:PromiseSlotsLoaded(), "load")
63
+ end
64
+ return offline
65
+ end,
66
+ destroy = function()
67
+ -- A PlayerMock never fires the real Players.PlayerRemoving, and an offline store is only
68
+ -- released by its handle, so shut down the way Roblox does before tearing the bag down.
69
+ DataStoreTestUtils.awaitServiceShutdown(playerDataStoreService)
70
+ maid:DoCleaning()
71
+ end,
72
+ }
73
+ end
74
+
75
+ describe("SaveSlotService.PromiseOfflineSaveSlots", function()
76
+ it("reads the absent player's stored slots", function()
77
+ local controller = setup()
78
+
79
+ controller.mock:SetRaw(tostring(ABSENT_USER_ID), {
80
+ SaveSlots = {
81
+ slotMetadata = {
82
+ ["slot-b"] = { SlotIndex = 2, SlotName = "Beta" },
83
+ ["slot-a"] = { SlotIndex = 1, SlotName = "Alpha" },
84
+ },
85
+ activeSlotId = "slot-a",
86
+ },
87
+ })
88
+
89
+ local offline = controller.openSlots()
90
+ local slots = offline:GetSlotsDataStore()
91
+
92
+ local slotList = slots:GetSlotList()
93
+ expect(#slotList).toEqual(2)
94
+ -- Ordered by index, since the backing map is not.
95
+ expect(slotList[1].SlotName).toEqual("Alpha")
96
+ expect(slotList[2].SlotName).toEqual("Beta")
97
+
98
+ -- Nothing selects in an offline session, so the stored pointer surfaces as the slot they would
99
+ -- resume on rather than as an active one.
100
+ expect(slots:GetActiveSlotId()).toBeNil()
101
+ expect(slots:GetLastActiveSlotId()).toEqual("slot-a")
102
+
103
+ offline:Destroy()
104
+ controller.destroy()
105
+ end)
106
+
107
+ it("writes a slot created offline into the player's datastore", function()
108
+ local controller = setup()
109
+
110
+ local offline = controller.openSlots()
111
+ local slotId = controller.await(offline:GetSlotsDataStore():PromiseCreateSlot(1), "create")
112
+ expect(type(slotId)).toEqual("string")
113
+
114
+ -- Releasing the session is what flushes it, so read the store only after the destroy settles.
115
+ offline:Destroy()
116
+
117
+ local reopened = controller.openSlots()
118
+ local slotList = reopened:GetSlotsDataStore():GetSlotList()
119
+ expect(#slotList).toEqual(1)
120
+ expect(slotList[1].SlotIndex).toEqual(1)
121
+
122
+ reopened:Destroy()
123
+ controller.destroy()
124
+ end)
125
+
126
+ it("releases the borrowed session, so the next open builds a fresh one", function()
127
+ local controller = setup()
128
+
129
+ local first = controller.openSlots()
130
+ local firstStore = first:GetSlotsDataStore()
131
+ first:Destroy()
132
+
133
+ local second = controller.openSlots()
134
+ -- A released session is gone, so this had to open its own rather than share the last one.
135
+ expect(second:GetSlotsDataStore() == firstStore).toEqual(false)
136
+
137
+ second:Destroy()
138
+ controller.destroy()
139
+ end)
140
+
141
+ -- The refusal for a player who *is* in this server is not covered: the guard reads
142
+ -- Players:GetPlayerByUserId, which only ever sees a real Player, and a PlayerMock is a Folder. An
143
+ -- attempt to stand one in by parenting it under Players collides with PlayerMockService instead.
144
+
145
+ it("does not accrue playtime, because an admin edit is not a play session", function()
146
+ local controller = setup()
147
+
148
+ local offline = controller.openSlots()
149
+ local slots = offline:GetSlotsDataStore()
150
+
151
+ local slotId = controller.await(slots:PromiseCreateSlot(1), "create")
152
+ controller.await(slots:PromiseSelectSlot(slotId), "select")
153
+
154
+ local metadata = slots:GetSlotMetadata(slotId)
155
+ expect(metadata.PlayCount).toBeNil()
156
+ expect(metadata.TimePlayed).toBeNil()
157
+
158
+ offline:Destroy()
159
+ controller.destroy()
160
+ end)
161
+
162
+ it("survives being destroyed twice", function()
163
+ local controller = setup()
164
+
165
+ local offline = controller.openSlots()
166
+ offline:Destroy()
167
+
168
+ expect(function()
169
+ offline:Destroy()
170
+ end).never.toThrow()
171
+
172
+ controller.destroy()
173
+ end)
174
+ end)
@@ -5,6 +5,7 @@
5
5
 
6
6
  local require = require(script.Parent.loader).load(script)
7
7
 
8
+ local Players = game:GetService("Players")
8
9
  local ReplicatedStorage = game:GetService("ReplicatedStorage")
9
10
 
10
11
  local Brio = require("Brio")
@@ -15,6 +16,7 @@ local Maid = require("Maid")
15
16
  local Observable = require("Observable")
16
17
  local ObservableMap = require("ObservableMap")
17
18
  local ObservableSet = require("ObservableSet")
19
+ local OfflineSaveSlots = require("OfflineSaveSlots")
18
20
  local Promise = require("Promise")
19
21
  local PromiseUtils = require("PromiseUtils")
20
22
  local Remoting = require("Remoting")
@@ -51,6 +53,8 @@ export type SaveSlotService = typeof(setmetatable(
51
53
  _preSelectCallbacks: any,
52
54
  _remoting: any,
53
55
  _teleportDataService: any,
56
+ _playerDataStoreService: any,
57
+ _sharedSaveSlotDataStoreService: any,
54
58
  _codeGenerator: SaveSlotCodeUtils.CodeGenerator?,
55
59
  },
56
60
  {} :: typeof({ __index = SaveSlotService })
@@ -62,12 +66,13 @@ function SaveSlotService.Init(self: SaveSlotService, serviceBag: ServiceBag.Serv
62
66
  self._maid = Maid.new()
63
67
 
64
68
  -- External
65
- self._serviceBag:GetService(require("PlayerDataStoreService"))
69
+ self._serviceBag:GetService(require("DataStoreService"))
70
+ self._playerDataStoreService = self._serviceBag:GetService(require("PlayerDataStoreService"))
66
71
  self._teleportDataService = self._serviceBag:GetService(TeleportDataService)
67
72
 
68
73
  -- Registered here (pre-start) so the HasSaveSlots binder can acquire it when a player binds,
69
74
  -- which happens after Start. Mirrors how PlayerDataStoreService/TeleportDataService are pulled in.
70
- self._serviceBag:GetService(SaveSlotSharedDataStoreService)
75
+ self._sharedSaveSlotDataStoreService = self._serviceBag:GetService(SaveSlotSharedDataStoreService)
71
76
 
72
77
  -- Internal
73
78
  self._serviceBag:GetService(require("SaveSlotCmdrService"))
@@ -270,6 +275,63 @@ function SaveSlotService.SetUnlimitedSlots(self: SaveSlotService): ()
270
275
  self:SetMaxSlotCount(math.huge)
271
276
  end
272
277
 
278
+ --[=[
279
+ Opens the save slots of a player who is **not in this server**, as an [OfflineSaveSlots] the caller
280
+ must destroy. The game's slot count and code generator are applied, so an offline edit behaves like
281
+ an online one.
282
+
283
+ :::warning
284
+ This steals the player's session lock, kicking them from wherever they are playing, and holds it
285
+ until the returned object is destroyed. It backs admin tooling ([SaveSlotCmdrService]); it is not
286
+ something to reach for on a normal code path.
287
+ :::
288
+
289
+ Rejects for a player who *is* in this server: they already have a live [HasSaveSlots] holding their
290
+ session, and a second copy of their data would be written from underneath it. Use the binder.
291
+
292
+ @param userId number
293
+ @return Promise<OfflineSaveSlots>
294
+ ]=]
295
+ function SaveSlotService.PromiseOfflineSaveSlots(
296
+ self: SaveSlotService,
297
+ userId: number
298
+ ): Promise.Promise<OfflineSaveSlots.OfflineSaveSlots>
299
+ assert(type(userId) == "number", "Bad userId")
300
+
301
+ if Players:GetPlayerByUserId(userId) then
302
+ return Promise.rejected(`{userId} is in this server -- use their HasSaveSlots binder`)
303
+ end
304
+
305
+ -- Deliberately not `_maid:GivePromise`, which cancels nothing upstream: on teardown the handle
306
+ -- still resolves, into a continuation the maid has already skipped, and the session it took stays
307
+ -- locked for the rest of the server's life. The maid is probed for liveness instead, so a handle
308
+ -- that arrives too late is handed straight back rather than orphaned.
309
+ local probe = {}
310
+ self._maid[probe] = probe
311
+
312
+ return self._playerDataStoreService:PromiseDataStoreHandle(userId):Then(function(handle)
313
+ local isAlive = self._maid[probe] == probe
314
+ self._maid[probe] = nil
315
+
316
+ if not isAlive then
317
+ handle:Destroy()
318
+ -- Cast because this branch makes the callback return a union with the slots below, which
319
+ -- the solver otherwise tries to unify into one type.
320
+ return (Promise :: any).rejected(`Destroyed while opening the datastore for {userId}`)
321
+ end
322
+
323
+ return OfflineSaveSlots.new(handle, {
324
+ SharedDataStoreService = self._sharedSaveSlotDataStoreService,
325
+ MaxSlotCount = self._maxSlotCount,
326
+ CodeGenerator = self._codeGenerator,
327
+ UserId = userId,
328
+ })
329
+ end, function(err)
330
+ self._maid[probe] = nil
331
+ return Promise.rejected(err)
332
+ end)
333
+ end
334
+
273
335
  --[=[
274
336
  Sets the share-code generator applied to every player's exports (see [SaveSlotCodeUtils.CodeGenerator]),
275
337
  so a game can choose a code format that suits its players. Defaults to
@@ -6,9 +6,14 @@
6
6
  local require = require(script.Parent.loader).load(script)
7
7
 
8
8
  local SaveSlotConstants = require("SaveSlotConstants")
9
+ local SaveSlotData = require("SaveSlotData")
9
10
 
10
11
  local SaveSlotCmdrUtils = {}
11
12
 
13
+ -- How deep a summary value is expanded before it collapses to "...". Summaries come out of a
14
+ -- JSON-encoded attribute, so they are shallow in practice; this only guards a pathological one.
15
+ local MAX_VALUE_DEPTH = 3
16
+
12
17
  function SaveSlotCmdrUtils.registerSlotIndexType(cmdr, saveSlotDataService)
13
18
  local slotIndex = {
14
19
  Transform = function(text: string, player: Player)
@@ -36,7 +41,7 @@ function SaveSlotCmdrUtils.registerSlotIndexType(cmdr, saveSlotDataService)
36
41
  -- Autocomplete can only ever offer the executor's own slots -- Cmdr resolves types against the
37
42
  -- executor -- but these commands target other players, whose slots the executor cannot see. So
38
43
  -- any literal index typed out is accepted even when the executor has no such slot, which is what
39
- -- makes `export-save-slot SomeoneElse 3` possible. A target without that slot is reported by the
44
+ -- makes `saveslot-export SomeoneElse 3` possible. A target without that slot is reported by the
40
45
  -- command itself, which resolves the index per player.
41
46
  local literalIndex = tonumber(text)
42
47
  if literalIndex and (literalIndex >= 0) and (literalIndex % 1 == 0) then
@@ -57,7 +62,7 @@ function SaveSlotCmdrUtils.registerSlotIndexType(cmdr, saveSlotDataService)
57
62
 
58
63
  -- "." resolves to the player's current slot: the active slot when one is selected, otherwise the
59
64
  -- slot they last played. Cmdr feeds this string back through Transform, so it fuzzy matches the
60
- -- real slot. MakeListableType inherits Default, so "." works for delete-save-slot's list too.
65
+ -- real slot. MakeListableType inherits Default, so "." works for saveslot-delete's list too.
61
66
  Default = function(player: Player): string?
62
67
  local slotId = saveSlotDataService:GetLastActiveSlotId(player)
63
68
  if not slotId then
@@ -75,4 +80,203 @@ function SaveSlotCmdrUtils.registerSlotIndexType(cmdr, saveSlotDataService)
75
80
  cmdr.Registry:RegisterType("slotIndices", cmdr.Util.MakeListableType(slotIndex))
76
81
  end
77
82
 
83
+ local function formatNumber(value: number): string
84
+ -- Datastore round-trips integers as floats, so print whole numbers without a decimal tail.
85
+ if value % 1 == 0 and math.abs(value) < 1e15 then
86
+ return string.format("%d", value)
87
+ end
88
+
89
+ return string.format("%.2f", value)
90
+ end
91
+
92
+ local function isArray(value: { [any]: any }): boolean
93
+ local count = 0
94
+ for _ in value do
95
+ count += 1
96
+ end
97
+
98
+ return count == #value
99
+ end
100
+
101
+ local function formatTableInner(value: { [any]: any }, depth: number): string
102
+ local parts = {}
103
+
104
+ if isArray(value) then
105
+ for _, item in value do
106
+ table.insert(parts, SaveSlotCmdrUtils.formatValue(item, depth - 1))
107
+ end
108
+ else
109
+ -- Sorted so repeated listings of the same slot read the same way.
110
+ local entries = {}
111
+ for key, item in value do
112
+ table.insert(entries, { key = tostring(key), value = item })
113
+ end
114
+ table.sort(entries, function(a, b)
115
+ return a.key < b.key
116
+ end)
117
+
118
+ for _, entry in entries do
119
+ table.insert(parts, `{entry.key} = {SaveSlotCmdrUtils.formatValue(entry.value, depth - 1)}`)
120
+ end
121
+ end
122
+
123
+ return table.concat(parts, ", ")
124
+ end
125
+
126
+ --[=[
127
+ Renders a JSON-shaped value on a single line, for console output. Tables become `{a = 1, b = 2}`
128
+ and arrays `[1, 2]`, nested up to `depth` levels before collapsing to "...".
129
+
130
+ @param value any
131
+ @param depth number? -- defaults to 3
132
+ @return string
133
+ ]=]
134
+ function SaveSlotCmdrUtils.formatValue(value: any, depth: number?): string
135
+ local remaining = depth or MAX_VALUE_DEPTH
136
+
137
+ if type(value) == "number" then
138
+ return formatNumber(value)
139
+ elseif type(value) ~= "table" then
140
+ return tostring(value)
141
+ end
142
+
143
+ if remaining <= 0 then
144
+ return "..."
145
+ end
146
+
147
+ local inner = formatTableInner(value, remaining)
148
+ if isArray(value) then
149
+ return `[{inner}]`
150
+ end
151
+
152
+ return "{" .. inner .. "}"
153
+ end
154
+
155
+ --[=[
156
+ Renders a duration in seconds as "1h 23m", "23m", or "45s".
157
+
158
+ @param seconds number
159
+ @return string
160
+ ]=]
161
+ function SaveSlotCmdrUtils.formatDuration(seconds: number): string
162
+ local total = math.max(0, math.floor(seconds))
163
+ local hours = math.floor(total / 3600)
164
+ local minutes = math.floor((total % 3600) / 60)
165
+
166
+ if hours > 0 then
167
+ return `{hours}h {minutes}m`
168
+ elseif minutes > 0 then
169
+ return `{minutes}m`
170
+ end
171
+
172
+ return `{total}s`
173
+ end
174
+
175
+ --[=[
176
+ Renders a unix timestamp as UTC plus how long ago it was, e.g. "2026-08-12 14:03 UTC (3h ago)".
177
+ The relative part is what an admin actually reads; the absolute one is what they quote back.
178
+
179
+ @param unixTime number
180
+ @param now number? -- defaults to os.time()
181
+ @return string
182
+ ]=]
183
+ function SaveSlotCmdrUtils.formatTimestamp(unixTime: number, now: number?): string
184
+ local absolute = os.date("!%Y-%m-%d %H:%M UTC", math.floor(unixTime))
185
+ local elapsed = (now or os.time()) - unixTime
186
+ if elapsed < 0 then
187
+ return absolute
188
+ end
189
+
190
+ local relative
191
+ if elapsed < 60 then
192
+ relative = "just now"
193
+ elseif elapsed < 3600 then
194
+ relative = `{math.floor(elapsed / 60)}m ago`
195
+ elseif elapsed < 86400 then
196
+ relative = `{math.floor(elapsed / 3600)}h ago`
197
+ else
198
+ relative = `{math.floor(elapsed / 86400)}d ago`
199
+ end
200
+
201
+ return `{absolute} ({relative})`
202
+ end
203
+
204
+ --[=[
205
+ Renders a slot's [SaveSlotData.SaveSlotSummary] as one line per summary provider, keyed by provider
206
+ name (see [HasSaveSlots.RegisterSummaryProvider]). A legacy plain-string summary is passed through
207
+ as its own line, and a summary with nothing in it yields no lines at all.
208
+
209
+ @param summary SaveSlotData.SaveSlotSummary | string | nil
210
+ @return { string }
211
+ ]=]
212
+ function SaveSlotCmdrUtils.formatSummaryLines(summary: SaveSlotData.SaveSlotSummary | string | nil): { string }
213
+ if summary == nil then
214
+ return {}
215
+ elseif type(summary) == "string" then
216
+ return { summary }
217
+ end
218
+
219
+ local names = {}
220
+ for name in summary do
221
+ table.insert(names, tostring(name))
222
+ end
223
+ table.sort(names)
224
+
225
+ local lines = {}
226
+ for _, name in names do
227
+ local value = (summary :: any)[name]
228
+ -- A provider's own table is unwrapped, so its fields sit next to the provider name rather than
229
+ -- inside a second pair of braces.
230
+ local text = if type(value) == "table" and next(value) ~= nil
231
+ then formatTableInner(value, MAX_VALUE_DEPTH)
232
+ else SaveSlotCmdrUtils.formatValue(value)
233
+ table.insert(lines, `{name}: {text}`)
234
+ end
235
+
236
+ return lines
237
+ end
238
+
239
+ --[=[
240
+ Renders one slot as the block `saveslot-list` prints for it: a header naming the slot, then an
241
+ indented line of playtime and timestamps, then a line per summary provider. Lines with nothing
242
+ behind them are left out, so a slot that has never been played prints as its header alone.
243
+
244
+ @param metadata SaveSlotData.SaveSlotMetadata
245
+ @param status string? -- appended to the header, e.g. "Active"
246
+ @param now number? -- defaults to os.time(), for the relative timestamps
247
+ @return string
248
+ ]=]
249
+ function SaveSlotCmdrUtils.formatSlotBlock(
250
+ metadata: SaveSlotData.SaveSlotMetadata,
251
+ status: string?,
252
+ now: number?
253
+ ): string
254
+ local name = metadata.SlotName or `Slot {metadata.SlotIndex}`
255
+ local lines = { `"{name}" ({metadata.SlotIndex}){if status then ` — {status}` else ""}` }
256
+
257
+ local played = {}
258
+ if metadata.TimePlayed and metadata.TimePlayed > 0 then
259
+ table.insert(played, `played {SaveSlotCmdrUtils.formatDuration(metadata.TimePlayed)}`)
260
+ end
261
+ if metadata.PlayCount and metadata.PlayCount > 0 then
262
+ table.insert(played, `{formatNumber(metadata.PlayCount)} session(s)`)
263
+ end
264
+ if metadata.LastPlayedTime then
265
+ table.insert(played, `last played {SaveSlotCmdrUtils.formatTimestamp(metadata.LastPlayedTime, now)}`)
266
+ end
267
+ if #played > 0 then
268
+ table.insert(lines, ` {table.concat(played, ", ")}`)
269
+ end
270
+
271
+ if metadata.CreatedTime then
272
+ table.insert(lines, ` created {SaveSlotCmdrUtils.formatTimestamp(metadata.CreatedTime, now)}`)
273
+ end
274
+
275
+ for _, line in SaveSlotCmdrUtils.formatSummaryLines(metadata.Summary) do
276
+ table.insert(lines, ` {line}`)
277
+ end
278
+
279
+ return table.concat(lines, "\n")
280
+ end
281
+
78
282
  return SaveSlotCmdrUtils