importCottonKitimportFoundation/// A business's object through the core, as `business.*` answers/// (`crates/cotton-ffi/src/phone/business.rs`): a synthetic studio whose/// pages follow the role the last sync or sign-in left, a booking made by/// `book` once someone is signed in, and refusals on demand. Every request is/// kept as it was sent.finalclassBusinessFake: CottonCalling, @unchecked Sendable {staticlet server = "https://cotton-business.synthetic.workers.dev"staticlet address = BusinessAddress(server: server, slug: "studio")/// A business app's manifest, as one shipped (no business app ships now):/// it founds nothing and names its business's object.staticfunc manifest(_ slug: String) -> String { #"{"genesis":"none","flavour":"\#(slug)","name":"SyntheticKitchen","databases":"single","fan":{"tools":false},"tools":["people","messages","kitchen"],"business":{"server":"\#(server)","slug":"\#(slug)"}}"# }staticlet photos = server + "/b/studio/v1/photos/"staticlet credential = "synthetic.business.credential.c2hlbGwy"/// The database the open host names for every number here.staticlet database = "11111111-1111-4111-8111-111111111111"privatelet lock = NSLock()privatevar _asked: [(method: String, body: String)] = []var asked: [(method: String, body: String)] { lock.withLock { _asked } }/// What the cache was last synced or signed in as.var role = "public"var booked = false/// The code the next call of a method is refused with, once.var refuseOnce: [String: String] = [:]/// The record pick an act asks (`shell.opened {step: pick, business}`):/// its `step` as the core answers it; nil asks the places stepper.var pickStep: String?/// Rows a person made on the phone's own local database: a connect/// answers that their adopt started (`personal.adopt`).var adoptRows: Int?/// What `personal.adoptStatus` answers, one each time it is asked (the/// last again once they run out).var adoptStatuses: [String] = []/// A synced sync that carries a credential is refused as revoked.var revoked = false/// The number has no account yet: a sign-in that says `nameAfter` and gives no name is answered `nameNeeded`.var newAccount = false/// Held until `release()`: the next sync.var holdsSync = falseprivatevar held: CheckedContinuation<Void, Never>?privatevar arrived: CheckedContinuation<Void, Never>?privatevar syncWaiting = false/// A number's stepper as the core says it (`shell_input::number_rows`).privatestaticfunc places(count: Double) -> String {let down = count > 1 ? [#"{"value":"down-1","words":"−1","does":"count","count":\#(count - 1)}"#] : []let rows = down + [#"{"value":"\#(Int(count))","words":"\#(Int(count))","does":"answer"}"#, #"{"value":"up-1","words":"+1","does":"count","count":\#(count + 1)}"#]return #"{"kind":"pick","label":"Places","index":0,"rest":\#(down.count),"writes":{"kind":"business_pick","answers":[],"of":1},"rows":[\#(rows.joined(separator: ","))]}"# }func requests(_ method: String) -> [[String: JSONValue]] { asked.filter { $0.method == method }.compactMap { try? JSONDecoder().decode([String: JSONValue].self, from: Data($0.body.utf8)) } }func callRaw(_ method: String, requestJSON: String) asyncthrows -> String { lock.withLock { _asked.append((method, requestJSON)) }let request = (try? JSONDecoder().decode([String: JSONValue].self, from: Data(requestJSON.utf8))) ?? [:]let signed = request["credential"]?.string == Self.credentialiflet code = lock.withLock({ refuseOnce.removeValue(forKey: method) }) { returnSelf.refusal(code) }switch method {caseCottonMethod.shellOpened:var count = 1.0ifcase .number(let asked)? = request["count"] { count = asked }returnSelf.ok(#"{"step":\#(pickStep ?? Self.places(count: count))}"#)caseCottonMethod.shellInput:returnSelf.ok(#"{"answers":["\#(request["words"]?.string ?? "")"]}"#)caseCottonMethod.businessSync:if holdsSync {await withCheckedContinuation { gate in lock.withLock { held = gate syncWaiting = true arrived?.resume() arrived = nil } } }if signed, revoked { returnSelf.refusal("credential_revoked") }if !signed { role = "public" }let person = signed ? Self.person(role) : "null"returnSelf.ok(#"{"version":3,"changed":4,"role":"\#(role)","person":\#(person),"business":{"slug":"studio","name":"SyntheticStudio"}}"#)caseCottonMethod.businessPages:returnSelf.ok(Self.pages(role: role, booked: booked))caseCottonMethod.businessCode:returnSelf.ok(#"{"challengeId":"ch-1","expiresIn":300,"sentTo":"We sent a code by text message to +1 ••••••••23."}"#)caseCottonMethod.businessSignIn:if newAccount, request["nameAfter"]?.bool == true, (request["name"]?.string ?? "").isEmpty { returnSelf.ok(#"{"nameNeeded":true}"#) } role = "member"returnSelf.ok(#"{"credential":"\#(Self.credential)","person":\#(Self.person("member")),"expiresIn":7776000}"#)caseCottonMethod.personalCode:returnSelf.ok(#"{"challengeId":"ch-1","expiresIn":300,"known":false,"databaseId":"\#(Self.database)","sentTo":"We sent a code by text message to +1 ••••••••23."}"#)caseCottonMethod.personalSignIn:guard request["databaseId"]?.string == Self.database else { returnSelf.refusal("no_such_database") }if newAccount, request["nameAfter"]?.bool == true, (request["name"]?.string ?? "").isEmpty { returnSelf.ok(#"{"nameNeeded":true}"#) }returnSelf.ok(#"{"credential":"\#(Self.credential)","person":\#(Self.person("owner")),"expiresIn":7776000,"databaseId":"\#(Self.database)"}"#)caseCottonMethod.personalConnect:guard signed else { returnSelf.refusal("not_signed_in") }guard request["databaseId"]?.string == Self.database else { returnSelf.refusal("wrong_database") }iflet rows = adoptRows { returnSelf.ok(#"{"adopt":{"status":"started","rows":\#(rows)}}"#) }returnSelf.ok(#"{"databaseId":"\#(Self.database)","ownerId":"p1"}"#)caseCottonMethod.personalAdoptStatus:let said = lock.withLock { adoptStatuses.count > 1 ? adoptStatuses.removeFirst() : (adoptStatuses.first ?? #"{"status":"none","sent":0,"rows":0,"refused":0}"#) }returnSelf.ok(#"{"adopt":\#(said)}"#)caseCottonMethod.personalStandLocal:returnSelf.ok(#"{}"#)caseCottonMethod.personalRemove:returnSelf.ok(#"{"removed":"\#(Self.database)"}"#)caseCottonMethod.businessSignOut: role = "public"returnSelf.ok(#"{"ok":true}"#)caseCottonMethod.businessAct:guard signed else { returnSelf.refusal("not_signed_in") }if request["act"]?.string == "book" { booked = true }if request["act"]?.string == "cancel" { booked = false }returnSelf.ok(#"{"version":5,"changed":[{"table":"yoga_booking","id":"b1","deleted":true}]}"#)default:returnSelf.refusal("unknown_method") } }/// Until the held sync has been asked.func syncAsked() async {await withCheckedContinuation { gate in lock.withLock { if syncWaiting { gate.resume() } else { arrived = gate } } } }func release() { lock.withLock { held?.resume(); held = nil; holdsSync = false } }func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}func close() {}staticfunc ok(_ data: String) -> String { #"{"ok":true,"data":\#(data)}"# }staticfunc refusal(_ code: String) -> String { #"{"ok":false,"error":{"code":"\#(code)","message":"the object said \#(code)"}}"# }staticfunc person(_ role: String) -> String { #"{"id":"p1","phone":"+15550100123","name":"Anita","role":"\#(role)"}"# }/// Book on a session, its quantity the one pick.staticfunc book(_ slot: String) -> String { #"{"id":"book","label":"Book","kind":"command","rank":"main","primary":true,"red":false,"act":"book","args":{"slot":"\#(slot)"},"picks":[{"argument":"quantity","kind":"number","label":"Places","min":1,"default":1}]}"# }staticlet cancel = #"{"id":"cancel","label":"Cancel","kind":"command","rank":"away","primary":false,"red":true,"confirm":"Cancel this booking?","act":"cancel","args":{"id":"b1"},"picks":[]}"#staticfunc session(_ id: String, _ title: String, _ line: String) -> String { #"{"table":"yoga_session","id":"\#(id)","title":"\#(title)","line":"\#(line)","owner":null,"data":{"name":"\#(title)","capacity":10,"@card":{"face":"event","corner":"\#(line)","fields":{"title":"\#(title)"}}},"acts":[\#(book(id))]}"# }/// The pages a role reads: the public views, a member's own beside them,/// staff's members view beside those.staticfunc pages(role: String, booked: Bool) -> String {var yoga = [ #"{"id":"yoga_session","label":"Today","visibility":"public","is_default":true,"face":null,"table":"yoga_session","count":1,"rows":[\#(session("s1", "Morning hatha", "07:00"))]}"#, #"{"id":"next","label":"Tomorrow","visibility":"public","is_default":false,"face":null,"table":"yoga_session","count":1,"rows":[\#(session("s2", "Vinyasa", "18:00"))]}"#, ]if role != "public" {let booking = booked ? #"{"table":"yoga_booking","id":"b1","title":"Morning hatha","line":"07:00","owner":"p1","data":{"name":"Morning hatha","session":"s1"},"acts":[\#(cancel)]}"# : "" yoga.append(#"{"id":"mine","label":"My bookings","visibility":"customer","table":"yoga_booking","count":\#(booked ? 1 : 0),"rows":[\#(booking)]}"#) }if role == "staff" || role == "owner" { yoga.append(#"{"id":"members","label":"Members","visibility":"staff","table":"yoga_member","count":1,"rows":[{"table":"yoga_member","id":"m1","title":"Anita","data":{"name":"Anita"},"acts":[]}]}"#) }let studio = #"{"id":"studio","label":"Studio","visibility":"public","table":"yoga_place","count":1,"rows":[{"table":"yoga_place","id":"p1","title":"InventedStudio","line":null,"data":{"name":"InventedStudio","photo":"studio/hall.jpg","@card":{"face":"sharmila.studio","fields":{"title":"InventedStudio","photo":"studio/hall.jpg"}}},"acts":[]}]}"#return #""" {"business":{"slug":"studio","name":"Synthetic Studio","currency":"INR","timezone":"Asia/Kolkata"},"role":"\#(role)","person":\#(role == "public" ? "null" : person(role)),"version":3,"photos":"\#(photos)","tools":[ {"tool":"yoga","name":"Yoga","picture":"yoga","card_stock":"sage","views":[\#(yoga.joined(separator: ","))]}, {"tool":"yoga_studio","name":"Studio","picture":null,"card_stock":null,"views":[\#(studio)]}]} """# }}