@quenty/saveslot 2.7.0 → 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.
@@ -1,13 +1,50 @@
1
1
  --!strict
2
2
  --[=[
3
+ Save slot admin commands.
4
+
5
+ | Command | What it does |
6
+ | --- | --- |
7
+ | `saveslot-list` | Lists every slot with its playtime, timestamps and summary |
8
+ | `saveslot-get-active` | Reports the slot being played, or the one that would resume |
9
+ | `saveslot-select` | Switches onto a slot |
10
+ | `saveslot-deselect` | Returns to the no-slot state |
11
+ | `saveslot-create` | Creates slots, defaulting to the lowest free index |
12
+ | `saveslot-delete` | Deletes slots |
13
+ | `saveslot-copy` | Copies one player's slot onto other players', **overwriting an occupied destination** |
14
+ | `saveslot-persist` | Turns the ephemeral session into a save and switches onto it |
15
+ | `saveslot-reset` | Empties slots, keeping their index and name |
16
+ | `saveslot-export` / `saveslot-import` | Moves a slot through the shared store as a code |
17
+ | `saveslot-read-json` / `saveslot-write-json` | Moves a slot as raw JSON, no shared store |
18
+ | `saveslot-import-ephemeral` | Loads a code into a throwaway session |
19
+
20
+ Commands take players as ids, so they reach a player who is not in this server as readily as one who
21
+ is: a player here is acted on through their bound [HasSaveSlots], and an absent player through an
22
+ [OfflineSaveSlots] opened over their datastore. Both hand back the same [HasSaveSlotsDataStore], so
23
+ the command bodies below never branch on which it was. `saveslot-import-ephemeral` is the one
24
+ exception, and refuses an absent player outright -- an ephemeral session only exists while it is
25
+ being played.
26
+
27
+ :::warning
28
+ Acting on an absent player **steals their session lock**, kicking them from wherever they are
29
+ playing. That is accepted for admin tooling -- the session is released again as soon as the command
30
+ finishes, so they can rejoin -- but it is why these are admin commands.
31
+ :::
32
+
33
+ @server
3
34
  @class SaveSlotCmdrService
4
35
  ]=]
5
36
 
6
37
  local require = require(script.Parent.loader).load(script)
7
38
 
39
+ local HttpService = game:GetService("HttpService")
40
+ local Players = game:GetService("Players")
41
+
42
+ local CmdrReplyUtils = require("CmdrReplyUtils")
8
43
  local CmdrService = require("CmdrService")
44
+ local CmdrTypes = require("CmdrTypes")
9
45
  local HasSaveSlots = require("HasSaveSlots")
10
46
  local Maid = require("Maid")
47
+ local PlayerDataStoreService = require("PlayerDataStoreService")
11
48
  local Promise = require("Promise")
12
49
  local SaveSlotCmdrUtils = require("SaveSlotCmdrUtils")
13
50
  local SaveSlotConstants = require("SaveSlotConstants")
@@ -19,6 +56,7 @@ SaveSlotCmdrService.ServiceName = "SaveSlotCmdrService"
19
56
 
20
57
  type SlotEntry = { slotIndex: number, slotId: string }
21
58
  type SlotEntries = { SlotEntry }
59
+ type CommandContext = CmdrTypes.CommandContext
22
60
 
23
61
  export type SaveSlotCmdrService = typeof(setmetatable(
24
62
  {} :: {
@@ -26,7 +64,9 @@ export type SaveSlotCmdrService = typeof(setmetatable(
26
64
  _maid: Maid.Maid,
27
65
  _cmdrService: any,
28
66
  _hasSaveSlotsBinder: any,
67
+ _playerDataStoreService: any,
29
68
  _saveSlotDataService: any,
69
+ _replyConfig: CmdrReplyUtils.CmdrReplyConfig,
30
70
  },
31
71
  {} :: typeof({ __index = SaveSlotCmdrService })
32
72
  ))
@@ -35,15 +75,29 @@ function SaveSlotCmdrService.Init(self: SaveSlotCmdrService, serviceBag: Service
35
75
  assert(not (self :: any)._serviceBag, "Already initialized")
36
76
  self._serviceBag = assert(serviceBag, "No serviceBag")
37
77
  self._maid = Maid.new()
78
+ self._replyConfig = CmdrReplyUtils.createConfig()
38
79
 
39
80
  -- External
40
81
  self._cmdrService = self._serviceBag:GetService(CmdrService)
82
+ self._playerDataStoreService = self._serviceBag:GetService(PlayerDataStoreService)
41
83
 
42
84
  -- Internal
43
85
  self._hasSaveSlotsBinder = self._serviceBag:GetService(HasSaveSlots)
44
86
  self._saveSlotDataService = self._serviceBag:GetService(SaveSlotDataService)
45
87
  end
46
88
 
89
+ --[=[
90
+ Sets how long a command may run before it tells the executor it is still working, and how that
91
+ line is colored.
92
+
93
+ @param replyConfig CmdrReplyConfig -- see [CmdrReplyUtils.createConfig]
94
+ ]=]
95
+ function SaveSlotCmdrService.SetReplyConfig(self: SaveSlotCmdrService, replyConfig: CmdrReplyUtils.CmdrReplyConfig): ()
96
+ assert(CmdrReplyUtils.isCmdrReplyConfig(replyConfig), "Bad replyConfig")
97
+
98
+ self._replyConfig = replyConfig
99
+ end
100
+
47
101
  function SaveSlotCmdrService.Start(self: SaveSlotCmdrService)
48
102
  self._maid:GivePromise(self._cmdrService:PromiseCmdr()):Then(function(cmdr)
49
103
  SaveSlotCmdrUtils.registerSlotIndexType(cmdr, self._saveSlotDataService)
@@ -51,83 +105,95 @@ function SaveSlotCmdrService.Start(self: SaveSlotCmdrService)
51
105
  end)
52
106
  end
53
107
 
108
+ -- Shared across every command, so the "which player" argument reads the same everywhere.
109
+ local PLAYERS_ARG_DESCRIPTION =
110
+ "Players to act on (e.g. . for yourself, * for everyone here, a username, or #userId). A player who is not in this server is acted on offline, which kicks them."
111
+
112
+ -- Tail on every description, because Cmdr's help list is where an admin reads about a command before
113
+ -- running it -- the class docstring above is not, and neither is the argument description, which only
114
+ -- surfaces once they are already typing the command out.
115
+ local REMOTE_NOTE = "Works remotely and on players in-game; a player reached remotely is kicked."
116
+
54
117
  function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
55
118
  self._cmdrService:RegisterCommand({
56
- Name = "list-save-slots",
57
- Description = "Lists all save slots.",
119
+ Name = "saveslot-list",
120
+ Description = `Lists each player's save slots with their playtime, timestamps and summary, marking the one being played. {REMOTE_NOTE}`,
58
121
  Group = "SaveSlots",
59
122
  Args = {
60
123
  {
61
124
  Name = "Players",
62
- Type = "players",
63
- Description = "Players to list slots for (e.g. . for yourself, or * for everyone).",
125
+ Type = "playerIds",
126
+ Description = PLAYERS_ARG_DESCRIPTION,
64
127
  },
65
128
  },
66
- }, function(_context, players: { Player })
67
- local listString = ""
68
-
69
- for _, player in players do
70
- local activeSlotId = self._saveSlotDataService:GetActiveSlotId(player)
71
- local slotList = self._saveSlotDataService:GetSlotList(player)
72
-
73
- listString ..= `\n{player.Name}:\n`
74
- if #slotList == 0 then
75
- listString ..= "No slots.\n"
76
- end
77
-
78
- for _, slot in slotList do
79
- local isActive = (slot.SlotId == activeSlotId)
80
- listString ..= `\n"{slot.SlotName}" ({slot.SlotIndex}){isActive and " — Active" or ""}\n{slot.Summary}\n`
129
+ }, function(context: CommandContext, userIds: { number })
130
+ return self:_runLines(context, userIds, function(slots, name)
131
+ local activeSlotId = slots:GetActiveSlotId()
132
+
133
+ local blocks = {}
134
+ for _, metadata in slots:GetSlotList() do
135
+ local status = if metadata.SlotId == activeSlotId then "Active" else nil
136
+ table.insert(blocks, SaveSlotCmdrUtils.formatSlotBlock(metadata, status))
81
137
  end
82
138
 
83
139
  -- An ephemeral session is not a save, so it is absent from the slot list above -- but it is what
84
- -- the player is playing right now and the thing persist-save-slot acts on, so list it under the
140
+ -- the player is playing right now and the thing saveslot-persist acts on, so list it under the
85
141
  -- reserved index the other commands address it by.
86
- if self._saveSlotDataService:IsActiveSlotEphemeral(player) then
87
- local metadata = self._saveSlotDataService:GetActiveSlotMetadata(player)
88
- listString ..= `\n"{metadata.SlotName}" ({metadata.SlotIndex}) — Active, ephemeral\n{metadata.Summary}\n`
142
+ if slots:IsActiveSlotEphemeral() then
143
+ table.insert(
144
+ blocks,
145
+ SaveSlotCmdrUtils.formatSlotBlock(slots:GetActiveSlotMetadata(), "Active, ephemeral")
146
+ )
147
+ end
148
+
149
+ if #blocks == 0 then
150
+ return `\n{name}:\nNo slots.`
89
151
  end
90
- end
91
152
 
92
- return listString
153
+ return `\n{name}:\n\n{table.concat(blocks, "\n\n")}`
154
+ end)
93
155
  end)
94
156
 
95
157
  self._cmdrService:RegisterCommand({
96
- Name = "get-active-save-slot",
97
- Description = "Returns the active save slot.",
158
+ Name = "saveslot-get-active",
159
+ Description = `Reports the slot each player is playing, or the one they would resume on when none is active. {REMOTE_NOTE}`,
98
160
  Group = "SaveSlots",
99
161
  Args = {
100
162
  {
101
163
  Name = "Players",
102
- Type = "players",
103
- Description = "Players to query (e.g. . for yourself, or * for everyone).",
164
+ Type = "playerIds",
165
+ Description = PLAYERS_ARG_DESCRIPTION,
104
166
  },
105
167
  },
106
- }, function(_context, players: { Player })
107
- local lines = {}
108
-
109
- for _, player in players do
110
- local activeSlotId = self._saveSlotDataService:GetActiveSlotId(player)
168
+ }, function(context: CommandContext, userIds: { number })
169
+ return self:_runLines(context, userIds, function(slots, name)
170
+ local activeSlotId = slots:GetActiveSlotId()
111
171
  if activeSlotId then
112
- local slotData = self._saveSlotDataService:GetSlotMetadata(player, activeSlotId)
113
- table.insert(lines, `{player.Name} is using slot {slotData.SlotIndex} ("{slotData.SlotName}").`)
114
- else
115
- table.insert(lines, `{player.Name} has no active slot.`)
172
+ local slotData = slots:GetSlotMetadata(activeSlotId)
173
+ return `{name} is using slot {slotData.SlotIndex} ("{slotData.SlotName}").`
174
+ end
175
+
176
+ -- Nobody is playing an offline session, so report what they would resume on instead of
177
+ -- flatly saying there is no slot.
178
+ local lastSlotId = slots:GetLastActiveSlotId()
179
+ local lastMetadata = if lastSlotId then slots:GetSlotMetadata(lastSlotId) else nil
180
+ if lastMetadata then
181
+ return `{name} has no active slot; would resume on slot {lastMetadata.SlotIndex} ("{lastMetadata.SlotName}").`
116
182
  end
117
- end
118
183
 
119
- return table.concat(lines, "\n")
184
+ return `{name} has no active slot.`
185
+ end)
120
186
  end)
121
187
 
122
188
  self._cmdrService:RegisterCommand({
123
- Name = "set-save-slot",
124
- Description = "Switches to the given save slot.",
189
+ Name = "saveslot-select",
190
+ Description = `Switches each player onto the given save slot, saving the slot they were on first. {REMOTE_NOTE}`,
125
191
  Group = "SaveSlots",
126
192
  Args = {
127
193
  {
128
194
  Name = "Players",
129
- Type = "players",
130
- Description = "Players to switch (e.g. . for yourself, or * for everyone).",
195
+ Type = "playerIds",
196
+ Description = PLAYERS_ARG_DESCRIPTION,
131
197
  },
132
198
  {
133
199
  Name = "Slot",
@@ -135,59 +201,55 @@ function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
135
201
  Description = "Slot index to switch to, or . for your current slot.",
136
202
  },
137
203
  },
138
- }, function(_context, players: { Player }, slotIndex: number)
139
- local lines = self:_promisePlayerLines(players, function(hasSaveSlots, player)
140
- local slotId = self:_getSlotIdFromIndex(player, slotIndex)
204
+ }, function(context: CommandContext, userIds: { number }, slotIndex: number)
205
+ return self:_runLines(context, userIds, function(slots, name)
206
+ local slotId = self:_getSlotIdFromIndex(slots, slotIndex)
141
207
  if not slotId then
142
- return `{player.Name} has no slot with index {slotIndex}.`
208
+ return `{name} has no slot with index {slotIndex}.`
143
209
  end
144
210
 
145
- if slotId == self._saveSlotDataService:GetActiveSlotId(player) then
146
- return `{player.Name} already has slot {slotIndex} active.`
211
+ if slotId == slots:GetActiveSlotId() then
212
+ return `{name} already has slot {slotIndex} active.`
147
213
  end
148
214
 
149
- return hasSaveSlots:PromiseSelectSlot(slotId):Then(function()
150
- return `{player.Name} switched to slot {slotIndex}.`
215
+ return slots:PromiseSelectSlot(slotId):Then(function()
216
+ return `{name} switched to slot {slotIndex}.`
151
217
  end)
152
- end):Wait()
153
-
154
- return table.concat(lines, "\n")
218
+ end)
155
219
  end)
156
220
 
157
221
  self._cmdrService:RegisterCommand({
158
- Name = "deselect-save-slot",
159
- Description = "Clears the active save slot, returning to a no-slot state.",
222
+ Name = "saveslot-deselect",
223
+ Description = `Returns each player to the no-slot state, saving their active slot first and remembering it as the one they would resume on. {REMOTE_NOTE}`,
160
224
  Group = "SaveSlots",
161
225
  Args = {
162
226
  {
163
227
  Name = "Players",
164
- Type = "players",
165
- Description = "Players to deselect (e.g. . for yourself, or * for everyone).",
228
+ Type = "playerIds",
229
+ Description = PLAYERS_ARG_DESCRIPTION,
166
230
  },
167
231
  },
168
- }, function(_context, players: { Player })
169
- local lines = self:_promisePlayerLines(players, function(hasSaveSlots, player)
170
- if not self._saveSlotDataService:GetActiveSlotId(player) then
171
- return `{player.Name} has no active slot.`
232
+ }, function(context: CommandContext, userIds: { number })
233
+ return self:_runLines(context, userIds, function(slots, name)
234
+ if not slots:GetActiveSlotId() then
235
+ return `{name} has no active slot.`
172
236
  end
173
237
 
174
- return hasSaveSlots:PromiseDeselectSlot():Then(function()
175
- return `{player.Name} deselected active slot.`
238
+ return slots:PromiseDeselectSlot():Then(function()
239
+ return `{name} deselected active slot.`
176
240
  end)
177
- end):Wait()
178
-
179
- return table.concat(lines, "\n")
241
+ end)
180
242
  end)
181
243
 
182
244
  self._cmdrService:RegisterCommand({
183
- Name = "create-save-slot",
184
- Description = "Creates save slots. Defaults to the lowest free index when none is given.",
245
+ Name = "saveslot-create",
246
+ Description = `Creates empty save slots, defaulting to the lowest free index when none is given. Creates nothing at all when any index in the batch is taken or past the player's slot cap. {REMOTE_NOTE}`,
185
247
  Group = "SaveSlots",
186
248
  Args = {
187
249
  {
188
250
  Name = "Players",
189
- Type = "players",
190
- Description = "Players to create slots for (e.g. . for yourself, or * for everyone).",
251
+ Type = "playerIds",
252
+ Description = PLAYERS_ARG_DESCRIPTION,
191
253
  },
192
254
  {
193
255
  Name = "Slots",
@@ -196,16 +258,16 @@ function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
196
258
  Optional = true,
197
259
  },
198
260
  },
199
- }, function(_context, players: { Player }, slotIndices: { number }?)
200
- local lines = self:_promisePlayerLines(players, function(hasSaveSlots, player)
261
+ }, function(context: CommandContext, userIds: { number }, slotIndices: { number }?)
262
+ return self:_runLines(context, userIds, function(slots, name)
201
263
  -- The cap is per-player, so it has to come off each target rather than the executor, whose
202
- -- cap may be larger. Read from the binder rather than the mirrored attribute, since that is
203
- -- what PromiseCreateSlot itself validates against.
204
- local maxSlotCount = hasSaveSlots.MaxSlotCount.Value
264
+ -- cap may be larger. Read from the slot system rather than a mirrored attribute, since that
265
+ -- is what PromiseCreateSlot itself validates against.
266
+ local maxSlotCount = slots.MaxSlotCount.Value
205
267
 
206
268
  -- Track indices already taken so a batch fills gaps and never collides within itself.
207
269
  local used = {}
208
- for _, metadata in self._saveSlotDataService:GetSlotList(player) do
270
+ for _, metadata in slots:GetSlotList() do
209
271
  used[metadata.SlotIndex] = true
210
272
  end
211
273
 
@@ -218,7 +280,7 @@ function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
218
280
  end
219
281
 
220
282
  if freeIndex > maxSlotCount then
221
- return `{player.Name}: all slots are already in use.`
283
+ return `{name}: all slots are already in use.`
222
284
  end
223
285
 
224
286
  table.insert(toCreate, freeIndex)
@@ -227,10 +289,10 @@ function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
227
289
  local seen = {}
228
290
  for _, slotIndex in slotIndices do
229
291
  if (slotIndex < 1) or (slotIndex > maxSlotCount) then
230
- return `{player.Name}: index must be in range [1, {maxSlotCount}].`
292
+ return `{name}: index must be in range [1, {maxSlotCount}].`
231
293
  end
232
294
  if used[slotIndex] then
233
- return `{player.Name}: slot {slotIndex} already exists.`
295
+ return `{name}: slot {slotIndex} already exists.`
234
296
  end
235
297
  if not seen[slotIndex] then
236
298
  seen[slotIndex] = true
@@ -243,27 +305,25 @@ function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
243
305
  local promise = Promise.resolved()
244
306
  for _, slotIndex in toCreate do
245
307
  promise = promise:Then(function()
246
- return hasSaveSlots:PromiseCreateSlot(slotIndex)
308
+ return slots:PromiseCreateSlot(slotIndex)
247
309
  end)
248
310
  end
249
311
 
250
312
  return promise:Then(function()
251
- return `{player.Name} created slot(s) {table.concat(toCreate, ", ")}.`
313
+ return `{name} created slot(s) {table.concat(toCreate, ", ")}.`
252
314
  end)
253
- end):Wait()
254
-
255
- return table.concat(lines, "\n")
315
+ end)
256
316
  end)
257
317
 
258
318
  self._cmdrService:RegisterCommand({
259
- Name = "delete-save-slot",
260
- Description = "Deletes the given save slots.",
319
+ Name = "saveslot-delete",
320
+ Description = `Permanently deletes the given save slots. Deleting the slot a player is on deselects it first; deleting their ephemeral session ends it. {REMOTE_NOTE}`,
261
321
  Group = "SaveSlots",
262
322
  Args = {
263
323
  {
264
324
  Name = "Players",
265
- Type = "players",
266
- Description = "Players to delete slots for (e.g. . for yourself, or * for everyone).",
325
+ Type = "playerIds",
326
+ Description = PLAYERS_ARG_DESCRIPTION,
267
327
  },
268
328
  {
269
329
  Name = "Slots",
@@ -271,213 +331,289 @@ function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
271
331
  Description = "Slot indices to delete (e.g. 1,2, . for your current slot, or * for all).",
272
332
  },
273
333
  },
274
- }, function(_context, players: { Player }, slotIndices: { number })
275
- local targets = self:_resolveTargets(players, slotIndices)
276
- if #targets == 0 then
277
- return "No matching slots to delete."
278
- end
334
+ }, function(context: CommandContext, userIds: { number }, slotIndices: { number })
335
+ return self:_runSlotLines(context, userIds, slotIndices, function(slots, entry, name)
336
+ return self:_promiseClearSlot(slots, entry.slotId):Then(function()
337
+ return `{name} deleted slot {entry.slotIndex}.`
338
+ end)
339
+ end)
340
+ end)
341
+
342
+ self._cmdrService:RegisterCommand(
343
+ {
344
+ Name = "saveslot-copy",
345
+ Description = "Copies one player's save slot onto other players' slots, OVERWRITING an occupied destination and defaulting to the lowest free index. Copying an ephemeral session saves it without switching onto the copy -- see saveslot-persist. Works remotely and on players in-game; every player reached remotely is kicked, the source as readily as a destination.",
346
+ Group = "SaveSlots",
347
+ Args = {
348
+ {
349
+ Name = "FromPlayer",
350
+ Type = "playerId",
351
+ Description = "Player to copy from (e.g. . for yourself, a username, or #userId). A player who is not in this server is read offline, which kicks them.",
352
+ },
353
+ {
354
+ Name = "FromSlot",
355
+ Type = "slotIndex",
356
+ Description = "Slot index to copy from, or . for your current slot.",
357
+ },
358
+ {
359
+ Name = "ToPlayers",
360
+ Type = "playerIds",
361
+ Description = PLAYERS_ARG_DESCRIPTION,
362
+ },
363
+ {
364
+ Name = "ToSlot",
365
+ Type = "slotIndex",
366
+ Description = "Slot index to copy onto. Omit for the lowest free index. An existing slot there is deleted first.",
367
+ Optional = true,
368
+ },
369
+ },
370
+ },
371
+ function(
372
+ context: CommandContext,
373
+ fromUserId: number,
374
+ fromSlotIndex: number,
375
+ toUserIds: { number },
376
+ toSlotIndex: number?
377
+ )
378
+ -- Rejected once for the whole command rather than per target, since neither destination depends
379
+ -- on who is being written to. An ephemeral session exists only while it is active, so it can be
380
+ -- a source (that is how a session becomes a save) but never a destination. The main slot is
381
+ -- refused because its store is the player's shared root: an import there would land on top of
382
+ -- their universe-wide data (see HasSaveSlotsDataStore.PromiseImportSlot).
383
+ if toSlotIndex == SaveSlotConstants.EPHEMERAL_SLOT_INDEX then
384
+ return "An ephemeral session cannot be copied onto."
385
+ elseif toSlotIndex == SaveSlotConstants.DEFAULT_SLOT_INDEX then
386
+ return `The main slot ({SaveSlotConstants.DEFAULT_SLOT_INDEX}) cannot be copied onto.`
387
+ end
388
+
389
+ -- Read the source once, up front, and give its session back before any destination is opened:
390
+ -- the source player may also be a destination, and a second session on the same player would be
391
+ -- racing the first for their own lock. Mirrors datastore-copy.
392
+ local readPromise = self:_promiseWithSlots(fromUserId, function(slots, name)
393
+ local sourceSlotId = self:_getSlotIdFromIndex(slots, fromSlotIndex)
394
+ if not sourceSlotId then
395
+ return Promise.rejected(`{name} has no slot with index {fromSlotIndex}`)
396
+ end
397
+
398
+ -- Admin tooling copies the main slot too, which the normal path refuses. See
399
+ -- HasSaveSlotsDataStore.PromiseExportSlot for what that carries.
400
+ return slots:PromiseExportSlot(sourceSlotId, true):Then(function(export)
401
+ return { export = export, slotId = sourceSlotId, name = name }
402
+ end)
403
+ end)
279
404
 
280
- local lines = self
281
- :_promiseSlotLines(targets, function(hasSaveSlots, entry, player)
282
- -- The active slot can't be deleted while selected, so deselect it first (flushing its
283
- -- progress) when reached. Read live rather than up front, since an earlier deletion in
284
- -- this batch may have already deselected it. An ephemeral session is left alone:
285
- -- PromiseDeleteSlot retires it itself, and deselecting first would retire it early,
286
- -- leaving nothing behind to delete.
287
- local isActive = (entry.slotId == self._saveSlotDataService:GetActiveSlotId(player))
288
- local deselect = if isActive and not self._saveSlotDataService:IsActiveSlotEphemeral(player)
289
- then hasSaveSlots:PromiseDeselectSlot()
405
+ local ok, source = CmdrReplyUtils.replyWhenSlow(
406
+ self._replyConfig,
407
+ context,
408
+ self._maid:GivePromise(readPromise),
409
+ `{fromUserId}: still reading...`
410
+ ):Yield()
411
+ if not ok then
412
+ return `Failed to read {fromUserId}: {tostring(source)}`
413
+ end
414
+
415
+ return self:_runLines(context, toUserIds, function(slots, name, userId)
416
+ local existingSlotId = if toSlotIndex then slots:GetSlotIdFromIndex(toSlotIndex) else nil
417
+ if (userId == fromUserId) and (existingSlotId == source.slotId) then
418
+ return `{name}: slot {fromSlotIndex} is both the source and the destination.`
419
+ end
420
+
421
+ -- Within one roster the copy would otherwise sit beside the original under its name, so it
422
+ -- is suffixed the way a duplicate always was. Across players it keeps the name it had.
423
+ local export = source.export
424
+ if (userId == fromUserId) and export.slotName then
425
+ export = table.clone(export)
426
+ export.slotName = `{export.slotName} (Copy)`
427
+ end
428
+
429
+ local clear = if existingSlotId
430
+ then self:_promiseClearSlot(slots, existingSlotId)
290
431
  else Promise.resolved()
291
432
 
292
- return deselect
433
+ return clear
293
434
  :Then(function()
294
- return hasSaveSlots:PromiseDeleteSlot(entry.slotId)
435
+ return slots:PromiseImportSlot(export, toSlotIndex)
295
436
  end)
296
- :Then(function()
297
- return `{player.Name} deleted slot {entry.slotIndex}.`
437
+ :Then(function(newSlotId)
438
+ local newMetadata = slots:GetSlotMetadata(newSlotId)
439
+ local overwrote = if existingSlotId then ", overwriting what was there" else ""
440
+ return `Copied {source.name} slot {fromSlotIndex} → {name} slot {newMetadata.SlotIndex} ("{newMetadata.SlotName}"){overwrote}`
298
441
  end)
299
442
  end)
300
- :Wait()
301
-
302
- return `Deleted:\n{table.concat(lines, "\n")}`
303
- end)
443
+ end
444
+ )
304
445
 
305
446
  self._cmdrService:RegisterCommand({
306
- Name = "duplicate-save-slot",
307
- Description = "Duplicates save slots into new slots at the lowest free indices. Duplicating an ephemeral session saves it without switching onto the copy -- see persist-save-slot.",
447
+ Name = "saveslot-persist",
448
+ Description = "Turns each player's ephemeral session into a real save slot at their lowest free index and switches them onto it. Only a player in this server has a session to persist, so this can do nothing for a remote player except kick them to find that out.",
308
449
  Group = "SaveSlots",
309
450
  Args = {
310
451
  {
311
452
  Name = "Players",
312
- Type = "players",
313
- Description = "Players to duplicate slots for (e.g. . for yourself, or * for everyone).",
314
- },
315
- {
316
- Name = "Slots",
317
- Type = "slotIndices",
318
- Description = "Slot indices to duplicate (e.g. 1,2, . for your current slot, or * for all).",
453
+ Type = "playerIds",
454
+ Description = PLAYERS_ARG_DESCRIPTION,
319
455
  },
320
456
  },
321
- }, function(_context, players: { Player }, slotIndices: { number })
322
- local targets = self:_resolveTargets(players, slotIndices)
323
- if #targets == 0 then
324
- return "No matching slots to duplicate."
325
- end
457
+ }, function(context: CommandContext, userIds: { number })
458
+ -- Takes no slot argument: an ephemeral slot exists only while it is active, so the active slot is
459
+ -- the only one there is to persist. An absent player has no session at all, so this only ever
460
+ -- reports on them.
461
+ return self:_runLines(context, userIds, function(slots, name)
462
+ if not slots:IsActiveSlotEphemeral() then
463
+ return `{name} has no ephemeral session active.`
464
+ end
326
465
 
327
- -- Each copy consumes a free index the next one must see, which the sequential walk guarantees.
328
- local lines = self
329
- :_promiseSlotLines(targets, function(hasSaveSlots, entry, player)
330
- return hasSaveSlots:PromiseDuplicateSlot(entry.slotId):Then(function(newSlotId)
331
- local newMetadata = self._saveSlotDataService:GetSlotMetadata(player, newSlotId)
332
- return `{player.Name} slot {entry.slotIndex} → slot {newMetadata.SlotIndex} ("{newMetadata.SlotName}")`
333
- end)
466
+ return slots:PromisePersistEphemeralSlot():Then(function(newSlotId)
467
+ local metadata = slots:GetSlotMetadata(newSlotId)
468
+ return `{name} persisted their session to slot {metadata.SlotIndex} ("{metadata.SlotName}").`
334
469
  end)
335
- :Wait()
336
-
337
- return `Duplicated:\n{table.concat(lines, "\n")}`
470
+ end)
338
471
  end)
339
472
 
340
473
  self._cmdrService:RegisterCommand({
341
- Name = "persist-save-slot",
342
- Description = "Turns an ephemeral session into a real save slot and switches onto it.",
474
+ Name = "saveslot-reset",
475
+ Description = `Empties save slots, keeping their index and name but permanently clearing their saved data and timestamps. Resetting the slot a player is on rebuilds it under them. {REMOTE_NOTE}`,
343
476
  Group = "SaveSlots",
344
477
  Args = {
345
478
  {
346
479
  Name = "Players",
347
- Type = "players",
348
- Description = "Players to persist the session of (e.g. . for yourself, or * for everyone).",
480
+ Type = "playerIds",
481
+ Description = PLAYERS_ARG_DESCRIPTION,
482
+ },
483
+ {
484
+ -- Required rather than defaulting to the active slot: with Players ahead of it, an
485
+ -- optional Slots would leave `saveslot-reset *` as valid syntax that wipes the active
486
+ -- slot of every player in the server.
487
+ Name = "Slots",
488
+ Type = "slotIndices",
489
+ Description = "Slot indices to reset (e.g. 1,2, . for your current slot, or * for all).",
349
490
  },
350
491
  },
351
- }, function(_context, players: { Player })
352
- -- Takes no slot argument: an ephemeral slot exists only while it is active, so the active slot is
353
- -- the only one there is to persist.
354
- local lines = self
355
- :_promisePlayerLines(players, function(hasSaveSlots, player)
356
- if not self._saveSlotDataService:IsActiveSlotEphemeral(player) then
357
- return `{player.Name} has no ephemeral session active.`
358
- end
359
-
360
- return hasSaveSlots:PromisePersistEphemeralSlot():Then(function(newSlotId)
361
- local metadata = self._saveSlotDataService:GetSlotMetadata(player, newSlotId)
362
- return `{player.Name} persisted their session to slot {metadata.SlotIndex} ("{metadata.SlotName}").`
363
- end)
492
+ }, function(context: CommandContext, userIds: { number }, slotIndices: { number })
493
+ return self:_runSlotLines(context, userIds, slotIndices, function(slots, entry, name)
494
+ return slots:PromiseResetSlot(entry.slotId):Then(function()
495
+ return `{name} reset slot {entry.slotIndex}.`
364
496
  end)
365
- :Wait()
366
-
367
- return table.concat(lines, "\n")
497
+ end)
368
498
  end)
369
499
 
370
500
  self._cmdrService:RegisterCommand({
371
- Name = "reset-save-slot",
372
- Description = "Resets save slots to fresh empty ones, keeping their index and name.",
501
+ Name = "saveslot-export",
502
+ Description = `Copies save slots into the shared store and prints a code for each, to be redeemed with saveslot-import. Reads only; the slot itself is left alone. {REMOTE_NOTE}`,
373
503
  Group = "SaveSlots",
374
504
  Args = {
375
505
  {
376
506
  Name = "Players",
377
- Type = "players",
378
- Description = "Players to reset slots for (e.g. . for yourself, or * for everyone).",
507
+ Type = "playerIds",
508
+ Description = PLAYERS_ARG_DESCRIPTION,
379
509
  },
380
510
  {
381
- -- Required rather than defaulting to the active slot: with Players ahead of it, an
382
- -- optional Slots would leave `reset-save-slot *` as valid syntax that wipes the active
383
- -- slot of every player in the server.
384
511
  Name = "Slots",
385
512
  Type = "slotIndices",
386
- Description = "Slot indices to reset (e.g. 1,2, . for your current slot, or * for all).",
513
+ Description = "Slot indices to export (e.g. 1,2, . for your current slot, or * for all). Omit for each player's current slot.",
514
+ Optional = true,
387
515
  },
388
516
  },
389
- }, function(_context, players: { Player }, slotIndices: { number })
390
- local targets = self:_resolveTargets(players, slotIndices)
391
- if #targets == 0 then
392
- return "No matching slots to reset."
393
- end
394
-
395
- local lines = self:_promiseSlotLines(targets, function(hasSaveSlots, entry, player)
396
- return hasSaveSlots:PromiseResetSlot(entry.slotId):Then(function()
397
- return `{player.Name} reset slot {entry.slotIndex}.`
517
+ }, function(context: CommandContext, userIds: { number }, slotIndices: { number }?)
518
+ -- Admin tooling exports the main slot too, which the normal path refuses. See
519
+ -- HasSaveSlotsDataStore.PromiseExportSlot for what that carries.
520
+ return self:_runSlotLines(context, userIds, slotIndices, function(slots, entry, name)
521
+ return slots:PromiseExportSaveSlotToCode(entry.slotId, true):Then(function(code)
522
+ return `{name} slot {entry.slotIndex} → {code}`
398
523
  end)
399
- end):Wait()
400
-
401
- return `Reset:\n{table.concat(lines, "\n")}`
524
+ end)
402
525
  end)
403
526
 
404
527
  self._cmdrService:RegisterCommand({
405
- Name = "export-save-slot",
406
- Description = "Exports save slots to the shared store and prints their codes.",
528
+ Name = "saveslot-read-json",
529
+ Description = `Prints save slots as raw JSON, writing nothing to the shared store. Pairs with saveslot-write-json. {REMOTE_NOTE}`,
407
530
  Group = "SaveSlots",
408
531
  Args = {
409
532
  {
410
533
  Name = "Players",
411
- Type = "players",
412
- Description = "Players to export from (e.g. . for yourself, or * for everyone).",
534
+ Type = "playerIds",
535
+ Description = PLAYERS_ARG_DESCRIPTION,
413
536
  },
414
537
  {
415
538
  Name = "Slots",
416
539
  Type = "slotIndices",
417
- Description = "Slot indices to export (e.g. 1,2, . for your current slot, or * for all). Omit for each player's active slot.",
540
+ Description = "Slot indices to read (e.g. 1,2, . for your current slot, or * for all). Omit for each player's current slot.",
418
541
  Optional = true,
419
542
  },
420
543
  },
421
- }, function(_context, players: { Player }, slotIndices: { number }?)
422
- local targets = self:_resolveTargets(players, slotIndices)
423
- if #targets == 0 then
424
- return "No matching slots to export."
425
- end
426
-
427
- -- Admin tooling exports the main slot too, which the normal path refuses. See
428
- -- HasSaveSlots.PromiseExportSlot for what that carries.
429
- local lines = self:_promiseSlotLines(targets, function(hasSaveSlots, entry, player)
430
- return hasSaveSlots:PromiseExportSaveSlotToCode(entry.slotId, true):Then(function(code)
431
- return `{player.Name} slot {entry.slotIndex} → {code}`
544
+ }, function(context: CommandContext, userIds: { number }, slotIndices: { number }?)
545
+ -- Admin tooling reads the main slot too, which the normal path refuses. See
546
+ -- HasSaveSlotsDataStore.PromiseExportSlot for what that carries.
547
+ return self:_runSlotLines(context, userIds, slotIndices, function(slots, entry, name)
548
+ return slots:PromiseExportSaveSlotToJson(entry.slotId, true):Then(function(json)
549
+ return `-- {name} slot {entry.slotIndex}\n{json}`
432
550
  end)
433
- end):Wait()
434
-
435
- return `Exported:\n{table.concat(lines, "\n")}`
551
+ end)
436
552
  end)
437
553
 
438
554
  self._cmdrService:RegisterCommand({
439
- Name = "export-save-slot-json",
440
- Description = "Exports save slots as raw JSON (no shared store) and prints them.",
555
+ Name = "saveslot-write-json",
556
+ Description = `Writes raw JSON, as printed by saveslot-read-json, into a save slot. OVERWRITES an occupied destination and defaults to the lowest free index. {REMOTE_NOTE}`,
441
557
  Group = "SaveSlots",
442
558
  Args = {
443
559
  {
444
560
  Name = "Players",
445
- Type = "players",
446
- Description = "Players to export from (e.g. . for yourself, or * for everyone).",
561
+ Type = "playerIds",
562
+ Description = PLAYERS_ARG_DESCRIPTION,
447
563
  },
564
+ -- Ahead of the optional slot, since Cmdr can only leave trailing arguments off.
448
565
  {
449
- Name = "Slots",
450
- Type = "slotIndices",
451
- Description = "Slot indices to export (e.g. 1,2, . for your current slot, or * for all). Omit for each player's active slot.",
566
+ Name = "Json",
567
+ Type = "string",
568
+ Description = "Save slot JSON to write.",
569
+ },
570
+ {
571
+ Name = "ToSlot",
572
+ Type = "slotIndex",
573
+ Description = "Slot index to write onto. Omit for the lowest free index. An existing slot there is deleted first.",
452
574
  Optional = true,
453
575
  },
454
576
  },
455
- }, function(_context, players: { Player }, slotIndices: { number }?)
456
- local targets = self:_resolveTargets(players, slotIndices)
457
- if #targets == 0 then
458
- return "No matching slots to export."
577
+ }, function(context: CommandContext, userIds: { number }, json: string, toSlotIndex: number?)
578
+ -- Decoded once, up front: a malformed argument is the whole command's problem, not something to
579
+ -- discover separately against each target after stealing their session.
580
+ local ok, export = pcall(HttpService.JSONDecode, HttpService, json)
581
+ if not ok then
582
+ return `Failed: could not decode JSON: {tostring(export)}`
459
583
  end
460
584
 
461
- -- Admin tooling exports the main slot too, which the normal path refuses. See
462
- -- HasSaveSlots.PromiseExportSlot for what that carries.
463
- local blocks = self:_promiseSlotLines(targets, function(hasSaveSlots, entry, player)
464
- return hasSaveSlots:PromiseExportSaveSlotToJson(entry.slotId, true):Then(function(json)
465
- return `-- {player.Name} slot {entry.slotIndex}\n{json}`
466
- end)
467
- end):Wait()
585
+ -- Refused for the same reasons saveslot-copy refuses them, and likewise once for the whole command.
586
+ if toSlotIndex == SaveSlotConstants.EPHEMERAL_SLOT_INDEX then
587
+ return "An ephemeral session cannot be written onto."
588
+ elseif toSlotIndex == SaveSlotConstants.DEFAULT_SLOT_INDEX then
589
+ return `The main slot ({SaveSlotConstants.DEFAULT_SLOT_INDEX}) cannot be written onto.`
590
+ end
468
591
 
469
- return table.concat(blocks, "\n\n")
592
+ return self:_runLines(context, userIds, function(slots, name)
593
+ local existingSlotId = if toSlotIndex then slots:GetSlotIdFromIndex(toSlotIndex) else nil
594
+ local clear = if existingSlotId then self:_promiseClearSlot(slots, existingSlotId) else Promise.resolved()
595
+
596
+ return clear
597
+ :Then(function()
598
+ return slots:PromiseImportSlot(export, toSlotIndex)
599
+ end)
600
+ :Then(function(newSlotId)
601
+ local metadata = slots:GetSlotMetadata(newSlotId)
602
+ local overwrote = if existingSlotId then ", overwriting what was there" else ""
603
+ return `{name} wrote JSON → slot {metadata.SlotIndex} ("{metadata.SlotName}"){overwrote}`
604
+ end)
605
+ end)
470
606
  end)
471
607
 
472
608
  self._cmdrService:RegisterCommand({
473
- Name = "import-save-slot",
474
- Description = "Imports a save slot code into a new persisted (non-main) slot.",
609
+ Name = "saveslot-import",
610
+ Description = `Redeems a saveslot-export code into a new slot at the player's lowest free index, leaving their existing slots alone. {REMOTE_NOTE}`,
475
611
  Group = "SaveSlots",
476
612
  Args = {
477
613
  {
478
614
  Name = "Player",
479
- Type = "player",
480
- Description = "Player to import into (e.g. . for yourself).",
615
+ Type = "playerId",
616
+ Description = "Player to import into (e.g. . for yourself, a username, or #userId). A player who is not in this server is imported into offline, which kicks them.",
481
617
  },
482
618
  {
483
619
  Name = "Code",
@@ -485,31 +621,24 @@ function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
485
621
  Description = "The code to import.",
486
622
  },
487
623
  },
488
- }, function(_context, player: Player, code: string)
489
- return self._maid
490
- :GivePromise(self._hasSaveSlotsBinder:Promise(player))
491
- :Then(function(hasSaveSlots)
492
- return hasSaveSlots:PromiseImportSlotFromSharedDataStore(code)
493
- end)
494
- :Then(function(newSlotId)
495
- local metadata = self._saveSlotDataService:GetSlotMetadata(player, newSlotId)
496
- return `Imported save slot from code into {player.Name} slot {metadata.SlotIndex} ("{metadata.SlotName}").`
624
+ }, function(context: CommandContext, userId: number, code: string)
625
+ return self:_runLines(context, { userId }, function(slots, name)
626
+ return slots:PromiseImportSlotFromSharedDataStore(code):Then(function(newSlotId)
627
+ local metadata = slots:GetSlotMetadata(newSlotId)
628
+ return `Imported save slot from code into {name} slot {metadata.SlotIndex} ("{metadata.SlotName}").`
497
629
  end)
498
- :Catch(function(err)
499
- return `Import failed: {tostring(err)}`
500
- end)
501
- :Wait()
630
+ end)
502
631
  end)
503
632
 
504
633
  self._cmdrService:RegisterCommand({
505
- Name = "import-ephemeral-save-slot",
506
- Description = "Imports a save slot code into a throwaway ephemeral slot and selects it.",
634
+ Name = "saveslot-import-ephemeral",
635
+ Description = "Loads a saveslot-export code into a throwaway session and switches the player onto it, saving nothing and touching none of their slots. The one command that cannot work remotely, and so the one that never kicks: an ephemeral session only exists while it is being played.",
507
636
  Group = "SaveSlots",
508
637
  Args = {
509
638
  {
510
639
  Name = "Player",
511
- Type = "player",
512
- Description = "Player to import into (e.g. . for yourself).",
640
+ Type = "playerId",
641
+ Description = "Player to import into (e.g. . for yourself, a username, or #userId). Must be in this server.",
513
642
  },
514
643
  {
515
644
  Name = "Code",
@@ -517,55 +646,90 @@ function SaveSlotCmdrService._registerCommands(self: SaveSlotCmdrService): ()
517
646
  Description = "The code to load.",
518
647
  },
519
648
  },
520
- }, function(_context, player: Player, code: string)
521
- return self._maid
522
- :GivePromise(self._hasSaveSlotsBinder:Promise(player))
523
- :Then(function(hasSaveSlots)
524
- return hasSaveSlots:PromiseImportEphemeralSaveSlotFromCode(code)
525
- end)
526
- :Then(function()
527
- return `Imported ephemeral save slot into {player.Name} from code: {code}`
528
- end)
529
- :Catch(function(err)
530
- return `Load failed: {tostring(err)}`
649
+ }, function(context: CommandContext, userId: number, code: string)
650
+ -- The one command with no offline meaning: an ephemeral slot exists only for the duration of a
651
+ -- live session, so importing one for an absent player would create it and immediately discard it.
652
+ local player = Players:GetPlayerByUserId(userId)
653
+ if not player then
654
+ return `{userId} is not in this server, and an ephemeral slot needs a live session.`
655
+ end
656
+
657
+ return self:_runLines(context, { userId }, function(slots, name)
658
+ return slots:PromiseImportEphemeralSaveSlotFromCode(code):Then(function()
659
+ return `Imported ephemeral save slot into {name} from code: {code}`
531
660
  end)
532
- :Wait()
661
+ end)
533
662
  end)
534
663
  end
535
664
 
536
- -- Resolves a slot index to the player's slot id, including the reserved ephemeral index (see
537
- -- [SaveSlotCmdrUtils]). The data service's index lookup only walks the save list, which an ephemeral slot
538
- -- is excluded from, so that one index resolves against the active slot instead.
539
- function SaveSlotCmdrService._getSlotIdFromIndex(self: SaveSlotCmdrService, player: Player, slotIndex: number): string?
665
+ -- SaveSlotService owns the offline entry point. Reached through the module instance rather than by
666
+ -- name, because `require("SaveSlotService")` from here is a cyclic module dependency: SaveSlotService
667
+ -- registers this service. Mirrors HasSaveSlots._promisePreSelectFromSaveSlotService.
668
+ function SaveSlotCmdrService._getSaveSlotService(self: SaveSlotCmdrService): any
669
+ local serviceModule = script.Parent.Parent:FindFirstChild("SaveSlotService")
670
+ if not serviceModule or not self._serviceBag:HasService(serviceModule) then
671
+ return nil
672
+ end
673
+
674
+ return self._serviceBag:GetService(serviceModule)
675
+ end
676
+
677
+ -- Resolves a slot index to the target's slot id, including the reserved ephemeral index (see
678
+ -- [SaveSlotCmdrUtils]). The index lookup only walks the save list, which an ephemeral slot is excluded
679
+ -- from, so that one index resolves against the active slot instead.
680
+ function SaveSlotCmdrService._getSlotIdFromIndex(_self: SaveSlotCmdrService, slots: any, slotIndex: number): string?
540
681
  if slotIndex == SaveSlotConstants.EPHEMERAL_SLOT_INDEX then
541
- if self._saveSlotDataService:IsActiveSlotEphemeral(player) then
542
- return self._saveSlotDataService:GetActiveSlotId(player)
682
+ if slots:IsActiveSlotEphemeral() then
683
+ return slots:GetActiveSlotId()
543
684
  end
544
685
  return nil
545
686
  end
546
687
 
547
- return self._saveSlotDataService:GetSlotIdFromIndex(player, slotIndex)
688
+ return slots:GetSlotIdFromIndex(slotIndex)
689
+ end
690
+
691
+ -- Deletes a slot, handling the case where it is the one being played. Backs saveslot-delete, and the
692
+ -- overwriting half of saveslot-copy and saveslot-write-json, which make room by deleting first.
693
+ --
694
+ -- The active slot can't be deleted while selected, so deselect it first (flushing its progress) when
695
+ -- reached. Read live rather than up front, since an earlier deletion in the same batch may have
696
+ -- already deselected it. An ephemeral session is left alone: PromiseDeleteSlot retires it itself, and
697
+ -- deselecting first would retire it early, leaving nothing behind to delete.
698
+ function SaveSlotCmdrService._promiseClearSlot(_self: SaveSlotCmdrService, slots: any, slotId: string): any
699
+ local isActive = (slotId == slots:GetActiveSlotId())
700
+ local deselect = if isActive and not slots:IsActiveSlotEphemeral()
701
+ then slots:PromiseDeselectSlot()
702
+ else Promise.resolved()
703
+
704
+ return deselect:Then(function()
705
+ return slots:PromiseDeleteSlot(slotId)
706
+ end)
548
707
  end
549
708
 
550
709
  -- Resolves a slotIndices argument (or nil = the active slot) into de-duplicated { slotIndex, slotId }
551
- -- entries for the player. An empty result means nothing matched, and the caller reports it.
710
+ -- entries. An empty result means nothing matched, and the caller reports it.
552
711
  function SaveSlotCmdrService._resolveSlotEntries(
553
712
  self: SaveSlotCmdrService,
554
- player: Player,
713
+ slots: any,
555
714
  slotIndices: { number }?
556
715
  ): SlotEntries
557
716
  local entries = {}
558
717
  if slotIndices == nil then
559
- local activeSlotId = self._saveSlotDataService:GetActiveSlotId(player)
560
- if not activeSlotId then
718
+ -- The slot they are on, or would resume on. Nothing is ever *selected* in an offline session,
719
+ -- so defaulting to the active slot alone would make every omitted-slot command a no-op there.
720
+ local currentSlotId = slots:GetLastActiveSlotId()
721
+ if not currentSlotId then
722
+ return entries
723
+ end
724
+ local metadata = slots:GetSlotMetadata(currentSlotId)
725
+ if not metadata then
561
726
  return entries
562
727
  end
563
- local metadata = self._saveSlotDataService:GetSlotMetadata(player, activeSlotId)
564
- table.insert(entries, { slotIndex = metadata.SlotIndex, slotId = activeSlotId })
728
+ table.insert(entries, { slotIndex = metadata.SlotIndex, slotId = currentSlotId })
565
729
  else
566
730
  local seen = {}
567
731
  for _, slotIndex in slotIndices do
568
- local slotId = self:_getSlotIdFromIndex(player, slotIndex)
732
+ local slotId = self:_getSlotIdFromIndex(slots, slotIndex)
569
733
  if slotId and not seen[slotId] then
570
734
  seen[slotId] = true
571
735
  table.insert(entries, { slotIndex = slotIndex, slotId = slotId })
@@ -575,47 +739,109 @@ function SaveSlotCmdrService._resolveSlotEntries(
575
739
  return entries
576
740
  end
577
741
 
578
- -- Pairs each player with their resolved slots, dropping players with nothing to act on. Note that
579
- -- Cmdr resolves the "." and "*" slot operators against the executor's slot list, since types only
580
- -- see the executor, so indices given that way come from the executor's slots.
581
- function SaveSlotCmdrService._resolveTargets(
742
+ -- Opens a slot system for the target and runs handler against it, whichever realm the target is in:
743
+ -- the bound binder's for a player here, a borrowed offline one otherwise. The offline session is
744
+ -- always released, including when the handler fails -- holding it would leave the player unable to
745
+ -- rejoin.
746
+ --
747
+ -- Waits for the slots to load first, because the read accessors handler uses are synchronous and see
748
+ -- an empty roster until they have.
749
+ function SaveSlotCmdrService._promiseWithSlots(
582
750
  self: SaveSlotCmdrService,
583
- players: { Player },
584
- slotIndices: { number }?
585
- ): { { player: Player, entries: SlotEntries } }
586
- local targets = {}
587
- for _, player in players do
588
- local entries = self:_resolveSlotEntries(player, slotIndices)
589
- if #entries > 0 then
590
- table.insert(targets, { player = player, entries = entries })
591
- end
751
+ userId: number,
752
+ handler: (any, string, number) -> any
753
+ ): any
754
+ local player = Players:GetPlayerByUserId(userId)
755
+
756
+ if player then
757
+ return self._maid:GivePromise(self._hasSaveSlotsBinder:Promise(player)):Then(function(hasSaveSlots)
758
+ local slots = hasSaveSlots:GetSlotsDataStore()
759
+ return slots:PromiseSlotsLoaded():Then(function()
760
+ return handler(slots, player.Name, userId)
761
+ end)
762
+ end)
763
+ end
764
+
765
+ local saveSlotService = self:_getSaveSlotService()
766
+ if not saveSlotService then
767
+ return Promise.rejected("not in this server, and offline save slots are unavailable")
592
768
  end
593
- return targets
769
+
770
+ -- Deliberately not `_maid:GivePromise`, which cancels nothing upstream: on teardown these slots
771
+ -- still resolve, into a continuation the maid has already skipped, and the session they took stays
772
+ -- locked for the rest of the server's life. The maid is probed for liveness instead, and then
773
+ -- handed the slots themselves.
774
+ local probe = {}
775
+ self._maid[probe] = probe
776
+
777
+ return saveSlotService:PromiseOfflineSaveSlots(userId):Then(function(offline)
778
+ local isAlive = self._maid[probe] == probe
779
+ self._maid[probe] = nil
780
+
781
+ if not isAlive then
782
+ offline:Destroy()
783
+ return Promise.rejected(`Destroyed while opening the save slots for {userId}`)
784
+ end
785
+
786
+ local offlineId = self._maid:GiveTask(offline :: any)
787
+
788
+ local function release(): any
789
+ self._maid[offlineId] = nil
790
+
791
+ -- Destroying only *starts* the borrowed session's save-and-close, so wait for it here: the
792
+ -- command reports success once the lock it took is gone, not while it is still held.
793
+ return self._playerDataStoreService:PromiseSessionClosed(userId)
794
+ end
795
+
796
+ return offline
797
+ :PromiseSlotsLoaded()
798
+ :Then(function()
799
+ return handler(offline:GetSlotsDataStore(), tostring(userId), userId)
800
+ end)
801
+ :Then(function(result)
802
+ return release():Then(function()
803
+ return result
804
+ end)
805
+ end, function(err)
806
+ return release():Then(function()
807
+ return Promise.rejected(err)
808
+ end)
809
+ end)
810
+ end, function(err)
811
+ self._maid[probe] = nil
812
+ return Promise.rejected(err)
813
+ end)
594
814
  end
595
815
 
596
- -- Runs handlePlayer once per player, sequentially, to avoid concurrent datastore writes. For the
597
- -- commands that act on a player as a whole rather than on a resolved slot list. handlePlayer may
598
- -- return a line directly to report without doing any work.
599
- function SaveSlotCmdrService._promisePlayerLines(
816
+ -- Runs handler once per target, sequentially, to avoid concurrent datastore writes and to keep only
817
+ -- one stolen session open at a time. Reports per target, so one failure still surfaces the successes.
818
+ --
819
+ -- Nothing reaches the console until every target is done, and opening an absent player's session can
820
+ -- take a while, so a target still going after the reply config's slowReplySeconds says so.
821
+ function SaveSlotCmdrService._promiseTargetLines(
600
822
  self: SaveSlotCmdrService,
601
- players: { Player },
602
- handlePlayer: (any, Player) -> any
823
+ context: CommandContext,
824
+ userIds: { number },
825
+ handler: (any, string, number) -> any
603
826
  ): any
604
827
  local promise = Promise.resolved()
605
828
  local results: { string } = {}
606
829
 
607
- for _, player in players do
830
+ for _, userId in userIds do
608
831
  promise = promise:Then(function()
609
- return self._maid
610
- :GivePromise(self._hasSaveSlotsBinder:Promise(player))
611
- :Then(function(hasSaveSlots)
612
- return handlePlayer(hasSaveSlots, player)
613
- end)
832
+ return CmdrReplyUtils.replyWhenSlow(
833
+ self._replyConfig,
834
+ context,
835
+ self:_promiseWithSlots(userId, handler),
836
+ `{userId}: still working...`
837
+ )
614
838
  :Then(function(line)
615
- table.insert(results, line)
839
+ if line ~= nil then
840
+ table.insert(results, line)
841
+ end
616
842
  end)
617
843
  :Catch(function(err)
618
- table.insert(results, `{player.Name}: {tostring(err)}`)
844
+ table.insert(results, `{userId}: {tostring(err)}`)
619
845
  end)
620
846
  end)
621
847
  end
@@ -625,39 +851,60 @@ function SaveSlotCmdrService._promisePlayerLines(
625
851
  end)
626
852
  end
627
853
 
628
- -- Runs handleSlot over every resolved slot of every target, sequentially, to avoid concurrent
629
- -- datastore writes. Reports per-slot so a mid-batch failure (e.g. one player's slot failing to
630
- -- load) still surfaces the successes.
631
- function SaveSlotCmdrService._promiseSlotLines(
854
+ -- Blocking form of _promiseTargetLines, for the command bodies. Cmdr runs commands on their own
855
+ -- thread, so yielding here is what lets a command report a finished result.
856
+ function SaveSlotCmdrService._runLines(
632
857
  self: SaveSlotCmdrService,
633
- targets: { { player: Player, entries: SlotEntries } },
634
- handleSlot: (any, SlotEntry, Player) -> any
635
- ): any
636
- local promise = Promise.resolved()
637
- local results: { string } = {}
858
+ context: CommandContext,
859
+ userIds: { number },
860
+ handler: (any, string, number) -> any
861
+ ): string
862
+ if #userIds == 0 then
863
+ return "No players to act on."
864
+ end
638
865
 
639
- for _, target in targets do
640
- promise = promise:Then(function()
641
- return self._maid:GivePromise(self._hasSaveSlotsBinder:Promise(target.player)):Then(function(hasSaveSlots)
642
- local slotPromise = Promise.resolved()
643
- for _, entry in target.entries do
644
- slotPromise = slotPromise:Then(function()
645
- return handleSlot(hasSaveSlots, entry, target.player)
646
- :Then(function(line)
647
- table.insert(results, line)
648
- end)
649
- :Catch(function(err)
650
- table.insert(results, `{target.player.Name} slot {entry.slotIndex}: {tostring(err)}`)
651
- end)
866
+ local lines = self:_promiseTargetLines(context, userIds, handler):Wait()
867
+ return table.concat(lines, "\n")
868
+ end
869
+
870
+ -- As _runLines, but resolves each target's slot argument first and runs handleSlot once per matching
871
+ -- slot. Reports per slot, so one bad slot does not hide the rest.
872
+ function SaveSlotCmdrService._runSlotLines(
873
+ self: SaveSlotCmdrService,
874
+ context: CommandContext,
875
+ userIds: { number },
876
+ slotIndices: { number }?,
877
+ handleSlot: (any, SlotEntry, string) -> any
878
+ ): string
879
+ return self:_runLines(context, userIds, function(slots, name)
880
+ local entries = self:_resolveSlotEntries(slots, slotIndices)
881
+ if #entries == 0 then
882
+ return `{name}: no matching slots.`
883
+ end
884
+
885
+ local lines: { string } = {}
886
+ local promise = Promise.resolved()
887
+
888
+ for _, entry in entries do
889
+ promise = promise:Then(function()
890
+ return Promise.resolved()
891
+ :Then(function()
892
+ return handleSlot(slots, entry, name)
893
+ end)
894
+ :Then(function(line)
895
+ if line ~= nil then
896
+ table.insert(lines, line)
897
+ end
898
+ end)
899
+ :Catch(function(err)
900
+ table.insert(lines, `{name} slot {entry.slotIndex}: {tostring(err)}`)
652
901
  end)
653
- end
654
- return slotPromise
655
902
  end)
656
- end)
657
- end
903
+ end
658
904
 
659
- return promise:Then(function()
660
- return results
905
+ return promise:Then(function()
906
+ return table.concat(lines, "\n")
907
+ end)
661
908
  end)
662
909
  end
663
910