@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
@@ -0,0 +1,457 @@
1
+ --!strict
2
+ -- Client-side Studio debug hook: a read-only view of what this client actually received,
3
+ -- meaning the replicated mirror, every applied op from boot (the Init snapshot included)
4
+ -- and the adopted service status. Studio play sessions only (gated in Client init), and
5
+ -- the surface has no mutating command.
6
+ --
7
+ -- Transport mirrors the server hook: one BindableFunction (request/response) and one
8
+ -- BindableEvent (stream digests) under ReplicatedStorage, created client-side so they
9
+ -- never exist on the server or replicate anywhere.
10
+
11
+ local RunService = game:GetService("RunService")
12
+ local ReplicatedStorage = game:GetService("ReplicatedStorage")
13
+ local Players = game:GetService("Players")
14
+
15
+ local Internal = script.Parent.Parent.Internal
16
+ local StudioCodec = require(Internal.StudioCodec)
17
+ local Util = require(Internal.Util)
18
+ local Template = require(Internal.Template)
19
+ local Datatypes = require(Internal.Datatypes)
20
+ local Health = require(Internal.Health)
21
+ local Log = require(Internal.Log)
22
+ local Metrics = require(Internal.Metrics)
23
+
24
+ local ClientDebugHook = {}
25
+
26
+ -- Versioned independently of the server hook: the two attach separately.
27
+ ClientDebugHook.PROTOCOL_VERSION = 2
28
+ ClientDebugHook.CONTAINER_NAME = "_ScribeClientDebugHook"
29
+
30
+ local OPS_FLUSH_HZ = 8
31
+ local METRICS_HZ = 1
32
+ local RECENT_OPS_CAP = 1000
33
+ local MAX_BATCH = 512
34
+ local MAX_TREE_NODES = 2000
35
+
36
+ local encode = StudioCodec.Encode
37
+ local decode = StudioCodec.Decode
38
+
39
+ local attached = false
40
+
41
+ local function readPath(root: any, path: { string | number }): any
42
+ local value: any = root
43
+ for _, segment in path do
44
+ if type(value) ~= "table" then
45
+ return nil
46
+ end
47
+ value = value[segment]
48
+ end
49
+ return value
50
+ end
51
+
52
+ -- deps: { Compiled, Mirror, Tree, IsLoaded: () -> boolean }
53
+ function ClientDebugHook.Attach(deps: any)
54
+ if not RunService:IsStudio() then
55
+ return
56
+ end
57
+ if attached or ReplicatedStorage:FindFirstChild(ClientDebugHook.CONTAINER_NAME) then
58
+ Log.Warn(
59
+ "Lifecycle",
60
+ "DEBUG_HOOK_DUPLICATE",
61
+ "a Scribe client debug hook already exists; only the first bundle is inspectable",
62
+ {}
63
+ )
64
+ return
65
+ end
66
+ attached = true
67
+
68
+ local compiled = deps.Compiled
69
+ local localPlayer = Players.LocalPlayer
70
+
71
+ local subscriptions: { [string]: boolean } = {}
72
+ local pending: { [string]: { any } } = { Ops = {}, Status = {} }
73
+ local statusHistory: { any } = {}
74
+
75
+ -- Ops ring: every applied op from boot (circular, oldest evicted).
76
+ local ring: { any } = table.create(RECENT_OPS_CAP)
77
+ local ringCount = 0
78
+ local ringNext = 1
79
+ local opSeq = 0
80
+
81
+ local function ringPush(record: any)
82
+ ring[ringNext] = record
83
+ ringNext = ringNext % RECENT_OPS_CAP + 1
84
+ if ringCount < RECENT_OPS_CAP then
85
+ ringCount += 1
86
+ end
87
+ end
88
+
89
+ local function ringSnapshotForReplay(): { any }
90
+ local out = table.create(ringCount)
91
+ local start = if ringCount < RECENT_OPS_CAP then 1 else ringNext
92
+ for i = 0, ringCount - 1 do
93
+ local record = table.clone(ring[(start + i - 1) % RECENT_OPS_CAP + 1])
94
+ record.Replay = true
95
+ table.insert(out, record)
96
+ end
97
+ return out
98
+ end
99
+
100
+ local container = Instance.new("Folder")
101
+ container.Name = ClientDebugHook.CONTAINER_NAME
102
+ local requestFn = Instance.new("BindableFunction")
103
+ requestFn.Name = "Request"
104
+ requestFn.Parent = container
105
+ local streamEv = Instance.new("BindableEvent")
106
+ streamEv.Name = "Stream"
107
+ streamEv.Parent = container
108
+
109
+ local function queue(stream: string, item: any)
110
+ if not subscriptions[stream] then
111
+ return
112
+ end
113
+ local bucket = pending[stream]
114
+ if #bucket < MAX_BATCH * 4 then
115
+ table.insert(bucket, item)
116
+ end
117
+ end
118
+
119
+ local function flushStream(stream: string)
120
+ local bucket = pending[stream]
121
+ if #bucket == 0 or not subscriptions[stream] then
122
+ if #bucket > 0 then
123
+ pending[stream] = {}
124
+ end
125
+ return
126
+ end
127
+ while #bucket > 0 do
128
+ local chunk = table.move(bucket, 1, math.min(MAX_BATCH, #bucket), 1, {})
129
+ local remaining = #bucket - #chunk
130
+ if remaining > 0 then
131
+ bucket = table.move(bucket, #chunk + 1, #chunk + remaining, 1, {})
132
+ else
133
+ bucket = {}
134
+ end
135
+ pending[stream] = bucket
136
+ local ok, err = pcall(function()
137
+ streamEv:Fire(stream, encode(chunk))
138
+ end)
139
+ if not ok then
140
+ Log.Warn("Lifecycle", "DEBUG_HOOK_ERROR", `client hook dropped a {stream} chunk: {tostring(err)}`, {})
141
+ end
142
+ end
143
+ pending[stream] = bucket
144
+ end
145
+
146
+ -- Record every applied op (Init snapshot included) before it mutates the
147
+ -- mirror, so Old is the true pre-op value.
148
+ local origApply = deps.Tree.ApplyOp
149
+ deps.Tree.ApplyOp = function(treeSelf: any, op: any)
150
+ local ok, err = pcall(function()
151
+ -- Old per op kind, matching the server hook's record shape: the removed
152
+ -- element for Remove, nil for Insert, the pre-write value otherwise
153
+ -- (full contents for Clear).
154
+ local old: any = nil
155
+ if op.Kind == "Remove" then
156
+ local arr = readPath(deps.Mirror, op.Path)
157
+ if type(arr) == "table" then
158
+ old = arr[math.clamp(op.Index or #arr, 1, math.max(#arr, 1))]
159
+ end
160
+ elseif op.Kind ~= "Insert" then
161
+ old = readPath(deps.Mirror, op.Path)
162
+ end
163
+ opSeq += 1
164
+ local record = {
165
+ HookSeq = opSeq,
166
+ T = os.clock(),
167
+ UserId = if localPlayer then localPlayer.UserId else 0,
168
+ Kind = op.Kind,
169
+ Path = table.clone(op.Path),
170
+ Index = op.Index,
171
+ Value = if type(op.Value) == "table" or type(op.Value) == "buffer"
172
+ then Util.deepClone(op.Value)
173
+ else op.Value,
174
+ Old = if type(old) == "table" or type(old) == "buffer" then Util.deepClone(old) else old,
175
+ Visibility = Template.VisibilityOf(compiled, op.Path),
176
+ }
177
+ ringPush(record)
178
+ queue("Ops", record)
179
+ end)
180
+ if not ok then
181
+ Log.Warn("Lifecycle", "DEBUG_HOOK_ERROR", tostring(err), {})
182
+ end
183
+ return origApply(treeSelf, op)
184
+ end
185
+
186
+ -- Genuine transitions only (the raw Status frame re-sends on every Init).
187
+ Health.OnStatusChanged:Connect(function(newStatus: string, oldStatus: string)
188
+ local record = {
189
+ T = os.clock(),
190
+ WallAt = os.time(),
191
+ From = oldStatus,
192
+ To = newStatus,
193
+ }
194
+ table.insert(statusHistory, record)
195
+ if #statusHistory > 100 then
196
+ table.remove(statusHistory, 1)
197
+ end
198
+ queue("Status", record)
199
+ end)
200
+
201
+ -- Paged tree pages, same shape as the server hook's ReadTree.
202
+ local function describeValue(value: any, depth: number, budget: { n: number }, schema: any): any
203
+ budget.n -= 1
204
+ if type(value) ~= "table" then
205
+ -- Packed datatype leaves read as their datatype, mirroring the server
206
+ -- hook (StudioCodec cannot carry Roblox datatypes, so a display string).
207
+ if type(value) == "buffer" and schema and schema.ValueType == "datatype" then
208
+ local name = schema.Datatype :: string
209
+ local ok, unpacked = pcall(Datatypes.Unpack, name, value)
210
+ if ok then
211
+ return { Leaf = true, Value = `{name}({tostring(unpacked)})`, Datatype = name }
212
+ end
213
+ end
214
+ return { Leaf = true, Value = value }
215
+ end
216
+ local count = Util.count(value)
217
+ if depth <= 0 or budget.n <= 0 then
218
+ return { Table = true, Count = count, Truncated = true }
219
+ end
220
+ local children: { [any]: any } = {}
221
+ for k, v in value do
222
+ if budget.n <= 0 then
223
+ return { Table = true, Count = count, Truncated = true, Children = children }
224
+ end
225
+ local childSchema = if schema then Template.ChildSchema(schema, k) else nil
226
+ children[k] = describeValue(v, depth - 1, budget, childSchema)
227
+ end
228
+ return { Table = true, Count = count, Children = children }
229
+ end
230
+
231
+ local function rosterEntry(): { [string]: any }
232
+ return {
233
+ UserId = if localPlayer then localPlayer.UserId else 0,
234
+ Name = if localPlayer then localPlayer.Name else "LocalPlayer",
235
+ DisplayName = if localPlayer then localPlayer.DisplayName else "LocalPlayer",
236
+ State = "Ready",
237
+ HandshakeReady = deps.IsLoaded(),
238
+ Dirty = false,
239
+ QueueDepth = 0,
240
+ Mock = false,
241
+ SizeBytes = Util.approxSize(deps.Mirror),
242
+ }
243
+ end
244
+
245
+ -- Command handlers, read-only ---------------------------------------------
246
+
247
+ local handlers: { [string]: (args: any) -> any } = {}
248
+
249
+ function handlers.Handshake(args: any): any
250
+ local major = tonumber(args.ProtocolVersion) or 0
251
+ local minSupported = tonumber(args.MinProtocolVersion) or major
252
+ -- NaN compares false both ways and would slip through the range check.
253
+ if major ~= major or minSupported ~= minSupported then
254
+ major, minSupported = 0, 0
255
+ end
256
+ if ClientDebugHook.PROTOCOL_VERSION < minSupported or ClientDebugHook.PROTOCOL_VERSION > major then
257
+ return {
258
+ Ok = false,
259
+ Error = `protocol mismatch: client hook speaks v{ClientDebugHook.PROTOCOL_VERSION}, plugin speaks v{minSupported}-v{major}`
260
+ .. if major < ClientDebugHook.PROTOCOL_VERSION
261
+ then "; update the Scribe Studio plugin"
262
+ else "; update the Scribe package in this game",
263
+ ProtocolVersion = ClientDebugHook.PROTOCOL_VERSION,
264
+ }
265
+ end
266
+ -- A handshake means a new plugin instance: reset subscriptions so the boot ring
267
+ -- replays on the first SetSubscriptions.
268
+ for stream in subscriptions do
269
+ subscriptions[stream] = false
270
+ end
271
+ for _, bucket in pending do
272
+ table.clear(bucket)
273
+ end
274
+ local scribeVersion = "unknown"
275
+ pcall(function()
276
+ scribeVersion = (require :: any)(script.Parent.Parent).Version
277
+ end)
278
+ return {
279
+ Ok = true,
280
+ ProtocolVersion = ClientDebugHook.PROTOCOL_VERSION,
281
+ ClientView = true,
282
+ ScribeVersion = scribeVersion,
283
+ TemplateHash = compiled.Hash,
284
+ NodeCount = compiled.NodeCount,
285
+ Clock = os.clock(),
286
+ WallClock = os.time(),
287
+ Status = Health.GetStatus(),
288
+ PlaceName = game.Name,
289
+ Loaded = deps.IsLoaded(),
290
+ UserId = if localPlayer then localPlayer.UserId else 0,
291
+ WritesEnabled = false,
292
+ AttributionEnabled = false,
293
+ }
294
+ end
295
+
296
+ function handlers.SetSubscriptions(args: any): any
297
+ local had: { [string]: boolean } = {}
298
+ for _, stream in { "Ops", "Status", "Metrics" } do
299
+ had[stream] = subscriptions[stream] == true
300
+ subscriptions[stream] = args[stream] == true
301
+ if not subscriptions[stream] and pending[stream] then
302
+ table.clear(pending[stream])
303
+ end
304
+ end
305
+ if subscriptions.Ops and not had.Ops and ringCount > 0 then
306
+ -- Replay everything applied since boot; records carry HookSeq for dedupe
307
+ -- and Replay=true so the plugin keeps them out of its live tree mirror.
308
+ pending.Ops = ringSnapshotForReplay()
309
+ flushStream("Ops")
310
+ end
311
+ return { Ok = true }
312
+ end
313
+
314
+ function handlers.ListPlayers(_args: any): any
315
+ return { Ok = true, Roster = { rosterEntry() } }
316
+ end
317
+
318
+ function handlers.ReadTree(args: any): any
319
+ local path: { string | number } = args.Path or {}
320
+ local depth = math.clamp(tonumber(args.Depth) or 2, 1, 6)
321
+ local budget = { n = math.clamp(tonumber(args.MaxNodes) or MAX_TREE_NODES, 50, MAX_TREE_NODES) }
322
+ local schema: any, dynStart = Template.Resolve(compiled, path)
323
+ for i = dynStart, #path do
324
+ schema = if schema then Template.ChildSchema(schema, path[i]) else nil
325
+ end
326
+ local page = describeValue(readPath(deps.Mirror, path), depth, budget, schema)
327
+ return { Ok = true, Path = path, Node = page }
328
+ end
329
+
330
+ function handlers.GetSchema(_args: any): any
331
+ local nodes = {}
332
+ for id = 0, compiled.NodeCount - 1 do
333
+ local node = compiled.ById[id]
334
+ if node then
335
+ local record: any = {
336
+ Id = node.Id,
337
+ Path = table.clone(node.Path),
338
+ Kind = node.Kind,
339
+ ValueType = node.ValueType,
340
+ Datatype = node.Datatype,
341
+ Visibility = node.Visibility,
342
+ Timed = node.Timed,
343
+ Min = node.Min,
344
+ Max = node.Max,
345
+ MaxLength = node.MaxLength,
346
+ Members = if node.Members then table.clone(node.Members) else nil,
347
+ HasChildren = node.Children ~= nil,
348
+ }
349
+ -- Same additive shape the server hook sends: without it the client view
350
+ -- renders derived fields as ordinary editable ones. Compute is a function
351
+ -- and never crosses the wire.
352
+ local derived = node.Derived
353
+ if derived then
354
+ local inputs = table.create(#derived.InputPaths)
355
+ for i, inputPath in derived.InputPaths do
356
+ inputs[i] = table.concat(inputPath, ".")
357
+ end
358
+ record.Derived = {
359
+ Inputs = inputs,
360
+ Transmit = derived.Transmit,
361
+ OfflineComputable = derived.OfflineComputable,
362
+ Label = derived.Label,
363
+ }
364
+ end
365
+ table.insert(nodes, record)
366
+ end
367
+ end
368
+ return { Ok = true, Hash = compiled.Hash, NodeCount = compiled.NodeCount, Nodes = nodes }
369
+ end
370
+
371
+ -- Same shape as the server hook's.
372
+ function handlers.GetMetrics(_args: any): any
373
+ return {
374
+ Ok = true,
375
+ T = os.clock(),
376
+ Metrics = Metrics.Get(),
377
+ Percentiles = Metrics.GetPercentiles(),
378
+ Status = Health.GetStatus(),
379
+ }
380
+ end
381
+
382
+ function handlers.GetStatusInfo(_args: any): any
383
+ return { Ok = true, Status = Health.GetStatus(), History = statusHistory }
384
+ end
385
+
386
+ function handlers.Snapshot(_args: any): any
387
+ return {
388
+ Ok = true,
389
+ UserId = if localPlayer then localPlayer.UserId else 0,
390
+ Name = if localPlayer then localPlayer.Name else "LocalPlayer",
391
+ Data = Util.deepClone(deps.Mirror),
392
+ Session = {},
393
+ }
394
+ end
395
+
396
+ function handlers.GetDefaults(_args: any): any
397
+ return {
398
+ Ok = true,
399
+ Persistent = Template.BuildDefaults(compiled, "Client"),
400
+ Session = {},
401
+ }
402
+ end
403
+
404
+ requestFn.OnInvoke = function(name: string, encodedArgs: string?): string
405
+ local handler = handlers[tostring(name)]
406
+ if handler == nil then
407
+ return encode({ Ok = false, Error = `unknown command "{tostring(name)}" (client hook is read-only)` })
408
+ end
409
+ local response
410
+ local ok, err = pcall(function()
411
+ local args: any = {}
412
+ if type(encodedArgs) == "string" and encodedArgs ~= "" then
413
+ args = decode(encodedArgs)
414
+ end
415
+ response = handler(if type(args) == "table" then args else {})
416
+ end)
417
+ if not ok then
418
+ response = { Ok = false, Error = tostring(err) }
419
+ end
420
+ return encode(response)
421
+ end
422
+
423
+ container.Parent = ReplicatedStorage
424
+
425
+ -- Digest pump; metrics ticks fire directly at 1 Hz.
426
+ task.spawn(function()
427
+ local lastMetrics = 0
428
+ local metricSeq = 0
429
+ while container.Parent ~= nil do
430
+ task.wait(1 / OPS_FLUSH_HZ)
431
+ pcall(function()
432
+ flushStream("Ops")
433
+ flushStream("Status")
434
+ local now = os.clock()
435
+ if subscriptions.Metrics and now - lastMetrics >= 1 / METRICS_HZ then
436
+ lastMetrics = now
437
+ metricSeq += 1
438
+ streamEv:Fire(
439
+ "Metrics",
440
+ encode({
441
+ {
442
+ MetricSeq = metricSeq,
443
+ T = now,
444
+ WallAt = os.time(),
445
+ Status = Health.GetStatus(),
446
+ Metrics = Metrics.Get(),
447
+ Percentiles = Metrics.GetPercentiles(),
448
+ },
449
+ })
450
+ )
451
+ end
452
+ end)
453
+ end
454
+ end)
455
+ end
456
+
457
+ return ClientDebugHook