@tilua-types/sunc 11.1.5 → 11.2.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.
package/runtime/sunc.luau CHANGED
@@ -275,3 +275,928 @@ __NAME__.http = {
275
275
  return send(options)
276
276
  end or nil,
277
277
  }
278
+
279
+ -- ============================================================
280
+ -- What this project keeps: executor.fingerprint, env.getmain
281
+ -- ============================================================
282
+ --
283
+ -- A table every script of this project shares — what `env.getmain()` answers,
284
+ -- and the HTTP cache beside it — kept in the first of `getgenv()`, `shared`
285
+ -- and `_G` there is. It is kept under a name nothing else can look up, as the
286
+ -- bridge names its remotes: the HMAC of this machine's fingerprint under the
287
+ -- project's secret, which the compiler writes in. Another
288
+ -- script sees one more key of random hex; only this project's scripts, on this
289
+ -- machine, know which.
290
+ --
291
+ -- The SHA-256, HMAC and AES-GCM are @tilua-types/crypto's runtime, put here
292
+ -- by the compiler and set up the first time it is needed.
293
+
294
+ local SECRET = __SECRET__
295
+
296
+ local freeze = table.freeze or function(t)
297
+ return t
298
+ end
299
+
300
+ local loadCrypto = __CRYPTO__
301
+ local cryptoLib
302
+
303
+ local function lib()
304
+ if cryptoLib == nil then
305
+ cryptoLib = loadCrypto()
306
+ end
307
+ return cryptoLib
308
+ end
309
+
310
+ local function hmacHex(key, text)
311
+ return lib().hmacSha256(key, text).hex
312
+ end
313
+
314
+ -- The fingerprint, as FingerprintJS makes a browser's: many components, each
315
+ -- something this machine and executor answer the same way on every run, put
316
+ -- together and hashed. A component that cannot be read is left out, as one
317
+ -- the browser does not have. Nothing timed (a benchmark of the CPU is
318
+ -- different on every run), nothing a player changes as they play (the
319
+ -- window's size, the client's settings), and nothing that changes every week
320
+ -- (Roblox's version, the executor's version), or what is kept under the
321
+ -- fingerprint would be lost with it:
322
+ --
323
+ -- - `hwid`: the executor's `gethwid`;
324
+ -- - `clientid`: Roblox's id for the client install;
325
+ -- - `executor`: the executor's name;
326
+ -- - `capabilities`: which of the library's functions the executor has;
327
+ -- - `genv`: how many of the names sUNC and UNC define (`hookfunction`,
328
+ -- `getrawmetatable`, ...) are a function in `getgenv()`. Only those
329
+ -- names: whatever else a script put there does not count;
330
+ -- - `math`: what the CPU and the C library make of awkward floating-point
331
+ -- arguments, as FingerprintJS's `math` component;
332
+ -- - `quirks`: what the executor's own functions answer for a fixed input —
333
+ -- its base64 of edge bytes, its LZ4, its SHA-256 — where executors differ;
334
+ -- - `locale`: the system's locale;
335
+ -- - `timezone`: the offset from UTC in January and in July, which is the
336
+ -- timezone and its daylight saving, the same all year;
337
+ -- - `platform`: touch, keyboard, mouse, the platform and a ten-foot
338
+ -- interface.
339
+
340
+ local components
341
+
342
+ -- Every global of the executor's this library reads, written in by the
343
+ -- compiler from the names the runtime hands to `pick`
344
+ local SUNC_NAMES = __SUNC_NAMES__
345
+
346
+ local function shortHash(text)
347
+ return string.sub(lib().sha256(text).hex, 1, 16)
348
+ end
349
+
350
+ local function sortedNames(names)
351
+ table.sort(names)
352
+ return #names .. ":" .. shortHash(table.concat(names, ","))
353
+ end
354
+
355
+ local function utcOffset(t)
356
+ local here, utc = os.date("*t", t), os.date("!*t", t)
357
+ here.isdst, utc.isdst = false, false
358
+ return os.time(here) - os.time(utc)
359
+ end
360
+
361
+ local COMPONENTS = {
362
+ hwid = function()
363
+ return __NAME__.executor.hwid()
364
+ end,
365
+ clientid = function()
366
+ return game:GetService("RbxAnalyticsService"):GetClientId()
367
+ end,
368
+ executor = function()
369
+ return __NAME__.executor.identify()[1]
370
+ end,
371
+ capabilities = function()
372
+ local names = {}
373
+ for space, members in pairs(__NAME__) do
374
+ if type(members) == "table" then
375
+ for member, value in pairs(members) do
376
+ if type(value) == "function" then
377
+ names[#names + 1] = space .. "." .. member
378
+ end
379
+ end
380
+ end
381
+ end
382
+ return sortedNames(names)
383
+ end,
384
+ genv = function()
385
+ local genv = __NAME__.env.getgenv()
386
+ local count = 0
387
+ for _, name in SUNC_NAMES do
388
+ local ok, value = pcall(function()
389
+ return genv[name]
390
+ end)
391
+ if ok and type(value) == "function" then
392
+ count = count + 1
393
+ end
394
+ end
395
+ return count
396
+ end,
397
+ math = function()
398
+ local values = {
399
+ math.acos(0.123124234234234242), math.asin(0.123124234234234242), math.atan(0.5),
400
+ math.atan2(-0.1, -1e-300), math.cos(21 * math.pi), math.sin(-1e300), math.tan(-1e300),
401
+ math.exp(1), math.log(1e300), math.log10(7), math.sinh(1), math.cosh(1), math.tanh(1),
402
+ math.pow(math.pi, -100), math.sqrt(2), math.fmod(1e300, 0.1),
403
+ }
404
+ local ok, noise = pcall(function()
405
+ return math.noise(0.4, 1.7, 2.3)
406
+ end)
407
+ if ok then
408
+ values[#values + 1] = noise
409
+ end
410
+ for i, value in values do
411
+ values[i] = string.format("%.17g", value)
412
+ end
413
+ return shortHash(table.concat(values, ","))
414
+ end,
415
+ quirks = function()
416
+ local parts = {}
417
+ local function add(f)
418
+ local ok, value = pcall(f)
419
+ parts[#parts + 1] = ok and tostring(value) or "-"
420
+ end
421
+ add(function()
422
+ return __NAME__.encoding.base64encode("\0\1\127\128\255tilua")
423
+ end)
424
+ add(function()
425
+ return shortHash(__NAME__.encoding.lz4compress(string.rep("tilua-sunc ", 16)))
426
+ end)
427
+ add(function()
428
+ return __NAME__.crypt.hash("tilua", "sha256")
429
+ end)
430
+ return shortHash(table.concat(parts, "|"))
431
+ end,
432
+ locale = function()
433
+ return game:GetService("LocalizationService").SystemLocaleId
434
+ end,
435
+ timezone = function()
436
+ return utcOffset(1577836800) .. "/" .. utcOffset(1593561600)
437
+ end,
438
+ platform = function()
439
+ local input = game:GetService("UserInputService")
440
+ local parts = { tostring(input.TouchEnabled), tostring(input.KeyboardEnabled), tostring(input.MouseEnabled) }
441
+ local ok, platform = pcall(function()
442
+ return input:GetPlatform()
443
+ end)
444
+ parts[#parts + 1] = ok and tostring(platform) or "-"
445
+ local tenFoot
446
+ ok, tenFoot = pcall(function()
447
+ return game:GetService("GuiService"):IsTenFootInterface()
448
+ end)
449
+ parts[#parts + 1] = ok and tostring(tenFoot) or "-"
450
+ return table.concat(parts, ",")
451
+ end,
452
+ }
453
+
454
+ local function collect()
455
+ if components == nil then
456
+ components = {}
457
+ for name, read in pairs(COMPONENTS) do
458
+ local ok, value = pcall(read)
459
+ if ok and value ~= nil then
460
+ components[name] = tostring(value)
461
+ end
462
+ end
463
+ freeze(components)
464
+ end
465
+ return components
466
+ end
467
+
468
+ local machineText
469
+
470
+ local function machine()
471
+ if machineText == nil then
472
+ local lines = {}
473
+ for name, value in pairs(collect()) do
474
+ lines[#lines + 1] = name .. "=" .. value
475
+ end
476
+ table.sort(lines)
477
+ machineText = table.concat(lines, "\n")
478
+ end
479
+ return machineText
480
+ end
481
+
482
+ __NAME__.executor.fingerprint = function(salt)
483
+ return hmacHex(type(salt) == "string" and salt or "tilua-sunc", machine())
484
+ end
485
+
486
+ __NAME__.executor.components = function()
487
+ local copy = {}
488
+ for name, value in pairs(collect()) do
489
+ copy[name] = value
490
+ end
491
+ return copy
492
+ end
493
+
494
+ local ROOT_VERSION = 1
495
+ local rootKey
496
+
497
+ local function holder()
498
+ local getgenv = __NAME__.env.getgenv
499
+ if getgenv then
500
+ local ok, genv = pcall(getgenv)
501
+ if ok and type(genv) == "table" then
502
+ return genv
503
+ end
504
+ end
505
+ if type(shared) == "table" then
506
+ return shared
507
+ end
508
+ return _G
509
+ end
510
+
511
+ local function root()
512
+ if rootKey == nil then
513
+ rootKey = string.sub(hmacHex(SECRET, "main\n" .. machine()), 1, 24)
514
+ end
515
+ local where = holder()
516
+ local found = rawget(where, rootKey)
517
+ if type(found) ~= "table" or found.version ~= ROOT_VERSION then
518
+ local globals = type(found) == "table" and type(found.globals) == "table" and found.globals or {}
519
+ found = { version = ROOT_VERSION, globals = globals, http = { entries = {}, count = 0, clock = 0 } }
520
+ rawset(where, rootKey, found)
521
+ end
522
+ return found
523
+ end
524
+
525
+ __NAME__.env.getmain = function()
526
+ return root().globals
527
+ end
528
+
529
+ -- ============================================================
530
+ -- http.to(url): an immutable request builder, cached as a browser does
531
+ -- ============================================================
532
+ --
533
+ -- Every method answers a new builder and leaves the one it was called on as it
534
+ -- was, so one with a base URL and headers can be kept and built on. What a
535
+ -- builder holds is in `states`, out of the builder itself: the builder is an
536
+ -- empty frozen table.
537
+ --
538
+ -- A GET is cached the way a browser's private cache does (RFC 9111): the
539
+ -- response's `Cache-Control` (`max-age`, `no-store`, `no-cache`,
540
+ -- `must-revalidate`), `Expires` and `Date`, `Age`, a guess from
541
+ -- `Last-Modified` when nothing says how long, `Vary`, and revalidation with
542
+ -- `If-None-Match` / `If-Modified-Since`, a 304 refreshing what was kept. The
543
+ -- request's own `Cache-Control` (`no-store`, `no-cache`, `max-age`,
544
+ -- `max-stale`, `min-fresh`, `only-if-cached`) and `Pragma: no-cache` are
545
+ -- honoured, and `:cache(mode)` takes fetch's modes. A POST, PUT, PATCH or
546
+ -- DELETE that succeeds forgets what was kept for its URL.
547
+ --
548
+ -- What is kept is in memory, in the table `env.getmain()` sits beside, and on
549
+ -- disk when the executor has a filesystem: one file a URL, in a folder, both
550
+ -- named by HMACs, each sealed with AES-GCM under a key from the project's
551
+ -- secret and this machine.
552
+
553
+ local CACHEABLE = {
554
+ [200] = true, [203] = true, [204] = true, [300] = true, [301] = true, [308] = true,
555
+ [404] = true, [405] = true, [410] = true, [414] = true, [501] = true,
556
+ }
557
+ local UNSAFE = { POST = true, PUT = true, PATCH = true, DELETE = true }
558
+ -- The longest a response is guessed fresh for from its Last-Modified
559
+ local HEURISTIC_LIMIT = 86400
560
+ -- Entries kept in memory; past it the least recently used goes (its file stays)
561
+ local MEMORY_LIMIT = 128
562
+ -- Varied on whether the response says so or not: one URL asked with two
563
+ -- tokens is two answers
564
+ local ALWAYS_VARY = { "authorization" }
565
+
566
+ local function lowerHeaders(headers)
567
+ local out = {}
568
+ if type(headers) == "table" then
569
+ for key, value in pairs(headers) do
570
+ if type(key) == "string" then
571
+ out[string.lower(key)] = tostring(value)
572
+ end
573
+ end
574
+ end
575
+ return out
576
+ end
577
+
578
+ local function copyOf(t)
579
+ local out = {}
580
+ for key, value in pairs(t) do
581
+ out[key] = value
582
+ end
583
+ return out
584
+ end
585
+
586
+ -- `Cache-Control` as `{ ["max-age"] = "60", ["no-cache"] = true }`
587
+ local function directives(value)
588
+ local out = {}
589
+ if type(value) ~= "string" then
590
+ return out
591
+ end
592
+ for part in string.gmatch(value, "[^,]+") do
593
+ local name, argument = string.match(part, "^%s*([^=%s]+)%s*=%s*\"?([^\"]*)\"?%s*$")
594
+ if name then
595
+ out[string.lower(name)] = argument
596
+ else
597
+ name = string.match(part, "^%s*(.-)%s*$")
598
+ if name ~= "" then
599
+ out[string.lower(name)] = true
600
+ end
601
+ end
602
+ end
603
+ return out
604
+ end
605
+
606
+ local function seconds(value)
607
+ if type(value) ~= "string" then
608
+ return nil
609
+ end
610
+ return tonumber(string.match(value, "^%s*(%d+)%s*$"))
611
+ end
612
+
613
+ local MONTHS = {
614
+ jan = 1, feb = 2, mar = 3, apr = 4, may = 5, jun = 6,
615
+ jul = 7, aug = 8, sep = 9, oct = 10, nov = 11, dec = 12,
616
+ }
617
+
618
+ -- Days from 1970-01-01 to a date of the proleptic Gregorian calendar
619
+ local function daysFromCivil(y, m, d)
620
+ if m <= 2 then
621
+ y = y - 1
622
+ end
623
+ local era = math.floor(y / 400)
624
+ local yearOfEra = y - era * 400
625
+ local dayOfYear = math.floor((153 * ((m + 9) % 12) + 2) / 5) + d - 1
626
+ local dayOfEra = yearOfEra * 365 + math.floor(yearOfEra / 4) - math.floor(yearOfEra / 100) + dayOfYear
627
+ return era * 146097 + dayOfEra - 719468
628
+ end
629
+
630
+ -- An HTTP date as Unix seconds: `Sun, 06 Nov 1994 08:49:37 GMT`, the RFC 850
631
+ -- form and asctime's. Nil for anything else.
632
+ local function httpDate(value)
633
+ if type(value) ~= "string" then
634
+ return nil
635
+ end
636
+ local d, mon, y, h, mi, s = string.match(value, "(%d%d?)[ %-](%a%a%a)[ %-](%d+) (%d%d):(%d%d):(%d%d)")
637
+ if not d then
638
+ mon, d, h, mi, s, y = string.match(value, "(%a%a%a) +(%d%d?) (%d%d):(%d%d):(%d%d) (%d%d%d%d)")
639
+ end
640
+ local month = mon and MONTHS[string.lower(mon)]
641
+ if not month then
642
+ return nil
643
+ end
644
+ local year = tonumber(y)
645
+ if year < 100 then
646
+ year = year + (year < 70 and 2000 or 1900)
647
+ end
648
+ return daysFromCivil(year, month, tonumber(d)) * 86400 + tonumber(h) * 3600 + tonumber(mi) * 60 + tonumber(s)
649
+ end
650
+
651
+ -- What a response is kept as, or nil when it is not to be kept
652
+ local function makeEntry(url, requestHeaders, status, statusText, headers, body, requestTime, responseTime)
653
+ local control = directives(headers["cache-control"])
654
+ if control["no-store"] then
655
+ return nil
656
+ end
657
+ local vary = {}
658
+ for _, name in ALWAYS_VARY do
659
+ vary[name] = requestHeaders[name] or ""
660
+ end
661
+ if headers["vary"] then
662
+ for name in string.gmatch(headers["vary"], "[^,%s]+") do
663
+ if name == "*" then
664
+ return nil
665
+ end
666
+ name = string.lower(name)
667
+ vary[name] = requestHeaders[name] or ""
668
+ end
669
+ end
670
+ local date = httpDate(headers["date"]) or responseTime
671
+ local initialAge = math.max(responseTime - date, seconds(headers["age"]) or 0) + (responseTime - requestTime)
672
+ local lifetime = 0
673
+ local maxAge = seconds(control["max-age"])
674
+ if maxAge then
675
+ lifetime = maxAge
676
+ elseif headers["expires"] then
677
+ local expires = httpDate(headers["expires"])
678
+ lifetime = expires and math.max(0, expires - date) or 0
679
+ elseif headers["last-modified"] then
680
+ local modified = httpDate(headers["last-modified"])
681
+ lifetime = modified and math.min(HEURISTIC_LIMIT, math.max(0, math.floor((date - modified) / 10))) or 0
682
+ end
683
+ local etag, lastModified = headers["etag"], headers["last-modified"]
684
+ -- Never to be fresh again and unable to be revalidated: no use keeping
685
+ if etag == nil and lastModified == nil and math.max(0, initialAge) >= lifetime then
686
+ return nil
687
+ end
688
+ return {
689
+ url = url,
690
+ status = status,
691
+ statusText = statusText,
692
+ headers = headers,
693
+ body = body,
694
+ responseTime = responseTime,
695
+ initialAge = math.max(0, initialAge),
696
+ lifetime = lifetime,
697
+ vary = vary,
698
+ etag = etag,
699
+ lastModified = lastModified,
700
+ noCache = control["no-cache"] ~= nil,
701
+ mustRevalidate = control["must-revalidate"] ~= nil,
702
+ }
703
+ end
704
+
705
+ local function currentAge(entry)
706
+ return entry.initialAge + math.max(0, os.time() - entry.responseTime)
707
+ end
708
+
709
+ local function varyMatches(entry, requestHeaders)
710
+ for name, value in pairs(entry.vary) do
711
+ if (requestHeaders[name] or "") ~= value then
712
+ return false
713
+ end
714
+ end
715
+ return true
716
+ end
717
+
718
+ -- "use" what was kept, "validate" it with the server, or "fetch" anew
719
+ local function decide(entry, control, mode)
720
+ if mode == "force-cache" then
721
+ return "use"
722
+ end
723
+ local canValidate = entry.etag ~= nil or entry.lastModified ~= nil
724
+ local otherwise = canValidate and "validate" or "fetch"
725
+ if mode == "no-cache" or control["no-cache"] or entry.noCache then
726
+ return otherwise
727
+ end
728
+ local age = currentAge(entry)
729
+ local maxAge = seconds(control["max-age"])
730
+ local minFresh = seconds(control["min-fresh"]) or 0
731
+ if age + minFresh < entry.lifetime and (maxAge == nil or age <= maxAge) then
732
+ return "use"
733
+ end
734
+ local maxStale = control["max-stale"]
735
+ if maxStale ~= nil and not entry.mustRevalidate and (maxAge == nil or age <= maxAge) then
736
+ local allowed = seconds(maxStale)
737
+ if maxStale == true or (allowed and age - entry.lifetime <= allowed) then
738
+ return "use"
739
+ end
740
+ end
741
+ return otherwise
742
+ end
743
+
744
+ --------------------------------------------------------------------------------
745
+ -- Where entries are kept
746
+ --------------------------------------------------------------------------------
747
+
748
+ local fs = __NAME__.fs
749
+ local hasDisk = fs.read ~= nil and fs.write ~= nil and fs.isfile ~= nil and fs.isfolder ~= nil
750
+ and fs.makefolder ~= nil and fs.delete ~= nil
751
+ local disk
752
+
753
+ local function diskState()
754
+ if disk == nil then
755
+ local fingerprint = machine()
756
+ local key = lib().hmacSha256(SECRET, "disk\n" .. fingerprint).bytes
757
+ disk = {
758
+ folder = string.sub(hmacHex(SECRET, "folder\n" .. fingerprint), 1, 24),
759
+ fingerprint = fingerprint,
760
+ sealer = lib().aesGcm.context(key),
761
+ }
762
+ end
763
+ return disk
764
+ end
765
+
766
+ local function pathOf(url)
767
+ local state = diskState()
768
+ return state.folder .. "/" .. string.sub(hmacHex(SECRET, "file\n" .. state.fingerprint .. "\n" .. url), 1, 32)
769
+ end
770
+
771
+ local KEPT = {
772
+ "url", "status", "statusText", "headers", "responseTime", "initialAge", "lifetime",
773
+ "vary", "etag", "lastModified", "noCache", "mustRevalidate",
774
+ }
775
+
776
+ -- The entry's fields as JSON, a newline, then the body as it is: JSON writes
777
+ -- control characters escaped, so the first newline is the end of the fields
778
+ local function writeDisk(url, entry)
779
+ if not hasDisk then
780
+ return
781
+ end
782
+ pcall(function()
783
+ local state = diskState()
784
+ local fields = {}
785
+ for _, name in KEPT do
786
+ fields[name] = entry[name]
787
+ end
788
+ local path = pathOf(url)
789
+ local sealed = state.sealer.encrypt(__JSON__.encode(fields) .. "\n" .. entry.body, { aad = path })
790
+ if not fs.isfolder(state.folder) then
791
+ fs.makefolder(state.folder)
792
+ end
793
+ fs.write(path, lib().base64.encode(sealed.iv .. sealed.tag .. sealed.ciphertext))
794
+ end)
795
+ end
796
+
797
+ local function deleteDisk(url)
798
+ if not hasDisk then
799
+ return
800
+ end
801
+ pcall(function()
802
+ local path = pathOf(url)
803
+ if fs.isfile(path) then
804
+ fs.delete(path)
805
+ end
806
+ end)
807
+ end
808
+
809
+ local function readDisk(url)
810
+ if not hasDisk then
811
+ return nil
812
+ end
813
+ local ok, entry = pcall(function()
814
+ local path = pathOf(url)
815
+ if not fs.isfile(path) then
816
+ return nil
817
+ end
818
+ local raw = lib().base64.decode(fs.read(path))
819
+ local text = diskState().sealer.decrypt({
820
+ iv = string.sub(raw, 1, 12),
821
+ tag = string.sub(raw, 13, 28),
822
+ ciphertext = string.sub(raw, 29),
823
+ }, path)
824
+ local split = text and string.find(text, "\n", 1, true)
825
+ if not split then
826
+ -- Not sealed by this project on this machine, or damaged
827
+ fs.delete(path)
828
+ return nil
829
+ end
830
+ local fields = __JSON__.decode(string.sub(text, 1, split - 1))
831
+ if type(fields) ~= "table" or fields.url ~= url then
832
+ return nil
833
+ end
834
+ fields.body = string.sub(text, split + 1)
835
+ return fields
836
+ end)
837
+ return ok and entry or nil
838
+ end
839
+
840
+ local function memory()
841
+ return root().http
842
+ end
843
+
844
+ local function remember(url, entry)
845
+ local kept = memory()
846
+ kept.clock = kept.clock + 1
847
+ entry.used = kept.clock
848
+ if kept.entries[url] == nil then
849
+ kept.count = kept.count + 1
850
+ end
851
+ kept.entries[url] = entry
852
+ while kept.count > MEMORY_LIMIT do
853
+ local oldest, oldestUrl = math.huge, nil
854
+ for key, value in pairs(kept.entries) do
855
+ if value.used < oldest then
856
+ oldest, oldestUrl = value.used, key
857
+ end
858
+ end
859
+ kept.entries[oldestUrl] = nil
860
+ kept.count = kept.count - 1
861
+ end
862
+ end
863
+
864
+ local function lookup(url)
865
+ local entry = memory().entries[url]
866
+ if entry == nil then
867
+ entry = readDisk(url)
868
+ if entry then
869
+ remember(url, entry)
870
+ end
871
+ end
872
+ return entry
873
+ end
874
+
875
+ local function store(url, entry)
876
+ remember(url, entry)
877
+ writeDisk(url, entry)
878
+ end
879
+
880
+ local function forget(url)
881
+ local kept = memory()
882
+ if kept.entries[url] ~= nil then
883
+ kept.entries[url] = nil
884
+ kept.count = kept.count - 1
885
+ end
886
+ deleteDisk(url)
887
+ end
888
+
889
+ local function clearCache()
890
+ local kept = memory()
891
+ kept.entries = {}
892
+ kept.count = 0
893
+ if hasDisk then
894
+ pcall(function()
895
+ local folder = diskState().folder
896
+ if not fs.isfolder(folder) then
897
+ return
898
+ end
899
+ if fs.deletefolder then
900
+ fs.deletefolder(folder)
901
+ elseif fs.list then
902
+ for _, path in fs.list(folder) do
903
+ fs.delete(path)
904
+ end
905
+ end
906
+ end)
907
+ end
908
+ end
909
+
910
+ --------------------------------------------------------------------------------
911
+ -- Responses
912
+ --------------------------------------------------------------------------------
913
+
914
+ local Result = {}
915
+ Result.__index = Result
916
+
917
+ function Result.json(self)
918
+ return __JSON__.decode(self.body)
919
+ end
920
+
921
+ local function result(url, status, statusText, headers, body, fromCache)
922
+ return freeze(setmetatable({
923
+ url = url,
924
+ status = status,
925
+ statusText = statusText or "",
926
+ ok = status >= 200 and status < 300,
927
+ headers = freeze(copyOf(headers)),
928
+ body = body,
929
+ fromCache = fromCache,
930
+ }, Result))
931
+ end
932
+
933
+ local function fromEntry(entry, fresh)
934
+ local kept = memory()
935
+ kept.clock = kept.clock + 1
936
+ entry.used = kept.clock
937
+ local headers = copyOf(entry.headers)
938
+ headers["age"] = tostring(math.floor(currentAge(entry)))
939
+ return result(entry.url, entry.status, entry.statusText, headers, entry.body, fresh)
940
+ end
941
+
942
+ --------------------------------------------------------------------------------
943
+ -- The builder
944
+ --------------------------------------------------------------------------------
945
+
946
+ local Builder = {}
947
+ Builder.__index = Builder
948
+
949
+ local states = setmetatable({}, { __mode = "k" })
950
+
951
+ local function make(state)
952
+ local builder = freeze(setmetatable({}, Builder))
953
+ states[builder] = freeze(state)
954
+ return builder
955
+ end
956
+
957
+ local function stateOf(builder, method)
958
+ local state = states[builder]
959
+ if state == nil then
960
+ error(("http builder:%s: call it with `:` on a builder"):format(method), 3)
961
+ end
962
+ return state
963
+ end
964
+
965
+ -- A copy of the builder's state with `changes` made to it
966
+ local function derive(builder, method, changes)
967
+ local state = copyOf(stateOf(builder, method))
968
+ for key, value in pairs(changes) do
969
+ state[key] = value
970
+ end
971
+ return make(state)
972
+ end
973
+
974
+ local function encodeComponent(value)
975
+ return (string.gsub(tostring(value), "[^%w%-%._~]", function(c)
976
+ return string.format("%%%02X", string.byte(c))
977
+ end))
978
+ end
979
+
980
+ -- Headers are kept by their name in lower case, as `{ name, value }`, so one
981
+ -- set twice in two cases is one header
982
+ local function withHeader(headers, name, value)
983
+ local out = copyOf(headers)
984
+ out[string.lower(name)] = value ~= nil and freeze({ name, tostring(value) }) or nil
985
+ return freeze(out)
986
+ end
987
+
988
+ function Builder.path(self, path)
989
+ local url = stateOf(self, "path").url
990
+ local main, rest = string.match(url, "^([^?#]*)(.*)$")
991
+ path = tostring(path)
992
+ if path == "" then
993
+ return self
994
+ end
995
+ main = string.gsub(main, "/+$", "")
996
+ path = string.gsub(path, "^/+", "")
997
+ return derive(self, "path", { url = main .. "/" .. path .. rest })
998
+ end
999
+
1000
+ function Builder.query(self, name, value)
1001
+ local query = copyOf(stateOf(self, "query").query)
1002
+ if type(name) == "table" then
1003
+ local keys = {}
1004
+ for key in pairs(name) do
1005
+ keys[#keys + 1] = tostring(key)
1006
+ end
1007
+ table.sort(keys)
1008
+ for _, key in keys do
1009
+ query[#query + 1] = encodeComponent(key) .. "=" .. encodeComponent(name[key])
1010
+ end
1011
+ else
1012
+ query[#query + 1] = encodeComponent(name) .. "=" .. encodeComponent(value)
1013
+ end
1014
+ return derive(self, "query", { query = freeze(query) })
1015
+ end
1016
+
1017
+ function Builder.header(self, name, value)
1018
+ return derive(self, "header", { headers = withHeader(stateOf(self, "header").headers, name, value) })
1019
+ end
1020
+
1021
+ function Builder.headers(self, headers)
1022
+ local out = stateOf(self, "headers").headers
1023
+ for name, value in pairs(headers) do
1024
+ out = withHeader(out, name, value)
1025
+ end
1026
+ return derive(self, "headers", { headers = out })
1027
+ end
1028
+
1029
+ function Builder.cookie(self, name, value)
1030
+ local cookies = copyOf(stateOf(self, "cookie").cookies)
1031
+ cookies[name] = value
1032
+ return derive(self, "cookie", { cookies = freeze(cookies) })
1033
+ end
1034
+
1035
+ function Builder.method(self, method)
1036
+ stateOf(self, "method")
1037
+ return derive(self, "method", { method = string.upper(method) })
1038
+ end
1039
+
1040
+ function Builder.body(self, body, contentType)
1041
+ local headers = stateOf(self, "body").headers
1042
+ if contentType ~= nil then
1043
+ headers = withHeader(headers, "Content-Type", contentType)
1044
+ end
1045
+ return derive(self, "body", { body = tostring(body), headers = headers })
1046
+ end
1047
+
1048
+ function Builder.json(self, value)
1049
+ local headers = stateOf(self, "json").headers
1050
+ if type(value) == "function" then
1051
+ value = value(types)
1052
+ end
1053
+ if headers["content-type"] == nil then
1054
+ headers = withHeader(headers, "Content-Type", "application/json")
1055
+ end
1056
+ return derive(self, "json", { body = __JSON__.encode(value), headers = headers })
1057
+ end
1058
+
1059
+ function Builder.cache(self, mode)
1060
+ stateOf(self, "cache")
1061
+ return derive(self, "cache", { cache = mode })
1062
+ end
1063
+
1064
+ local function urlOf(state)
1065
+ local url = string.match(state.url, "^([^#]*)")
1066
+ if #state.query == 0 then
1067
+ return url
1068
+ end
1069
+ return url .. (string.find(url, "?", 1, true) and "&" or "?") .. table.concat(state.query, "&")
1070
+ end
1071
+
1072
+ local function requestOf(state)
1073
+ local headers = {}
1074
+ for _, header in pairs(state.headers) do
1075
+ headers[header[1]] = header[2]
1076
+ end
1077
+ return {
1078
+ Url = urlOf(state),
1079
+ Method = state.method,
1080
+ Headers = headers,
1081
+ Body = state.body,
1082
+ Cookies = next(state.cookies) ~= nil and copyOf(state.cookies) or nil,
1083
+ }
1084
+ end
1085
+
1086
+ function Builder.build(self)
1087
+ return requestOf(stateOf(self, "build"))
1088
+ end
1089
+
1090
+ local function perform(state)
1091
+ local options = requestOf(state)
1092
+ local url = options.Url
1093
+ local method = options.Method
1094
+ local requestHeaders = lowerHeaders(options.Headers)
1095
+ local control = directives(requestHeaders["cache-control"])
1096
+ if requestHeaders["cache-control"] == nil and requestHeaders["pragma"]
1097
+ and string.find(string.lower(requestHeaders["pragma"]), "no-cache", 1, true) then
1098
+ control["no-cache"] = true
1099
+ end
1100
+ local mode = state.cache
1101
+ if control["no-store"] then
1102
+ mode = "no-store"
1103
+ elseif control["only-if-cached"] then
1104
+ mode = "only-if-cached"
1105
+ end
1106
+
1107
+ local cacheable = method == "GET"
1108
+ local entry
1109
+ if cacheable and mode ~= "no-store" and mode ~= "reload" then
1110
+ entry = lookup(url)
1111
+ if entry and not varyMatches(entry, requestHeaders) then
1112
+ entry = nil
1113
+ end
1114
+ end
1115
+ if mode == "only-if-cached" then
1116
+ if entry then
1117
+ return fromEntry(entry, true)
1118
+ end
1119
+ return result(url, 504, "Gateway Timeout", {}, "", false)
1120
+ end
1121
+
1122
+ local revalidating = false
1123
+ if entry then
1124
+ local decision = decide(entry, control, mode)
1125
+ if decision == "use" then
1126
+ return fromEntry(entry, true)
1127
+ elseif decision == "validate" then
1128
+ if entry.etag and requestHeaders["if-none-match"] == nil then
1129
+ options.Headers["If-None-Match"] = entry.etag
1130
+ end
1131
+ if entry.lastModified and requestHeaders["if-modified-since"] == nil then
1132
+ options.Headers["If-Modified-Since"] = entry.lastModified
1133
+ end
1134
+ revalidating = true
1135
+ end
1136
+ end
1137
+
1138
+ local requestTime = os.time()
1139
+ local response = send(options)
1140
+ local responseTime = os.time()
1141
+ local status = tonumber(response.StatusCode) or 0
1142
+ local headers = lowerHeaders(response.Headers)
1143
+
1144
+ if revalidating and status == 304 then
1145
+ -- Still good: what was kept, with the headers the 304 brought
1146
+ local merged = copyOf(entry.headers)
1147
+ -- The kept Date and Age were of the first answer, not of this one
1148
+ merged["date"], merged["age"] = nil, nil
1149
+ for name, value in pairs(headers) do
1150
+ merged[name] = value
1151
+ end
1152
+ local refreshed = makeEntry(url, requestHeaders, entry.status, entry.statusText, merged, entry.body, requestTime, responseTime)
1153
+ if refreshed then
1154
+ store(url, refreshed)
1155
+ return fromEntry(refreshed, true)
1156
+ end
1157
+ forget(url)
1158
+ return result(url, entry.status, entry.statusText, merged, entry.body, true)
1159
+ end
1160
+
1161
+ local body = response.Body or ""
1162
+ if cacheable then
1163
+ local made = mode ~= "no-store" and CACHEABLE[status] and makeEntry(url, requestHeaders, status, response.StatusMessage, headers, body, requestTime, responseTime)
1164
+ if made then
1165
+ store(url, made)
1166
+ elseif entry or mode == "reload" then
1167
+ forget(url)
1168
+ end
1169
+ elseif UNSAFE[method] and status >= 200 and status < 400 then
1170
+ forget(url)
1171
+ end
1172
+ return result(url, status, response.StatusMessage, headers, body, false)
1173
+ end
1174
+
1175
+ function Builder.send(self)
1176
+ return perform(stateOf(self, "send"))
1177
+ end
1178
+
1179
+ for _, method in { "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS" } do
1180
+ local name = string.lower(method)
1181
+ Builder[name] = function(self)
1182
+ local state = copyOf(stateOf(self, name))
1183
+ state.method = method
1184
+ return perform(state)
1185
+ end
1186
+ end
1187
+
1188
+ __NAME__.http.to = send and function(url)
1189
+ if type(url) ~= "string" then
1190
+ error("http.to: a URL is a string", 2)
1191
+ end
1192
+ return make({
1193
+ url = url,
1194
+ method = "GET",
1195
+ query = freeze({}),
1196
+ headers = freeze({}),
1197
+ cookies = freeze({}),
1198
+ cache = "default",
1199
+ })
1200
+ end or nil
1201
+
1202
+ __NAME__.http.clearcache = clearCache